Debian Codegraph @

tpl/tplimpl/templatestore.go

raw
1 // Copyright 2025 The Hugo Authors. All rights reserved.
2 //
3 // Portions Copyright The Go Authors.
4
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 package tplimpl
17
18 import (
19 "bytes"
20 "context"
21 "embed"
22 "errors"
23 "fmt"
24 "io"
25 "io/fs"
26 "iter"
27 "os"
28 "path"
29 "path/filepath"
30 "reflect"
31 "regexp"
32 "slices"
33 "sort"
34 "strings"
35 "sync"
36 "sync/atomic"
37 "time"
38
39 "github.com/gohugoio/hugo/common/collections"
40 "github.com/gohugoio/hugo/common/herrors"
41 "github.com/gohugoio/hugo/common/hmaps"
42 "github.com/gohugoio/hugo/common/hstrings"
43 "github.com/gohugoio/hugo/common/loggers"
44 "github.com/gohugoio/hugo/common/paths"
45 "github.com/gohugoio/hugo/helpers"
46 "github.com/gohugoio/hugo/hugofs"
47 "github.com/gohugoio/hugo/hugofs/files"
48 "github.com/gohugoio/hugo/hugolib/doctree"
49 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
50 "github.com/gohugoio/hugo/identity"
51 gc "github.com/gohugoio/hugo/markup/goldmark/goldmark_config"
52 "github.com/gohugoio/hugo/media"
53 "github.com/gohugoio/hugo/metrics"
54 "github.com/gohugoio/hugo/output"
55 "github.com/gohugoio/hugo/resources/kinds"
56 "github.com/gohugoio/hugo/resources/page"
57 "github.com/gohugoio/hugo/tpl"
58 htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"
59 texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
60 "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
61 "github.com/spf13/afero"
62 )
63
64 const (
65 CategoryLayout Category = iota + 1
66 CategoryBaseof
67 CategoryMarkup
68 CategoryShortcode
69 CategoryPartial
70 // Internal categories
71 CategoryServer
72 CategoryHugo
73 )
74
75 const (
76 SubCategoryMain SubCategory = iota
77 SubCategoryEmbedded // Internal Hugo templates
78 SubCategoryInline // Inline partials
79 )
80
81 const (
82 containerMarkup = "_markup"
83 containerShortcodes = "_shortcodes"
84 shortcodesPathIdentifier = "/_shortcodes/"
85 containerPartials = "_partials"
86 )
87
88 const (
89 layoutAll = "all"
90 layoutList = "list"
91 layoutSingle = "single"
92 )
93
94 var (
95 _ identity.IdentityProvider = (*TemplInfo)(nil)
96 _ identity.IsProbablyDependentProvider = (*TemplInfo)(nil)
97 _ identity.IsProbablyDependencyProvider = (*TemplInfo)(nil)
98 )
99
100 const (
101 processingStateInitial processingState = iota
102 processingStateTransformed
103 )
104
105 // The identifiers may be truncated in the log, e.g.
106 // "executing "main" at <$scaled.SRelPermalin...>: can't evaluate field SRelPermalink in type *resource.Image"
107 // We need this to identify position in templates with base templates applied.
108 var identifiersRe = regexp.MustCompile(`at \<(.*?)(\.{3})?\>:`)
109
110 var weightNoMatch = weight{w1: -1}
111
112 //
113 //go:embed all:embedded/templates/*
114 var embeddedTemplatesFs embed.FS
115
116 func NewStore(opts StoreOptions, siteOpts SiteOptions) (*TemplateStore, error) {
117 html, ok := opts.OutputFormats.GetByName("html")
118 if !ok {
119 panic("HTML output format not found")
120 }
121 s := &TemplateStore{
122 opts: opts,
123 siteOpts: siteOpts,
124 optsOrig: opts,
125 siteOptsOrig: siteOpts,
126 htmlFormat: html,
127 storeSite: configureSiteStorage(siteOpts, opts.Watching),
128 treeMain: doctree.NewSimpleTree[map[nodeKey]*TemplInfo](),
129 treeShortcodes: doctree.NewSimpleTree[map[string]map[TemplateDescriptor]*TemplInfo](),
130 templatesByPath: hmaps.NewCache[string, *TemplInfo](),
131 shortcodesByName: hmaps.NewCache[string, *TemplInfo](),
132 cacheLookupPartials: hmaps.NewCache[string, *TemplInfo](),
133 templatesSnapshotSet: hmaps.NewCache[*parse.Tree, struct{}](),
134
135 // Note that the funcs passed below is just for name validation.
136 tns: newTemplateNamespace(siteOpts.TemplateFuncs),
137
138 dh: descriptorHandler{
139 opts: opts,
140 },
141 }
142
143 if err := s.init(); err != nil {
144 return nil, err
145 }
146 if err := s.insertTemplates(nil, false); err != nil {
147 return nil, err
148 }
149 if err := s.insertEmbedded(); err != nil {
150 return nil, err
151 }
152 if err := s.parseTemplates(); err != nil {
153 return nil, err
154 }
155 if err := s.extractInlinePartials(false); err != nil {
156 return nil, err
157 }
158 if err := s.transformTemplates(); err != nil {
159 return nil, err
160 }
161 if err := s.tns.createPrototypes(true); err != nil {
162 return nil, err
163 }
164 if err := s.prepareTemplates(); err != nil {
165 return nil, err
166 }
167 return s, nil
168 }
169
170 //go:generate stringer -type Category
171
172 type Category int
173
174 type SiteOptions struct {
175 Site page.Site
176 TemplateFuncs map[string]any
177 }
178
179 type StoreOptions struct {
180 // The filesystem to use.
181 Fs afero.Fs
182
183 // The logger to use.
184 Log loggers.Logger
185
186 // The path handler to use.
187 PathParser *paths.PathParser
188
189 // Set when --enableTemplateMetrics is set.
190 Metrics metrics.Provider
191
192 // All configured output formats.
193 OutputFormats output.Formats
194
195 // All configured media types.
196 MediaTypes media.Types
197
198 // The default output format.
199 DefaultOutputFormat string
200
201 // Taxonomy config.
202 TaxonomySingularPlural map[string]string
203
204 // Whether we are in watch or server mode.
205 Watching bool
206
207 // The render hook configuration.
208 RenderHooks gc.RenderHooks
209
210 // compiled.
211 legacyMappingTaxonomy map[string]legacyOrdinalMapping
212 legacyMappingTerm map[string]legacyOrdinalMapping
213 legacyMappingSection map[string]legacyOrdinalMapping
214 }
215
216 //go:generate stringer -type SubCategory
217
218 type SubCategory int
219
220 type TemplInfo struct {
221 // The category of this template.
222 category Category
223
224 subCategory SubCategory
225
226 // PathInfo info.
227 PathInfo *paths.Path
228
229 // Set when backed by a file.
230 Fi hugofs.FileMetaInfo
231
232 // The template content with any leading BOM removed.
233 content string
234
235 // The parsed template.
236 // Note that any baseof template will be applied later.
237 Template tpl.Template
238
239 // If no baseof is needed, this will be set to true.
240 // E.g. shortcode templates do not need a baseof.
241 noBaseOf bool
242
243 // If NoBaseOf is false, we will look for the final template in this tree.
244 baseVariants *doctree.SimpleTree[map[TemplateDescriptor]*TemplWithBaseApplied]
245
246 // The template variants that are based on this template.
247 overlays []*TemplInfo
248
249 // The base template used, if any.
250 base *TemplInfo
251
252 // For partial decorator inner templates, the template the inner block was defined in.
253 decoratorOwner *TemplInfo
254
255 // The descriptior that this template represents.
256 D TemplateDescriptor
257
258 matrix sitesmatrix.VectorProvider // language, version, role.
259
260 // Parser state.
261 ParseInfo ParseInfo
262
263 // The execution counter for this template.
264 executionCounter atomic.Uint64
265
266 // processing state.
267 state processingState
268 isLegacyMapped bool
269 }
270
271 func (ti *TemplInfo) SubCategory() SubCategory {
272 return ti.subCategory
273 }
274
275 func (ti *TemplInfo) BaseVariantsSeq() iter.Seq[*TemplWithBaseApplied] {
276 return func(yield func(*TemplWithBaseApplied) bool) {
277 for _, v := range ti.baseVariants.All() {
278 for _, vv := range v {
279 if !yield(vv) {
280 return
281 }
282 }
283 }
284 }
285 }
286
287 func (t *TemplInfo) IdentifierBase() string {
288 if t.PathInfo == nil {
289 return t.Name()
290 }
291 return t.PathInfo.IdentifierBase()
292 }
293
294 func (t *TemplInfo) GetIdentity() identity.Identity {
295 return t
296 }
297
298 func (ti *TemplInfo) Name() string {
299 if ti.Template == nil {
300 if ti.PathInfo != nil {
301 return ti.PathInfo.PathNoLeadingSlash()
302 }
303 }
304 return ti.Template.Name()
305 }
306
307 func (ti *TemplInfo) Prepare() (*texttemplate.Template, error) {
308 return ti.Template.Prepare()
309 }
310
311 func (t *TemplInfo) IsProbablyDependency(other identity.Identity) bool {
312 return t.isProbablyTheSameIDAs(other)
313 }
314
315 func (t *TemplInfo) IsProbablyDependent(other identity.Identity) bool {
316 for _, overlay := range t.overlays {
317 if overlay.isProbablyTheSameIDAs(other) {
318 return true
319 }
320 }
321 return t.isProbablyTheSameIDAs(other)
322 }
323
324 func (ti *TemplInfo) String() string {
325 if ti == nil {
326 return "<nil>"
327 }
328 return ti.PathInfo.String()
329 }
330
331 func (ti *TemplInfo) findBestMatchBaseof(s *TemplateStore, d1 TemplateDescriptor, dims1 sitesmatrix.VectorProvider, k1 string, slashCountK1 int, best *bestMatch) {
332 if ti.baseVariants == nil {
333 return
334 }
335
336 ti.baseVariants.WalkPath(k1, func(k2 string, v map[TemplateDescriptor]*TemplWithBaseApplied) (bool, error) {
337 if !s.inPath(k1, k2) {
338 return false, nil
339 }
340 slashCountK2 := strings.Count(k2, "/")
341 distance := slashCountK1 - slashCountK2
342
343 for d2, vv := range v {
344
345 weight := s.dh.compareDescriptors(CategoryBaseof, d1, d2, dims1, vv.Base.matrix)
346
347 weight.distance = distance
348 if best.isBetter(weight, vv.Template) {
349 best.updateValues(weight, k2, d2, vv.Template)
350 }
351 }
352 return false, nil
353 })
354 }
355
356 func (t *TemplInfo) isProbablyTheSameIDAs(other identity.Identity) bool {
357 if t.IdentifierBase() == other.IdentifierBase() {
358 return true
359 }
360
361 if t.Fi != nil && t.Fi.Meta().PathInfo != t.PathInfo {
362 return other.IdentifierBase() == t.Fi.Meta().PathInfo.IdentifierBase()
363 }
364
365 return false
366 }
367
368 // Implements the additional methods in tpl.CurrentTemplateInfoOps.
369 func (ti *TemplInfo) Base() tpl.CurrentTemplateInfoCommonOps {
370 return ti.base
371 }
372
373 func (ti *TemplInfo) Filename() string {
374 if ti.Fi == nil {
375 return ""
376 }
377 return ti.Fi.Meta().Filename
378 }
379
380 type TemplWithBaseApplied struct {
381 // The template that's overlaid on top of the base template.
382 Overlay *TemplInfo
383 // The base template.
384 Base *TemplInfo
385 // This is the final template that can be used to render a page.
386 Template *TemplInfo
387 }
388
389 // TemplateQuery is used in LookupPagesLayout to find the best matching template.
390 type TemplateQuery struct {
391 // The path to walk down to.
392 Path string
393
394 // Currently only set for page.Render, e.g. using "foo/bar/mylayout";
395 // in that example SubPath will be "foo/bar" and LayoutFromUser will be "mylayout".
396 SubPath string
397
398 // The name to look for. Used for shortcode queries.
399 Name string
400
401 // The category to look in.
402 Category Category
403
404 // The sites variants to consider.
405 Sites sitesmatrix.VectorProvider
406
407 // The template descriptor to match against.
408 Desc TemplateDescriptor
409
410 // Whether to even consider this candidate.
411 Consider func(candidate *TemplInfo) bool
412 }
413
414 func (q *TemplateQuery) init() {
415 if q.Desc.Kind == kinds.KindTemporary {
416 q.Desc.Kind = ""
417 } else if kinds.GetKindMain(q.Desc.Kind) == "" {
418 q.Desc.Kind = ""
419 }
420 if q.Desc.LayoutFromTemplate == "" && q.Desc.Kind != "" {
421 if q.Desc.Kind == kinds.KindPage {
422 q.Desc.LayoutFromTemplate = layoutSingle
423 } else {
424 q.Desc.LayoutFromTemplate = layoutList
425 }
426 }
427
428 if q.Consider == nil {
429 q.Consider = func(match *TemplInfo) bool {
430 return true
431 }
432 }
433
434 q.Name = strings.ToLower(q.Name)
435 q.Desc.LayoutFromUser = strings.ToLower(q.Desc.LayoutFromUser)
436 if q.SubPath != "" {
437 q.SubPath = paths.AddLeadingSlash(strings.ToLower(paths.ToSlashTrim(q.SubPath)))
438 }
439
440 if q.Category == 0 {
441 panic("category not set")
442 }
443 }
444
445 type TemplateStore struct {
446 opts StoreOptions
447 siteOpts SiteOptions
448 htmlFormat output.Format
449
450 treeMain *doctree.SimpleTree[map[nodeKey]*TemplInfo]
451 treeShortcodes *doctree.SimpleTree[map[string]map[TemplateDescriptor]*TemplInfo]
452 templatesByPath *hmaps.Cache[string, *TemplInfo]
453 shortcodesByName *hmaps.Cache[string, *TemplInfo]
454 templatesSnapshotSet *hmaps.Cache[*parse.Tree, struct{}]
455
456 dh descriptorHandler
457
458 // The template namespace.
459 tns *templateNamespace
460
461 // Site specific state.
462 // All above this is reused.
463 storeSite *storeSite
464
465 // For testing benchmarking.
466 optsOrig StoreOptions
467 siteOptsOrig SiteOptions
468
469 // caches. These need to be refreshed when the templates are refreshed.
470 cacheLookupPartials *hmaps.Cache[string, *TemplInfo]
471 }
472
473 // NewFromOpts creates a new store with the same configuration as the original.
474 // Used for testing/benchmarking.
475 func (s *TemplateStore) NewFromOpts() (*TemplateStore, error) {
476 return NewStore(s.optsOrig, s.siteOptsOrig)
477 }
478
479 // In the previous implementation of base templates in Hugo, we parsed and applied these base templates on
480 // request, e.g. in the middle of rendering. The idea was that we couldn't know upfront which layoyt/base template
481 // combination that would be used.
482 // This, however, added a lot of complexity involving a careful dance of template cloning and parsing
483 // (Go HTML tenplates cannot be parsed after any of the templates in the tree have been executed).
484 // FindAllBaseTemplateCandidates finds all base template candidates for the given descriptor so we can apply them upfront.
485 // In this setup we may end up with unused base templates, but not having to do the cloning should more than make up for that.
486 func (s *TemplateStore) FindAllBaseTemplateCandidates(overlayKey string, d1 TemplateDescriptor, dims1 sitesmatrix.VectorProvider) []keyTemplateInfo {
487 var result []keyTemplateInfo
488
489 s.treeMain.Walk(func(k string, v map[nodeKey]*TemplInfo) (bool, error) {
490 for _, vv := range v {
491 if vv.category != CategoryBaseof {
492 continue
493 }
494
495 if vv.D.isKindInLayout(d1.LayoutFromTemplate) && s.dh.compareDescriptors(CategoryBaseof, d1, vv.D, dims1, vv.matrix).w1 > 0 {
496 result = append(result, keyTemplateInfo{Key: k, Info: vv})
497 }
498 }
499 return false, nil
500 })
501
502 return result
503 }
504
505 // PrepareTopLevelRenderCtx prepares a context for top-level rendering of a page.
506 func (t *TemplateStore) PrepareTopLevelRenderCtx(ctx context.Context, p page.Page) context.Context {
507 if p != nil {
508 ctx = tpl.Context.Page.Set(ctx, p)
509 }
510 ctx = tpl.Context.PartialDecoratorIDStack.Set(ctx, collections.NewStack[*tpl.StringBool]())
511 return ctx
512 }
513
514 func (t *TemplateStore) ExecuteWithContext(ctx context.Context, ti *TemplInfo, wr io.Writer, data any) error {
515 return t.ExecuteWithContextAndKey(ctx, "", ti, wr, data)
516 }
517
518 func (t *TemplateStore) ExecuteWithContextAndKey(ctx context.Context, key string, ti *TemplInfo, wr io.Writer, data any) error {
519 defer func() {
520 ti.executionCounter.Add(1)
521 if ti.base != nil {
522 ti.base.executionCounter.Add(1)
523 }
524 }()
525
526 templ := ti.Template
527
528 parent := tpl.Context.CurrentTemplate.Get(ctx)
529 var level int
530 if parent != nil {
531 level = parent.Level + 1
532 }
533 currentTi := &tpl.CurrentTemplateInfo{
534 Parent: parent,
535 Level: level,
536 Key: key,
537 CurrentTemplateInfoOps: ti,
538 }
539
540 ctx = tpl.Context.CurrentTemplate.Set(ctx, currentTi)
541
542 const levelThreshold = 999
543 if level > levelThreshold {
544 return fmt.Errorf("maximum template call stack size exceeded in %q", ti.Filename())
545 }
546
547 if t.opts.Metrics != nil {
548 defer t.opts.Metrics.MeasureSince(templ.Name(), time.Now())
549 }
550
551 execErr := t.storeSite.executer.ExecuteWithContext(ctx, ti, wr, data)
552 if execErr != nil {
553 return t.addFileContext(ti, "execute of template failed", execErr)
554 }
555 return nil
556 }
557
558 func (t *TemplateStore) GetFunc(name string) (reflect.Value, bool) {
559 v, found := t.storeSite.execHelper.funcs[name]
560 return v, found
561 }
562
563 func (s *TemplateStore) GetIdentity(p string) identity.Identity {
564 p = paths.AddLeadingSlash(p)
565 v, found := s.templatesByPath.Get(p)
566 if !found {
567 return nil
568 }
569 return v.GetIdentity()
570 }
571
572 func (t *TemplateStore) LookupByPath(templatePath string) *TemplInfo {
573 v, _ := t.templatesByPath.Get(templatePath)
574 return v
575 }
576
577 var bestPool = sync.Pool{
578 New: func() any {
579 return &bestMatch{}
580 },
581 }
582
583 func (s *TemplateStore) getBest() *bestMatch {
584 v := bestPool.Get()
585 b := v.(*bestMatch)
586 b.defaultOutputformat = s.opts.DefaultOutputFormat
587 return b
588 }
589
590 func (s *TemplateStore) putBest(b *bestMatch) {
591 b.reset()
592 bestPool.Put(b)
593 }
594
595 func (s *TemplateStore) LookupPagesLayout(q TemplateQuery) *TemplInfo {
596 q.init()
597 key := s.key(q.Path)
598
599 slashCountKey := strings.Count(key, "/")
600 best1 := s.getBest()
601 defer s.putBest(best1)
602 s.findBestMatchWalkPath(q, key, slashCountKey, best1)
603 if best1.w.w1 <= 0 {
604 return nil
605 }
606 m := best1.templ
607 if m.noBaseOf {
608 return m
609 }
610 best1.reset()
611 m.findBestMatchBaseof(s, q.Desc, q.Sites, key, slashCountKey, best1)
612 if best1.w.w1 <= 0 {
613 return nil
614 }
615
616 return best1.templ
617 }
618
619 func (s *TemplateStore) LookupPartial(pth string) *TemplInfo {
620 ti, _ := s.cacheLookupPartials.GetOrCreate(pth, func() (*TemplInfo, error) {
621 pi := s.opts.PathParser.Parse(files.ComponentFolderLayouts, pth).ForType(paths.TypePartial)
622 k1, _, _, desc, matrix, err := s.toKeyCategoryAndDescriptor(pi, nil)
623 if err != nil {
624 return nil, err
625 }
626 if desc.OutputFormat == "" && desc.MediaType == "" {
627 // Assume HTML.
628 desc.OutputFormat = s.htmlFormat.Name
629 desc.MediaType = s.htmlFormat.MediaType.Type
630 desc.IsPlainText = s.htmlFormat.IsPlainText
631 }
632
633 best := s.getBest()
634 defer s.putBest(best)
635 s.findBestMatchGet(s.key(path.Join(containerPartials, k1)), CategoryPartial, nil, desc, matrix, best)
636 return best.templ, nil
637 })
638
639 return ti
640 }
641
642 // ResolvePartialName resolves partial names starting with "./" or "../"
643 // relative to the directory of the calling partial.
644 func (s *TemplateStore) ResolvePartialName(ctx context.Context, name string) (string, error) {
645 if !strings.HasPrefix(name, "./") && !strings.HasPrefix(name, "../") {
646 return name, nil
647 }
648 cur := tpl.Context.CurrentTemplate.Get(ctx)
649 if cur == nil {
650 return "", fmt.Errorf("relative partial path %q can only be used from within a partial", name)
651 }
652 ti := cur.CurrentTemplateInfoOps.(*TemplInfo)
653 for ti.decoratorOwner != nil {
654 ti = ti.decoratorOwner
655 }
656 if ti.category != CategoryPartial {
657 return "", fmt.Errorf("relative partial path %q can only be used from within a partial, called from %q", name, ti.Name())
658 }
659 dir := strings.TrimPrefix(strings.TrimPrefix(ti.PathInfo.Dir(), "/"+containerPartials), "/")
660 resolved := path.Join(dir, name)
661 if resolved == ".." || strings.HasPrefix(resolved, "../") {
662 return "", fmt.Errorf("relative partial path %q in %q resolves outside the partials directory", name, ti.Name())
663 }
664 return resolved, nil
665 }
666
667 func (s *TemplateStore) LookupShortcodeByName(name string) *TemplInfo {
668 name = strings.ToLower(name)
669 ti, _ := s.shortcodesByName.Get(name)
670 if ti == nil {
671 return nil
672 }
673 return ti
674 }
675
676 func (s *TemplateStore) LookupShortcode(q TemplateQuery) (*TemplInfo, error) {
677 q.init()
678 k1 := s.key(q.Path)
679
680 slashCountK1 := strings.Count(k1, "/")
681
682 best := s.getBest()
683 defer s.putBest(best)
684
685 s.treeShortcodes.WalkPath(k1, func(k2 string, m map[string]map[TemplateDescriptor]*TemplInfo) (bool, error) {
686 if !s.inPath(k1, k2) {
687 return false, nil
688 }
689 slashCountK2 := strings.Count(k2, "/")
690 distance := slashCountK1 - slashCountK2
691
692 v, found := m[q.Name]
693 if !found {
694 return false, nil
695 }
696
697 for k, vv := range v {
698 best.candidates = append(best.candidates, vv)
699 if !q.Consider(vv) {
700 continue
701 }
702
703 weight := s.dh.compareDescriptors(q.Category, q.Desc, k, q.Sites, vv.matrix)
704 weight.distance = distance
705 isBetter := best.isBetter(weight, vv)
706 if isBetter {
707 best.updateValues(weight, k2, k, vv)
708 }
709 }
710
711 return false, nil
712 })
713
714 if best.w.w1 <= 0 {
715 var err error
716 if s := best.candidatesAsStringSlice(); s != nil {
717 msg := fmt.Sprintf("no compatible template found for shortcode %q in %s", q.Name, s)
718 if !q.Desc.IsPlainText {
719 msg += "; note that to use plain text template shortcodes in HTML you need to use the shortcode {{% delimiter"
720 }
721 err = errors.New(msg)
722 } else {
723 err = fmt.Errorf("no template found for shortcode %q", q.Name)
724 }
725 return nil, err
726 }
727
728 return best.templ, nil
729 }
730
731 // PrintDebug is for testing/debugging only.
732 func (s *TemplateStore) PrintDebug(prefix string, category Category, w io.Writer) {
733 if w == nil {
734 w = os.Stdout
735 }
736
737 printOne := func(key string, vv *TemplInfo) {
738 level := strings.Count(key, "/")
739 if category != vv.category {
740 return
741 }
742 s := strings.ReplaceAll(strings.TrimSpace(vv.content), "\n", " ")
743 ts := fmt.Sprintf("kind: %q layout: %q content: %.30s", vv.D.Kind, vv.D.LayoutFromTemplate, s)
744 fmt.Fprintf(w, "%s%s %s\n", strings.Repeat(" ", level), key, ts)
745 }
746 s.treeMain.WalkPrefix(prefix, func(key string, v map[nodeKey]*TemplInfo) (bool, error) {
747 for _, vv := range v {
748 printOne(key, vv)
749 }
750 return false, nil
751 })
752 s.treeShortcodes.WalkPrefix(prefix, func(key string, v map[string]map[TemplateDescriptor]*TemplInfo) (bool, error) {
753 for _, vv := range v {
754 for _, vv2 := range vv {
755 printOne(key, vv2)
756 }
757 }
758 return false, nil
759 })
760 }
761
762 func (s *TemplateStore) clearCaches() {
763 s.cacheLookupPartials.Reset()
764 }
765
766 // RefreshFiles refreshes this store for the files matching the given predicate.
767 func (s *TemplateStore) RefreshFiles(include func(fi hugofs.FileMetaInfo) bool) error {
768 s.clearCaches()
769
770 if err := s.tns.createPrototypesParse(); err != nil {
771 return err
772 }
773 if err := s.insertTemplates(include, true); err != nil {
774 return err
775 }
776 if err := s.createTemplatesSnapshot(); err != nil {
777 return err
778 }
779 if err := s.parseTemplates(); err != nil {
780 return err
781 }
782 if err := s.extractInlinePartials(true); err != nil {
783 return err
784 }
785
786 if err := s.transformTemplates(); err != nil {
787 return err
788 }
789 if err := s.tns.createPrototypes(false); err != nil {
790 return err
791 }
792 if err := s.prepareTemplates(); err != nil {
793 return err
794 }
795 return nil
796 }
797
798 func (s *TemplateStore) HasTemplate(templatePath string) bool {
799 templatePath = strings.ToLower(templatePath)
800 templatePath = paths.AddLeadingSlash(templatePath)
801 return s.templatesByPath.Contains(templatePath)
802 }
803
804 func (t *TemplateStore) TextLookup(name string) *TemplInfo {
805 templ := t.tns.standaloneText.Lookup(name)
806 if templ == nil {
807 return nil
808 }
809 return &TemplInfo{
810 Template: templ,
811 }
812 }
813
814 func (t *TemplateStore) TextParse(name, tpl string) (*TemplInfo, error) {
815 templ, err := t.tns.standaloneText.New(name).Parse(tpl)
816 if err != nil {
817 return nil, err
818 }
819 return &TemplInfo{
820 Template: templ,
821 }, nil
822 }
823
824 func (t *TemplateStore) UnusedTemplates() []*TemplInfo {
825 var unused []*TemplInfo
826
827 for vv := range t.templates() {
828 if vv.subCategory != SubCategoryMain || vv.isLegacyMapped {
829 // Skip inline partials and internal templates.
830 continue
831 }
832 if vv.executionCounter.Load() == 0 {
833 unused = append(unused, vv)
834 }
835 }
836
837 sort.Sort(byPath(unused))
838 return unused
839 }
840
841 // WithSiteOpts creates a new store with the given site options.
842 // This is used to create per site template store, all sharing the same templates,
843 // but with a different template function execution context.
844 func (s TemplateStore) WithSiteOpts(opts SiteOptions) *TemplateStore {
845 s.siteOpts = opts
846 s.storeSite = configureSiteStorage(opts, s.opts.Watching)
847 return &s
848 }
849
850 // GetTemplateFuncsNamespace returns the given template funcs namespace.
851 // Used in tests only.
852 func (s *TemplateStore) GetTemplateFuncsNamespace(ns string) any {
853 v, err := s.storeSite.opts.TemplateFuncs[ns].(func(cctx context.Context, args ...any) (any, error))(context.Background())
854 if err != nil {
855 panic(fmt.Sprintf("template func namespace %q not found: %s", ns, err))
856 }
857 return v
858 }
859
860 func (s *TemplateStore) findBestMatchGet(key string, category Category,
861 consider func(candidate *TemplInfo) bool, d1 TemplateDescriptor, dims1 sitesmatrix.VectorProvider, best *bestMatch,
862 ) {
863 key = strings.ToLower(key)
864
865 v := s.treeMain.Get(key)
866 if v == nil {
867 return
868 }
869
870 for k, vv := range v {
871 if vv.category != category {
872 continue
873 }
874
875 if consider != nil && !consider(vv) {
876 continue
877 }
878
879 weight := s.dh.compareDescriptors(category, d1, k.d, dims1, vv.matrix)
880
881 if best.isBetter(weight, vv) {
882 best.updateValues(weight, key, k.d, vv)
883 }
884 }
885 }
886
887 func (s *TemplateStore) inPath(k1, k2 string) bool {
888 if k1 != k2 && !strings.HasPrefix(k1, k2+"/") {
889 return false
890 }
891 return true
892 }
893
894 func (s *TemplateStore) findBestMatchWalkPath(q TemplateQuery, k1 string, slashCountK1 int, best *bestMatch) {
895 if q.SubPath != "" {
896 // Match templates in <dir><SubPath> only, for every ancestor dir of k1.
897 // Walk from the root down (as WalkPath does) so the nearest match wins
898 // on equal-weight ties.
899 for i, distance := 0, slashCountK1; ; distance-- {
900 k2 := k1[:i] + q.SubPath
901 if v := s.treeMain.Get(k2); v != nil {
902 s.findBestMatchIn(q, k2, distance, v, best)
903 }
904 if i == len(k1) {
905 break
906 }
907 if j := strings.IndexByte(k1[i+1:], '/'); j >= 0 {
908 i += j + 1
909 } else {
910 i = len(k1)
911 }
912 }
913 return
914 }
915
916 s.treeMain.WalkPath(k1, func(k2 string, v map[nodeKey]*TemplInfo) (bool, error) {
917 if !s.inPath(k1, k2) {
918 return false, nil
919 }
920 s.findBestMatchIn(q, k2, slashCountK1-strings.Count(k2, "/"), v, best)
921 return false, nil
922 })
923 }
924
925 func (s *TemplateStore) findBestMatchIn(q TemplateQuery, k2 string, distance int, v map[nodeKey]*TemplInfo, best *bestMatch) {
926 for k, vv := range v {
927 if vv.category != q.Category {
928 continue
929 }
930
931 if !q.Consider(vv) {
932 continue
933 }
934
935 weight := s.dh.compareDescriptors(q.Category, q.Desc, k.d, q.Sites, vv.matrix)
936 weight.distance = distance
937
938 if best.isBetter(weight, vv) {
939 best.updateValues(weight, k2, k.d, vv)
940 }
941 }
942 }
943
944 func (t *TemplateStore) addDeferredTemplate(owner *TemplInfo, name string, n *parse.ListNode) error {
945 if _, found := t.templatesByPath.Get(name); found {
946 return nil
947 }
948
949 var templ tpl.Template
950
951 if owner.D.IsPlainText {
952 prototype := t.tns.parseText
953 tt, err := prototype.New(name).Parse("")
954 if err != nil {
955 return fmt.Errorf("failed to parse empty text template %q: %w", name, err)
956 }
957 tt.Tree.Root = n
958 templ = tt
959 } else {
960 prototype := t.tns.parseHTML
961 tt, err := prototype.New(name).Parse("")
962 if err != nil {
963 return fmt.Errorf("failed to parse empty HTML template %q: %w", name, err)
964 }
965 tt.Tree.Root = n
966 templ = tt
967 }
968
969 t.templatesByPath.Set(name, &TemplInfo{
970 Fi: owner.Fi,
971 PathInfo: owner.PathInfo,
972 D: owner.D,
973 Template: templ,
974 category: owner.category,
975 decoratorOwner: owner.decoratorOwner,
976 })
977
978 return nil
979 }
980
981 func (s *TemplateStore) addFileContext(ti *TemplInfo, what string, inerr error) error {
982 if ti.Fi == nil {
983 return inerr
984 }
985
986 identifiers := s.extractIdentifiers(inerr.Error())
987
988 checkFilename := func(fi hugofs.FileMetaInfo, inErr error) (int, error) {
989 var matchWeight int
990 lineMatcher := func(m herrors.LineMatcher) int {
991 if m.Position.LineNumber != m.LineNumber {
992 return -1
993 }
994
995 matchWeight++
996 for _, id := range identifiers {
997 if strings.Contains(m.Line, id) {
998 // We found the line, but return a 0 to signal to
999 // use the column from the error message.
1000 matchWeight++
1001 return 0
1002 }
1003 }
1004 return 0
1005 }
1006
1007 f, err := fi.Meta().Open()
1008 if err != nil {
1009 return -1, inErr
1010 }
1011 defer f.Close()
1012
1013 fe := herrors.NewFileErrorFromName(inErr, fi.Meta().Filename)
1014 fe.UpdateContent(f, lineMatcher)
1015
1016 return matchWeight, fe
1017 }
1018
1019 inerr = fmt.Errorf("%s: %w", what, inerr)
1020
1021 var (
1022 err1 error
1023 weight1 int
1024 err2 error
1025 weight2 int
1026 )
1027
1028 weight1, err1 = checkFilename(ti.Fi, inerr)
1029
1030 if ti.base != nil {
1031 weight2, err2 = checkFilename(ti.base.Fi, inerr)
1032 }
1033
1034 if err2 != nil && weight2 > weight1 {
1035 return err2
1036 }
1037
1038 return err1
1039 }
1040
1041 func (s *TemplateStore) extractIdentifiers(line string) []string {
1042 m := identifiersRe.FindAllStringSubmatch(line, -1)
1043 identifiers := make([]string, len(m))
1044 for i := range m {
1045 identifiers[i] = m[i][1]
1046 }
1047 return identifiers
1048 }
1049
1050 func (s *TemplateStore) extractInlinePartials(rebuild bool) error {
1051 isPartialName := func(s string) bool {
1052 return strings.HasPrefix(s, "partials/") || strings.HasPrefix(s, "_partials/")
1053 }
1054
1055 // We may find both inline and external partials in the current template namespaces,
1056 // so only add the ones we have not seen before.
1057 for templ := range s.allRawTemplates() {
1058 if templ.Name() == "" || !isPartialName(templ.Name()) {
1059 continue
1060 }
1061 if rebuild && s.templatesSnapshotSet.Contains(getParseTree(templ)) {
1062 // This partial was not created during this build.
1063 continue
1064 }
1065 name := templ.Name()
1066 if !paths.HasExt(name) {
1067 // Assume HTML. This in line with how the lookup works.
1068 name = name + s.htmlFormat.MediaType.FirstSuffix.FullSuffix
1069 }
1070 if !strings.HasPrefix(name, "_") {
1071 name = "_" + name
1072 }
1073 pi := s.opts.PathParser.Parse(files.ComponentFolderLayouts, name)
1074 ti, err := s.insertTemplate(pi, nil, SubCategoryInline, false, s.treeMain)
1075 if err != nil {
1076 return err
1077 }
1078
1079 if ti != nil {
1080 ti.Template = templ
1081 ti.noBaseOf = true
1082 ti.subCategory = SubCategoryInline
1083 ti.D.IsPlainText = isText(templ)
1084 }
1085 }
1086
1087 return nil
1088 }
1089
1090 func (s *TemplateStore) allRawTemplates() iter.Seq[tpl.Template] {
1091 p := s.tns
1092 return func(yield func(tpl.Template) bool) {
1093 for t := range p.templatesIn(p.parseHTML) {
1094 if !yield(t) {
1095 return
1096 }
1097 }
1098 for t := range p.templatesIn(p.parseText) {
1099 if !yield(t) {
1100 return
1101 }
1102 }
1103
1104 for _, tt := range p.baseofHtmlClones {
1105 for t := range p.templatesIn(tt) {
1106 if !yield(t) {
1107 return
1108 }
1109 }
1110 }
1111 for _, tt := range p.baseofTextClones {
1112 for t := range p.templatesIn(tt) {
1113 if !yield(t) {
1114 return
1115 }
1116 }
1117 }
1118 }
1119 }
1120
1121 func (s *TemplateStore) insertEmbedded() error {
1122 return fs.WalkDir(embeddedTemplatesFs, ".", func(tpath string, d fs.DirEntry, err error) error {
1123 if err != nil {
1124 return err
1125 }
1126 if d == nil || d.IsDir() || strings.HasPrefix(d.Name(), ".") {
1127 return nil
1128 }
1129
1130 templb, err := embeddedTemplatesFs.ReadFile(tpath)
1131 if err != nil {
1132 return err
1133 }
1134
1135 // Get the newlines on Windows in line with how we had it back when we used Go Generate
1136 // to write the templates to Go files.
1137 templ := string(bytes.ReplaceAll(templb, []byte("\r\n"), []byte("\n")))
1138 name := strings.TrimPrefix(filepath.ToSlash(tpath), "embedded/templates/")
1139
1140 insertOne := func(name, content string) error {
1141 pi := s.opts.PathParser.Parse(files.ComponentFolderLayouts, name)
1142 var (
1143 ti *TemplInfo
1144 err error
1145 )
1146 if pi.Section() == containerShortcodes {
1147 ti, err = s.insertShortcode(pi, nil, false, s.treeShortcodes)
1148 if err != nil {
1149 return err
1150 }
1151 } else {
1152 ti, err = s.insertTemplate(pi, nil, SubCategoryEmbedded, false, s.treeMain)
1153 if err != nil {
1154 return err
1155 }
1156 }
1157
1158 if ti != nil {
1159 // Currently none of the embedded templates need a baseof template.
1160 ti.noBaseOf = true
1161 ti.content = content
1162 ti.subCategory = SubCategoryEmbedded
1163 }
1164
1165 return nil
1166 }
1167
1168 // Copy the embedded HTML table render hook to each output format.
1169 // See https://github.com/gohugoio/hugo/issues/13351.
1170 if name == path.Join(containerMarkup, "render-table.html") {
1171 for _, of := range s.opts.OutputFormats {
1172 path := paths.TrimExt(name) + "." + of.Name + of.MediaType.FirstSuffix.FullSuffix
1173 if err := insertOne(path, templ); err != nil {
1174 return err
1175 }
1176 }
1177
1178 return nil
1179 }
1180
1181 if err := insertOne(name, templ); err != nil {
1182 return err
1183 }
1184
1185 if aliases, found := embeddedTemplatesAliases[name]; found {
1186 for _, alias := range aliases {
1187 if err := insertOne(alias, templ); err != nil {
1188 return err
1189 }
1190 }
1191 }
1192
1193 return nil
1194 })
1195 }
1196
1197 func (s *TemplateStore) setTemplateByPath(p string, ti *TemplInfo) {
1198 s.templatesByPath.Set(p, ti)
1199 }
1200
1201 func (s *TemplateStore) insertShortcode(pi *paths.Path, fi hugofs.FileMetaInfo, replace bool, tree doctree.Tree[map[string]map[TemplateDescriptor]*TemplInfo]) (*TemplInfo, error) {
1202 k1, k2, _, d, matrix, err := s.toKeyCategoryAndDescriptor(pi, fi)
1203 if err != nil {
1204 return nil, err
1205 }
1206
1207 m := tree.Get(k1)
1208 if m == nil {
1209 m = make(map[string]map[TemplateDescriptor]*TemplInfo)
1210 tree.Insert(k1, m)
1211 }
1212
1213 m1, found := m[k2]
1214 if found {
1215 if _, found := m1[d]; found {
1216 if !replace {
1217 return nil, nil
1218 }
1219 }
1220 } else {
1221 m1 = make(map[TemplateDescriptor]*TemplInfo)
1222 m[k2] = m1
1223 }
1224
1225 ti := &TemplInfo{
1226 PathInfo: pi,
1227 Fi: fi,
1228 D: d,
1229 matrix: matrix,
1230 category: CategoryShortcode,
1231 noBaseOf: true,
1232 }
1233
1234 m1[d] = ti
1235
1236 s.shortcodesByName.Set(k2, ti)
1237 s.setTemplateByPath(pi.Path(), ti)
1238
1239 if fi != nil {
1240 if pi2 := fi.Meta().PathInfo; pi2 != pi {
1241 s.setTemplateByPath(pi2.Path(), ti)
1242 }
1243 }
1244
1245 return ti, nil
1246 }
1247
1248 func (s *TemplateStore) insertTemplate(pi *paths.Path, fi hugofs.FileMetaInfo, subCategory SubCategory, replace bool, tree doctree.Tree[map[nodeKey]*TemplInfo]) (*TemplInfo, error) {
1249 key, _, category, d, matrix, err := s.toKeyCategoryAndDescriptor(pi, fi)
1250 // See #13577. Warn for now.
1251 if err != nil {
1252 var loc string
1253 if fi != nil {
1254 loc = fmt.Sprintf("file %q", fi.Meta().Filename)
1255 } else {
1256 loc = fmt.Sprintf("path %q", pi.Path())
1257 }
1258 s.opts.Log.Warnf("skipping template %s: %s", loc, err)
1259 return nil, nil
1260 }
1261
1262 return s.insertTemplate2(pi, fi, key, category, subCategory, d, matrix, replace, false, tree)
1263 }
1264
1265 func (s *TemplateStore) insertTemplate2(
1266 pi *paths.Path,
1267 fi hugofs.FileMetaInfo,
1268 key string,
1269 category Category,
1270 subCategory SubCategory,
1271 d TemplateDescriptor,
1272 matrix sitesmatrix.VectorStore,
1273 replace, isLegacyMapped bool,
1274 tree doctree.Tree[map[nodeKey]*TemplInfo],
1275 ) (*TemplInfo, error) {
1276 if category == 0 {
1277 panic("category not set")
1278 }
1279
1280 if category == CategoryPartial && d.OutputFormat == "" && d.MediaType == "" {
1281 // See issue #13601.
1282 d.OutputFormat = s.htmlFormat.Name
1283 d.MediaType = s.htmlFormat.MediaType.Type
1284 }
1285
1286 m := tree.Get(key)
1287 nk := nodeKey{c: category, d: d}
1288
1289 if m == nil {
1290 m = make(map[nodeKey]*TemplInfo)
1291 tree.Insert(key, m)
1292 }
1293
1294 var (
1295 nkExisting *TemplInfo
1296 existingFound bool
1297 )
1298
1299 if d.SitesHash == 0 {
1300 // inline partials.
1301 for k, v := range m {
1302 d2 := v.D
1303 d2.SitesHash = 0
1304 if d == d2 {
1305 nkExisting = v
1306 nk = k
1307 existingFound = true
1308 break
1309 }
1310 }
1311 } else {
1312 nkExisting, existingFound = m[nk]
1313 }
1314
1315 if !replace && existingFound && fi != nil && nkExisting.Fi != nil {
1316 // See issue #13715.
1317 // We do the merge on the file system level, but from Hugo v0.146.0 we have a situation where
1318 // the project may well have a different layouts layout compared to the theme(s) it uses.
1319 // We could possibly have fixed that on a lower (file system) level, but since this is just
1320 // a temporary situation (until all projects are updated),
1321 // do a replace here if the file comes from higher up in the module chain.
1322 replace = fi.Meta().ModuleOrdinal < nkExisting.Fi.Meta().ModuleOrdinal
1323 }
1324
1325 if !replace && existingFound {
1326 // Always replace inline partials to allow for reloading.
1327 replace = subCategory == SubCategoryInline && nkExisting.subCategory == SubCategoryInline
1328 }
1329
1330 if !replace && existingFound {
1331 if len(pi.Identifiers()) >= len(nkExisting.PathInfo.Identifiers()) {
1332 if d.MediaType != "" && pi.Ext() != nkExisting.PathInfo.Ext() {
1333 // Issue #13877: when multiple templates differ only in their file extension
1334 // and both extensions are valid suffixes for the same media type,
1335 // prefer the one whose extension matches an earlier suffix.
1336 if mt, ok := s.opts.MediaTypes.GetByType(d.MediaType); ok {
1337 suffixes := mt.Suffixes()
1338 newIdx := slices.Index(suffixes, pi.Ext())
1339 if newIdx != -1 {
1340 existingIdx := slices.Index(suffixes, nkExisting.PathInfo.Ext())
1341 if existingIdx == -1 || newIdx < existingIdx {
1342 replace = true
1343 }
1344 }
1345 }
1346 }
1347 if !replace {
1348 // e.g. /pages/home.foo.html and /pages/home.html where foo may be a valid language name in another site.
1349 return nil, nil
1350 }
1351 }
1352 }
1353
1354 ti := &TemplInfo{
1355 PathInfo: pi,
1356 Fi: fi,
1357 D: d,
1358 matrix: matrix,
1359 category: category,
1360 subCategory: subCategory,
1361 noBaseOf: category > CategoryLayout,
1362 isLegacyMapped: isLegacyMapped,
1363 }
1364
1365 m[nk] = ti
1366
1367 if !isLegacyMapped {
1368 s.setTemplateByPath(pi.Path(), ti)
1369 if fi != nil {
1370 if pi2 := fi.Meta().PathInfo; pi2 != pi {
1371 s.setTemplateByPath(pi2.Path(), ti)
1372 }
1373 }
1374 }
1375
1376 return ti, nil
1377 }
1378
1379 func (s *TemplateStore) insertTemplates(include func(fi hugofs.FileMetaInfo) bool, partialRebuild bool) error {
1380 if include == nil {
1381 include = func(fi hugofs.FileMetaInfo) bool {
1382 return true
1383 }
1384 }
1385
1386 // Set if we need to reset the base variants.
1387 var (
1388 resetBaseVariants bool
1389 )
1390
1391 legacyOrdinalMappings := map[legacyTargetPathIdentifiers]legacyOrdinalMappingFi{}
1392
1393 walker := func(ctx context.Context, pth string, fi hugofs.FileMetaInfo) error {
1394 if fi.IsDir() {
1395 return nil
1396 }
1397
1398 if isDotFile(pth) || isBackupFile(pth) {
1399 return nil
1400 }
1401
1402 if !include(fi) {
1403 return nil
1404 }
1405
1406 piOrig := fi.Meta().PathInfo
1407
1408 // Convert any legacy value to new format.
1409 fromLegacyPath := func(pi *paths.Path) *paths.Path {
1410 p := pi.Path()
1411 p = strings.TrimPrefix(p, "/_default")
1412 if strings.HasPrefix(p, "/shortcodes") || strings.HasPrefix(p, "/partials") {
1413 // Insert an underscore so it becomes /_shortcodes or /_partials.
1414 p = "/_" + p[1:]
1415 }
1416
1417 if strings.Contains(p, "-"+baseNameBaseof) {
1418 // Before Hugo 0.146.0 we prepended one identifier (layout, type or kind) in front of the baseof keyword,
1419 // and then separated with a hyphen before the baseof keyword.
1420 // This identifier needs to be moved right after the baseof keyword and the hyphen removed, e.g.
1421 // /docs/list-baseof.html => /docs/baseof.list.html.
1422 dir, name := path.Split(p)
1423 hyphenIdx := strings.Index(name, "-")
1424 if hyphenIdx > 0 {
1425 id := name[:hyphenIdx]
1426 name = name[hyphenIdx+1+len(baseNameBaseof):]
1427 if !strings.HasPrefix(name, ".") {
1428 name = "." + name
1429 }
1430 p = path.Join(dir, baseNameBaseof+"."+id+name)
1431 }
1432 }
1433 if p == pi.Path() {
1434 return pi
1435 }
1436 return s.opts.PathParser.Parse(files.ComponentFolderLayouts, p)
1437 }
1438
1439 pi := piOrig
1440 var applyLegacyMapping bool
1441 switch pi.Section() {
1442 case containerPartials, containerShortcodes, containerMarkup:
1443 // OK.
1444 default:
1445 pi = fromLegacyPath(pi)
1446 applyLegacyMapping = strings.Count(pi.Path(), "/") <= 2
1447 }
1448
1449 if applyLegacyMapping {
1450 handleMapping := func(m1 legacyOrdinalMapping) {
1451 key := legacyTargetPathIdentifiers{
1452 targetPath: m1.mapping.targetPath,
1453 targetCategory: m1.mapping.targetCategory,
1454 kind: m1.mapping.targetDesc.Kind,
1455 ext: pi.Ext(),
1456 outputFormat: pi.OutputFormat(),
1457 }
1458
1459 if m2, ok := legacyOrdinalMappings[key]; ok {
1460 if m1.ordinal < m2.m.ordinal {
1461 // Higher up == better match.
1462 legacyOrdinalMappings[key] = legacyOrdinalMappingFi{m1, fi}
1463 }
1464 } else {
1465 legacyOrdinalMappings[key] = legacyOrdinalMappingFi{m1, fi}
1466 }
1467 }
1468
1469 if m1, ok := s.opts.legacyMappingTaxonomy[piOrig.PathBeforeLangAndOutputFormatAndExt()]; ok {
1470 handleMapping(m1)
1471 }
1472
1473 if m1, ok := s.opts.legacyMappingTerm[piOrig.PathBeforeLangAndOutputFormatAndExt()]; ok {
1474 handleMapping(m1)
1475 }
1476
1477 const (
1478 sectionKindToken = "SECTIONKIND"
1479 sectionToken = "THESECTION"
1480 )
1481
1482 base := piOrig.PathBeforeLangAndOutputFormatAndExt()
1483 identifiers := []string{}
1484 if pi.Layout() != "" {
1485 identifiers = append(identifiers, pi.Layout())
1486 }
1487 if pi.Kind() != "" {
1488 identifiers = append(identifiers, pi.Kind())
1489 }
1490
1491 shouldIncludeSection := func(section string) bool {
1492 switch section {
1493 case containerShortcodes, containerPartials, containerMarkup:
1494 return false
1495 case "taxonomy", "":
1496 return false
1497 default:
1498 for k, v := range s.opts.TaxonomySingularPlural {
1499 if k == section || v == section {
1500 return false
1501 }
1502 }
1503 return true
1504 }
1505 }
1506 if shouldIncludeSection(pi.Section()) {
1507 identifiers = append(identifiers, pi.Section())
1508 }
1509
1510 identifiers = hstrings.UniqueStrings(identifiers)
1511
1512 // Tokens on e.g. form /SECTIONKIND/THESECTION
1513 insertSectionTokens := func(section string) []string {
1514 kindOnly := isLayoutStandard(section)
1515 var ss []string
1516 s1 := base
1517 if !kindOnly {
1518 s1 = strings.ReplaceAll(s1, section, sectionToken)
1519 }
1520 s1 = strings.ReplaceAll(s1, kinds.KindSection, sectionKindToken)
1521 if s1 != base {
1522 ss = append(ss, s1)
1523 }
1524 s1 = strings.ReplaceAll(base, kinds.KindSection, sectionKindToken)
1525 if !kindOnly {
1526 s1 = strings.ReplaceAll(s1, section, sectionToken)
1527 }
1528 if s1 != base {
1529 ss = append(ss, s1)
1530 }
1531
1532 hstrings.UniqueStringsReuse(ss)
1533
1534 return ss
1535 }
1536
1537 for _, id := range identifiers {
1538 if id == "" {
1539 continue
1540 }
1541
1542 p := insertSectionTokens(id)
1543 for _, ss := range p {
1544 if m1, ok := s.opts.legacyMappingSection[ss]; ok {
1545 targetPath := m1.mapping.targetPath
1546
1547 if targetPath != "" {
1548 targetPath = strings.ReplaceAll(targetPath, sectionToken, id)
1549 targetPath = strings.ReplaceAll(targetPath, sectionKindToken, id)
1550 targetPath = strings.ReplaceAll(targetPath, "//", "/")
1551 }
1552 m1.mapping.targetPath = targetPath
1553 handleMapping(m1)
1554 }
1555 }
1556 }
1557
1558 }
1559
1560 if partialRebuild && pi.NameNoIdentifier() == baseNameBaseof {
1561 // A baseof file has changed.
1562 resetBaseVariants = true
1563 }
1564
1565 var ti *TemplInfo
1566 var err error
1567 var insertFunc func() (*TemplInfo, error)
1568
1569 insertFunc = func() (*TemplInfo, error) {
1570 return s.insertTemplate(pi, fi, SubCategoryMain, partialRebuild, s.treeMain)
1571 }
1572
1573 switch pi.Type() {
1574 case paths.TypeShortcode:
1575 insertFunc = func() (*TemplInfo, error) {
1576 return s.insertShortcode(pi, fi, partialRebuild, s.treeShortcodes)
1577 }
1578 case paths.TypeMarkup:
1579 skipImageRenderHook := pi.Name() == "render-image.html" && s.opts.RenderHooks.Image.UseEmbedded == "always"
1580 skipLinkRenderHook := pi.Name() == "render-link.html" && s.opts.RenderHooks.Link.UseEmbedded == "always"
1581 if skipImageRenderHook || skipLinkRenderHook {
1582 insertFunc = nil
1583 }
1584 }
1585
1586 if insertFunc != nil {
1587 ti, err = insertFunc()
1588 if err != nil || ti == nil {
1589 return err
1590 }
1591 }
1592
1593 if ti != nil {
1594 if err := s.tns.readTemplateInto(ti); err != nil {
1595 return err
1596 }
1597 }
1598
1599 return nil
1600 }
1601
1602 if err := helpers.Walk(s.opts.Fs, "", walker); err != nil {
1603 if !herrors.IsNotExist(err) {
1604 return err
1605 }
1606 return nil
1607 }
1608
1609 for k, v := range legacyOrdinalMappings {
1610 targetPath := k.targetPath
1611 m := v.m.mapping
1612 fi := v.fi
1613 pi := fi.Meta().PathInfo
1614 outputFormat, mediaType := s.resolveOutputFormatAndOrMediaType(k.outputFormat, k.ext)
1615 category := m.targetCategory
1616 desc := m.targetDesc
1617 desc.Kind = k.kind
1618 desc.OutputFormat = outputFormat.Name
1619 desc.IsPlainText = outputFormat.IsPlainText
1620 desc.MediaType = mediaType.Type
1621 desc.SitesHash = fi.Meta().SitesMatrix.MustHash()
1622
1623 ti, err := s.insertTemplate2(pi, fi, targetPath, category, SubCategoryMain, desc, fi.Meta().SitesMatrix, true, true, s.treeMain)
1624 if err != nil {
1625 return err
1626 }
1627 if ti == nil {
1628 continue
1629 }
1630 ti.isLegacyMapped = true
1631 if err := s.tns.readTemplateInto(ti); err != nil {
1632 return err
1633 }
1634
1635 }
1636
1637 if resetBaseVariants {
1638 s.tns.baseofHtmlClones = nil
1639 s.tns.baseofTextClones = nil
1640 s.treeMain.Walk(func(key string, v map[nodeKey]*TemplInfo) (bool, error) {
1641 for _, vv := range v {
1642 if !vv.noBaseOf {
1643 vv.state = processingStateInitial
1644 }
1645 }
1646 return false, nil
1647 })
1648 }
1649
1650 return nil
1651 }
1652
1653 func (s *TemplateStore) key(dir string) string {
1654 dir = paths.AddLeadingSlash(dir)
1655 if dir == "/" {
1656 return ""
1657 }
1658 return paths.TrimTrailing(dir)
1659 }
1660
1661 func (s *TemplateStore) createTemplatesSnapshot() error {
1662 s.templatesSnapshotSet.Reset()
1663 for t := range s.allRawTemplates() {
1664 s.templatesSnapshotSet.Set(getParseTree(t), struct{}{})
1665 }
1666 return nil
1667 }
1668
1669 func (s *TemplateStore) addTransformedTemplateInsert(name string, subCategory SubCategory) (*TemplInfo, error) {
1670 pi := s.opts.PathParser.Parse(files.ComponentFolderLayouts, name)
1671 ti, err := s.insertTemplate(pi, nil, subCategory, true, s.treeMain)
1672 if err != nil {
1673 return nil, err
1674 }
1675 return ti, nil
1676 }
1677
1678 func (s *TemplateStore) addTransformedTemplateSetTree(this *TemplInfo, root *parse.ListNode) (*parse.Tree, error) {
1679 templ := s.tns.newBlankTemplate(this)
1680 tree := getParseTree(templ)
1681 tree.Root = root
1682 this.Template = templ
1683 this.state = processingStateTransformed
1684 return tree, nil
1685 }
1686
1687 func (s *TemplateStore) parseTemplates() error {
1688 if err := func() error {
1689 // Read and parse all templates.
1690 for _, v := range s.treeMain.All() {
1691 for _, vv := range v {
1692 if vv.state == processingStateTransformed {
1693 continue
1694 }
1695 if err := s.parseTemplate(vv); err != nil {
1696 return err
1697 }
1698 }
1699 }
1700
1701 // Lookup and apply base templates where needed.
1702 for key, v := range s.treeMain.All() {
1703 for _, vv := range v {
1704 if vv.state == processingStateTransformed {
1705 continue
1706 }
1707 if !vv.noBaseOf {
1708 d := vv.D
1709 // Find all compatible base templates.
1710 baseTemplates := s.FindAllBaseTemplateCandidates(key, d, vv.matrix)
1711 if len(baseTemplates) == 0 {
1712 // The regular expression used to detect if a template needs a base template has some
1713 // rare false positives. Assume we don't need one.
1714 vv.noBaseOf = true
1715 if err := s.parseTemplate(vv); err != nil {
1716 return err
1717 }
1718 continue
1719 }
1720 vv.baseVariants = doctree.NewSimpleTree[map[TemplateDescriptor]*TemplWithBaseApplied]()
1721
1722 for _, base := range baseTemplates {
1723 if err := s.tns.applyBaseTemplate(vv, base); err != nil {
1724 return s.addFileContext(base.Info, "apply base template failed", err)
1725 }
1726 }
1727
1728 }
1729 }
1730 }
1731
1732 return nil
1733 }(); err != nil {
1734 return err
1735 }
1736
1737 // Parse shortcodes.
1738 for _, v := range s.treeShortcodes.All() {
1739 for _, vv := range v {
1740 for _, vvv := range vv {
1741 if vvv.state == processingStateTransformed {
1742 continue
1743 }
1744 if err := s.parseTemplate(vvv); err != nil {
1745 return err
1746 }
1747 }
1748 }
1749 }
1750
1751 return nil
1752 }
1753
1754 // prepareTemplates prepares all templates for execution.
1755 func (s *TemplateStore) prepareTemplates() error {
1756 for t := range s.templates() {
1757 if t.category == CategoryBaseof {
1758 continue
1759 }
1760 if _, err := t.Prepare(); err != nil {
1761 return err
1762 }
1763 }
1764 return nil
1765 }
1766
1767 type PathTemplateDescriptor struct {
1768 Path string
1769 Desc TemplateDescriptor
1770 }
1771
1772 // resolveOutputFormatAndOrMediaType resolves the output format and/or media type
1773 // based on the given output format suffix and media type suffix.
1774 // Either of the suffixes can be empty, and the function will try to find a match
1775 // based on the other suffix. If both are empty, the function will return zero values.
1776 func (s *TemplateStore) resolveOutputFormatAndOrMediaType(ofs, mns string) (output.Format, media.Type) {
1777 var outputFormat output.Format
1778 var mediaType media.Type
1779
1780 if ofs != "" {
1781 if of, found := s.opts.OutputFormats.GetByName(ofs); found {
1782 outputFormat = of
1783 mediaType = of.MediaType
1784 }
1785 }
1786
1787 if mns != "" && mediaType.IsZero() {
1788 if of, found := s.opts.OutputFormats.GetBySuffix(mns); found {
1789 outputFormat = of
1790 mediaType = of.MediaType
1791 } else {
1792 if mt, _, found := s.opts.MediaTypes.GetFirstBySuffix(mns); found {
1793 mediaType = mt
1794 if outputFormat.IsZero() {
1795 // For e.g. index.xml we will in the default confg now have the application/rss+xml media type.
1796 // Try a last time to find the output format using the SubType as the name.
1797 // As to template resolution, this value is currently only used to
1798 // decide if this is a text or HTML template.
1799 outputFormat, _ = s.opts.OutputFormats.GetByName(mt.SubType)
1800 }
1801 }
1802 }
1803 }
1804
1805 return outputFormat, mediaType
1806 }
1807
1808 // templates iterates over all templates in the store.
1809 // Note that for templates with one or more base templates applied,
1810 // we will yield the variants, e.g. the templates that's actually in use.
1811 func (s *TemplateStore) templates() iter.Seq[*TemplInfo] {
1812 return func(yield func(*TemplInfo) bool) {
1813 for _, v := range s.treeMain.All() {
1814 for _, vv := range v {
1815 if !vv.noBaseOf {
1816 for vvv := range vv.BaseVariantsSeq() {
1817 if !yield(vvv.Template) {
1818 return
1819 }
1820 }
1821 } else {
1822 if !yield(vv) {
1823 return
1824 }
1825 }
1826 }
1827 }
1828 for _, v := range s.treeShortcodes.All() {
1829 for _, vv := range v {
1830 for _, vvv := range vv {
1831 if !yield(vvv) {
1832 return
1833 }
1834 }
1835 }
1836 }
1837 }
1838 }
1839
1840 func (s *TemplateStore) toKeyCategoryAndDescriptor(p *paths.Path, fi hugofs.FileMetaInfo) (string, string, Category, TemplateDescriptor, sitesmatrix.VectorStore, error) {
1841 k1 := p.Dir()
1842 k2 := ""
1843
1844 outputFormat, mediaType := s.resolveOutputFormatAndOrMediaType(p.OutputFormat(), p.Ext())
1845 nameNoIdentifier := p.NameNoIdentifier()
1846
1847 var vactorStore sitesmatrix.VectorStore
1848 if fi != nil {
1849 vactorStore = fi.Meta().SitesMatrix
1850 } else {
1851 vactorStore = s.opts.PathParser.SitesMatrixFromPath(p)
1852 }
1853
1854 d := TemplateDescriptor{
1855 SitesHash: vactorStore.MustHash(),
1856 OutputFormat: p.OutputFormat(),
1857 MediaType: mediaType.Type,
1858 Kind: p.Kind(),
1859 LayoutFromTemplate: p.Layout(),
1860 IsPlainText: outputFormat.IsPlainText,
1861 }
1862
1863 d.normalizeFromFile()
1864
1865 section := p.Section()
1866
1867 var category Category
1868 switch p.Type() {
1869 case paths.TypeShortcode:
1870 category = CategoryShortcode
1871 case paths.TypePartial:
1872 category = CategoryPartial
1873 case paths.TypeMarkup:
1874 category = CategoryMarkup
1875 }
1876
1877 if category == 0 {
1878 if nameNoIdentifier == baseNameBaseof {
1879 category = CategoryBaseof
1880 } else {
1881 switch section {
1882 case "_hugo":
1883 category = CategoryHugo
1884 case "_server":
1885 category = CategoryServer
1886 default:
1887 category = CategoryLayout
1888 }
1889 }
1890 }
1891
1892 if category == CategoryPartial {
1893 d.LayoutFromTemplate = ""
1894 k1 = p.PathNoIdentifier()
1895 }
1896
1897 if category == CategoryShortcode {
1898 k1 = p.PathNoIdentifier()
1899
1900 parts := strings.Split(k1, "/"+containerShortcodes+"/")
1901 k1 = parts[0]
1902 if len(parts) > 1 {
1903 k2 = parts[1]
1904 }
1905 k1 = s.key(k1)
1906 }
1907
1908 // Legacy layout for home page.
1909 if d.LayoutFromTemplate == "index" {
1910 if d.Kind == "" {
1911 d.Kind = kinds.KindHome
1912 }
1913 d.LayoutFromTemplate = ""
1914 }
1915
1916 if d.LayoutFromTemplate == d.Kind {
1917 d.LayoutFromTemplate = ""
1918 }
1919
1920 k1 = strings.TrimPrefix(k1, "/_default")
1921 if k1 == "/" {
1922 k1 = ""
1923 }
1924
1925 if category == CategoryMarkup {
1926 // We store all template nodes for a given directory on the same level.
1927 k1 = strings.TrimSuffix(k1, "/_markup")
1928 v, found := strings.CutPrefix(d.LayoutFromTemplate, "render-")
1929 if !found {
1930 return "", "", 0, TemplateDescriptor{}, nil, fmt.Errorf("unrecognized render hook template")
1931 }
1932 hyphenIdx := strings.Index(v, "-")
1933
1934 d.Variant1 = v
1935 if hyphenIdx > 0 {
1936 d.Variant1 = v[:hyphenIdx]
1937 d.Variant2 = v[hyphenIdx+1:]
1938 }
1939
1940 d.LayoutFromTemplate = "" // This allows using page layout as part of the key for lookups.
1941 }
1942
1943 return k1, k2, category, d, vactorStore, nil
1944 }
1945
1946 func (s *TemplateStore) transformTemplates() error {
1947 lookup := func(name string, in *TemplInfo) *TemplInfo {
1948 if in.D.IsPlainText {
1949 templ := in.Template.(*texttemplate.Template).Lookup(name)
1950 if templ != nil {
1951 return &TemplInfo{
1952 Template: templ,
1953 }
1954 }
1955 } else {
1956 templ := in.Template.(*htmltemplate.Template).Lookup(name)
1957 if templ != nil {
1958 return &TemplInfo{
1959 Template: templ,
1960 }
1961 }
1962 }
1963
1964 return nil
1965 }
1966
1967 for vv := range s.templates() {
1968 if vv.state == processingStateTransformed {
1969 continue
1970 }
1971 vv.state = processingStateTransformed
1972 if vv.category == CategoryBaseof {
1973 continue
1974 }
1975 tctx, err := applyTemplateTransformers(vv, s, lookup)
1976 if err != nil {
1977 return err
1978 }
1979 for name, node := range tctx.deferNodes {
1980 if err := s.addDeferredTemplate(vv, name, node); err != nil {
1981 return err
1982 }
1983 }
1984 }
1985
1986 return nil
1987 }
1988
1989 func (s *TemplateStore) init() error {
1990 // Before Hugo 0.146 we had a very elaborate template lookup system, especially for
1991 // terms and taxonomies. This is a way of preserving backwards compatibility
1992 // by mapping old paths into the new tree.
1993 s.opts.legacyMappingTaxonomy = make(map[string]legacyOrdinalMapping)
1994 s.opts.legacyMappingTerm = make(map[string]legacyOrdinalMapping)
1995 s.opts.legacyMappingSection = make(map[string]legacyOrdinalMapping)
1996
1997 // Placeholders.
1998 const singular = "SINGULAR"
1999 const plural = "PLURAL"
2000
2001 replaceTokens := func(s, singularv, pluralv string) string {
2002 s = strings.Replace(s, singular, singularv, -1)
2003 s = strings.Replace(s, plural, pluralv, -1)
2004 return s
2005 }
2006
2007 hasSingularOrPlural := func(s string) bool {
2008 return strings.Contains(s, singular) || strings.Contains(s, plural)
2009 }
2010
2011 expand := func(v layoutLegacyMapping) []layoutLegacyMapping {
2012 var result []layoutLegacyMapping
2013
2014 if hasSingularOrPlural(v.sourcePath) || hasSingularOrPlural(v.target.targetPath) {
2015 for s, p := range s.opts.TaxonomySingularPlural {
2016 target := v.target
2017 target.targetPath = replaceTokens(target.targetPath, s, p)
2018 vv := replaceTokens(v.sourcePath, s, p)
2019 result = append(result, layoutLegacyMapping{sourcePath: vv, target: target})
2020 }
2021 } else {
2022 result = append(result, v)
2023 }
2024 return result
2025 }
2026
2027 expandSections := func(v layoutLegacyMapping) []layoutLegacyMapping {
2028 var result []layoutLegacyMapping
2029 result = append(result, v)
2030 baseofVariant := v
2031 baseofVariant.sourcePath += "-" + baseNameBaseof
2032 baseofVariant.target.targetCategory = CategoryBaseof
2033 result = append(result, baseofVariant)
2034 return result
2035 }
2036
2037 var terms []layoutLegacyMapping
2038 for _, v := range legacyTermMappings {
2039 terms = append(terms, expand(v)...)
2040 }
2041 var taxonomies []layoutLegacyMapping
2042 for _, v := range legacyTaxonomyMappings {
2043 taxonomies = append(taxonomies, expand(v)...)
2044 }
2045 var sections []layoutLegacyMapping
2046 for _, v := range legacySectionMappings {
2047 sections = append(sections, expandSections(v)...)
2048 }
2049
2050 for i, m := range terms {
2051 s.opts.legacyMappingTerm[m.sourcePath] = legacyOrdinalMapping{ordinal: i, mapping: m.target}
2052 }
2053 for i, m := range taxonomies {
2054 s.opts.legacyMappingTaxonomy[m.sourcePath] = legacyOrdinalMapping{ordinal: i, mapping: m.target}
2055 }
2056 for i, m := range sections {
2057 s.opts.legacyMappingSection[m.sourcePath] = legacyOrdinalMapping{ordinal: i, mapping: m.target}
2058 }
2059
2060 return nil
2061 }
2062
2063 type TemplateStoreProvider interface {
2064 GetTemplateStore() *TemplateStore
2065 }
2066
2067 type TextTemplatHandler interface {
2068 ExecuteWithContext(ctx context.Context, ti *TemplInfo, wr io.Writer, data any) error
2069 TextLookup(name string) *TemplInfo
2070 TextParse(name, tpl string) (*TemplInfo, error)
2071 }
2072
2073 type bestMatch struct {
2074 templ *TemplInfo
2075 desc TemplateDescriptor
2076 w weight
2077 key string
2078 candidates []*TemplInfo
2079
2080 // settings.
2081 defaultOutputformat string
2082 }
2083
2084 func (best *bestMatch) reset() {
2085 best.templ = nil
2086 best.w = weight{}
2087 best.desc = TemplateDescriptor{}
2088 best.key = ""
2089 best.candidates = nil
2090 }
2091
2092 func (best *bestMatch) candidatesAsStringSlice() []string {
2093 if len(best.candidates) == 0 {
2094 return nil
2095 }
2096 candidates := make([]string, len(best.candidates))
2097 for i, v := range best.candidates {
2098 candidates[i] = v.PathInfo.Path()
2099 }
2100 return candidates
2101 }
2102
2103 func (best *bestMatch) isBetter(w weight, ti *TemplInfo) bool {
2104 if best.templ == nil {
2105 // Anything is better than nothing.
2106 return true
2107 }
2108
2109 if w.w1 <= 0 {
2110 if best.w.w1 <= 0 {
2111 return ti.PathInfo.Path() < best.templ.PathInfo.Path()
2112 }
2113 return false
2114 }
2115
2116 // Note that for render hook templates, we need to make
2117 // the embedded render hook template win if they're a better match,
2118 // e.g. render-codeblock-goat.html.
2119 if (best.templ.category != CategoryMarkup || best.templ.D.Variant1 == "table") && best.w.w1 > 0 {
2120 currentBestIsEmbedded := best.templ.subCategory == SubCategoryEmbedded
2121 if currentBestIsEmbedded {
2122 if ti.subCategory != SubCategoryEmbedded {
2123 return true
2124 }
2125 } else {
2126 if ti.subCategory == SubCategoryEmbedded {
2127 // Prefer user provided template.
2128 return false
2129 }
2130 }
2131 }
2132
2133 if w.distance < best.w.distance {
2134 if w.wsm < best.w.wsm {
2135 return false
2136 }
2137 if w.w2 < best.w.w2 {
2138 return false
2139 }
2140
2141 if w.w3 < best.w.w3 {
2142 return false
2143 }
2144 } else {
2145 if w.w1 < best.w.w1 {
2146 return false
2147 }
2148 }
2149
2150 if w.isEqualWeights(best.w) {
2151 if ti.subCategory != SubCategoryEmbedded && best.templ.subCategory == SubCategoryEmbedded {
2152 return true
2153 }
2154
2155 if w.distance < best.w.distance {
2156 return true
2157 }
2158
2159 return ti.PathInfo.Path() < best.templ.PathInfo.Path()
2160 }
2161
2162 return true
2163 }
2164
2165 func (best *bestMatch) updateValues(w weight, key string, k TemplateDescriptor, vv *TemplInfo) {
2166 best.w = w
2167 best.templ = vv
2168 best.desc = k
2169 best.key = key
2170 }
2171
2172 type byPath []*TemplInfo
2173
2174 func (a byPath) Len() int { return len(a) }
2175 func (a byPath) Less(i, j int) bool {
2176 return a[i].PathInfo.Path() < a[j].PathInfo.Path()
2177 }
2178
2179 func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
2180
2181 type keyTemplateInfo struct {
2182 Key string
2183 Info *TemplInfo
2184 }
2185
2186 type nodeKey struct {
2187 c Category
2188 d TemplateDescriptor
2189 }
2190
2191 type processingState int
2192
2193 // the parts of a template store that's set per site.
2194 type storeSite struct {
2195 opts SiteOptions
2196 execHelper *templateExecHelper
2197 executer texttemplate.Executer
2198 }
2199
2200 type weight struct {
2201 w1 int
2202 w2 int
2203 w3 int
2204 wsm int
2205 distance int
2206 }
2207
2208 func isLayoutStandard(s string) bool {
2209 switch s {
2210 case layoutAll, layoutList, layoutSingle:
2211 return true
2212 default:
2213 return false
2214 }
2215 }
2216
2217 func (w weight) isEqualWeights(other weight) bool {
2218 return w.w1 == other.w1 && w.w2 == other.w2 && w.w3 == other.w3
2219 }
2220
2221 func configureSiteStorage(opts SiteOptions, watching bool) *storeSite {
2222 funcsv := make(map[string]reflect.Value)
2223
2224 for k, v := range opts.TemplateFuncs {
2225 vv := reflect.ValueOf(v)
2226 funcsv[k] = vv
2227 }
2228
2229 // Duplicate Go's internal funcs here for faster lookups.
2230 for k, v := range htmltemplate.GoFuncs {
2231 if _, exists := funcsv[k]; !exists {
2232 vv, ok := v.(reflect.Value)
2233 if !ok {
2234 vv = reflect.ValueOf(v)
2235 }
2236 funcsv[k] = vv
2237 }
2238 }
2239
2240 for k, v := range texttemplate.GoFuncs {
2241 if _, exists := funcsv[k]; !exists {
2242 funcsv[k] = v
2243 }
2244 }
2245
2246 s := &storeSite{
2247 opts: opts,
2248 execHelper: &templateExecHelper{
2249 watching: watching,
2250 funcs: funcsv,
2251 site: reflect.ValueOf(opts.Site),
2252 siteParams: reflect.ValueOf(opts.Site.Params()),
2253 },
2254 }
2255
2256 s.executer = texttemplate.NewExecuter(s.execHelper)
2257
2258 return s
2259 }
2260
2261 func isBackupFile(path string) bool {
2262 return path[len(path)-1] == '~'
2263 }
2264
2265 func isDotFile(path string) bool {
2266 return filepath.Base(path)[0] == '.'
2267 }