Debian Codegraph @

hugolib/content_map.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hugolib
15
16 import (
17 "context"
18 "fmt"
19 "iter"
20 "path"
21 "path/filepath"
22 "strings"
23 "unicode"
24
25 "github.com/bep/logg"
26 "github.com/gohugoio/hugo/common/hugio"
27 "github.com/gohugoio/hugo/common/paths"
28 "github.com/gohugoio/hugo/hugofs/files"
29 "github.com/gohugoio/hugo/hugolib/pagesfromdata"
30 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
31 "github.com/gohugoio/hugo/identity"
32
33 "github.com/gohugoio/hugo/resources/page"
34 "github.com/gohugoio/hugo/resources/page/pagemeta"
35 "github.com/gohugoio/hugo/resources/resource"
36
37 "github.com/gohugoio/hugo/hugofs"
38 )
39
40 // Used to mark ambiguous keys in reverse index lookups.
41 var ambiguousContentNode = &pageState{}
42
43 var trimCutsetDotSlashSpace = func(r rune) bool {
44 return r == '.' || r == '/' || unicode.IsSpace(r)
45 }
46
47 type contentMapConfig struct {
48 lang string
49 taxonomyConfig taxonomiesConfigValues
50 taxonomyDisabled bool
51 taxonomyTermDisabled bool
52 pageDisabled bool
53 isRebuild bool
54 }
55
56 type resourceSourceState int
57
58 const (
59 resourceStateNew resourceSourceState = iota
60 resourceStateAssigned
61 )
62
63 type resourceSource struct {
64 state resourceSourceState
65 sv sitesmatrix.Vector
66 path *paths.Path
67 opener hugio.OpenReadSeekCloser
68 fi hugofs.FileMetaInfo
69 rc *pagemeta.ResourceConfig
70
71 r resource.Resource
72 }
73
74 func (r *resourceSource) assignSiteVector(vec sitesmatrix.Vector) *resourceSource {
75 if r.state == resourceStateAssigned {
76 panic("cannot assign site vector to a resourceSource that is already assigned")
77 }
78 r.sv = vec
79 r.state = resourceStateAssigned
80 return r
81 }
82
83 func (r resourceSource) clone() *resourceSource {
84 r.state = resourceStateNew
85 r.r = nil
86 return &r
87 }
88
89 func (r *resourceSource) forEeachContentNode(f func(v sitesmatrix.Vector, n contentNode) bool) bool {
90 return f(r.sv, r)
91 }
92
93 func (r *resourceSource) nodeCategorySingle() {
94 // Marker method.
95 }
96
97 func (r *resourceSource) String() string {
98 var sb strings.Builder
99 if r.fi != nil {
100 sb.WriteString("filename: " + r.fi.Meta().Filename)
101 sb.WriteString(fmt.Sprintf(" matrix: %v", r.fi.Meta().SitesMatrix))
102 sb.WriteString(fmt.Sprintf(" complements: %v", r.fi.Meta().SitesComplements))
103 }
104 if r.rc != nil {
105 sb.WriteString(fmt.Sprintf("rc matrix: %v", r.rc.SitesMatrix))
106 sb.WriteString(fmt.Sprintf("rc complements: %v", r.rc.SitesComplements))
107 }
108 sb.WriteString(fmt.Sprintf(" sv: %v", r.sv))
109 return sb.String()
110 }
111
112 func (r *resourceSource) siteVector() sitesmatrix.Vector {
113 return r.sv
114 }
115
116 func (r *resourceSource) MarkStale() {
117 resource.MarkStale(r.r)
118 }
119
120 func (r *resourceSource) resetBuildState() {
121 if rr, ok := r.r.(contentNodeBuildStateResetter); ok {
122 rr.resetBuildState()
123 }
124 }
125
126 func (r *resourceSource) GetIdentity() identity.Identity {
127 if r.r != nil {
128 return r.r.(identity.IdentityProvider).GetIdentity()
129 }
130 return r.path
131 }
132
133 func (p *resourceSource) nodeSourceEntryID() any {
134 if p.rc != nil {
135 return p.rc.ContentAdapterSourceEntryHash
136 }
137 if p.fi != nil {
138 return p.fi.Meta().Filename
139 }
140 return p.path
141 }
142
143 func (p *resourceSource) lookupContentNode(v sitesmatrix.Vector) contentNode {
144 if p.state >= resourceStateAssigned {
145 if p.sv == v {
146 return p
147 }
148 return nil
149 }
150
151 // A site has not been assigned yet.
152
153 if p.rc != nil && p.rc.MatchSiteVector(v) {
154 return p
155 }
156
157 if p.rc != nil && p.rc.SitesMatrix.LenVectors() > 0 {
158 // Do not consider file mount matrix if the resource config has its own.
159 return nil
160 }
161
162 if p.fi != nil && p.fi.Meta().SitesMatrix.HasVector(v) {
163 return p
164 }
165
166 return nil
167 }
168
169 func (p *resourceSource) lookupContentNodes(siteVector sitesmatrix.Vector, fallback bool) iter.Seq[contentNodeForSite] {
170 if siteVector == p.sv {
171 found := p.rc == nil
172 if !found {
173 // For content adapter resources with explicit sites.matrix config,
174 // verify the vector is allowed even on exact match,
175 // since sv is the creating site's vector, not necessarily the target.
176 // In the exact-match path (siteVector == p.sv), always use strict matching.
177 // The coarse language-excluding fallback only applies for cross-site matching.
178 found = p.rc.Sites.Matrix.IsZero() || p.rc.MatchSiteVector(siteVector)
179 }
180 if !found {
181 return nil
182 }
183
184 return func(yield func(n contentNodeForSite) bool) {
185 yield(p)
186 }
187 }
188
189 pc := p.rc
190
191 var found bool
192 if !fallback {
193 if pc != nil && pc.MatchSiteVector(siteVector) {
194 found = true
195 } else {
196 return nil
197 }
198 }
199
200 if !found {
201 if pc != nil {
202 // Content adapter resources have explicit site matrix config; respect all dimensions.
203 found = pc.MatchSiteVectorCoarse(siteVector)
204 } else if p.fi != nil {
205 // File-based resources: exclude the language dimension in the coarse match.
206 // The typical setup is to provide translated content files but one resource (e.g. an image) that is shared between the translations.
207 // To give all the languages a full set, we ignore that dimension for this last fallback check.
208 found = p.fi.Meta().MatchSiteVectorCoarseExcludeLanguage(siteVector)
209 }
210 }
211
212 if !found {
213 return nil
214 }
215
216 return func(yield func(n contentNodeForSite) bool) {
217 if !yield(p) {
218 return
219 }
220 }
221 }
222
223 func (r *resourceSource) Path() string {
224 return r.path.Base()
225 }
226
227 func (r *resourceSource) PathInfo() *paths.Path {
228 return r.path
229 }
230
231 func (cfg contentMapConfig) getTaxonomyConfig(s string) (v viewName) {
232 for _, n := range cfg.taxonomyConfig.views {
233 if strings.HasPrefix(s, n.pluralTreeKey) {
234 return n
235 }
236 }
237 return
238 }
239
240 func (m *pageMap) AddFi(fi hugofs.FileMetaInfo, buildConfig *BuildCfg) (pageSourceCount uint64, resourceSourceCount uint64, addErr error) {
241 if fi.IsDir() {
242 return
243 }
244
245 if m == nil {
246 panic("nil pageMap")
247 }
248
249 h := m.s.h
250
251 insertResource := func(fim hugofs.FileMetaInfo) error {
252 resourceSourceCount++
253 pi := fi.Meta().PathInfo
254 key := pi.Base()
255 tree := m.treeResources
256
257 tree.Lock(true)
258 defer tree.Unlock(true)
259
260 if pi.IsContent() {
261 pm, err := h.newPageMetaSourceFromFile(fi)
262 if err != nil {
263 return fmt.Errorf("failed to create page from file %q: %w", fi.Meta().Filename, err)
264 }
265 pm.bundled = true
266 m.treeResources.Insert(key, pm)
267 } else {
268 r := func() (hugio.ReadSeekCloser, error) {
269 return fim.Meta().Open()
270 }
271 // Create one dimension now, the rest later on demand.
272 rs := &resourceSource{path: pi, opener: r, fi: fim, sv: fim.Meta().SitesMatrix.VectorSample()}
273 m.treeResources.Insert(key, rs)
274 }
275
276 return nil
277 }
278
279 meta := fi.Meta()
280 pi := meta.PathInfo
281
282 switch pi.Type() {
283 case paths.TypeFile, paths.TypeContentResource:
284 m.s.Log.Trace(logg.StringFunc(
285 func() string {
286 return fmt.Sprintf("insert resource: %q", fi.Meta().Filename)
287 },
288 ))
289 if err := insertResource(fi); err != nil {
290 addErr = err
291 return
292 }
293 case paths.TypeContentData:
294 pc, rc, err := m.addPagesFromGoTmplFi(fi, buildConfig)
295 pageSourceCount += pc
296 resourceSourceCount += rc
297 if err != nil {
298 addErr = err
299 return
300 }
301
302 default:
303 m.s.Log.Trace(logg.StringFunc(
304 func() string {
305 return fmt.Sprintf("insert bundle: %q", fi.Meta().Filename)
306 },
307 ))
308
309 pageSourceCount++
310
311 pm, err := h.newPageMetaSourceFromFile(fi)
312 if err != nil {
313 addErr = fmt.Errorf("failed to create page meta from file %q: %w", fi.Meta().Filename, err)
314 return
315 }
316
317 m.treePages.InsertWithLock(pm.pathInfo.Base(), pm)
318 }
319 return
320 }
321
322 func (m *pageMap) addPagesFromGoTmplFi(fi hugofs.FileMetaInfo, buildConfig *BuildCfg) (pageCount uint64, resourceCount uint64, addErr error) {
323 meta := fi.Meta()
324 pi := meta.PathInfo
325
326 m.s.Log.Trace(logg.StringFunc(
327 func() string {
328 return fmt.Sprintf("insert pages from data file: %q", fi.Meta().Filename)
329 },
330 ))
331
332 if !files.IsGoTmplExt(pi.Ext()) {
333 addErr = fmt.Errorf("unsupported data file extension %q", pi.Ext())
334 return
335 }
336
337 sitesMatrix := fi.Meta().SitesMatrix
338
339 s := m.s.h.resolveFirstSite(sitesMatrix)
340 h := s.h
341
342 contentAdapter := s.pageMap.treePagesFromTemplateAdapters.Get(pi.Base())
343 var rebuild bool
344 if contentAdapter != nil {
345 // Rebuild
346 contentAdapter = contentAdapter.CloneForGoTmpl(fi)
347 rebuild = true
348 } else {
349 contentAdapter = pagesfromdata.NewPagesFromTemplate(
350 pagesfromdata.PagesFromTemplateOptions{
351 GoTmplFi: fi,
352 Site: s,
353 DepsFromSite: func(s page.Site) pagesfromdata.PagesFromTemplateDeps {
354 ss := s.(*Site)
355 return pagesfromdata.PagesFromTemplateDeps{
356 TemplateStore: ss.GetTemplateStore(),
357 }
358 },
359 DependencyManager: s.Conf.NewIdentityManager(),
360 Watching: s.Conf.Watching(),
361 HandlePage: func(pt *pagesfromdata.PagesFromTemplate, pe *pagemeta.PageConfigEarly) error {
362 s := pt.Site.(*Site)
363
364 if err := pe.CompileForPagesFromDataPre(pt.GoTmplFi.Meta().PathInfo.Base(), m.s.Log, s.conf.MediaTypes.Config); err != nil {
365 return err
366 }
367
368 ps, err := s.h.newPageMetaSourceForContentAdapter(fi, s.siteVector, pe)
369 if err != nil {
370 return err
371 }
372
373 if ps == nil {
374 // Disabled page.
375 return nil
376 }
377
378 u, n, replaced := s.pageMap.treePages.InsertWithLock(ps.pathInfo.Base(), ps)
379
380 if h.isRebuild() {
381 if replaced {
382 pt.AddChange(cnh.GetIdentity(n))
383 } else {
384 pt.AddChange(cnh.GetIdentity(u))
385 // New content not in use anywhere.
386 // To make sure that these gets listed in any site.RegularPages ranges or similar
387 // we could invalidate everything, but first try to collect a sample set
388 // from the surrounding pages.
389 var surroundingIDs []identity.Identity
390 ids := h.pageTrees.collectIdentitiesSurrounding(pi.Base(), 10)
391 if len(ids) > 0 {
392 surroundingIDs = append(surroundingIDs, ids...)
393 } else {
394 // No surrounding pages found, so invalidate everything.
395 surroundingIDs = []identity.Identity{identity.GenghisKhan}
396 }
397 for _, id := range surroundingIDs {
398 pt.AddChange(id)
399 }
400 }
401 }
402
403 return nil
404 },
405 HandleResource: func(pt *pagesfromdata.PagesFromTemplate, rc *pagemeta.ResourceConfig) error {
406 s := pt.Site.(*Site)
407 if err := rc.Compile(
408 pt.GoTmplFi.Meta().PathInfo.Base(),
409 pt.GoTmplFi,
410 s.Conf,
411 s.conf.MediaTypes.Config,
412 ); err != nil {
413 return err
414 }
415
416 // Create one dimension now, the rest later on demand.
417 rs := &resourceSource{path: rc.PathInfo, rc: rc, opener: nil, fi: pt.GoTmplFi, sv: s.siteVector}
418
419 _, n, updated := s.pageMap.treeResources.InsertWithLock(rs.path.Base(), rs)
420
421 if h.isRebuild() && updated {
422 pt.AddChange(cnh.GetIdentity(n))
423 }
424 return nil
425 },
426 },
427 )
428
429 s.pageMap.treePagesFromTemplateAdapters.Insert(pi.Base(), contentAdapter)
430
431 }
432
433 handleBuildInfo := func(s *Site, bi pagesfromdata.BuildInfo) {
434 resourceCount += bi.NumResourcesAdded
435 pageCount += bi.NumPagesAdded
436 s.handleContentAdapterChanges(bi, buildConfig)
437 }
438
439 bi, err := contentAdapter.Execute(context.Background())
440 if err != nil {
441 addErr = err
442 return
443 }
444 handleBuildInfo(s, bi)
445
446 if !rebuild && (bi.EnableAllLanguages || bi.EnableAllDimensions) {
447 // Clone and insert the adapter for the other sites.
448 var iter iter.Seq[*Site]
449 if bi.EnableAllLanguages {
450 include := func(ss *Site) bool {
451 return s.siteVector.Language() != ss.siteVector.Language()
452 }
453 iter = h.allSiteLanguages(include)
454 } else {
455 include := func(ss *Site) bool {
456 return s.siteVector != ss.siteVector
457 }
458 iter = h.allSites(include)
459 }
460
461 for ss := range iter {
462 clone := contentAdapter.CloneForSite(ss)
463
464 // Make sure it gets executed for the first time.
465 bi, err := clone.Execute(context.Background())
466 if err != nil {
467
468 addErr = err
469 return
470 }
471 handleBuildInfo(ss, bi)
472
473 // Insert into the correct language tree so it get rebuilt on changes.
474 ss.pageMap.treePagesFromTemplateAdapters.Insert(pi.Base(), clone)
475
476 }
477 }
478
479 return
480 }
481
482 // The home page is represented with the zero string.
483 // All other keys starts with a leading slash. No trailing slash.
484 // Slashes are Unix-style.
485 func cleanTreeKey(elem ...string) string {
486 var s string
487 if len(elem) > 0 {
488 s = elem[0]
489 if len(elem) > 1 {
490 s = path.Join(elem...)
491 }
492 }
493 s = strings.TrimFunc(s, trimCutsetDotSlashSpace)
494 s = filepath.ToSlash(strings.ToLower(paths.Sanitize(s)))
495 if s == "" || s == "/" {
496 return ""
497 }
498 if s[0] != '/' {
499 s = "/" + s
500 }
501 return s
502 }