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