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