Debian Codegraph @

hugolib/page.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 "fmt"
19 "iter"
20 "path/filepath"
21 "slices"
22 "strings"
23 "sync/atomic"
24
25 "github.com/gohugoio/hugo/hugofs"
26 "github.com/gohugoio/hugo/hugolib/segments"
27 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
28 "github.com/gohugoio/hugo/identity"
29 "github.com/gohugoio/hugo/media"
30 "github.com/gohugoio/hugo/output"
31 "github.com/gohugoio/hugo/related"
32 "github.com/gohugoio/hugo/resources"
33 "github.com/gohugoio/hugo/tpl/tplimpl"
34 "github.com/spf13/afero"
35
36 "github.com/gohugoio/hugo/markup/converter"
37 "github.com/gohugoio/hugo/markup/tableofcontents"
38
39 "github.com/gohugoio/hugo/common/herrors"
40 "github.com/gohugoio/hugo/common/types"
41
42 "github.com/gohugoio/hugo/source"
43
44 "github.com/gohugoio/hugo/common/collections"
45 "github.com/gohugoio/hugo/common/text"
46 "github.com/gohugoio/hugo/resources/kinds"
47 "github.com/gohugoio/hugo/resources/page"
48 "github.com/gohugoio/hugo/resources/resource"
49 )
50
51 var (
52 _ page.Page = (*pageState)(nil)
53 _ collections.Grouper = (*pageState)(nil)
54 _ collections.Slicer = (*pageState)(nil)
55 _ identity.DependencyManagerScopedProvider = (*pageState)(nil)
56 _ pageContext = (*pageState)(nil)
57 )
58
59 var (
60 pageTypesProvider = resource.NewResourceTypesProvider(media.Builtin.OctetType, pageResourceType)
61 nopPageOutput = &pageOutput{
62 pagePerOutputProviders: nopPagePerOutput,
63 MarkupProvider: page.NopPage,
64 ContentProvider: page.NopPage,
65 }
66 )
67
68 // pageContext provides contextual information about this page, for error
69 // logging and similar.
70 type pageContext interface {
71 posOffset(offset int) text.Position
72 wrapError(err error) error
73 getContentConverter() converter.Converter
74 }
75
76 type pageSiteAdapter struct {
77 p page.Page
78 s *Site
79 }
80
81 func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) {
82 p, err := pa.s.getPage(pa.p, ref)
83
84 if p == nil {
85 // The nil struct has meaning in some situations, mostly to avoid breaking
86 // existing sites doing $nilpage.IsDescendant($p), which will always return
87 // false.
88 p = page.NilPage
89 }
90 return p, err
91 }
92
93 type pageState struct {
94 // Incremented for each new page created.
95 // Note that this will change between builds for a given Page.
96 pid uint64
97
98 s *Site
99
100 // This slice will be of same length as the number of global slice of output
101 // formats (for all sites).
102 pageOutputs []*pageOutput
103
104 // Used to determine if we can reuse content across output formats.
105 pageOutputTemplateVariationsState atomic.Uint32
106
107 // This will be shifted out when we start to render a new output format.
108 pageOutputIdx int
109 *pageOutput
110
111 // Common for all output formats.
112 *pageCommon
113
114 resource.Staler
115 dependencyManager identity.Manager
116 }
117
118 // This is not accurate and only used for progress reporting.
119 // We can do better, but this will do for now.
120 func (p *pageState) hasRenderableOutput() bool {
121 for _, po := range p.pageOutputs {
122 if po.render {
123 return true
124 }
125 }
126 return false
127 }
128
129 func (p *pageState) incrPageOutputTemplateVariation() {
130 p.pageOutputTemplateVariationsState.Add(1)
131 }
132
133 func (ps *pageState) canReusePageOutputContent() bool {
134 return ps.pageOutputTemplateVariationsState.Load() == 1
135 }
136
137 func (ps *pageState) IdentifierBase() string {
138 return ps.Path()
139 }
140
141 func (ps *pageState) GetIdentity() identity.Identity {
142 return ps
143 }
144
145 func (ps *pageState) ForEeachIdentity(f func(identity.Identity) bool) bool {
146 return f(ps)
147 }
148
149 func (ps *pageState) GetDependencyManager() identity.Manager {
150 return ps.dependencyManager
151 }
152
153 func (ps *pageState) GetDependencyManagerForScope(scope int) identity.Manager {
154 switch scope {
155 case pageDependencyScopeDefault:
156 return ps.dependencyManagerOutput
157 case pageDependencyScopeGlobal:
158 return ps.dependencyManager
159 default:
160 return identity.NopManager
161 }
162 }
163
164 func (ps *pageState) GetDependencyManagerForScopesAll() []identity.Manager {
165 return []identity.Manager{ps.dependencyManager, ps.dependencyManagerOutput}
166 }
167
168 // Param is a convenience method to do lookups in Page's and Site's Params map,
169 // in that order.
170 //
171 // This method is also implemented on SiteInfo.
172 func (ps *pageState) Param(key any) (any, error) {
173 return resource.Param(ps, ps.s.Params(), key)
174 }
175
176 // RelatedKeywords implements the related.Document interface needed for fast page searches.
177 func (ps *pageState) RelatedKeywords(cfg related.IndexConfig) ([]string, error) {
178 v, found, err := page.NamedPageMetaValue(ps, cfg.Name)
179 if err != nil || !found {
180 return nil, err
181 }
182
183 return cfg.ToKeywords(v)
184 }
185
186 func (ps *pageState) resetBuildState() {
187 ps.m.prepareRebuild()
188 }
189
190 func (ps *pageState) skipRender() bool {
191 b := ps.s.conf.Segments.Config.SegmentFilter.ShouldExcludeFine(
192 segments.SegmentQuery{
193 Path: ps.Path(),
194 Kind: ps.Kind(),
195 Site: ps.s.siteVector,
196 Output: ps.pageOutput.f.Name,
197 },
198 )
199
200 return b
201 }
202
203 func (ps *pageState) isRenderedAny() bool {
204 for _, o := range ps.pageOutputs {
205 if o.isRendered() {
206 return true
207 }
208 }
209 return false
210 }
211
212 // Implements contentNode.
213
214 func (ps *pageState) forEeachContentNode(f func(v sitesmatrix.Vector, n contentNode) bool) bool {
215 return f(ps.s.siteVector, ps)
216 }
217
218 func (ps *pageState) contentWeight() int {
219 return ps.m.pageMetaSource.contentWeight()
220 }
221
222 func (ps *pageState) nodeSourceEntryID() any {
223 return ps.m.nodeSourceEntryID()
224 }
225
226 func (ps *pageState) nodeCategoryPage() {
227 // Marker method.
228 }
229
230 func (m *pageState) nodeCategorySingle() {
231 // Marker method.
232 }
233
234 func (ps *pageState) lookupContentNode(v sitesmatrix.Vector) contentNode {
235 pc := ps.m.pageConfigSource
236 if pc.MatchSiteVector(v) {
237 return ps
238 }
239 return nil
240 }
241
242 func (ps *pageState) lookupContentNodes(vec sitesmatrix.Vector, fallback bool) iter.Seq[contentNodeForSite] {
243 nop := func(yield func(n contentNodeForSite) bool) {}
244 pc := ps.m.pageConfigSource
245 if !fallback {
246 if !pc.MatchSiteVector(vec) {
247 return nop
248 }
249 return func(yield func(n contentNodeForSite) bool) {
250 yield(ps)
251 }
252 }
253
254 if !pc.MatchLanguageCoarse(vec) {
255 return nop
256 }
257
258 if !pc.MatchVersionCoarse(vec) {
259 return nop
260 }
261 if !pc.MatchRoleCoarse(vec) {
262 return nop
263 }
264
265 return func(yield func(n contentNodeForSite) bool) {
266 yield(ps)
267 }
268 }
269
270 // Eq returns whether the current page equals the given page.
271 // This is what's invoked when doing `{{ if eq $page $otherPage }}`
272 func (ps *pageState) Eq(other any) bool {
273 pp, err := unwrapPage(other)
274 if err != nil {
275 return false
276 }
277
278 return ps == pp
279 }
280
281 func (ps *pageState) HeadingsFiltered(context.Context) tableofcontents.Headings {
282 return nil
283 }
284
285 type pageHeadingsFiltered struct {
286 *pageState
287 headings tableofcontents.Headings
288 }
289
290 func (p *pageHeadingsFiltered) HeadingsFiltered(context.Context) tableofcontents.Headings {
291 return p.headings
292 }
293
294 func (p *pageHeadingsFiltered) page() page.Page {
295 return p.pageState
296 }
297
298 // For internal use by the related content feature.
299 func (ps *pageState) ApplyFilterToHeadings(ctx context.Context, fn func(*tableofcontents.Heading) bool) related.Document {
300 fragments := ps.pageOutput.pco.c().Fragments(ctx)
301 headings := fragments.Headings.FilterBy(fn)
302 return &pageHeadingsFiltered{
303 pageState: ps,
304 headings: headings,
305 }
306 }
307
308 func (ps *pageState) GitInfo() *source.GitInfo {
309 return ps.gitInfo
310 }
311
312 func (ps *pageState) CodeOwners() []string {
313 return ps.codeowners
314 }
315
316 // GetTerms gets the terms defined on this page in the given taxonomy.
317 // The pages returned will be ordered according to the front matter.
318 func (ps *pageState) GetTerms(taxonomy string) page.Pages {
319 return ps.s.pageMap.getTermsForPageInTaxonomy(ps.Path(), taxonomy)
320 }
321
322 func (ps *pageState) MarshalJSON() ([]byte, error) {
323 return page.MarshalPageToJSON(ps)
324 }
325
326 func (ps *pageState) RegularPagesRecursive() page.Pages {
327 switch ps.Kind() {
328 case kinds.KindSection, kinds.KindHome:
329 return ps.s.pageMap.getPagesInSection(
330 pageMapQueryPagesInSection{
331 Path: ps.Path(),
332 Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(),
333 Recursive: true,
334 },
335 )
336 default:
337 return ps.RegularPages()
338 }
339 }
340
341 func (ps *pageState) PagesRecursive() page.Pages {
342 return nil
343 }
344
345 func (ps *pageState) RegularPages() page.Pages {
346 switch ps.Kind() {
347 case kinds.KindPage:
348 case kinds.KindSection, kinds.KindHome, kinds.KindTaxonomy:
349 return ps.s.pageMap.getPagesInSection(
350 pageMapQueryPagesInSection{
351 Path: ps.Path(),
352 Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(),
353 },
354 )
355 case kinds.KindTerm:
356 return ps.s.pageMap.getPagesWithTerm(
357 pageMapQueryPagesBelowPath{
358 Path: ps.Path(),
359 Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(),
360 },
361 )
362 default:
363 return ps.s.RegularPages()
364 }
365 return nil
366 }
367
368 func (ps *pageState) Pages() page.Pages {
369 switch ps.Kind() {
370 case kinds.KindPage:
371 case kinds.KindSection, kinds.KindHome:
372 return ps.s.pageMap.getPagesInSection(
373 pageMapQueryPagesInSection{
374 Path: ps.Path(),
375 KeyPart: "page-section",
376 Include: pagePredicates.ShouldListLocal.And(
377 pagePredicates.KindPage.Or(pagePredicates.KindSection),
378 ).BoolFunc(),
379 },
380 )
381 case kinds.KindTerm:
382 return ps.s.pageMap.getPagesWithTerm(
383 pageMapQueryPagesBelowPath{
384 Path: ps.Path(),
385 },
386 )
387 case kinds.KindTaxonomy:
388 return ps.s.pageMap.getPagesInSection(
389 pageMapQueryPagesInSection{
390 Path: ps.Path(),
391 KeyPart: "term",
392 Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindTerm).BoolFunc(),
393 Recursive: true,
394 },
395 )
396 default:
397 return ps.s.Pages()
398 }
399 return nil
400 }
401
402 // RawContent returns the un-rendered source content without
403 // any leading front matter.
404 func (ps *pageState) RawContent() string {
405 if ps.m.content.pi.itemsStep2 == nil {
406 return ""
407 }
408 start := ps.m.content.pi.posMainContent
409 if start == -1 {
410 start = 0
411 }
412 source, err := ps.m.content.pi.contentSource(ps.m.content)
413 if err != nil {
414 panic(err)
415 }
416 return string(source[start:])
417 }
418
419 func (ps *pageState) Resources() resource.Resources {
420 return ps.s.pageMap.getOrCreateResourcesForPage(ps)
421 }
422
423 func (ps *pageState) HasShortcode(name string) bool {
424 p := ps.m.content.hasShortcode.Load()
425 if p == nil {
426 return false
427 }
428 hasShortcode := *p
429 return hasShortcode(name)
430 }
431
432 func (ps *pageState) Site() page.Site {
433 return ps.s.siteWrapped
434 }
435
436 func (ps *pageState) String() string {
437 var sb strings.Builder
438 if ps.File() != nil {
439 // The forward slashes even on Windows is motivated by
440 // getting stable tests.
441 // This information is meant for getting positional information in logs,
442 // so the direction of the slashes should not matter.
443 sb.WriteString(filepath.ToSlash(ps.File().Filename()))
444 if ps.File().IsContentAdapter() {
445 // Also include the path.
446 sb.WriteString(":")
447 sb.WriteString(ps.Path())
448 }
449 } else {
450 sb.WriteString(ps.Path())
451 }
452 return sb.String()
453 }
454
455 // IsTranslated returns whether this content file is translated to
456 // other language(s).
457 func (ps *pageState) IsTranslated() bool {
458 return len(ps.AllTranslations()) > 1
459 }
460
461 // TranslationKey returns the key used to identify a translation of this content.
462 func (ps *pageState) TranslationKey() string {
463 if ps.m.pageConfig.TranslationKey != "" {
464 return ps.m.pageConfig.TranslationKey
465 }
466 return ps.Path()
467 }
468
469 // AllTranslations returns all translations, including the current Page.
470 func (ps *pageState) AllTranslations() page.Pages {
471 key := ps.Path() + "/" + "translations-all"
472 // This is called from Translations, so we need to use a different partition, cachePages2,
473 // to avoid potential deadlocks.
474 pages, err := ps.s.pageMap.getOrCreatePagesFromCache(ps.s.pageMap.cachePages2, key, func(string) (page.Pages, error) {
475 if ps.m.pageConfig.TranslationKey != "" {
476 // translationKey set by user.
477 pas, _ := ps.s.h.translationKeyPages.Get(ps.m.pageConfig.TranslationKey)
478 pasc := slices.Clone(pas)
479 page.SortByLanguage(pasc)
480 return pasc, nil
481 }
482 var pas page.Pages
483
484 ps.s.pageMap.treePages.ForEeachInDimension(ps.Path(), ps.s.siteVector, sitesmatrix.Language,
485 func(n contentNode) bool {
486 if n != nil {
487 pas = append(pas, n.(page.Page))
488 }
489 return true
490 },
491 )
492
493 pas = pagePredicates.ShouldLink.Filter(pas)
494 page.SortByLanguage(pas)
495 return pas, nil
496 })
497 if err != nil {
498 panic(err)
499 }
500
501 return pages
502 }
503
504 // For internal use only.
505 func (ps *pageState) SiteVector() sitesmatrix.Vector {
506 return ps.s.siteVector
507 }
508
509 func (ps *pageState) siteVector() sitesmatrix.Vector {
510 return ps.s.siteVector
511 }
512
513 func (ps *pageState) siteVectors() sitesmatrix.VectorIterator {
514 return ps.s.siteVector
515 }
516
517 // Rotate returns all pages in the given dimension for this page.
518 func (ps *pageState) Rotate(dimensionStr string) (page.Pages, error) {
519 dimensionStr = strings.ToLower(dimensionStr)
520 key := ps.Path() + "/" + "rotate-" + dimensionStr
521 d, err := sitesmatrix.ParseDimension(dimensionStr)
522 if err != nil {
523 return nil, fmt.Errorf("failed to parse dimension %q: %w", dimensionStr, err)
524 }
525
526 pages, err := ps.s.pageMap.getOrCreatePagesFromCache(ps.s.pageMap.cachePages2, key, func(string) (page.Pages, error) {
527 var pas page.Pages
528 ps.s.pageMap.treePages.ForEeachInDimension(ps.Path(), ps.s.siteVector, d,
529 func(n contentNode) bool {
530 if n != nil {
531 p := n.(page.Page)
532 pas = append(pas, p)
533 }
534 return true
535 },
536 )
537
538 if dimensionStr == "language" && ps.m.pageConfig.TranslationKey != "" {
539 // translationKey set by user.
540 // This is an old construct back from when languages were introduced.
541 // We keep it for backward compatibility.
542 // Also see AllTranslations.
543 pas, _ := ps.s.h.translationKeyPages.Get(ps.m.pageConfig.TranslationKey)
544 pasc := slices.Clone(pas)
545 page.SortByLanguage(pasc)
546 return pasc, nil
547 }
548
549 pas = pagePredicates.ShouldLink.Filter(pas)
550 page.SortByDims(pas)
551 return pas, nil
552 })
553
554 return pages, err
555 }
556
557 // Translations returns the translations excluding the current Page.
558 func (ps *pageState) Translations() page.Pages {
559 key := ps.Path() + "/" + "translations"
560 pages, err := ps.s.pageMap.getOrCreatePagesFromCache(nil, key, func(string) (page.Pages, error) {
561 var pas page.Pages
562 for _, pp := range ps.AllTranslations() {
563 if !pp.Eq(ps) {
564 pas = append(pas, pp)
565 }
566 }
567 return pas, nil
568 })
569 if err != nil {
570 panic(err)
571 }
572 return pages
573 }
574
575 func (ps *pageState) initCommonProviders(pp pagePaths) error {
576 if ps.IsPage() {
577 if ps.s == nil {
578 panic("no site")
579 }
580 ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext}
581 ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection}
582 ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection)
583 ps.Positioner = newPagePosition(ps.posNextPrev)
584 }
585
586 ps.OutputFormatsProvider = pp
587 ps.targetPathDescriptor = pp.targetPathDescriptor
588 ps.RefProvider = newPageRef(ps)
589 ps.SitesProvider = ps.s
590 ps.SiteProvider = ps
591
592 return nil
593 }
594
595 // Exported so it can be used in integration tests.
596 func (po *pageOutput) GetInternalTemplateBasePathAndDescriptor() (string, tplimpl.TemplateDescriptor) {
597 p := po.p
598 f := po.f
599
600 base := p.PathInfo().BaseReTyped(p.m.pageConfig.Type)
601 return base, tplimpl.TemplateDescriptor{
602 Kind: p.Kind(),
603 LayoutFromUser: p.Layout(),
604 OutputFormat: f.Name,
605 MediaType: f.MediaType.Type,
606 IsPlainText: f.IsPlainText,
607 }
608 }
609
610 func (ps *pageState) resolveTemplate(layouts ...string) (*tplimpl.TemplInfo, bool, error) {
611 pth, d := ps.GetInternalTemplateBasePathAndDescriptor()
612 var subPath string
613
614 if len(layouts) > 0 {
615 layout := layouts[0]
616 if i := strings.LastIndexByte(layout, '/'); i != -1 {
617 // A layout in a sub path, e.g. "foo/mylayout".
618 subPath, layout = layout[:i], layout[i+1:]
619 if layout == "" {
620 return nil, false, nil
621 }
622 }
623 d.LayoutFromUser = layout
624 d.LayoutFromUserMustMatch = true
625 }
626
627 q := tplimpl.TemplateQuery{
628 Path: pth,
629 SubPath: subPath,
630 Category: tplimpl.CategoryLayout,
631 Sites: ps.s.siteVector,
632 Desc: d,
633 }
634
635 tinfo := ps.s.TemplateStore.LookupPagesLayout(q)
636 if tinfo == nil {
637 return nil, false, nil
638 }
639
640 return tinfo, true, nil
641 }
642
643 // Must be run after the site section tree etc. is built and ready.
644 func (ps *pageState) initPage() error {
645 var initErr error
646 ps.pageInit.Do(func() {
647 var pp pagePaths
648 pp, initErr = newPagePaths(ps)
649 if initErr != nil {
650 return
651 }
652
653 var outputFormatsForPage output.Formats
654 var renderFormats output.Formats
655
656 if ps.m.standaloneOutputFormat.IsZero() {
657 outputFormatsForPage = ps.outputFormats()
658 renderFormats = ps.s.h.renderFormats
659 } else {
660 // One of the fixed output format pages, e.g. 404.
661 outputFormatsForPage = output.Formats{ps.m.standaloneOutputFormat}
662 renderFormats = outputFormatsForPage
663 }
664
665 // Prepare output formats for all sites.
666 // We do this even if this page does not get rendered on
667 // its own. It may be referenced via one of the site collections etc.
668 // it will then need an output format.
669 ps.pageOutputs = make([]*pageOutput, len(renderFormats))
670 created := make(map[string]*pageOutput)
671 shouldRenderPage := !ps.m.noRender()
672
673 for i, f := range renderFormats {
674
675 if po, found := created[f.Name]; found {
676 ps.pageOutputs[i] = po
677 continue
678 }
679
680 render := shouldRenderPage
681 if render {
682 _, render = outputFormatsForPage.GetByName(f.Name)
683 }
684
685 po := newPageOutput(ps, pp, f, render)
686
687 // Create a content provider for the first,
688 // we may be able to reuse it.
689 if i == 0 {
690 var contentProvider *pageContentOutput
691 contentProvider, initErr = newPageContentOutput(po)
692 if initErr != nil {
693 return
694 }
695 po.setContentProvider(contentProvider)
696 }
697
698 ps.pageOutputs[i] = po
699 created[f.Name] = po
700
701 }
702
703 if initErr = ps.initCommonProviders(pp); initErr != nil {
704 return
705 }
706 })
707
708 return initErr
709 }
710
711 func (ps *pageState) renderResources() error {
712 for _, r := range ps.Resources() {
713 if _, ok := r.(page.Page); ok {
714 if !ps.s.h.BuildState.IsRebuild() {
715 // Pages gets rendered with the owning page but we count them here.
716 ps.s.PathSpec.ProcessingStats.Incr(&ps.s.PathSpec.ProcessingStats.Pages)
717 }
718 continue
719 }
720
721 if resources.IsPublished(r) {
722 continue
723 }
724
725 src, ok := r.(resource.Source)
726 if !ok {
727 return fmt.Errorf("resource %T does not support resource.Source", r)
728 }
729
730 if err := src.Publish(); err != nil {
731 if !herrors.IsNotExist(err) {
732 ps.s.Log.Errorf("Failed to publish Resource for page %q: %s", ps.pathOrTitle(), err)
733 }
734 } else {
735 ps.s.PathSpec.ProcessingStats.Incr(&ps.s.PathSpec.ProcessingStats.Files)
736 }
737 }
738
739 return nil
740 }
741
742 func (ps *pageState) AlternativeOutputFormats() page.OutputFormats {
743 f := ps.outputFormat()
744 var o page.OutputFormats
745 for _, of := range ps.OutputFormats() {
746 if of.Format.NotAlternative || of.Format.Name == f.Name {
747 continue
748 }
749
750 o = append(o, of)
751 }
752 return o
753 }
754
755 type renderStringOpts struct {
756 Display string
757 Markup string
758 }
759
760 var defaultRenderStringOpts = renderStringOpts{
761 Display: "inline",
762 Markup: "", // Will inherit the page's value when not set.
763 }
764
765 func (m *pageMetaSource) wrapError(err error, sourceFs afero.Fs) error {
766 if err == nil {
767 panic("wrapError with nil")
768 }
769
770 if m.f == nil {
771 // No more details to add.
772 return fmt.Errorf("%q: %w", m.Path(), err)
773 }
774
775 return hugofs.AddFileInfoToError(err, m.f.FileInfo(), sourceFs)
776 }
777
778 // wrapError adds some more context to the given error if possible/needed
779 func (ps *pageState) wrapError(err error) error {
780 return ps.m.wrapError(err, ps.s.h.SourceFs)
781 }
782
783 func (ps *pageState) getPageInfoForError() string {
784 s := fmt.Sprintf("kind: %q, path: %q", ps.Kind(), ps.Path())
785 if ps.File() != nil {
786 s += fmt.Sprintf(", file: %q", ps.File().Filename())
787 }
788 return s
789 }
790
791 func (ps *pageState) getContentConverter() converter.Converter {
792 var err error
793 ps.contentConverterInit.Do(func() {
794 if ps.m.pageConfigSource.ContentMediaType.IsZero() {
795 panic("ContentMediaType not set")
796 }
797 markup := ps.m.pageConfigSource.ContentMediaType.SubType
798
799 if markup == "html" {
800 // Only reachable for shortcode inner content rendering; file-based
801 // HTML pages are gated at initFrontMatter via security.allowContent.
802 markup = "markdown"
803 }
804 ps.contentConverter, err = ps.m.newContentConverter(ps, markup)
805 })
806
807 if err != nil {
808 ps.s.Log.Errorln("Failed to create content converter:", err)
809 }
810 return ps.contentConverter
811 }
812
813 func (ps *pageState) errorf(err error, format string, a ...any) error {
814 if herrors.UnwrapFileError(err) != nil {
815 // More isn't always better.
816 return err
817 }
818 args := append([]any{ps.Language().Lang, ps.pathOrTitle()}, a...)
819 args = append(args, err)
820 format = "[%s] page %q: " + format + ": %w"
821 if err == nil {
822 return fmt.Errorf(format, args...)
823 }
824 return fmt.Errorf(format, args...)
825 }
826
827 func (ps *pageState) outputFormat() (f output.Format) {
828 if ps.pageOutput == nil {
829 panic("no pageOutput")
830 }
831 return ps.pageOutput.f
832 }
833
834 func (ps *pageState) parseError(err error, input []byte, offset int) error {
835 pos := posFromInput("", input, offset)
836 return herrors.NewFileErrorFromName(err, ps.File().Filename()).UpdatePosition(pos)
837 }
838
839 func (ps *pageState) pathOrTitle() string {
840 if ps.File() != nil {
841 return ps.File().Filename()
842 }
843
844 if ps.Path() != "" {
845 return ps.Path()
846 }
847
848 return ps.Title()
849 }
850
851 func (ps *pageState) posFromInput(input []byte, offset int) text.Position {
852 return posFromInput(ps.pathOrTitle(), input, offset)
853 }
854
855 func (ps *pageState) posOffset(offset int) text.Position {
856 return ps.posFromInput(ps.m.content.mustSource(), offset)
857 }
858
859 // shiftToOutputFormat is serialized. The output format idx refers to the
860 // full set of output formats for all sites.
861 // This is serialized.
862 func (ps *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error {
863 if err := ps.initPage(); err != nil {
864 return err
865 }
866
867 if len(ps.pageOutputs) == 1 {
868 idx = 0
869 }
870
871 ps.pageOutputIdx = idx
872 ps.pageOutput = ps.pageOutputs[idx]
873 if ps.pageOutput == nil {
874 panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx))
875 }
876
877 // Reset any built paginator. This will trigger when re-rendering pages in
878 // server mode.
879 if isRenderingSite && ps.pageOutput.paginator != nil && ps.pageOutput.paginator.current != nil {
880 ps.pageOutput.paginator.reset()
881 }
882
883 if isRenderingSite {
884 cp := ps.pageOutput.pco
885 if cp == nil && ps.canReusePageOutputContent() {
886 // Look for content to reuse.
887 for i := range ps.pageOutputs {
888 if i == idx {
889 continue
890 }
891 po := ps.pageOutputs[i]
892
893 if po.pco != nil {
894 cp = po.pco
895 break
896 }
897 }
898 }
899
900 if cp == nil {
901 var err error
902 cp, err = newPageContentOutput(ps.pageOutput)
903 if err != nil {
904 return err
905 }
906 }
907 ps.pageOutput.setContentProvider(cp)
908 } else {
909 // We attempt to assign pageContentOutputs while preparing each site
910 // for rendering and before rendering each site. This lets us share
911 // content between page outputs to conserve resources. But if a template
912 // unexpectedly calls a method of a ContentProvider that is not yet
913 // initialized, we assign a LazyContentProvider that performs the
914 // initialization just in time.
915 if lcp, ok := (ps.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok {
916 lcp.Reset()
917 } else {
918 lcp = page.NewLazyContentProvider(func(context.Context) page.OutputFormatContentProvider {
919 cp, err := newPageContentOutput(ps.pageOutput)
920 if err != nil {
921 panic(err)
922 }
923 return cp
924 })
925
926 ps.pageOutput.contentRenderer = lcp
927 ps.pageOutput.ContentProvider = lcp
928 ps.pageOutput.MarkupProvider = lcp
929 ps.pageOutput.PageRenderProvider = lcp
930 ps.pageOutput.TableOfContentsProvider = lcp
931 }
932 }
933
934 return nil
935 }
936
937 var (
938 _ page.Page = (*pageWithOrdinal)(nil)
939 _ collections.Order = (*pageWithOrdinal)(nil)
940 _ pageWrapper = (*pageWithOrdinal)(nil)
941 )
942
943 type pageWithOrdinal struct {
944 ordinal int
945 *pageState
946 }
947
948 func (p pageWithOrdinal) Ordinal() int {
949 return p.ordinal
950 }
951
952 func (p pageWithOrdinal) page() page.Page {
953 return p.pageState
954 }
955
956 type pageWithWeight0 struct {
957 weight0 int
958 *pageState
959 }
960
961 func (p pageWithWeight0) Weight0() int {
962 return p.weight0
963 }
964
965 func (p pageWithWeight0) page() page.Page {
966 return p.pageState
967 }
968
969 var _ types.Unwrapper = (*pageWithWeight0)(nil)
970
971 func (p pageWithWeight0) Unwrapv() any {
972 return p.pageState
973 }