Debian Codegraph @

hugolib/site.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hugolib
15
16 import (
17 "context"
18 "errors"
19 "fmt"
20 "io"
21 "maps"
22 "mime"
23 "net/url"
24 "os"
25 "path/filepath"
26 "runtime"
27 "slices"
28 "sort"
29 "strings"
30 "sync"
31 "time"
32
33 "github.com/bep/logg"
34 "github.com/gohugoio/go-radix"
35 "github.com/gohugoio/hugo/cache/dynacache"
36 "github.com/gohugoio/hugo/common/hmaps"
37 "github.com/gohugoio/hugo/common/hstore"
38 "github.com/gohugoio/hugo/common/hsync"
39 "github.com/gohugoio/hugo/common/htime"
40 "github.com/gohugoio/hugo/common/hugio"
41 "github.com/gohugoio/hugo/common/hugo"
42 "github.com/gohugoio/hugo/common/loggers"
43 "github.com/gohugoio/hugo/common/para"
44 "github.com/gohugoio/hugo/common/types"
45 "github.com/gohugoio/hugo/config"
46 "github.com/gohugoio/hugo/config/allconfig"
47 "github.com/gohugoio/hugo/deps"
48 "github.com/gohugoio/hugo/hugolib/doctree"
49 "github.com/gohugoio/hugo/hugolib/pagesfromdata"
50 "github.com/gohugoio/hugo/hugolib/roles"
51 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
52 "github.com/gohugoio/hugo/hugolib/versions"
53 "github.com/gohugoio/hugo/internal/js/esbuild"
54 "github.com/gohugoio/hugo/internal/warpc"
55 "github.com/gohugoio/hugo/langs/i18n"
56 "github.com/gohugoio/hugo/modules"
57 "github.com/gohugoio/hugo/resources"
58
59 "github.com/gohugoio/hugo/tpl/tplimpl"
60 "github.com/gohugoio/hugo/tpl/tplimplinit"
61
62 // Loads the template funcs namespaces.
63
64 "golang.org/x/text/unicode/norm"
65
66 "github.com/gohugoio/hugo/common/paths"
67
68 "github.com/gohugoio/hugo/identity"
69
70 "github.com/gohugoio/hugo/markup/converter/hooks"
71
72 "github.com/gohugoio/hugo/markup/converter"
73
74 "github.com/gohugoio/hugo/common/text"
75
76 "github.com/gohugoio/hugo/publisher"
77
78 "github.com/gohugoio/hugo/langs"
79
80 "github.com/gohugoio/hugo/resources/kinds"
81 "github.com/gohugoio/hugo/resources/page"
82 "github.com/gohugoio/hugo/resources/page/pagemeta"
83 "github.com/gohugoio/hugo/resources/page/siteidentities"
84 "github.com/gohugoio/hugo/resources/resource"
85
86 "github.com/fsnotify/fsnotify"
87 bp "github.com/gohugoio/hugo/bufferpool"
88 "github.com/gohugoio/hugo/helpers"
89 "github.com/gohugoio/hugo/navigation"
90 "github.com/gohugoio/hugo/output"
91 "github.com/gohugoio/hugo/tpl"
92 )
93
94 var _ page.Site = (*Site)(nil)
95
96 type siteState int
97
98 const (
99 siteStateInit siteState = iota
100 siteStateReady
101 )
102
103 type Site struct {
104 state siteState
105 conf *allconfig.Config
106 language *langs.Language
107 store *hstore.Scratch
108 siteWrapped page.Site
109
110 // The owning container.
111 h *HugoSites
112
113 *deps.Deps
114 *siteLanguageVersionRole
115
116 relatedDocsHandler *page.RelatedDocsHandler
117
118 publisher publisher.Publisher
119 frontmatterHandler pagemeta.FrontMatterHandler
120 }
121
122 func (s Site) cloneForVersionAndRole(version, role int) (*Site, error) {
123 s.siteLanguageVersionRole = s.siteLanguageVersionRole.cloneForVersionAndRole(version, role)
124 d, err := s.Deps.Clone(&s, s.Conf)
125 if err != nil {
126 return nil, err
127 }
128 s.Deps = d
129 ss := &s
130 ss.siteWrapped = page.WrapSite(ss)
131 return ss, nil
132 }
133
134 // For debugging purposes only.
135 func (s *Site) resolveDimensionNames() types.Strings3 {
136 return s.Conf.ConfiguredDimensions().ResolveNames(s.siteVector)
137 }
138
139 type siteLanguageVersionRole struct {
140 siteVector sitesmatrix.Vector
141 isDefaultLanguage bool
142
143 roleInternal roles.RoleInternal
144 role roles.Role
145
146 versionInternal versions.VersionInternal
147 version versions.Version
148
149 pageMap *pageMap
150
151 // Page navigation.
152 *pageFinder
153 siteRefLinker siteRefLinker
154
155 // Shortcut to the home page. Note that this may be nil if
156 // home page, for some odd reason, is disabled.
157 home *pageState
158
159 // The last modification date of this site.
160 lastmod time.Time
161
162 // Lazily loaded site dependencies
163 init *siteInit
164
165 // The output formats that we need to render this site in. This slice
166 // will be fixed once set.
167 // This will be the union of Site.Pages' outputFormats.
168 // This slice will be sorted.
169 renderFormats output.Formats
170 }
171
172 func (s siteLanguageVersionRole) cloneForVersionAndRole(version, role int) *siteLanguageVersionRole {
173 s.siteVector[sitesmatrix.Version] = version
174 s.siteVector[sitesmatrix.Role] = role
175 s.home = nil
176 s.lastmod = time.Time{}
177 s.init = &siteInit{}
178 return &s
179 }
180
181 func (s siteLanguageVersionRole) Role() roles.Role {
182 return s.role
183 }
184
185 func (s siteLanguageVersionRole) Version() versions.Version {
186 return s.version
187 }
188
189 func (s siteLanguageVersionRole) isDefault() bool {
190 return s.isDefaultLanguage && s.roleInternal.Default && s.versionInternal.Default
191 }
192
193 func (s *Site) Debug() {
194 fmt.Println("Debugging site", s.Lang(), "=>")
195 // fmt.Println(s.pageMap.testDump())
196 }
197
198 // NewHugoSites creates HugoSites from the given config.
199 func NewHugoSites(cfg deps.DepsCfg) (*HugoSites, error) {
200 if !cfg.TestCfg.IsZero() && !cfg.IsIntegrationTest {
201 panic("DepsCfg.TestCfg must only be set in integration tests")
202 }
203
204 conf := cfg.Configs.GetFirstLanguageConfig()
205 rolesSorted := cfg.Configs.Base.Roles.Config.Sorted
206 versionsSorted := cfg.Configs.Base.Versions.Config.Sorted
207
208 var (
209 poolSizeKatex = 2
210 poolSizeWebP = 1
211 poolSizeAvif = 1
212 )
213 if n := config.GetNumWorkerMultiplier(); n > 1 {
214 poolSizeKatex = min(n, 8)
215 poolSizeWebP = max(2, n/2)
216 poolSizeAvif = max(2, n/2)
217 }
218
219 var logger loggers.Logger
220 if cfg.TestLogger != nil {
221 logger = cfg.TestLogger
222 } else {
223 var logHookLast func(e *logg.Entry) error
224 if cfg.Configs.Base.PanicOnWarning {
225 logHookLast = loggers.PanicOnWarningHook
226 }
227 if cfg.StdOut == nil {
228 cfg.StdOut = os.Stdout
229 }
230 if cfg.StdErr == nil {
231 cfg.StdErr = os.Stderr
232 }
233 if cfg.LogLevel == 0 {
234 cfg.LogLevel = logg.LevelWarn
235 }
236
237 logOpts := loggers.Options{
238 Level: cfg.LogLevel,
239 DistinctLevel: logg.LevelWarn, // This will drop duplicate log warning and errors.
240 HandlerPost: logHookLast,
241 StdOut: cfg.StdOut,
242 StdErr: cfg.StdErr,
243 StoreErrors: conf.Watching(),
244 SuppressStatements: conf.IgnoredLogs(),
245 }
246 logger = loggers.New(logOpts)
247
248 }
249
250 memCache := dynacache.New(dynacache.Options{Watching: conf.Watching(), Log: logger})
251
252 var h *HugoSites
253 onSignalRebuild := func(ids ...identity.Identity) {
254 // This channel is buffered, but make sure we do this in a non-blocking way.
255 if cfg.ChangesFromBuild != nil {
256 go func() {
257 cfg.ChangesFromBuild <- ids
258 }()
259 }
260 }
261
262 compilationCacheDir := filepath.Join(conf.Dirs().CacheDir, "_warpc")
263
264 imageWasmMemory := 384 // 384 MiB (4096 MiB Max)
265 if m := cfg.TestCfg.WarpcMemory; m > 0 {
266 imageWasmMemory = m
267 }
268
269 firstSiteDeps := &deps.Deps{
270 Fs: cfg.Fs,
271 Log: logger,
272 Conf: conf,
273 BuildState: &deps.BuildState{
274 OnSignalRebuild: onSignalRebuild,
275 },
276 Counters: &deps.Counters{},
277 MemCache: memCache,
278 TranslationProvider: i18n.NewTranslationProvider(),
279 WasmDispatchers: warpc.AllDispatchers(
280 // Katex options.
281 warpc.Options{
282 CompilationCacheDir: compilationCacheDir,
283
284 PoolSize: poolSizeKatex,
285 Infof: logger.InfoCommand("katex").Logf,
286 Warnf: logger.WarnCommand("katex").Logf,
287 },
288 // WebP options.
289 warpc.Options{
290 CompilationCacheDir: compilationCacheDir,
291 PoolSize: poolSizeWebP,
292 Memory: imageWasmMemory,
293 Infof: logger.InfoCommand("webp").Logf,
294 Warnf: logger.WarnCommand("webp").Logf,
295 },
296 // Avif options.
297 warpc.Options{
298 CompilationCacheDir: compilationCacheDir,
299 PoolSize: poolSizeAvif,
300 Memory: imageWasmMemory,
301 Infof: logger.InfoCommand("avif").Logf,
302 Warnf: logger.WarnCommand("avif").Logf,
303 },
304 ),
305 }
306
307 if err := firstSiteDeps.Init(); err != nil {
308 return nil, err
309 }
310
311 // Prevent leaking goroutines in tests.
312 if cfg.IsIntegrationTest && cfg.ChangesFromBuild != nil {
313 firstSiteDeps.BuildClosers.Add(types.CloserFunc(func() error {
314 close(cfg.ChangesFromBuild)
315 return nil
316 }))
317 }
318
319 batcherClient, err := esbuild.NewBatcherClient(firstSiteDeps)
320 if err != nil {
321 return nil, err
322 }
323 firstSiteDeps.JSBatcherClient = batcherClient
324
325 confm := cfg.Configs
326 if err := confm.Validate(logger); err != nil {
327 return nil, err
328 }
329 var sites []*Site
330
331 ns := &contentNodeShifter{
332 conf: conf,
333 }
334
335 treeConfig := doctree.Config[contentNode]{
336 Shifter: ns,
337 TransformerRaw: &contentNodeTransformerRaw{},
338 }
339
340 dimensionLengths := sitesmatrix.Vector{len(confm.Languages), len(versionsSorted), len(rolesSorted)}
341
342 pageTrees := &pageTrees{
343 treePages: doctree.New(
344 treeConfig,
345 ),
346 treeResources: doctree.New(
347 treeConfig,
348 ),
349 treeTaxonomyEntries: doctree.NewTreeShiftTree[*weightedContentNode](dimensionLengths),
350 treePagesFromTemplateAdapters: doctree.NewTreeShiftTree[*pagesfromdata.PagesFromTemplate](dimensionLengths),
351 }
352
353 pageTrees.createMutableTrees()
354
355 for i, confp := range confm.ConfigLangs() {
356 language := confp.Language().(*langs.Language)
357 if language.Disabled {
358 panic("cannot create site for disabled language: " + language.Lang)
359 }
360 k := language.Lang
361 conf := confm.LanguageConfigMap[k]
362 frontmatterHandler, err := pagemeta.NewFrontmatterHandler(firstSiteDeps.Log, conf.Frontmatter)
363 if err != nil {
364 return nil, err
365 }
366
367 langs.SetParams(language, conf.Params)
368
369 s := &Site{
370 conf: conf,
371 language: language,
372 frontmatterHandler: frontmatterHandler,
373 store: hstore.NewScratch(),
374 siteLanguageVersionRole: &siteLanguageVersionRole{
375 isDefaultLanguage: language.IsDefault(),
376 siteVector: sitesmatrix.Vector{i, 0, 0},
377 },
378 }
379
380 s.siteWrapped = page.WrapSite(s)
381
382 if i == 0 {
383 firstSiteDeps.Site = s
384 s.Deps = firstSiteDeps
385 } else {
386 d, err := firstSiteDeps.Clone(s, confp)
387 if err != nil {
388 return nil, err
389 }
390 s.Deps = d
391 }
392
393 // Set up the main publishing chain.
394 pub, err := publisher.NewDestinationPublisher(
395 firstSiteDeps.ResourceSpec,
396 s.conf.OutputFormats.Config,
397 s.conf.MediaTypes.Config,
398 )
399 if err != nil {
400 return nil, err
401 }
402
403 s.publisher = pub
404 s.relatedDocsHandler = page.NewRelatedDocsHandler(s.conf.Related)
405 // Site deps end.
406
407 sites = append(sites, s)
408
409 }
410
411 if len(sites) == 0 {
412 return nil, errors.New("no sites to build")
413 }
414
415 sitesVersionsRoles := make([][][]*Site, len(sites))
416 for i := 0; i < len(sites); i++ {
417 sitesVersionsRoles[i] = make([][]*Site, len(versionsSorted))
418 for j := range versionsSorted {
419 sitesVersionsRoles[i][j] = make([]*Site, len(rolesSorted))
420 }
421 }
422
423 siteVersionRoles := map[types.Ints2][]roles.Role{}
424 siteRoleVersions := map[types.Ints2][]versions.Version{}
425 // i = site, j = version, k = role
426 for i, v1 := range sitesVersionsRoles {
427 for j, v2 := range v1 {
428 for k := range v2 {
429 var vrs *Site
430 if j == 0 && k == 0 {
431 vrs = sites[i]
432 } else {
433 prototype := sites[i]
434 vrs, err = prototype.cloneForVersionAndRole(j, k)
435 if err != nil {
436 return nil, err
437 }
438 }
439 vrs.roleInternal = rolesSorted[k]
440 vrs.role = roles.NewRole(rolesSorted[k])
441 vrs.versionInternal = versionsSorted[j]
442 vrs.version = versions.NewVersion(versionsSorted[j])
443 siteRoleVersions[types.Ints2{i, k}] = append(siteRoleVersions[types.Ints2{i, k}], vrs.version)
444 siteVersionRoles[types.Ints2{i, j}] = append(siteVersionRoles[types.Ints2{i, j}], vrs.role)
445 vrs.pageMap = newPageMap(vrs, memCache, pageTrees)
446 vrs.pageFinder = newPageFinder(vrs.pageMap)
447 vrs.siteRefLinker = newSiteRefLinker(vrs)
448 vrs.prepareInits()
449 v2[k] = vrs
450 }
451 }
452 }
453
454 h, err = newHugoSites(cfg, firstSiteDeps, pageTrees, sitesVersionsRoles)
455 if err == nil && h == nil {
456 panic("hugo: newHugoSitesNew returned nil error and nil HugoSites")
457 }
458
459 return h, err
460 }
461
462 func newHugoSites(
463 cfg deps.DepsCfg,
464 d *deps.Deps,
465 pageTrees *pageTrees,
466 sitesVersionsRoles [][][]*Site,
467 ) (*HugoSites, error) {
468 first := make([]*Site, len(sitesVersionsRoles))
469 for i, v := range sitesVersionsRoles {
470 first[i] = v[0][0]
471 }
472
473 sitesVersionsRolesMap := map[sitesmatrix.Vector]*Site{}
474 for _, v1 := range sitesVersionsRoles {
475 for _, v2 := range v1 {
476 for _, s := range v2 {
477 sitesVersionsRolesMap[s.siteVector] = s
478 }
479 }
480 }
481
482 numWorkers := config.GetNumWorkerMultiplier()
483 numWorkersSite := min(numWorkers, len(sitesVersionsRolesMap))
484 workersSite := para.New(numWorkersSite)
485
486 var sitesLanguages []*Site
487 for _, v := range sitesVersionsRoles {
488 sitesLanguages = append(sitesLanguages, v[0][0])
489 }
490
491 h := &HugoSites{
492 Sites: first,
493 sitesVersionsRoles: sitesVersionsRoles,
494 sitesVersionsRolesMap: sitesVersionsRolesMap,
495 sitesLanguages: sitesLanguages,
496 Deps: first[0].Deps,
497 Configs: cfg.Configs,
498 workersSite: workersSite,
499 numWorkersSites: numWorkers,
500 numWorkers: numWorkers,
501 pageTrees: pageTrees,
502 cachePages: dynacache.GetOrCreatePartition[string,
503 page.Pages](d.MemCache, "/pags/all",
504 dynacache.OptionsPartition{Weight: 10, ClearWhen: dynacache.ClearOnRebuild},
505 ),
506 cacheContentSource: dynacache.GetOrCreatePartition[uint64, *resources.StaleValue[[]byte]](d.MemCache, "/cont/src", dynacache.OptionsPartition{Weight: 70, ClearWhen: dynacache.ClearOnChange}),
507 translationKeyPages: hmaps.NewSliceCache[page.Page](),
508 currentSite: first[0],
509 skipRebuildForFilenames: make(map[string]bool),
510 init: &hugoSitesInit{},
511 progressReporter: &progressReporter{},
512 }
513
514 // Assemble dependencies to be used in hugo.Deps.
515 var dependencies []*hugo.Dependency
516 var depFromMod func(m modules.Module) *hugo.Dependency
517 depFromMod = func(m modules.Module) *hugo.Dependency {
518 dep := &hugo.Dependency{
519 Path: m.Path(),
520 Version: m.Version(),
521 Time: m.Time(),
522 Vendor: m.Vendor(),
523 }
524
525 // These are pointers, but this all came from JSON so there's no recursive navigation,
526 // so just create new values.
527 if m.Replace() != nil {
528 dep.Replace = depFromMod(m.Replace())
529 }
530 if m.Owner() != nil {
531 dep.Owner = depFromMod(m.Owner())
532 }
533 return dep
534 }
535 for _, m := range d.Paths.AllModules() {
536 dependencies = append(dependencies, depFromMod(m))
537 }
538
539 // Create providers that avoid naming conflicts with HugoSites fields.
540 sp := hugoSitesSitesProvider{h: h}
541
542 opts := page.HugoInfoOptions{
543 Conf: h.Configs.GetFirstLanguageConfig(),
544 HugoInfoHugoSitesProvider: sp,
545 Deps: dependencies,
546 }
547
548 if bi := hugo.GetBuildInfo(); bi != nil {
549 opts.CommitHash = bi.Revision
550 opts.BuildDate = bi.RevisionTime
551 opts.GoVersion = bi.GoVersion
552 }
553
554 if opts.BuildDate == "" {
555 opts.BuildDate = hugo.GetBuildDate()
556 }
557
558 h.hugoInfo = page.NewHugoInfo(opts)
559
560 var prototype *deps.Deps
561
562 var i int
563 for _, v := range sitesVersionsRoles {
564 for _, r := range v {
565 for _, s := range r {
566 s.h = h
567 // The template store needs to be initialized after the h container is set on s.
568 if i == 0 {
569 templateStore, err := tplimpl.NewStore(
570 tplimpl.StoreOptions{
571 Fs: s.BaseFs.Layouts.Fs,
572 Log: s.Log,
573 Watching: s.Conf.Watching(),
574 PathParser: s.Conf.PathParser(),
575 Metrics: d.Metrics,
576 OutputFormats: s.conf.OutputFormats.Config,
577 MediaTypes: s.conf.MediaTypes.Config,
578 DefaultOutputFormat: s.conf.DefaultOutputFormat,
579 TaxonomySingularPlural: s.conf.Taxonomies,
580 RenderHooks: s.conf.Markup.Goldmark.RenderHooks,
581 }, tplimpl.SiteOptions{
582 Site: s,
583 TemplateFuncs: tplimplinit.CreateFuncMap(s.Deps),
584 })
585 if err != nil {
586 return nil, err
587 }
588 s.Deps.TemplateStore = templateStore
589 } else {
590 s.Deps.TemplateStore = prototype.TemplateStore.WithSiteOpts(
591 tplimpl.SiteOptions{
592 Site: s,
593 TemplateFuncs: tplimplinit.CreateFuncMap(s.Deps),
594 })
595 }
596 if err := s.Deps.Compile(prototype); err != nil {
597 return nil, err
598 }
599 if i == 0 {
600 prototype = s.Deps
601 }
602
603 i++
604 }
605 }
606 }
607
608 h.fatalErrorHandler = &fatalErrorHandler{
609 h: h,
610 donec: make(chan bool),
611 }
612
613 h.init.data = hsync.OnceMoreFunc(func(ctx context.Context) error {
614 return h.loadData()
615 })
616
617 h.init.gitInfo = hsync.OnceMoreFunc(func(ctx context.Context) error {
618 return h.loadGitInfo()
619 })
620
621 return h, nil
622 }
623
624 // GetSiteDimension returns the value of the specified site dimension (such as language, version, or role)
625 // based on the provided dimension name string. If the dimension name is unknown, it panics.
626 func (s *Site) Dimension(d string) page.SiteDimension {
627 switch d {
628 case sitesmatrix.DimensionName(sitesmatrix.Language):
629 return s.language
630 case sitesmatrix.DimensionName(sitesmatrix.Version):
631 return s.version
632 case sitesmatrix.DimensionName(sitesmatrix.Role):
633 return s.role
634 default:
635 panic(fmt.Sprintf("unknown dimension %q", d))
636 }
637 }
638
639 // Returns the server port.
640 func (s *Site) ServerPort() int {
641 return s.conf.C.BaseURL.Port()
642 }
643
644 // Returns the configured title for this Site.
645 func (s *Site) Title() string {
646 return s.conf.Title
647 }
648
649 func (s *Site) Copyright() string {
650 return s.conf.Copyright
651 }
652
653 func (s *Site) Lang() string {
654 return s.language.Lang
655 }
656
657 func (s *Site) Config() page.SiteConfig {
658 return page.SiteConfig{
659 Privacy: s.conf.Privacy,
660 Services: s.conf.Services,
661 }
662 }
663
664 // Deprecated: Use .Language.Locale instead.
665 func (s *Site) LanguageCode() string {
666 hugo.DeprecateWithLogger(".Site.LanguageCode", "Use .Site.Language.Locale instead.", "v0.158.0", s.Language().Logger())
667 return s.Language().Locale()
668 }
669
670 // Returns all sites for all dimensions.
671 // Deprecated: Use hugo.Sites instead.
672 func (s *Site) Sites() page.Sites {
673 s.h.printSiteSitesDeprecationInit.Do(func() {
674 hugo.Deprecate(".Site.Sites and .Page.Sites", "Use hugo.Sites instead.", "v0.156.0")
675 })
676 return slices.Collect(s.h.allSitesInterface(nil))
677 }
678
679 // IsDefault reports whether this site is the default across all dimensions.
680 func (s *Site) IsDefault() bool {
681 return s.siteLanguageVersionRole.isDefault()
682 }
683
684 // Returns Site currently rendering.
685 func (s *Site) Current() page.Site {
686 return s.h.currentSite
687 }
688
689 // MainSections returns the list of main sections.
690 func (s *Site) MainSections() []string {
691 s.CheckReady()
692 return s.conf.C.MainSections
693 }
694
695 // Returns a struct with some information about the build.
696 func (s *Site) Hugo() page.HugoInfo {
697 return s.h.hugoInfo
698 }
699
700 // Returns the BaseURL for this Site.
701 func (s *Site) BaseURL() string {
702 return s.conf.C.BaseURL.WithPath
703 }
704
705 // Returns the last modification date of the content.
706 func (s *Site) Lastmod() time.Time {
707 return s.lastmod
708 }
709
710 // Returns the Params configured for this site.
711 func (s *Site) Params() hmaps.Params {
712 return s.conf.Params
713 }
714
715 func (s *Site) Param(key any) (any, error) {
716 return resource.Param(s, nil, key)
717 }
718
719 // Returns a map of all the data inside /data.
720 // Deprecated: Use hugo.Data instead.
721 func (s *Site) Data() map[string]any {
722 s.h.printSiteDataDeprecationInit.Do(func() {
723 hugo.Deprecate(".Site.Data", "Use hugo.Data instead.", "v0.156.0")
724 })
725 return s.h.Data()
726 }
727
728 // Deprecated: See https://discourse.gohugo.io/t/56732.
729 func (s *Site) BuildDrafts() bool {
730 s.h.printSiteBuildDraftsDeprecationInit.Do(func() {
731 hugo.Deprecate(".Site.BuildDrafts", "See https://discourse.gohugo.io/t/56732.", "v0.156.0")
732 })
733 return s.conf.BuildDrafts
734 }
735
736 func (s *Site) LanguagePrefix() string {
737 prefix := s.GetLanguagePrefix()
738 if prefix == "" {
739 return ""
740 }
741 return "/" + prefix
742 }
743
744 func (s *Site) Site() page.Site {
745 return page.WrapSite(s)
746 }
747
748 func (s *Site) ForEeachIdentityByName(name string, f func(identity.Identity) bool) {
749 if id, found := siteidentities.FromString(name); found {
750 if f(id) {
751 return
752 }
753 }
754 }
755
756 // Pages returns all pages.
757 // This is for the current language only.
758 func (s *Site) Pages() page.Pages {
759 s.CheckReady()
760 return s.pageMap.getPagesInSection(
761 pageMapQueryPagesInSection{
762 pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{
763 Path: "",
764 KeyPart: "global",
765 Include: pagePredicates.ShouldListGlobal.BoolFunc(),
766 },
767 Recursive: true,
768 IncludeSelf: true,
769 },
770 )
771 }
772
773 // RegularPages returns all the regular pages.
774 // This is for the current language only.
775 func (s *Site) RegularPages() page.Pages {
776 s.CheckReady()
777 return s.pageMap.getPagesInSection(
778 pageMapQueryPagesInSection{
779 pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{
780 Path: "",
781 KeyPart: "global",
782 Include: pagePredicates.ShouldListGlobal.And(pagePredicates.KindPage).BoolFunc(),
783 },
784 Recursive: true,
785 },
786 )
787 }
788
789 // AllPages returns all pages for all sites.
790 // Deprecated: See https://discourse.gohugo.io/t/56732.
791 func (s *Site) AllPages() page.Pages {
792 s.h.printSiteAllPagesDeprecationInit.Do(func() {
793 hugo.Deprecate(".Site.AllPages", "See https://discourse.gohugo.io/t/56732.", "v0.156.0")
794 })
795 s.CheckReady()
796 return s.h.Pages()
797 }
798
799 // AllRegularPages returns all regular pages for all sites.
800 func (s *Site) AllRegularPages() page.Pages {
801 s.CheckReady()
802 return s.h.RegularPages()
803 }
804
805 func (s *Site) Store() *hstore.Scratch {
806 return s.store
807 }
808
809 func (s *Site) CheckReady() {
810 if s.state != siteStateReady {
811 panic("this method cannot be called before the site is fully initialized")
812 }
813 }
814
815 func (s *Site) Taxonomies() page.TaxonomyList {
816 s.CheckReady()
817 return s.init.taxonomies.Value(context.Background())
818 }
819
820 type (
821 taxonomiesConfig map[string]string
822 taxonomiesConfigValues struct {
823 views []viewName
824 viewsByTreeKey map[string]viewName
825 }
826 )
827
828 func (t taxonomiesConfig) Values() taxonomiesConfigValues {
829 var views []viewName
830 for k, v := range t {
831 views = append(views, viewName{singular: k, plural: v, pluralTreeKey: cleanTreeKey(v)})
832 }
833 sort.Slice(views, func(i, j int) bool {
834 return views[i].plural < views[j].plural
835 })
836
837 viewsByTreeKey := make(map[string]viewName)
838 for _, v := range views {
839 viewsByTreeKey[v.pluralTreeKey] = v
840 }
841
842 return taxonomiesConfigValues{
843 views: views,
844 viewsByTreeKey: viewsByTreeKey,
845 }
846 }
847
848 // Lazily loaded site dependencies.
849 type siteInit struct {
850 prevNext hsync.FuncResetter
851 prevNextInSection hsync.FuncResetter
852
853 menus hsync.ValueResetter[navigation.Menus]
854 taxonomies hsync.ValueResetter[page.TaxonomyList]
855 }
856
857 func (init *siteInit) Reset() {
858 init.prevNext.Reset()
859 init.prevNextInSection.Reset()
860 init.menus.Reset()
861 init.taxonomies.Reset()
862 }
863
864 func (s *Site) prepareInits() {
865 s.init = &siteInit{}
866
867 s.init.prevNext = hsync.OnceMoreFunc(func(ctx context.Context) error {
868 regularPages := s.RegularPages()
869 if s.conf.Page.NextPrevSortOrder == "asc" {
870 regularPages = regularPages.Reverse()
871 }
872 for i, p := range regularPages {
873 np, ok := p.(nextPrevProvider)
874 if !ok {
875 continue
876 }
877
878 pos := np.getNextPrev()
879 if pos == nil {
880 continue
881 }
882
883 pos.nextPage = nil
884 pos.prevPage = nil
885
886 if i > 0 {
887 pos.nextPage = regularPages[i-1]
888 }
889
890 if i < len(regularPages)-1 {
891 pos.prevPage = regularPages[i+1]
892 }
893 }
894 return nil
895 })
896
897 s.init.prevNextInSection = hsync.OnceMoreFunc(func(ctx context.Context) error {
898 setNextPrev := func(pas page.Pages) {
899 for i, p := range pas {
900 np, ok := p.(nextPrevInSectionProvider)
901 if !ok {
902 continue
903 }
904
905 pos := np.getNextPrevInSection()
906 if pos == nil {
907 continue
908 }
909
910 pos.nextPage = nil
911 pos.prevPage = nil
912
913 if i > 0 {
914 pos.nextPage = pas[i-1]
915 }
916
917 if i < len(pas)-1 {
918 pos.prevPage = pas[i+1]
919 }
920 }
921 }
922
923 sections := s.pageMap.getPagesInSection(
924 pageMapQueryPagesInSection{
925 pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{
926 Path: "",
927 KeyPart: "sectionorhome",
928 Include: pagePredicates.KindSection.Or(pagePredicates.KindHome).BoolFunc(),
929 },
930 IncludeSelf: true,
931 Recursive: true,
932 },
933 )
934
935 for _, section := range sections {
936 ps := section.RegularPages()
937 if s.conf.Page.NextPrevInSectionSortOrder == "asc" {
938 ps = ps.Reverse()
939 }
940 setNextPrev(ps)
941 }
942
943 return nil
944 })
945
946 s.init.menus = hsync.OnceMoreValue(func(ctx context.Context) navigation.Menus {
947 m, err := s.assembleMenus()
948 if err != nil {
949 panic(err)
950 }
951 return m
952 })
953
954 s.init.taxonomies = hsync.OnceMoreValue(func(ctx context.Context) page.TaxonomyList {
955 taxonomies, err := s.pageMap.CreateSiteTaxonomies(ctx)
956 if err != nil {
957 panic(err)
958 }
959 return taxonomies
960 })
961 }
962
963 func (s *Site) Menus() navigation.Menus {
964 s.CheckReady()
965 return s.init.menus.Value(context.Background())
966 }
967
968 func (s *Site) initRenderFormats() {
969 formatSet := make(map[string]bool)
970 formats := output.Formats{}
971
972 w := &doctree.NodeShiftTreeWalker[contentNode]{
973 Tree: s.pageMap.treePages,
974 Handle: func(key string, n contentNode) (radix.WalkFlag, error) {
975 if p, ok := n.(*pageState); ok {
976 for _, f := range p.m.pageConfig.ConfiguredOutputFormats {
977 if !formatSet[f.Name] {
978 formats = append(formats, f)
979 formatSet[f.Name] = true
980 }
981 }
982 }
983 return radix.WalkContinue, nil
984 },
985 }
986
987 if err := w.Walk(context.TODO()); err != nil {
988 panic(err)
989 }
990
991 // Add the per kind configured output formats
992 for _, kind := range kinds.AllKindsInPages {
993 if siteFormats, found := s.conf.C.KindOutputFormats[kind]; found {
994 for _, f := range siteFormats {
995 if !formatSet[f.Name] {
996 formats = append(formats, f)
997 formatSet[f.Name] = true
998 }
999 }
1000 }
1001 }
1002
1003 sort.Sort(formats)
1004 s.renderFormats = formats
1005 }
1006
1007 func (s *Site) GetInternalRelatedDocsHandler() *page.RelatedDocsHandler {
1008 return s.relatedDocsHandler
1009 }
1010
1011 func (s *Site) Language() *langs.Language {
1012 return s.language
1013 }
1014
1015 // Deprecated: See https://discourse.gohugo.io/t/56732.
1016 func (s *Site) Languages() langs.Languages {
1017 s.h.printSiteLanguagesDeprecationInit.Do(func() {
1018 hugo.Deprecate(".Site.Languages", "See https://discourse.gohugo.io/t/56732.", "v0.156.0")
1019 })
1020 return s.h.Configs.Languages
1021 }
1022
1023 type siteRefLinker struct {
1024 s *Site
1025
1026 errorLogger logg.LevelLogger
1027 notFoundURL string
1028 }
1029
1030 func newSiteRefLinker(s *Site) siteRefLinker {
1031 logger := s.Log.Error()
1032
1033 notFoundURL := s.conf.RefLinksNotFoundURL
1034 errLevel := s.conf.RefLinksErrorLevel
1035 if strings.EqualFold(errLevel, "warning") {
1036 logger = s.Log.Warn()
1037 }
1038 return siteRefLinker{s: s, errorLogger: logger, notFoundURL: notFoundURL}
1039 }
1040
1041 func (s siteRefLinker) logNotFound(ref, what string, p page.Page, position text.Position) {
1042 if position.IsValid() {
1043 s.errorLogger.Logf("[%s] REF_NOT_FOUND: Ref %q: %s: %s", s.s.Lang(), ref, position.String(), what)
1044 } else if p == nil {
1045 s.errorLogger.Logf("[%s] REF_NOT_FOUND: Ref %q: %s", s.s.Lang(), ref, what)
1046 } else {
1047 s.errorLogger.Logf("[%s] REF_NOT_FOUND: Ref %q from page %q: %s", s.s.Lang(), ref, p.Path(), what)
1048 }
1049 }
1050
1051 func (s *siteRefLinker) refLink(ref string, source any, relative bool, outputFormat string) (string, error) {
1052 p, err := unwrapPage(source)
1053 if err != nil {
1054 return "", err
1055 }
1056
1057 var refURL *url.URL
1058
1059 ref = filepath.ToSlash(ref)
1060
1061 refURL, err = url.Parse(ref)
1062 if err != nil {
1063 return s.notFoundURL, err
1064 }
1065
1066 var target page.Page
1067 var link string
1068
1069 if refURL.Path != "" {
1070 var err error
1071 target, err = s.s.getPageRef(p, refURL.Path)
1072 var pos text.Position
1073 if err != nil || target == nil {
1074 if p, ok := source.(text.Positioner); ok {
1075 pos = p.Position()
1076 }
1077 }
1078
1079 if err != nil {
1080 s.logNotFound(refURL.Path, err.Error(), p, pos)
1081 return s.notFoundURL, nil
1082 }
1083
1084 if target == nil {
1085 s.logNotFound(refURL.Path, "page not found", p, pos)
1086 return s.notFoundURL, nil
1087 }
1088
1089 var permalinker Permalinker = target
1090
1091 if outputFormat != "" {
1092 o := target.OutputFormats().Get(outputFormat)
1093
1094 if o.IsZero() {
1095 s.logNotFound(refURL.Path, fmt.Sprintf("output format %q", outputFormat), p, pos)
1096 return s.notFoundURL, nil
1097 }
1098 permalinker = o
1099 }
1100
1101 if relative {
1102 link = permalinker.RelPermalink()
1103 } else {
1104 link = permalinker.Permalink()
1105 }
1106 }
1107
1108 if refURL.Fragment != "" {
1109 _ = target
1110 link = link + "#" + refURL.Fragment
1111
1112 if pctx, ok := target.(pageContext); ok {
1113 if refURL.Path != "" {
1114 if di, ok := pctx.getContentConverter().(converter.DocumentInfo); ok {
1115 link = link + di.AnchorSuffix()
1116 }
1117 }
1118 } else if pctx, ok := p.(pageContext); ok {
1119 if di, ok := pctx.getContentConverter().(converter.DocumentInfo); ok {
1120 link = link + di.AnchorSuffix()
1121 }
1122 }
1123
1124 }
1125
1126 return link, nil
1127 }
1128
1129 func (s *Site) watching() bool {
1130 return s.h != nil && s.h.Configs.Base.Internal.Watch
1131 }
1132
1133 type WhatChanged struct {
1134 mu sync.Mutex
1135
1136 needsPagesAssembly bool
1137
1138 ids map[identity.Identity]bool
1139 }
1140
1141 func (w *WhatChanged) init() {
1142 if w.ids == nil {
1143 w.ids = make(map[identity.Identity]bool)
1144 }
1145 }
1146
1147 func (w *WhatChanged) Add(ids ...identity.Identity) {
1148 w.mu.Lock()
1149 defer w.mu.Unlock()
1150
1151 w.init()
1152
1153 for _, id := range ids {
1154 w.ids[id] = true
1155 }
1156 }
1157
1158 func (w *WhatChanged) Clear() {
1159 w.mu.Lock()
1160 defer w.mu.Unlock()
1161 w.clear()
1162 }
1163
1164 func (w *WhatChanged) clear() {
1165 w.ids = nil
1166 }
1167
1168 func (w *WhatChanged) Changes() []identity.Identity {
1169 if w == nil || w.ids == nil {
1170 return nil
1171 }
1172 return slices.Collect(maps.Keys(w.ids))
1173 }
1174
1175 func (w *WhatChanged) Drain() []identity.Identity {
1176 w.mu.Lock()
1177 defer w.mu.Unlock()
1178 ids := w.Changes()
1179 w.clear()
1180 return ids
1181 }
1182
1183 // RegisterMediaTypes will register the Site's media types in the mime
1184 // package, so it will behave correctly with Hugo's built-in server.
1185 func (s *Site) RegisterMediaTypes() {
1186 for _, mt := range s.conf.MediaTypes.Config {
1187 for _, suffix := range mt.Suffixes() {
1188 _ = mime.AddExtensionType(mt.Delimiter+suffix, mt.Type)
1189 }
1190 }
1191 }
1192
1193 func (h *HugoSites) fileEventsFilter(events []fsnotify.Event) []fsnotify.Event {
1194 seen := make(map[fsnotify.Event]bool)
1195
1196 n := 0
1197 for _, ev := range events {
1198 // Avoid processing the same event twice.
1199 if seen[ev] {
1200 continue
1201 }
1202 seen[ev] = true
1203
1204 if h.SourceSpec.IgnoreFile(ev.Name) {
1205 continue
1206 }
1207
1208 if runtime.GOOS == "darwin" { // When a file system is HFS+, its filepath is in NFD form.
1209 ev.Name = norm.NFC.String(ev.Name)
1210 }
1211
1212 events[n] = ev
1213 n++
1214 }
1215 events = events[:n]
1216
1217 eventOrdinal := func(e fsnotify.Event) int {
1218 // Pull the structural changes to the top.
1219 if e.Op.Has(fsnotify.Create) {
1220 return 1
1221 }
1222 if e.Op.Has(fsnotify.Remove) {
1223 return 2
1224 }
1225 if e.Op.Has(fsnotify.Rename) {
1226 return 3
1227 }
1228 if e.Op.Has(fsnotify.Write) {
1229 return 4
1230 }
1231 return 5
1232 }
1233
1234 sort.Slice(events, func(i, j int) bool {
1235 // First sort by event type.
1236 if eventOrdinal(events[i]) != eventOrdinal(events[j]) {
1237 return eventOrdinal(events[i]) < eventOrdinal(events[j])
1238 }
1239 // Then sort by name.
1240 return events[i].Name < events[j].Name
1241 })
1242
1243 return events
1244 }
1245
1246 type fileEventInfo struct {
1247 fsnotify.Event
1248 fi os.FileInfo
1249 added bool
1250 removed bool
1251 isChangedDir bool
1252 }
1253
1254 func (h *HugoSites) fileEventsApplyInfo(events []fsnotify.Event) []fileEventInfo {
1255 var infos []fileEventInfo
1256 for _, ev := range events {
1257 removed := false
1258 added := false
1259
1260 fi, statErr := h.Fs.Source.Stat(ev.Name)
1261
1262 // Some editors (Vim) sometimes issue only a Rename operation when writing an existing file,
1263 // and an atomic save (write temp file, then rename it into place) makes the watcher
1264 // report the replaced file as removed (kqueue/macOS).
1265 // So, if the file is still on disk, it's only been updated, if it's not, it's gone.
1266 if ev.Op.Has(fsnotify.Remove) || ev.Op.Has(fsnotify.Rename) {
1267 removed = statErr != nil
1268 }
1269 if ev.Op.Has(fsnotify.Create) {
1270 added = true
1271 }
1272
1273 isChangedDir := statErr == nil && fi.IsDir()
1274
1275 infos = append(infos, fileEventInfo{
1276 Event: ev,
1277 fi: fi,
1278 added: added,
1279 removed: removed,
1280 isChangedDir: isChangedDir,
1281 })
1282 }
1283
1284 n := 0
1285
1286 for _, ev := range infos {
1287 // Remove any directories that's also represented by a file.
1288 keep := true
1289 if ev.isChangedDir {
1290 for _, ev2 := range infos {
1291 if ev2.fi != nil && !ev2.fi.IsDir() && filepath.Dir(ev2.Name) == ev.Name {
1292 keep = false
1293 break
1294 }
1295 }
1296 }
1297 if keep {
1298 infos[n] = ev
1299 n++
1300 }
1301 }
1302 infos = infos[:n]
1303
1304 return infos
1305 }
1306
1307 func (h *HugoSites) fileEventsTrim(events []fsnotify.Event) []fsnotify.Event {
1308 seen := make(map[string]bool)
1309 n := 0
1310 for _, ev := range events {
1311 if seen[ev.Name] {
1312 continue
1313 }
1314 seen[ev.Name] = true
1315 events[n] = ev
1316 n++
1317 }
1318 return events
1319 }
1320
1321 func (h *HugoSites) fileEventsContentPaths(p []pathChange) []pathChange {
1322 var bundles []pathChange
1323 var dirs []pathChange
1324 var regular []pathChange
1325
1326 var others []pathChange
1327 for _, p := range p {
1328 if p.isDir {
1329 dirs = append(dirs, p)
1330 } else {
1331 others = append(others, p)
1332 }
1333 }
1334
1335 // Remove all files below dir.
1336 if len(dirs) > 0 {
1337 n := 0
1338 for _, o := range others {
1339 keep := true
1340 for _, d := range dirs {
1341 if strings.HasPrefix(o.p.Path(), d.p.Path()+"/") {
1342 keep = false
1343 break
1344 }
1345 }
1346 if keep {
1347 others[n] = o
1348 n++
1349 }
1350 }
1351 others = others[:n]
1352 }
1353
1354 for _, p := range others {
1355 if p.p.IsBundle() {
1356 bundles = append(bundles, p)
1357 } else {
1358 regular = append(regular, p)
1359 }
1360 }
1361
1362 // Remove any files below leaf bundles.
1363 // Remove any files in the same folder as branch bundles.
1364 var keepers []pathChange
1365
1366 for _, o := range regular {
1367 keep := true
1368 for _, b := range bundles {
1369 prefix := b.p.Base() + "/"
1370 if b.p.IsLeafBundle() && strings.HasPrefix(o.p.Path(), prefix) {
1371 keep = false
1372 break
1373 } else if b.p.IsBranchBundle() && o.p.Dir() == b.p.Dir() {
1374 keep = false
1375 break
1376 }
1377 }
1378
1379 if keep {
1380 keepers = append(keepers, o)
1381 }
1382 }
1383
1384 keepers = append(dirs, keepers...)
1385 keepers = append(bundles, keepers...)
1386
1387 return keepers
1388 }
1389
1390 // SitemapAbsURL is a convenience method giving the absolute URL to the sitemap.
1391 func (s *Site) SitemapAbsURL() string {
1392 base := ""
1393 if s.Conf.IsMultilingual() || s.Conf.DefaultContentLanguageInSubdir() {
1394 base = s.Language().Lang
1395 }
1396 p := s.AbsURL(base, false)
1397 if !strings.HasSuffix(p, "/") {
1398 p += "/"
1399 }
1400 p += s.conf.Sitemap.Filename
1401 return p
1402 }
1403
1404 func (s *Site) createNodeMenuEntryURL(in string) string {
1405 if !strings.HasPrefix(in, "/") {
1406 return in
1407 }
1408 // make it match the nodes
1409 menuEntryURL := in
1410 menuEntryURL = s.PathSpec.URLize(menuEntryURL)
1411 if !s.conf.CanonifyURLs {
1412 menuEntryURL = paths.AddContextRoot(s.PathSpec.Cfg.BaseURL().String(), menuEntryURL)
1413 }
1414 return menuEntryURL
1415 }
1416
1417 func (s *Site) assembleMenus() (navigation.Menus, error) {
1418 menus := make(navigation.Menus)
1419
1420 type twoD struct {
1421 MenuName, EntryName string
1422 }
1423 flat := map[twoD]*navigation.MenuEntry{}
1424 children := map[twoD]navigation.Menu{}
1425
1426 // add menu entries from config to flat hash
1427 for name, menu := range s.conf.Menus.Config {
1428 for _, x := range menu {
1429 // Shallow copy the menu entry, so we can set the URL and page without modifying the config.
1430 c := *x
1431 me := &c
1432
1433 if me.PageRef != "" {
1434 // Try to resolve the page.
1435 me.Page, _ = s.getPage(nil, me.PageRef)
1436 }
1437
1438 // If page is still nill, we must make sure that we have a URL that considers baseURL etc.
1439 if types.IsNil(me.Page) {
1440 me.ConfiguredURL = s.createNodeMenuEntryURL(me.MenuConfig.URL)
1441 } else {
1442 navigation.SetPageValues(me, me.Page)
1443 }
1444
1445 flat[twoD{name, me.KeyName()}] = me
1446 }
1447 }
1448
1449 sectionPagesMenu := s.conf.SectionPagesMenu
1450
1451 if sectionPagesMenu != "" {
1452 if err := s.pageMap.forEachPage(pagePredicates.ShouldListGlobal, func(p *pageState) (bool, error) {
1453 if p.Kind() != kinds.KindSection || !p.m.shouldBeCheckedForMenuDefinitions() {
1454 return false, nil
1455 }
1456
1457 // The section pages menus are attached to the top level section.
1458 id := p.Section()
1459 if id == "" {
1460 id = "/"
1461 }
1462
1463 if _, ok := flat[twoD{sectionPagesMenu, id}]; ok {
1464 return false, nil
1465 }
1466 me := navigation.MenuEntry{
1467 MenuConfig: navigation.MenuConfig{
1468 Identifier: id,
1469 Name: p.LinkTitle(),
1470 Weight: p.Weight(),
1471 },
1472 Page: p,
1473 }
1474
1475 navigation.SetPageValues(&me, p)
1476 flat[twoD{sectionPagesMenu, me.KeyName()}] = &me
1477 return false, nil
1478 }); err != nil {
1479 return nil, err
1480 }
1481 }
1482
1483 // Add menu entries provided by pages
1484 if err := s.pageMap.forEachPage(pagePredicates.ShouldListGlobal, func(p *pageState) (bool, error) {
1485 for name, me := range p.pageMenus.menus() {
1486 if _, ok := flat[twoD{name, me.KeyName()}]; ok {
1487 err := p.wrapError(fmt.Errorf("duplicate menu entry with identifier %q in menu %q", me.KeyName(), name))
1488 s.Log.Warnln(err)
1489 continue
1490 }
1491 flat[twoD{name, me.KeyName()}] = me
1492 }
1493 return false, nil
1494 }); err != nil {
1495 return nil, err
1496 }
1497
1498 // Create Children Menus First
1499 for _, e := range flat {
1500 if e.Parent != "" {
1501 children[twoD{e.Menu, e.Parent}] = children[twoD{e.Menu, e.Parent}].Add(e)
1502 }
1503 }
1504
1505 // Placing Children in Parents (in flat)
1506 for p, childmenu := range children {
1507 _, ok := flat[twoD{p.MenuName, p.EntryName}]
1508 if !ok {
1509 // if parent does not exist, create one without a URL
1510 flat[twoD{p.MenuName, p.EntryName}] = &navigation.MenuEntry{
1511 MenuConfig: navigation.MenuConfig{
1512 Name: p.EntryName,
1513 },
1514 }
1515 }
1516 flat[twoD{p.MenuName, p.EntryName}].Children = childmenu
1517 }
1518
1519 // Assembling Top Level of Tree
1520 for menu, e := range flat {
1521 if e.Parent == "" {
1522 _, ok := menus[menu.MenuName]
1523 if !ok {
1524 menus[menu.MenuName] = navigation.Menu{}
1525 }
1526 menus[menu.MenuName] = menus[menu.MenuName].Add(e)
1527 }
1528 }
1529
1530 return menus, nil
1531 }
1532
1533 // get any language code to prefix the target file path with.
1534 func (s *Site) getLanguageTargetPathLang(alwaysInSubDir bool) string {
1535 if s.h.Conf.IsMultihost() {
1536 return s.Language().Lang
1537 }
1538
1539 return s.getLanguagePermalinkLang(alwaysInSubDir)
1540 }
1541
1542 // get any language code to prefix the relative permalink with.
1543 func (s *Site) getLanguagePermalinkLang(alwaysInSubDir bool) string {
1544 if s.h.Conf.IsMultihost() {
1545 return ""
1546 }
1547
1548 if s.h.Conf.IsMultilingual() && alwaysInSubDir {
1549 return s.Language().Lang
1550 }
1551
1552 return s.GetLanguagePrefix()
1553 }
1554
1555 func (s *Site) getPrefixRole() string {
1556 role := s.roleInternal
1557 if role.Default {
1558 if s.conf.DefaultContentRoleInSubdir {
1559 return role.Name
1560 }
1561 return ""
1562 }
1563 return role.Name
1564 }
1565
1566 func (s *Site) getPrefixVersion() string {
1567 version := s.versionInternal
1568 if version.Default {
1569 if s.conf.DefaultContentVersionInSubdir {
1570 return version.Name
1571 }
1572 return ""
1573 }
1574 return version.Name
1575 }
1576
1577 // Prepare site for a new full build.
1578 func (s *Site) resetBuildState(sourceChanged bool) {
1579 s.relatedDocsHandler = s.relatedDocsHandler.Clone()
1580 s.init.Reset()
1581 s.pageMap.Reset()
1582 }
1583
1584 func (s *Site) errorCollator(results <-chan error, errs chan<- error) {
1585 var errors []error
1586 defer func() {
1587 errs <- s.h.filterAndJoinErrors(errors)
1588 close(errs)
1589 }()
1590 const maxErrors = 10
1591 for e := range results {
1592 errors = append(errors, e)
1593 if len(errors) >= maxErrors {
1594 s.h.Stop()
1595 break
1596 }
1597 }
1598 }
1599
1600 // GetPage looks up a page of a given type for the given ref.
1601 // In Hugo <= 0.44 you had to add Page Kind (section, home) etc. as the first
1602 // argument and then either a unix styled path (with or without a leading slash))
1603 // or path elements separated.
1604 // When we now remove the Kind from this API, we need to make the transition as painless
1605 // as possible for existing sites. Most sites will use {{ .Site.GetPage "section" "my/section" }},
1606 // i.e. 2 arguments, so we test for that.
1607 func (s *Site) GetPage(ref ...string) (page.Page, error) {
1608 s.CheckReady()
1609 p, err := s.getPageForRefs(ref...)
1610
1611 if p == nil {
1612 // The nil struct has meaning in some situations, mostly to avoid breaking
1613 // existing sites doing $nilpage.IsDescendant($p), which will always return
1614 // false.
1615 p = page.NilPage
1616 }
1617
1618 return p, err
1619 }
1620
1621 func (s *Site) absURLPath(targetPath string) string {
1622 var path string
1623 if s.conf.RelativeURLs {
1624 path = helpers.GetDottedRelativePath(targetPath)
1625 } else {
1626 url := s.PathSpec.Cfg.BaseURL().String()
1627 if !strings.HasSuffix(url, "/") {
1628 url += "/"
1629 }
1630 path = url
1631 }
1632
1633 return path
1634 }
1635
1636 const (
1637 pageDependencyScopeDefault int = iota
1638 pageDependencyScopeGlobal
1639 )
1640
1641 func (s *Site) renderAndWritePage(statCounter *uint64, targetPath string, p *pageState, d any, templ *tplimpl.TemplInfo) error {
1642 s.h.onPageRender()
1643 renderBuffer := bp.GetBuffer()
1644 defer bp.PutBuffer(renderBuffer)
1645
1646 of := p.outputFormat()
1647 p.incrRenderState()
1648
1649 ctx := s.TemplateStore.PrepareTopLevelRenderCtx(context.Background(), p)
1650 ctx = tpl.Context.DependencyManagerScopedProvider.Set(ctx, p)
1651
1652 if err := s.renderForTemplate(ctx, p.Kind(), of.Name, d, renderBuffer, templ); err != nil {
1653 return err
1654 }
1655
1656 if renderBuffer.Len() == 0 {
1657 return nil
1658 }
1659
1660 isHTML := of.IsHTML
1661 isRSS := of.Name == "rss"
1662
1663 pd := publisher.Descriptor{
1664 Src: renderBuffer,
1665 TargetPath: targetPath,
1666 StatCounter: statCounter,
1667 OutputFormat: p.outputFormat(),
1668 }
1669
1670 if isRSS {
1671 // Always canonify URLs in RSS
1672 pd.AbsURLPath = s.absURLPath(targetPath)
1673 } else if isHTML {
1674 if s.conf.RelativeURLs || s.conf.CanonifyURLs {
1675 pd.AbsURLPath = s.absURLPath(targetPath)
1676 }
1677
1678 if s.watching() && s.conf.Internal.Running && !s.conf.DisableLiveReload {
1679 pd.LiveReloadBaseURL = s.Conf.BaseURLLiveReload().URL()
1680 }
1681
1682 // For performance reasons we only inject the Hugo generator tag on the home page.
1683 if p.IsHome() {
1684 pd.AddHugoGeneratorTag = !s.conf.DisableHugoGeneratorInject
1685 }
1686
1687 }
1688
1689 return s.publisher.Publish(pd)
1690 }
1691
1692 var infoOnMissingLayout = map[string]bool{
1693 // The 404 layout is very much optional in Hugo, but we do look for it.
1694 "404": true,
1695 }
1696
1697 // hookRendererTemplate is the canonical implementation of all hooks.ITEMRenderer,
1698 // where ITEM is the thing being hooked.
1699 type hookRendererTemplate struct {
1700 templateHandler *tplimpl.TemplateStore
1701 templ *tplimpl.TemplInfo
1702 resolvePosition func(renderContext any, pos int) text.Position
1703 }
1704
1705 func (hr hookRendererTemplate) RenderLink(cctx context.Context, w io.Writer, ctx hooks.LinkContext) error {
1706 return hr.templateHandler.ExecuteWithContext(cctx, hr.templ, w, ctx)
1707 }
1708
1709 func (hr hookRendererTemplate) RenderHeading(cctx context.Context, w io.Writer, ctx hooks.HeadingContext) error {
1710 return hr.templateHandler.ExecuteWithContext(cctx, hr.templ, w, ctx)
1711 }
1712
1713 func (hr hookRendererTemplate) RenderCodeblock(cctx context.Context, w hugio.FlexiWriter, ctx hooks.CodeblockContext) error {
1714 return hr.templateHandler.ExecuteWithContext(cctx, hr.templ, w, ctx)
1715 }
1716
1717 func (hr hookRendererTemplate) RenderPassthrough(cctx context.Context, w io.Writer, ctx hooks.PassthroughContext) error {
1718 return hr.templateHandler.ExecuteWithContext(cctx, hr.templ, w, ctx)
1719 }
1720
1721 func (hr hookRendererTemplate) RenderBlockquote(cctx context.Context, w hugio.FlexiWriter, ctx hooks.BlockquoteContext) error {
1722 return hr.templateHandler.ExecuteWithContext(cctx, hr.templ, w, ctx)
1723 }
1724
1725 func (hr hookRendererTemplate) RenderTable(cctx context.Context, w hugio.FlexiWriter, ctx hooks.TableContext) error {
1726 return hr.templateHandler.ExecuteWithContext(cctx, hr.templ, w, ctx)
1727 }
1728
1729 func (hr hookRendererTemplate) ResolvePosition(renderContext any, pos int) text.Position {
1730 return hr.resolvePosition(renderContext, pos)
1731 }
1732
1733 func (hr hookRendererTemplate) IsDefaultCodeBlockRenderer() bool {
1734 return false
1735 }
1736
1737 func (s *Site) renderForTemplate(ctx context.Context, name, outputFormat string, d any, w io.Writer, templ *tplimpl.TemplInfo) (err error) {
1738 if templ == nil {
1739 s.logMissingLayout(name, "", "", outputFormat)
1740 return nil
1741 }
1742
1743 if ctx == nil {
1744 panic("nil context")
1745 }
1746
1747 if err = s.GetTemplateStore().ExecuteWithContext(ctx, templ, w, d); err != nil {
1748 filename := name
1749 if p, ok := d.(*pageState); ok {
1750 filename = p.String()
1751 }
1752 return fmt.Errorf("render of %q failed: %w", filename, err)
1753 }
1754 return
1755 }
1756
1757 func (s *Site) shouldBuild(p page.Page) bool {
1758 if !s.conf.IsKindEnabled(p.Kind()) {
1759 return false
1760 }
1761 return shouldBuild(s.Conf.BuildFuture(), s.Conf.BuildExpired(),
1762 s.Conf.BuildDrafts(), p.Draft(), p.PublishDate(), p.ExpiryDate())
1763 }
1764
1765 func shouldBuild(buildFuture bool, buildExpired bool, buildDrafts bool, Draft bool,
1766 publishDate time.Time, expiryDate time.Time,
1767 ) bool {
1768 if !(buildDrafts || !Draft) {
1769 return false
1770 }
1771 hnow := htime.Now()
1772 if !buildFuture && !publishDate.IsZero() && publishDate.After(hnow) {
1773 return false
1774 }
1775 if !buildExpired && !expiryDate.IsZero() && expiryDate.Before(hnow) {
1776 return false
1777 }
1778 return true
1779 }
1780
1781 func (s *Site) render(ctx *siteRenderContext) (err error) {
1782 if err := page.Clear(); err != nil {
1783 return err
1784 }
1785
1786 if err = s.renderPages(ctx); err != nil {
1787 return
1788 }
1789
1790 if !ctx.shouldRenderStandalonePage("") {
1791 return
1792 }
1793
1794 return
1795 }
1796
1797 func (s *Site) String() string {
1798 if s == nil {
1799 return "Site (nil)"
1800 }
1801
1802 return fmt.Sprintf("Site %v: %s", s.siteVector, s.resolveDimensionNames())
1803 }