repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page.go
hugolib/page.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "fmt" "iter" "path/filepath" "slices" "strconv" "strings" "sync/atomic" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugolib/segments" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/related" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/tpl/tplimpl" "github.com/spf13/afero" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) _ identity.DependencyManagerScopedProvider = (*pageState)(nil) _ pageContext = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.Builtin.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, MarkupProvider: page.NopPage, ContentProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter } type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPage(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // Incremented for each new page created. // Note that this will change between builds for a given Page. pid uint64 s *Site // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // Used to determine if we can reuse content across output formats. pageOutputTemplateVariationsState atomic.Uint32 // This will be shifted out when we start to render a new output format. pageOutputIdx int *pageOutput // Common for all output formats. *pageCommon resource.Staler dependencyManager identity.Manager } // This is not accurate and only used for progress reporting. // We can do better, but this will do for now. func (p *pageState) hasRenderableOutput() bool { for _, po := range p.pageOutputs { if po.render { return true } } return false } func (p *pageState) incrPageOutputTemplateVariation() { p.pageOutputTemplateVariationsState.Add(1) } func (ps *pageState) canReusePageOutputContent() bool { return ps.pageOutputTemplateVariationsState.Load() == 1 } func (ps *pageState) IdentifierBase() string { return ps.Path() } func (ps *pageState) GetIdentity() identity.Identity { return ps } func (ps *pageState) ForEeachIdentity(f func(identity.Identity) bool) bool { return f(ps) } func (ps *pageState) GetDependencyManager() identity.Manager { return ps.dependencyManager } func (ps *pageState) GetDependencyManagerForScope(scope int) identity.Manager { switch scope { case pageDependencyScopeDefault: return ps.dependencyManagerOutput case pageDependencyScopeGlobal: return ps.dependencyManager default: return identity.NopManager } } func (ps *pageState) GetDependencyManagerForScopesAll() []identity.Manager { return []identity.Manager{ps.dependencyManager, ps.dependencyManagerOutput} } // Param is a convenience method to do lookups in Page's and Site's Params map, // in that order. // // This method is also implemented on SiteInfo. func (ps *pageState) Param(key any) (any, error) { return resource.Param(ps, ps.s.Params(), key) } func (ps *pageState) Key() string { return "page-" + strconv.FormatUint(ps.pid, 10) } // RelatedKeywords implements the related.Document interface needed for fast page searches. func (ps *pageState) RelatedKeywords(cfg related.IndexConfig) ([]related.Keyword, error) { v, found, err := page.NamedPageMetaValue(ps, cfg.Name) if err != nil { return nil, err } if !found { return nil, nil } return cfg.ToKeywords(v) } func (ps *pageState) resetBuildState() { ps.m.prepareRebuild() } func (ps *pageState) skipRender() bool { b := ps.s.conf.Segments.Config.SegmentFilter.ShouldExcludeFine( segments.SegmentQuery{ Path: ps.Path(), Kind: ps.Kind(), Site: ps.s.siteVector, Output: ps.pageOutput.f.Name, }, ) return b } func (ps *pageState) isRenderedAny() bool { for _, o := range ps.pageOutputs { if o.isRendered() { return true } } return false } // Implements contentNode. func (ps *pageState) forEeachContentNode(f func(v sitesmatrix.Vector, n contentNode) bool) bool { return f(ps.s.siteVector, ps) } func (ps *pageState) contentWeight() int { if ps.m.f == nil { return 0 } return ps.m.f.FileInfo().Meta().Weight } func (ps *pageState) nodeSourceEntryID() any { return ps.m.nodeSourceEntryID() } func (ps *pageState) nodeCategoryPage() { // Marker method. } func (m *pageState) nodeCategorySingle() { // Marker method. } func (ps *pageState) lookupContentNode(v sitesmatrix.Vector) contentNode { pc := ps.m.pageConfigSource if pc.MatchSiteVector(v) { return ps } return nil } func (ps *pageState) lookupContentNodes(vec sitesmatrix.Vector, fallback bool) iter.Seq[contentNodeForSite] { nop := func(yield func(n contentNodeForSite) bool) {} pc := ps.m.pageConfigSource if !fallback { if !pc.MatchSiteVector(vec) { return nop } return func(yield func(n contentNodeForSite) bool) { yield(ps) } } if !pc.MatchLanguageCoarse(vec) { return nop } if !pc.MatchVersionCoarse(vec) { return nop } if !pc.MatchRoleCoarse(vec) { return nop } return func(yield func(n contentNodeForSite) bool) { yield(ps) } } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (ps *pageState) Eq(other any) bool { pp, err := unwrapPage(other) if err != nil { return false } return ps == pp } func (ps *pageState) HeadingsFiltered(context.Context) tableofcontents.Headings { return nil } type pageHeadingsFiltered struct { *pageState headings tableofcontents.Headings } func (p *pageHeadingsFiltered) HeadingsFiltered(context.Context) tableofcontents.Headings { return p.headings } func (p *pageHeadingsFiltered) page() page.Page { return p.pageState } // For internal use by the related content feature. func (ps *pageState) ApplyFilterToHeadings(ctx context.Context, fn func(*tableofcontents.Heading) bool) related.Document { fragments := ps.pageOutput.pco.c().Fragments(ctx) headings := fragments.Headings.FilterBy(fn) return &pageHeadingsFiltered{ pageState: ps, headings: headings, } } func (ps *pageState) GitInfo() *source.GitInfo { return ps.gitInfo } func (ps *pageState) CodeOwners() []string { return ps.codeowners } // GetTerms gets the terms defined on this page in the given taxonomy. // The pages returned will be ordered according to the front matter. func (ps *pageState) GetTerms(taxonomy string) page.Pages { return ps.s.pageMap.getTermsForPageInTaxonomy(ps.Path(), taxonomy) } func (ps *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(ps) } func (ps *pageState) RegularPagesRecursive() page.Pages { switch ps.Kind() { case kinds.KindSection, kinds.KindHome: return ps.s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ Path: ps.Path(), Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(), }, Recursive: true, }, ) default: return ps.RegularPages() } } func (ps *pageState) PagesRecursive() page.Pages { return nil } func (ps *pageState) RegularPages() page.Pages { switch ps.Kind() { case kinds.KindPage: case kinds.KindSection, kinds.KindHome, kinds.KindTaxonomy: return ps.s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ Path: ps.Path(), Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(), }, }, ) case kinds.KindTerm: return ps.s.pageMap.getPagesWithTerm( pageMapQueryPagesBelowPath{ Path: ps.Path(), Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(), }, ) default: return ps.s.RegularPages() } return nil } func (ps *pageState) Pages() page.Pages { switch ps.Kind() { case kinds.KindPage: case kinds.KindSection, kinds.KindHome: return ps.s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ Path: ps.Path(), KeyPart: "page-section", Include: pagePredicates.ShouldListLocal.And( pagePredicates.KindPage.Or(pagePredicates.KindSection), ).BoolFunc(), }, }, ) case kinds.KindTerm: return ps.s.pageMap.getPagesWithTerm( pageMapQueryPagesBelowPath{ Path: ps.Path(), }, ) case kinds.KindTaxonomy: return ps.s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ Path: ps.Path(), KeyPart: "term", Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindTerm).BoolFunc(), }, Recursive: true, }, ) default: return ps.s.Pages() } return nil } // RawContent returns the un-rendered source content without // any leading front matter. func (ps *pageState) RawContent() string { if ps.m.content.pi.itemsStep2 == nil { return "" } start := ps.m.content.pi.posMainContent if start == -1 { start = 0 } source, err := ps.m.content.pi.contentSource(ps.m.content) if err != nil { panic(err) } return string(source[start:]) } func (ps *pageState) Resources() resource.Resources { return ps.s.pageMap.getOrCreateResourcesForPage(ps) } func (ps *pageState) HasShortcode(name string) bool { p := ps.m.content.hasShortcode.Load() if p == nil { return false } hasShortcode := *p return hasShortcode(name) } func (ps *pageState) Site() page.Site { return ps.s.siteWrapped } func (ps *pageState) String() string { var sb strings.Builder if ps.File() != nil { // The forward slashes even on Windows is motivated by // getting stable tests. // This information is meant for getting positional information in logs, // so the direction of the slashes should not matter. sb.WriteString(filepath.ToSlash(ps.File().Filename())) if ps.File().IsContentAdapter() { // Also include the path. sb.WriteString(":") sb.WriteString(ps.Path()) } } else { sb.WriteString(ps.Path()) } return sb.String() } // IsTranslated returns whether this content file is translated to // other language(s). func (ps *pageState) IsTranslated() bool { return len(ps.Translations()) > 0 } // TranslationKey returns the key used to identify a translation of this content. func (ps *pageState) TranslationKey() string { if ps.m.pageConfig.TranslationKey != "" { return ps.m.pageConfig.TranslationKey } return ps.Path() } // AllTranslations returns all translations, including the current Page. func (ps *pageState) AllTranslations() page.Pages { key := ps.Path() + "/" + "translations-all" // This is called from Translations, so we need to use a different partition, cachePages2, // to avoid potential deadlocks. pages, err := ps.s.pageMap.getOrCreatePagesFromCache(ps.s.pageMap.cachePages2, key, func(string) (page.Pages, error) { if ps.m.pageConfig.TranslationKey != "" { // translationKey set by user. pas, _ := ps.s.h.translationKeyPages.Get(ps.m.pageConfig.TranslationKey) pasc := slices.Clone(pas) page.SortByLanguage(pasc) return pasc, nil } var pas page.Pages ps.s.pageMap.treePages.ForEeachInDimension(ps.Path(), ps.s.siteVector, sitesmatrix.Language, func(n contentNode) bool { if n != nil { pas = append(pas, n.(page.Page)) } return true }, ) pas = pagePredicates.ShouldLink.Filter(pas) page.SortByLanguage(pas) return pas, nil }) if err != nil { panic(err) } return pages } // For internal use only. func (ps *pageState) SiteVector() sitesmatrix.Vector { return ps.s.siteVector } func (ps *pageState) siteVector() sitesmatrix.Vector { return ps.s.siteVector } func (ps *pageState) siteVectors() sitesmatrix.VectorIterator { return ps.s.siteVector } // Rotate returns all pages in the given dimension for this page. func (ps *pageState) Rotate(dimensionStr string) (page.Pages, error) { dimensionStr = strings.ToLower(dimensionStr) key := ps.Path() + "/" + "rotate-" + dimensionStr d, err := sitesmatrix.ParseDimension(dimensionStr) if err != nil { return nil, fmt.Errorf("failed to parse dimension %q: %w", dimensionStr, err) } pages, err := ps.s.pageMap.getOrCreatePagesFromCache(ps.s.pageMap.cachePages2, key, func(string) (page.Pages, error) { var pas page.Pages ps.s.pageMap.treePages.ForEeachInDimension(ps.Path(), ps.s.siteVector, d, func(n contentNode) bool { if n != nil { p := n.(page.Page) pas = append(pas, p) } return true }, ) if dimensionStr == "language" && ps.m.pageConfig.TranslationKey != "" { // translationKey set by user. // This is an old construct back from when languages were introduced. // We keep it for backward compatibility. // Also see AllTranslations. pas, _ := ps.s.h.translationKeyPages.Get(ps.m.pageConfig.TranslationKey) pasc := slices.Clone(pas) page.SortByLanguage(pasc) return pasc, nil } pas = pagePredicates.ShouldLink.Filter(pas) page.SortByDims(pas) return pas, nil }) return pages, err } // Translations returns the translations excluding the current Page. func (ps *pageState) Translations() page.Pages { key := ps.Path() + "/" + "translations" pages, err := ps.s.pageMap.getOrCreatePagesFromCache(nil, key, func(string) (page.Pages, error) { var pas page.Pages for _, pp := range ps.AllTranslations() { if !pp.Eq(ps) { pas = append(pas, pp) } } return pas, nil }) if err != nil { panic(err) } return pages } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { if ps.s == nil { panic("no site") } ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s return nil } // Exported so it can be used in integration tests. func (po *pageOutput) GetInternalTemplateBasePathAndDescriptor() (string, tplimpl.TemplateDescriptor) { p := po.p f := po.f base := p.PathInfo().BaseReTyped(p.m.pageConfig.Type) return base, tplimpl.TemplateDescriptor{ Kind: p.Kind(), LayoutFromUser: p.Layout(), OutputFormat: f.Name, MediaType: f.MediaType.Type, IsPlainText: f.IsPlainText, } } func (ps *pageState) resolveTemplate(layouts ...string) (*tplimpl.TemplInfo, bool, error) { dir, d := ps.GetInternalTemplateBasePathAndDescriptor() if len(layouts) > 0 { d.LayoutFromUser = layouts[0] d.LayoutFromUserMustMatch = true } q := tplimpl.TemplateQuery{ Path: dir, Category: tplimpl.CategoryLayout, Sites: ps.s.siteVector, Desc: d, } tinfo := ps.s.TemplateStore.LookupPagesLayout(q) if tinfo == nil { return nil, false, nil } return tinfo, true, nil } // Must be run after the site section tree etc. is built and ready. func (ps *pageState) initPage() error { var initErr error ps.pageInit.Do(func() { var pp pagePaths pp, initErr = newPagePaths(ps) if initErr != nil { return } var outputFormatsForPage output.Formats var renderFormats output.Formats if ps.m.standaloneOutputFormat.IsZero() { outputFormatsForPage = ps.outputFormats() renderFormats = ps.s.h.renderFormats } else { // One of the fixed output format pages, e.g. 404. outputFormatsForPage = output.Formats{ps.m.standaloneOutputFormat} renderFormats = outputFormatsForPage } // Prepare output formats for all sites. // We do this even if this page does not get rendered on // its own. It may be referenced via one of the site collections etc. // it will then need an output format. ps.pageOutputs = make([]*pageOutput, len(renderFormats)) created := make(map[string]*pageOutput) shouldRenderPage := !ps.m.noRender() for i, f := range renderFormats { if po, found := created[f.Name]; found { ps.pageOutputs[i] = po continue } render := shouldRenderPage if render { _, render = outputFormatsForPage.GetByName(f.Name) } po := newPageOutput(ps, pp, f, render) // Create a content provider for the first, // we may be able to reuse it. if i == 0 { var contentProvider *pageContentOutput contentProvider, initErr = newPageContentOutput(po) if initErr != nil { return } po.setContentProvider(contentProvider) } ps.pageOutputs[i] = po created[f.Name] = po } if initErr = ps.initCommonProviders(pp); initErr != nil { return } }) return initErr } func (ps *pageState) renderResources() error { for _, r := range ps.Resources() { if _, ok := r.(page.Page); ok { if ps.s.h.buildCounter.Load() == 0 { // Pages gets rendered with the owning page but we count them here. ps.s.PathSpec.ProcessingStats.Incr(&ps.s.PathSpec.ProcessingStats.Pages) } continue } if resources.IsPublished(r) { continue } src, ok := r.(resource.Source) if !ok { return fmt.Errorf("resource %T does not support resource.Source", r) } if err := src.Publish(); err != nil { if !herrors.IsNotExist(err) { ps.s.Log.Errorf("Failed to publish Resource for page %q: %s", ps.pathOrTitle(), err) } } else { ps.s.PathSpec.ProcessingStats.Incr(&ps.s.PathSpec.ProcessingStats.Files) } } return nil } func (ps *pageState) AlternativeOutputFormats() page.OutputFormats { f := ps.outputFormat() var o page.OutputFormats for _, of := range ps.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defaultRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (m *pageMetaSource) wrapError(err error, sourceFs afero.Fs) error { if err == nil { panic("wrapError with nil") } if m.f == nil { // No more details to add. return fmt.Errorf("%q: %w", m.Path(), err) } return hugofs.AddFileInfoToError(err, m.f.FileInfo(), sourceFs) } // wrapError adds some more context to the given error if possible/needed func (ps *pageState) wrapError(err error) error { return ps.m.wrapError(err, ps.s.h.SourceFs) } func (ps *pageState) getPageInfoForError() string { s := fmt.Sprintf("kind: %q, path: %q", ps.Kind(), ps.Path()) if ps.File() != nil { s += fmt.Sprintf(", file: %q", ps.File().Filename()) } return s } func (ps *pageState) getContentConverter() converter.Converter { var err error ps.contentConverterInit.Do(func() { if ps.m.pageConfigSource.ContentMediaType.IsZero() { panic("ContentMediaType not set") } markup := ps.m.pageConfigSource.ContentMediaType.SubType if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } ps.contentConverter, err = ps.m.newContentConverter(ps, markup) }) if err != nil { ps.s.Log.Errorln("Failed to create content converter:", err) } return ps.contentConverter } func (ps *pageState) errorf(err error, format string, a ...any) error { if herrors.UnwrapFileError(err) != nil { // More isn't always better. return err } args := append([]any{ps.Language().Lang, ps.pathOrTitle()}, a...) args = append(args, err) format = "[%s] page %q: " + format + ": %w" if err == nil { return fmt.Errorf(format, args...) } return fmt.Errorf(format, args...) } func (ps *pageState) outputFormat() (f output.Format) { if ps.pageOutput == nil { panic("no pageOutput") } return ps.pageOutput.f } func (ps *pageState) parseError(err error, input []byte, offset int) error { pos := posFromInput("", input, offset) return herrors.NewFileErrorFromName(err, ps.File().Filename()).UpdatePosition(pos) } func (ps *pageState) pathOrTitle() string { if ps.File() != nil { return ps.File().Filename() } if ps.Path() != "" { return ps.Path() } return ps.Title() } func (ps *pageState) posFromInput(input []byte, offset int) text.Position { return posFromInput(ps.pathOrTitle(), input, offset) } func (ps *pageState) posOffset(offset int) text.Position { return ps.posFromInput(ps.m.content.mustSource(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. // This is serialized. func (ps *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := ps.initPage(); err != nil { return err } if len(ps.pageOutputs) == 1 { idx = 0 } ps.pageOutputIdx = idx ps.pageOutput = ps.pageOutputs[idx] if ps.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && ps.pageOutput.paginator != nil && ps.pageOutput.paginator.current != nil { ps.pageOutput.paginator.reset() } if isRenderingSite { cp := ps.pageOutput.pco if cp == nil && ps.canReusePageOutputContent() { // Look for content to reuse. for i := range ps.pageOutputs { if i == idx { continue } po := ps.pageOutputs[i] if po.pco != nil { cp = po.pco break } } } if cp == nil { var err error cp, err = newPageContentOutput(ps.pageOutput) if err != nil { return err } } ps.pageOutput.setContentProvider(cp) } else { // We attempt to assign pageContentOutputs while preparing each site // for rendering and before rendering each site. This lets us share // content between page outputs to conserve resources. But if a template // unexpectedly calls a method of a ContentProvider that is not yet // initialized, we assign a LazyContentProvider that performs the // initialization just in time. if lcp, ok := (ps.pageOutput.ContentProvider.(*page.LazyContentProvider)); ok { lcp.Reset() } else { lcp = page.NewLazyContentProvider(func(context.Context) page.OutputFormatContentProvider { cp, err := newPageContentOutput(ps.pageOutput) if err != nil { panic(err) } return cp }) ps.pageOutput.contentRenderer = lcp ps.pageOutput.ContentProvider = lcp ps.pageOutput.MarkupProvider = lcp ps.pageOutput.PageRenderProvider = lcp ps.pageOutput.TableOfContentsProvider = lcp } } return nil } var ( _ page.Page = (*pageWithOrdinal)(nil) _ collections.Order = (*pageWithOrdinal)(nil) _ pageWrapper = (*pageWithOrdinal)(nil) ) type pageWithOrdinal struct { ordinal int *pageState } func (p pageWithOrdinal) Ordinal() int { return p.ordinal } func (p pageWithOrdinal) page() page.Page { return p.pageState } type pageWithWeight0 struct { weight0 int *pageState } func (p pageWithWeight0) Weight0() int { return p.weight0 } func (p pageWithWeight0) page() page.Page { return p.pageState } var _ types.Unwrapper = (*pageWithWeight0)(nil) func (p pageWithWeight0) Unwrapv() any { return p.pageState }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__data.go
hugolib/page__data.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "strings" "sync" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" ) type dataFunc func() any func (f dataFunc) Data() any { return f() } func newDataFunc(p *pageState) dataFunc { return sync.OnceValue(func() any { data := make(page.Data) if p.Kind() == kinds.KindPage { return data } switch p.Kind() { case kinds.KindTerm: path := p.Path() name := p.s.pageMap.cfg.getTaxonomyConfig(path) term := p.s.Taxonomies()[name.plural].Get(strings.TrimPrefix(path, name.pluralTreeKey)) data[name.singular] = term data["Singular"] = name.singular data["Plural"] = name.plural data["Term"] = p.m.term case kinds.KindTaxonomy: viewCfg := p.s.pageMap.cfg.getTaxonomyConfig(p.Path()) data["Singular"] = viewCfg.singular data["Plural"] = viewCfg.plural data["Terms"] = p.s.Taxonomies()[viewCfg.plural] // keep the following just for legacy reasons data["OrderedIndex"] = data["Terms"] data["Index"] = data["Terms"] } // Assign the function to the map to make sure it is lazily initialized data["pages"] = p.Pages return data }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/rendershortcodes_test.go
hugolib/rendershortcodes_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "path/filepath" "strings" "testing" ) func TestRenderShortcodesBasic(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["home", "taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- ## p1-h1 {{% include "p2" %}} -- content/p2.md -- --- title: "p2" --- ### p2-h1 {{< withhtml >}} ### p2-h2 {{% withmarkdown %}} ### p2-h3 {{% include "p3" %}} -- content/p3.md -- --- title: "p3" --- ### p3-h1 {{< withhtml >}} ### p3-h2 {{% withmarkdown %}} {{< level3 >}} -- layouts/_shortcodes/include.html -- {{ $p := site.GetPage (.Get 0) }} {{ $p.RenderShortcodes }} -- layouts/_shortcodes/withhtml.html -- <div>{{ .Page.Title }} withhtml</div> -- layouts/_shortcodes/withmarkdown.html -- #### {{ .Page.Title }} withmarkdown -- layouts/_shortcodes/level3.html -- Level 3: {{ .Page.Title }} -- layouts/single.html -- Fragments: {{ .Fragments.Identifiers }}| HasShortcode Level 1: {{ .HasShortcode "include" }}| HasShortcode Level 2: {{ .HasShortcode "withmarkdown" }}| HasShortcode Level 3: {{ .HasShortcode "level3" }}| HasShortcode not found: {{ .HasShortcode "notfound" }}| Content: {{ .Content }}| ` b := Test(t, files) b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/p1/index.html", "Fragments: [p1-h1 p2-h1 p2-h2 p2-h3 p2-withmarkdown p3-h1 p3-h2 p3-withmarkdown]|", "HasShortcode Level 1: true|", "HasShortcode Level 2: true|", "HasShortcode Level 3: true|", "HasShortcode not found: false|", ) } func TestRenderShortcodesNestedMultipleOutputFormatTemplates(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["home", "taxonomy", "term", "section", "rss", "sitemap", "robotsTXT", "404"] [outputs] page = ["html", "json"] -- content/p1.md -- --- title: "p1" --- ## p1-h1 {{% include "p2" %}} -- content/p2.md -- --- title: "p2" --- ### p2-h1 {{% myshort %}} -- layouts/_shortcodes/include.html -- {{ $p := site.GetPage (.Get 0) }} {{ $p.RenderShortcodes }} -- layouts/_shortcodes/myshort.html -- Myshort HTML. -- layouts/_shortcodes/myshort.json -- Myshort JSON. -- layouts/single.html -- HTML: {{ .Content }} -- layouts/single.json -- JSON: {{ .Content }} ` b := Test(t, files) b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/p1/index.html", "Myshort HTML") b.AssertFileContent("public/p1/index.json", "Myshort JSON") } func TestRenderShortcodesEditNested(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true disableKinds = ["home", "taxonomy", "term", "section", "rss", "sitemap", "robotsTXT", "404"] -- content/p1.md -- --- title: "p1" --- ## p1-h1 {{% include "p2" %}} -- content/p2.md -- --- title: "p2" --- ### p2-h1 {{% myshort %}} -- layouts/_shortcodes/include.html -- {{ $p := site.GetPage (.Get 0) }} {{ $p.RenderShortcodes }} -- layouts/_shortcodes/myshort.html -- Myshort Original. -- layouts/single.html -- {{ .Content }} ` b := TestRunning(t, files) b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/p1/index.html", "Myshort Original.") b.EditFileReplaceAll("layouts/_shortcodes/myshort.html", "Original", "Edited").Build() b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/p1/index.html", "Myshort Edited.") } func TestRenderShortcodesEditIncludedPage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true disableKinds = ["home", "taxonomy", "term", "section", "rss", "sitemap", "robotsTXT", "404"] -- content/p1.md -- --- title: "p1" --- ## p1-h1 {{% include "p2" %}} -- content/p2.md -- --- title: "p2" --- ### Original {{% myshort %}} -- layouts/_shortcodes/include.html -- {{ $p := site.GetPage (.Get 0) }} {{ $p.RenderShortcodes }} -- layouts/_shortcodes/myshort.html -- Myshort Original. -- layouts/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/p1/index.html", "Original") b.EditFileReplaceFunc("content/p2.md", func(s string) string { return strings.Replace(s, "Original", "Edited", 1) }) b.Build() b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/p1/index.html", "Edited") } func TestRenderShortcodesEditSectionContentWithShortcodeInIncludedPageIssue12458(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true disableKinds = ["home", "taxonomy", "term", "rss", "sitemap", "robotsTXT", "404"] -- content/mysection/_index.md -- --- title: "My Section" --- ## p1-h1 {{% include "p2" %}} -- content/mysection/p2.md -- --- title: "p2" --- ### Original {{% myshort %}} -- layouts/_shortcodes/include.html -- {{ $p := .Page.GetPage (.Get 0) }} {{ $p.RenderShortcodes }} -- layouts/_shortcodes/myshort.html -- Myshort Original. -- layouts/list.html -- {{ .Content }} ` b := TestRunning(t, files) b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/mysection/index.html", "p1-h1") b.EditFileReplaceAll("content/mysection/_index.md", "p1-h1", "p1-h1 Edited").Build() b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/mysection/index.html", "p1-h1 Edited") } func TestRenderShortcodesNestedPageContextIssue12356(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap", "robotsTXT", "404"] -- layouts/_markup/render-image.html -- {{- with .PageInner.Resources.Get .Destination -}}Image: {{ .RelPermalink }}|{{- end -}} -- layouts/_markup/render-link.html -- {{- with .PageInner.GetPage .Destination -}}Link: {{ .RelPermalink }}|{{- end -}} -- layouts/_markup/render-heading.html -- Heading: {{ .PageInner.Title }}: {{ .PlainText }}| -- layouts/_markup/render-codeblock.html -- CodeBlock: {{ .PageInner.Title }}: {{ .Type }}| -- layouts/list.html -- Content:{{ .Content }}| Fragments: {{ with .Fragments }}{{.Identifiers }}{{ end }}| -- layouts/single.html -- Content:{{ .Content }}| -- layouts/_shortcodes/include.html -- {{ with site.GetPage (.Get 0) }} {{ .RenderShortcodes }} {{ end }} -- content/markdown/_index.md -- --- title: "Markdown" --- # H1 |{{% include "/posts/p1" %}}| ![kitten](pixel3.png "Pixel 3") §§§go fmt.Println("Hello") §§§ -- content/markdown2/_index.md -- --- title: "Markdown 2" --- |{{< include "/posts/p1" >}}| -- content/html/_index.html -- --- title: "HTML" --- |{{% include "/posts/p1" %}}| -- content/posts/p1/index.md -- --- title: "p1" --- ## H2-p1 ![kitten](pixel1.png "Pixel 1") ![kitten](pixel2.png "Pixel 2") [p2](p2) §§§bash echo "Hello" §§§ -- content/posts/p2/index.md -- --- title: "p2" --- -- content/posts/p1/pixel1.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- content/posts/p1/pixel2.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- content/markdown/pixel3.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- content/html/pixel4.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== ` b := Test(t, files) b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/markdown/index.html", // Images. "Image: /posts/p1/pixel1.png|\nImage: /posts/p1/pixel2.png|\n|\nImage: /markdown/pixel3.png|</p>\n|", // Links. "Link: /posts/p2/|", // Code blocks "CodeBlock: p1: bash|", "CodeBlock: Markdown: go|", // Headings. "Heading: Markdown: H1|", "Heading: p1: H2-p1|", // Fragments. "Fragments: [h1 h2-p1]|", // Check that the special context markup is not rendered. "! hugo_ctx", ) b.AssertFileContent("public/markdown2/index.html", "! hugo_ctx", "Content:<p>|\n ![kitten](pixel1.png \"Pixel 1\")\n![kitten](pixel2.png \"Pixel 2\")\n|</p>\n|") b.AssertFileContent("public/html/index.html", "! hugo_ctx") } // Issue 12854. func TestRenderShortcodesWithHTML(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true disableKinds = ["home", "taxonomy", "term"] markup.goldmark.renderer.unsafe = true -- content/p1.md -- --- title: "p1" --- {{% include "p2" %}} -- content/p2.md -- --- title: "p2" --- Hello <b>world</b>. Some **bold** text. Some Unicode: 神真美好. -- layouts/_shortcodes/include.html -- {{ with site.GetPage (.Get 0) }} <div>{{ .RenderShortcodes }}</div> {{ end }} -- layouts/single.html -- {{ .Content }} ` b := TestRunning(t, files, TestOptWarn()) b.AssertNoRenderShortcodesArtifacts() b.AssertLogContains(filepath.ToSlash("WARN .RenderShortcodes detected inside HTML block in \"/content/p1.md\"; this may not be what you intended, see https://gohugo.io/methods/page/rendershortcodes/#limitations\nYou can suppress this warning by adding the following to your site configuration:\nignoreLogs = ['warning-rendershortcodes-in-html']")) b.AssertFileContent("public/p1/index.html", "<div>Hello <b>world</b>. Some **bold** text. Some Unicode: 神真美好.\n</div>") b.EditFileReplaceAll("content/p2.md", "Hello", "Hello Edited").Build() b.AssertNoRenderShortcodesArtifacts() b.AssertFileContent("public/p1/index.html", "<div>Hello Edited <b>world</b>. Some **bold** text. Some Unicode: 神真美好.\n</div>") } func TestRenderShortcodesIncludeMarkdownFileWithoutTrailingNewline(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true disableKinds = ["home", "taxonomy", "term"] markup.goldmark.renderer.unsafe = true -- content/p1.md -- --- title: "p1" --- Content p1 id-1000.{{% include "p2" %}}{{% include "p3" %}} §§§ go code_p1 §§§ §§§ go code_p1_2 §§§ §§§ go code_p1_3 §§§ -- content/p2.md -- --- title: "p2" --- §§§ bash code_p2 §§§ Foo. -- content/p3.md -- --- title: "p3" --- §§§ php code_p3 §§§ -- layouts/_shortcodes/include.html -- {{ with site.GetPage (.Get 0) -}} {{ .RenderShortcodes -}} {{ end -}} -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-codeblock.html -- <code>{{ .Inner | safeHTML }}</code> ` b := TestRunning(t, files, TestOptWarn()) b.AssertNoRenderShortcodesArtifacts() b.AssertFileContentEquals("public/p1/index.html", "<p>Content p1 id-1000.</p>\n<code>code_p2</code><p>Foo.</p>\n<code>code_p3</code><code>code_p1</code><code>code_p1_2</code><code>code_p1_3</code>") b.EditFileReplaceAll("content/p1.md", "id-1000.", "id-100.").Build() b.AssertNoRenderShortcodesArtifacts() b.AssertFileContentEquals("public/p1/index.html", "<p>Content p1 id-100.</p>\n<code>code_p2</code><p>Foo.</p>\n<code>code_p3</code><code>code_p1</code><code>code_p1_2</code><code>code_p1_3</code>") b.EditFileReplaceAll("content/p2.md", "code_p2", "codep2").Build() b.AssertNoRenderShortcodesArtifacts() b.AssertFileContentEquals("public/p1/index.html", "<p>Content p1 id-100.</p>\n<code>codep2</code><p>Foo.</p>\n<code>code_p3</code><code>code_p1</code><code>code_p1_2</code><code>code_p1_3</code>") b.EditFileReplaceAll("content/p3.md", "code_p3", "code_p3_edited").Build() b.AssertNoRenderShortcodesArtifacts() b.AssertFileContentEquals("public/p1/index.html", "<p>Content p1 id-100.</p>\n<code>codep2</code><p>Foo.</p>\n<code>code_p3_edited</code><code>code_p1</code><code>code_p1_2</code><code>code_p1_3</code>") } // Issue 13004. func TestRenderShortcodesIncludeShortRefEdit(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true disableKinds = ["home", "taxonomy", "term", "section", "rss", "sitemap", "robotsTXT", "404"] -- content/first/p1.md -- --- title: "p1" --- ## p1-h1 {{% include "p2" %}} -- content/second/p2.md -- --- title: "p2" --- ### p2-h1 This is some **markup**. -- layouts/_shortcodes/include.html -- {{ $p := site.GetPage (.Get 0) -}} {{ $p.RenderShortcodes -}} -- layouts/single.html -- {{ .Content }} ` b := TestRunning(t, files) b.AssertNoRenderShortcodesArtifacts() b.AssertFileContentEquals("public/first/p1/index.html", "<h2 id=\"p1-h1\">p1-h1</h2>\n<h3 id=\"p2-h1\">p2-h1</h3>\n<p>This is some <strong>markup</strong>.</p>\n") b.EditFileReplaceAll("content/second/p2.md", "p2-h1", "p2-h1-edited").Build() b.AssertNoRenderShortcodesArtifacts() b.AssertFileContentEquals("public/first/p1/index.html", "<h2 id=\"p1-h1\">p1-h1</h2>\n<h3 id=\"p2-h1-edited\">p2-h1-edited</h3>\n<p>This is some <strong>markup</strong>.</p>\n") } // Issue 13051. func TestRenderShortcodesEmptyParagraph(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['section','rss','sitemap','taxonomy','term'] -- layouts/home.html -- {{ .Content }} -- layouts/single.html -- {{ .Content }} -- layouts/_shortcodes/include.html -- {{ with site.GetPage (.Get 0) }} {{ .RenderShortcodes }} {{ end }} -- content/_index.md -- --- title: home --- a {{% include "/snippet" %}} b -- content/snippet.md -- --- title: snippet build: render: never list: never --- _emphasized_ not emphasized ` b := Test(t, files) b.AssertNoRenderShortcodesArtifacts() b.AssertFileContentEquals("public/index.html", "<p>a</p>\n<p><em>emphasized</em></p>\n<p>not emphasized</p>\n<p>b</p>\n", ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/pagecollections_test.go
hugolib/pagecollections_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "path/filepath" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" ) type getPageTest struct { name string kind string context page.Page pathVariants []string expectedTitle string } func (t *getPageTest) check(p page.Page, err error, errorMsg string, c *qt.C) { c.Helper() errorComment := qt.Commentf(errorMsg) switch t.kind { case "Ambiguous": c.Assert(err, qt.Not(qt.IsNil)) c.Assert(p, qt.IsNil, errorComment) case "NoPage": c.Assert(err, qt.IsNil) c.Assert(p, qt.IsNil, errorComment) default: c.Assert(err, qt.IsNil, errorComment) c.Assert(p, qt.Not(qt.IsNil), errorComment) c.Assert(p.Kind(), qt.Equals, t.kind, errorComment) c.Assert(p.Title(), qt.Equals, t.expectedTitle, errorComment) } } func TestGetPage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- layouts/single.html -- {{ .Title }} -- layouts/list.html -- {{ .Title }} -- content/_index.md -- --- title: "home page" categories: - Hugo --- # Doc -- content/about.md -- --- title: "about page" categories: - Hugo --- # Doc -- content/sect0/page1.md -- --- title: "Title0_1" categories: - Hugo --- # Doc -- content/sect1/page1.md -- --- title: "Title1_1" categories: - Hugo --- # Doc -- content/sect2/_index.md -- --- title: "Section 2" categories: - Hugo --- # Doc -- content/sect3/_index.md -- --- title: "section 3" categories: - Hugo --- # Doc -- content/sect3/page1.md -- --- title: "Title3_1" categories: - Hugo --- # Doc -- content/sect3/unique.md -- --- title: "UniqueBase" categories: - Hugo --- # Doc -- content/sect3/Unique2.md -- --- title: "UniqueBase2" categories: - Hugo --- # Doc -- content/sect3/sect7/_index.md -- --- title: "another sect7" categories: - Hugo --- # Doc -- content/sect3/subsect/deep.md -- --- title: "deep page" categories: - Hugo --- # Doc -- content/sect3/b1/index.md -- --- title: "b1 bundle" categories: - Hugo --- # Doc -- content/sect3/index/index.md -- --- title: "index bundle" categories: - Hugo --- # Doc -- content/sect4/page2.md -- --- title: "Title4_2" categories: - Hugo --- # Doc -- content/sect5/page3.md -- --- title: "Title5_3" categories: - Hugo --- # Doc -- content/sect7/somesubpage.md -- --- title: "Some Sub Page in Sect7" categories: - Hugo --- # Doc -- content/sect7/page9.md -- --- title: "Title7_9" categories: - Hugo --- # Doc -- content/section_bundle_overlap/_index.md -- --- title: "index overlap section" categories: - Hugo --- # Doc -- content/section_bundle_overlap_bundle/index.md -- --- title: "index overlap bundle" categories: - Hugo --- # Doc ` b := Test(t, files) s := b.H.Sites[0] sec3, err := s.getPage(nil, "/sect3") b.Assert(err, qt.IsNil) b.Assert(sec3, qt.Not(qt.IsNil)) tests := []getPageTest{ // legacy content root relative paths {"Root relative, no slash, home", kinds.KindHome, nil, []string{""}, "home page"}, {"Root relative, no slash, root page", kinds.KindPage, nil, []string{"about.md", "ABOUT.md"}, "about page"}, {"Root relative, no slash, section", kinds.KindSection, nil, []string{"sect3"}, "section 3"}, {"Root relative, no slash, section page", kinds.KindPage, nil, []string{"sect3/page1.md"}, "Title3_1"}, {"Root relative, no slash, sub section", kinds.KindSection, nil, []string{"sect3/sect7"}, "another sect7"}, {"Root relative, no slash, nested page", kinds.KindPage, nil, []string{"sect3/subsect/deep.md"}, "deep page"}, {"Root relative, no slash, OS slashes", kinds.KindPage, nil, []string{filepath.FromSlash("sect5/page3.md")}, "Title5_3"}, {"Short ref, unique", kinds.KindPage, nil, []string{"unique.md", "unique"}, "UniqueBase"}, {"Short ref, unique, upper case", kinds.KindPage, nil, []string{"Unique2.md", "unique2.md", "unique2"}, "UniqueBase2"}, {"Short ref, ambiguous", "Ambiguous", nil, []string{"page1.md"}, ""}, // ISSUE: This is an ambiguous ref, but because we have to support the legacy // content root relative paths without a leading slash, the lookup // returns /sect7. This undermines ambiguity detection, but we have no choice. //{"Ambiguous", nil, []string{"sect7"}, ""}, {"Section, ambiguous", kinds.KindSection, nil, []string{"sect7"}, "Sect7s"}, {"Absolute, home", kinds.KindHome, nil, []string{"/", ""}, "home page"}, {"Absolute, page", kinds.KindPage, nil, []string{"/about.md", "/about"}, "about page"}, {"Absolute, sect", kinds.KindSection, nil, []string{"/sect3"}, "section 3"}, {"Absolute, page in subsection", kinds.KindPage, nil, []string{"/sect3/page1.md", "/Sect3/Page1.md"}, "Title3_1"}, {"Absolute, section, subsection with same name", kinds.KindSection, nil, []string{"/sect3/sect7"}, "another sect7"}, {"Absolute, page, deep", kinds.KindPage, nil, []string{"/sect3/subsect/deep.md"}, "deep page"}, {"Absolute, page, OS slashes", kinds.KindPage, nil, []string{filepath.FromSlash("/sect5/page3.md")}, "Title5_3"}, // test OS-specific path {"Absolute, unique", kinds.KindPage, nil, []string{"/sect3/unique.md"}, "UniqueBase"}, {"Absolute, unique, case", kinds.KindPage, nil, []string{"/sect3/Unique2.md", "/sect3/unique2.md", "/sect3/unique2", "/sect3/Unique2"}, "UniqueBase2"}, // next test depends on this page existing // {"NoPage", nil, []string{"/unique.md"}, ""}, // ISSUE #4969: this is resolving to /sect3/unique.md {"Absolute, missing page", "NoPage", nil, []string{"/missing-page.md"}, ""}, {"Absolute, missing section", "NoPage", nil, []string{"/missing-section"}, ""}, // relative paths {"Dot relative, home", kinds.KindHome, sec3, []string{".."}, "home page"}, {"Dot relative, home, slash", kinds.KindHome, sec3, []string{"../"}, "home page"}, {"Dot relative about", kinds.KindPage, sec3, []string{"../about.md"}, "about page"}, {"Dot", kinds.KindSection, sec3, []string{"."}, "section 3"}, {"Dot slash", kinds.KindSection, sec3, []string{"./"}, "section 3"}, {"Page relative, no dot", kinds.KindPage, sec3, []string{"page1.md"}, "Title3_1"}, {"Page relative, dot", kinds.KindPage, sec3, []string{"./page1.md"}, "Title3_1"}, {"Up and down another section", kinds.KindPage, sec3, []string{"../sect4/page2.md"}, "Title4_2"}, {"Rel sect7", kinds.KindSection, sec3, []string{"sect7"}, "another sect7"}, {"Rel sect7 dot", kinds.KindSection, sec3, []string{"./sect7"}, "another sect7"}, {"Dot deep", kinds.KindPage, sec3, []string{"./subsect/deep.md"}, "deep page"}, {"Dot dot inner", kinds.KindPage, sec3, []string{"./subsect/../../sect7/page9.md"}, "Title7_9"}, {"Dot OS slash", kinds.KindPage, sec3, []string{filepath.FromSlash("../sect5/page3.md")}, "Title5_3"}, // test OS-specific path {"Dot unique", kinds.KindPage, sec3, []string{"./unique.md"}, "UniqueBase"}, {"Dot sect", "NoPage", sec3, []string{"./sect2"}, ""}, //{"NoPage", sec3, []string{"sect2"}, ""}, // ISSUE: /sect3 page relative query is resolving to /sect2 {"Abs, ignore context, home", kinds.KindHome, sec3, []string{"/"}, "home page"}, {"Abs, ignore context, about", kinds.KindPage, sec3, []string{"/about.md"}, "about page"}, {"Abs, ignore context, page in section", kinds.KindPage, sec3, []string{"/sect4/page2.md"}, "Title4_2"}, {"Abs, ignore context, page subsect deep", kinds.KindPage, sec3, []string{"/sect3/subsect/deep.md"}, "deep page"}, // next test depends on this page existing {"Abs, ignore context, page deep", "NoPage", sec3, []string{"/subsect/deep.md"}, ""}, // Taxonomies {"Taxonomy term", kinds.KindTaxonomy, nil, []string{"categories"}, "Categories"}, {"Taxonomy", kinds.KindTerm, nil, []string{"categories/hugo", "categories/Hugo"}, "Hugo"}, // Bundle variants {"Bundle regular", kinds.KindPage, nil, []string{"sect3/b1", "sect3/b1/index.md", "sect3/b1/index.en.md"}, "b1 bundle"}, {"Bundle index name", kinds.KindPage, nil, []string{"sect3/index/index.md", "sect3/index"}, "index bundle"}, // https://github.com/gohugoio/hugo/issues/7301 {"Section and bundle overlap", kinds.KindPage, nil, []string{"section_bundle_overlap_bundle"}, "index overlap bundle"}, } for _, test := range tests { b.Run(test.name, func(c *qt.C) { errorMsg := fmt.Sprintf("Test case %v %v -> %s", test.context, test.pathVariants, test.expectedTitle) // test legacy public Site.GetPage (which does not support page context relative queries) if test.context == nil { for _, ref := range test.pathVariants { args := append([]string{test.kind}, ref) page, err := s.GetPage(args...) test.check(page, err, errorMsg, c) } } // test new internal Site.getPage for _, ref := range test.pathVariants { page2, err := s.getPage(test.context, ref) test.check(page2, err, errorMsg, c) } }) } } // #11664 func TestGetPageIndexIndex(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] -- content/mysect/index/index.md -- --- title: "Mysect Index" --- -- layouts/home.html -- GetPage 1: {{ with site.GetPage "mysect/index/index.md" }}{{ .Title }}|{{ .RelPermalink }}|{{ .Path }}{{ end }}| GetPage 2: {{ with site.GetPage "mysect/index" }}{{ .Title }}|{{ .RelPermalink }}|{{ .Path }}{{ end }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "GetPage 1: Mysect Index|/mysect/index/|/mysect/index|", "GetPage 2: Mysect Index|/mysect/index/|/mysect/index|", ) } // https://github.com/gohugoio/hugo/issues/6034 func TestGetPageRelative(t *testing.T) { files := ` -- hugo.toml -- -- content/what/_index.md -- ---title: what --- -- content/what/members.md -- ---title: members what draft: false --- -- content/where/_index.md -- ---title: where --- -- content/where/members.md -- ---title: members where draft: false --- -- content/who/_index.md -- ---title: who --- -- content/who/members.md -- ---title: members who draft: true --- -- layouts/list.html -- {{ with .GetPage "members.md" }} Members: {{ .Title }} {{ else }} NOT FOUND {{ end }} ` b := Test(t, files) b.AssertFileContent("public/what/index.html", `Members: members what`) b.AssertFileContent("public/where/index.html", `Members: members where`) b.AssertFileContent("public/who/index.html", `NOT FOUND`) } func TestGetPageIssue11883(t *testing.T) { files := ` -- hugo.toml -- -- p1/index.md -- --- title: p1 --- -- p1/p1.xyz -- xyz. -- layouts/home.html -- Home. {{ with .Page.GetPage "p1.xyz" }}{{ else }}OK 1{{ end }} {{ with .Site.GetPage "p1.xyz" }}{{ else }}OK 2{{ end }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "Home. OK 1 OK 2") } func TestGetPageIssue12120(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] -- content/s1/p1/index.md -- --- title: p1 layout: p1 --- -- content/s1/p2.md -- --- title: p2 layout: p2 --- -- layouts/p1.html -- {{ (.GetPage "p2.md").Title }}| -- layouts/p2.html -- {{ (.GetPage "p1").Title }}| ` b := Test(t, files) b.AssertFileContent("public/s1/p1/index.html", "p2") // failing test b.AssertFileContent("public/s1/p2/index.html", "p1") } func TestGetPageNewsVsTagsNewsIssue12638(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','section','sitemap'] [taxonomies] tag = "tags" -- content/p1.md -- --- title: p1 tags: [news] --- -- layouts/home.html -- /tags/news: {{ with .Site.GetPage "/tags/news" }}{{ .Title }}{{ end }}| news: {{ with .Site.GetPage "news" }}{{ .Title }}{{ end }}| /news: {{ with .Site.GetPage "/news" }}{{ .Title }}{{ end }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "/tags/news: News|", "news: News|", "/news: |", ) } func TestGetPageBundleToRegular(t *testing.T) { files := ` -- hugo.toml -- -- content/s1/p1/index.md -- --- title: p1 --- -- content/s1/p2.md -- --- title: p2 --- -- layouts/single.html -- {{ with .GetPage "p2" }} OK: {{ .LinkTitle }} {{ else }} Unable to get p2. {{ end }} ` b := Test(t, files) b.AssertFileContent("public/s1/p1/index.html", "OK: p2") b.AssertFileContent("public/s1/p2/index.html", "OK: p2") } func TestPageGetPageVariations(t *testing.T) { files := ` -- hugo.toml -- -- content/s1/_index.md -- --- title: s1 section --- -- content/s1/p1/index.md -- --- title: p1 --- -- content/s1/p2.md -- --- title: p2 --- -- content/s2/p3/index.md -- --- title: p3 --- -- content/p2.md -- --- title: p2_root --- -- layouts/home.html -- /s1: {{ with .GetPage "/s1" }}{{ .Title }}{{ end }}| /s1/: {{ with .GetPage "/s1/" }}{{ .Title }}{{ end }}| /s1/p2.md: {{ with .GetPage "/s1/p2.md" }}{{ .Title }}{{ end }}| /s1/p2: {{ with .GetPage "/s1/p2" }}{{ .Title }}{{ end }}| /s1/p1/index.md: {{ with .GetPage "/s1/p1/index.md" }}{{ .Title }}{{ end }}| /s1/p1: {{ with .GetPage "/s1/p1" }}{{ .Title }}{{ end }}| -- layouts/single.html -- ../p2: {{ with .GetPage "../p2" }}{{ .Title }}{{ end }}| ../p2.md: {{ with .GetPage "../p2.md" }}{{ .Title }}{{ end }}| p1/index.md: {{ with .GetPage "p1/index.md" }}{{ .Title }}{{ end }}| ../s2/p3/index.md: {{ with .GetPage "../s2/p3/index.md" }}{{ .Title }}{{ end }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", ` /s1: s1 section| /s1/: s1 section| /s1/p2.md: p2| /s1/p2: p2| /s1/p1/index.md: p1| /s1/p1: p1| `) b.AssertFileContent("public/s1/p1/index.html", ` ../p2: p2_root| ../p2.md: p2| `) b.AssertFileContent("public/s1/p2/index.html", ` ../p2: p2_root| ../p2.md: p2_root| p1/index.md: p1| ../s2/p3/index.md: p3| `) } func TestPageGetPageMountsReverseLookup(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/" [module] [[module.mounts]] source = "layouts" target = "layouts" [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "blog" target = "content/posts" [[module.mounts]] source = "docs" target = "content/mydocs" -- README.md -- --- title: README --- -- blog/b1.md -- --- title: b1 --- {{< ref "../docs/d1.md" >}} -- blog/b2/index.md -- --- title: b2 --- {{< ref "../../docs/d1.md" >}} -- docs/d1.md -- --- title: d1 --- -- layouts/_shortcodes/ref.html -- {{ $ref := .Get 0 }} .Page.GetPage({{ $ref }}).Title: {{ with .Page.GetPage $ref }}{{ .Title }}{{ end }}| -- layouts/home.html -- Home. /blog/b1.md: {{ with .GetPage "/blog/b1.md" }}{{ .Title }}{{ end }}| /blog/b2/index.md: {{ with .GetPage "/blog/b2/index.md" }}{{ .Title }}{{ end }}| /docs/d1.md: {{ with .GetPage "/docs/d1.md" }}{{ .Title }}{{ end }}| /README.md: {{ with .GetPage "/README.md" }}{{ .Title }}{{ end }}| -- layouts/single.html -- Single. /README.md: {{ with .GetPage "/README.md" }}{{ .Title }}{{ end }}| {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` /blog/b1.md: b1| /blog/b2/index.md: b2| /docs/d1.md: d1| /README.md: README `, ) b.AssertFileContent("public/mydocs/d1/index.html", `README.md: README|`) b.AssertFileContent("public/posts/b1/index.html", `.Page.GetPage(../docs/d1.md).Title: d1|`) b.AssertFileContent("public/posts/b2/index.html", `.Page.GetPage(../../docs/d1.md).Title: d1|`) } // https://github.com/gohugoio/hugo/issues/7016 func TestGetPageMultilingual(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.org/" languageCode = "en-us" defaultContentLanguage = "ru" title = "My New Hugo Site" uglyurls = true [languages] [languages.ru] [languages.en] -- content/docs/1.md -- --- title: p1 --- -- content/news/1.md -- --- title: p1 --- -- content/news/1.en.md -- --- title: p1en --- -- content/news/about/1.md -- --- title: about1 --- -- content/news/about/1.en.md -- --- title: about1en --- -- layouts/home.html -- {{ with site.GetPage "docs/1" }} Docs p1: {{ .Title }} {{ else }} NOT FOUND {{ end }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", `Docs p1: p1`) b.AssertFileContent("public/en/index.html", `NOT FOUND`) } func TestRegularPagesRecursive(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.org/" title = "My New Hugo Site" -- content/docs/1.md -- --- title: docs1 --- -- content/docs/sect1/_index.md -- --- title: docs_sect1 --- -- content/docs/sect1/ps1.md -- --- title: docs_sect1_ps1 --- -- content/docs/sect1/ps2.md -- --- title: docs_sect1_ps2 --- -- content/docs/sect1/sect1_s2/_index.md -- --- title: docs_sect1_s2 --- -- content/docs/sect1/sect1_s2/ps2_1.md -- --- title: docs_sect1_s2_1 --- -- content/docs/sect2/_index.md -- --- title: docs_sect2 --- -- content/docs/sect2/ps1.md -- --- title: docs_sect2_ps1 --- -- content/docs/sect2/ps2.md -- --- title: docs_sect2_ps2 --- -- content/news/1.md -- --- title: news1 --- -- layouts/home.html -- {{ $sect1 := site.GetPage "sect1" }} Sect1 RegularPagesRecursive: {{ range $sect1.RegularPagesRecursive }}{{ .Kind }}:{{ .RelPermalink}}|{{ end }}|End. ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` Sect1 RegularPagesRecursive: page:/docs/sect1/ps1/|page:/docs/sect1/ps2/|page:/docs/sect1/sect1_s2/ps2_1/||End. `) } func TestRegularPagesRecursiveHome(t *testing.T) { files := ` -- hugo.toml -- -- content/p1.md -- -- content/post/p2.md -- -- layouts/home.html -- RegularPagesRecursive: {{ range .RegularPagesRecursive }}{{ .Kind }}:{{ .RelPermalink}}|{{ end }}|End. ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }).Build() b.AssertFileContent("public/index.html", `RegularPagesRecursive: page:/p1/|page:/post/p2/||End.`) } // Issue #12169. func TestPagesSimilarSectionNames(t *testing.T) { files := ` -- hugo.toml -- -- content/draftsection/_index.md -- --- draft: true --- -- content/draftsection/sub/_index.md --got -- content/draftsection/sub/d1.md -- -- content/s1/_index.md -- -- content/s1/p1.md -- -- content/s1-foo/_index.md -- -- content/s1-foo/p2.md -- -- content/s1-foo/s2/_index.md -- -- content/s1-foo/s2/p3.md -- -- content/s1-foo/s2-foo/_index.md -- -- content/s1-foo/s2-foo/p4.md -- -- layouts/list.html -- {{ .RelPermalink }}: Pages: {{ range .Pages }}{{ .RelPermalink }}|{{ end }}$ ` b := Test(t, files) b.AssertFileContent("public/index.html", "/: Pages: /s1-foo/|/s1/|$") b.AssertFileContent("public/s1/index.html", "/s1/: Pages: /s1/p1/|$") b.AssertFileContent("public/s1-foo/index.html", "/s1-foo/: Pages: /s1-foo/p2/|/s1-foo/s2-foo/|/s1-foo/s2/|$") b.AssertFileContent("public/s1-foo/s2/index.html", "/s1-foo/s2/: Pages: /s1-foo/s2/p3/|$") } func TestGetPageContentAdapterBaseIssue12561(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- Test A: {{ (site.GetPage "/s1/p1").Title }} Test B: {{ (site.GetPage "p1").Title }} Test C: {{ (site.GetPage "/s2/p2").Title }} Test D: {{ (site.GetPage "p2").Title }} -- layouts/single.html -- {{ .Title }} -- content/s1/p1.md -- --- title: p1 --- -- content/s2/_content.gotmpl -- {{ .AddPage (dict "path" "p2" "title" "p2") }} ` b := Test(t, files) b.AssertFileExists("public/s1/p1/index.html", true) b.AssertFileExists("public/s2/p2/index.html", true) b.AssertFileContent("public/index.html", "Test A: p1", "Test B: p1", "Test C: p2", "Test D: p2", // fails ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__common.go
hugolib/page__common.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "sync" "github.com/gohugoio/hugo/common/hstore" "github.com/gohugoio/hugo/compare" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/navigation" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/source" ) type nextPrevProvider interface { getNextPrev() *nextPrev } func (p *pageCommon) getNextPrev() *nextPrev { return p.posNextPrev } type nextPrevInSectionProvider interface { getNextPrevInSection() *nextPrev } func (p *pageCommon) getNextPrevInSection() *nextPrev { return p.posNextPrevSection } type pageCommon struct { s *Site // TODO(bep) get rid of this. m *pageMeta // Lazily initialized dependencies. pageInit sync.Once // Store holds state that survives server rebuilds. store func() *hstore.Scratch // All of these represents the common parts of a page.Page navigation.PageMenusProvider page.AlternativeOutputFormatsProvider page.ChildCareProvider page.FileProvider page.GetPageProvider page.GitInfoProvider page.InSectionPositioner page.OutputFormatsProvider page.PageMetaProvider page.PageMetaInternalProvider page.Positioner page.RawContentProvider page.RefProvider page.ShortcodeInfoProvider page.SitesProvider page.TranslationsProvider page.TreeProvider resource.LanguageProvider resource.ResourceDataProvider resource.ResourceNameTitleProvider resource.ResourceParamsProvider resource.ResourceTypeProvider resource.MediaTypeProvider resource.TranslationKeyProvider compare.Eqer // Describes how paths and URLs for this page and its descendants // should look like. targetPathDescriptor page.TargetPathDescriptor // Set if feature enabled and this is in a Git repo. gitInfo *source.GitInfo codeowners []string // Positional navigation posNextPrev *nextPrev posNextPrevSection *nextPrev // Menus pageMenus *pageMenus // Internal use page.RelatedDocsHandlerProvider pageContentConverter } type pageContentConverter struct { contentConverterInit sync.Once contentConverter converter.Converter } func (p *pageCommon) Store() *hstore.Scratch { return p.store() } // See issue 13016. func (p *pageCommon) Scratch() *hstore.Scratch { return p.Store() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/config_test.go
hugolib/config_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "bytes" "fmt" "strings" "testing" "github.com/bep/logg" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/allconfig" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/maps" "github.com/spf13/afero" ) func TestLoadConfigLanguageParamsOverrideIssue10620(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] title = "Base Title" staticDir = "mystatic" [params] [params.comments] color = "blue" title = "Default Comments Title" [languages] [languages.en] title = "English Title" [languages.en.params.comments] title = "English Comments Title" ` b := Test(t, files) enSite := b.H.Sites[0] b.Assert(enSite.Title(), qt.Equals, "English Title") b.Assert(enSite.Home().Title(), qt.Equals, "English Title") b.Assert(enSite.Params(), qt.DeepEquals, maps.Params{ "comments": maps.Params{ "color": "blue", "title": "English Comments Title", }, }, ) } func TestLoadConfig(t *testing.T) { t.Run("2 languages", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] title = "Base Title" staticDir = "mystatic" [params] p1 = "p1base" p2 = "p2base" [languages] [languages.en] title = "English Title" [languages.en.params] myparam = "enParamValue" p1 = "p1en" weight = 1 [languages.sv] title = "Svensk Title" staticDir = "mysvstatic" weight = 2 [languages.sv.params] myparam = "svParamValue" ` b := Test(t, files) b.Assert(len(b.H.Sites), qt.Equals, 2) enSiteH := b.SiteHelper("en", "", "") svSiteH := b.SiteHelper("sv", "", "") b.Assert(enSiteH.S.Title(), qt.Equals, "English Title") b.Assert(enSiteH.S.Home().Title(), qt.Equals, "English Title") b.Assert(enSiteH.S.Params()["myparam"], qt.Equals, "enParamValue") b.Assert(enSiteH.S.Params()["p1"], qt.Equals, "p1en") b.Assert(enSiteH.S.Params()["p2"], qt.Equals, "p2base") b.Assert(svSiteH.S.Params()["p1"], qt.Equals, "p1base") b.Assert(enSiteH.S.conf.StaticDir[0], qt.Equals, "mystatic") b.Assert(svSiteH.S.Title(), qt.Equals, "Svensk Title") b.Assert(svSiteH.S.Home().Title(), qt.Equals, "Svensk Title") b.Assert(svSiteH.S.Params()["myparam"], qt.Equals, "svParamValue") b.Assert(svSiteH.S.conf.StaticDir[0], qt.Equals, "mysvstatic") }) t.Run("disable default language", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] title = "Base Title" defaultContentLanguage = "sv" disableLanguages = ["sv"] [languages.en] weight = 1 [languages.sv] weight = 2 ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `default language "sv" is disabled`) }) t.Run("no internal config from outside", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" [internal] running = true ` b := Test(t, files) b.Assert(b.H.Conf.Running(), qt.Equals, false) }) t.Run("env overrides", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] title = "Base Title" [params] p1 = "p1base" p2 = "p2base" [params.pm2] pm21 = "pm21base" pm22 = "pm22base" -- layouts/home.html -- p1: {{ .Site.Params.p1 }} p2: {{ .Site.Params.p2 }} pm21: {{ .Site.Params.pm2.pm21 }} pm22: {{ .Site.Params.pm2.pm22 }} pm31: {{ .Site.Params.pm3.pm31 }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Environ: []string{"HUGO_PARAMS_P2=p2env", "HUGO_PARAMS_PM2_PM21=pm21env", "HUGO_PARAMS_PM3_PM31=pm31env"}, }, ).Build() b.AssertFileContent("public/index.html", "p1: p1base\np2: p2env\npm21: pm21env\npm22: pm22base\npm31: pm31env") }) } func TestLoadConfigThemeLanguage(t *testing.T) { t.Parallel() files := ` -- /hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true theme = "mytheme" [languages] [languages.en] title = "English Title" weight = 1 [languages.sv] weight = 2 -- themes/mytheme/hugo.toml -- [params] p1 = "p1base" [languages] [languages.en] title = "English Title Theme" [languages.en.params] p2 = "p2en" [languages.en.params.sub] sub1 = "sub1en" [languages.sv] title = "Svensk Title Theme" -- layouts/home.html -- title: {{ .Title }}| p1: {{ .Site.Params.p1 }}| p2: {{ .Site.Params.p2 }}| sub: {{ .Site.Params.sub }}| ` b := Test(t, files) b.AssertFileContent("public/en/index.html", ` title: English Title| p1: p1base p2: p2en sub: map[sub1:sub1en] `) } func TestDisableRootSlicesFromEnv(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 [languages.sv] weight = 2 [languages.no] weight = 3 -- layouts/home.html -- Home. ` for _, delim := range []string{" ", ","} { environ := []string{"HUGO_DISABLELANGUAGES=sv no", "HUGO_DISABLEKINDS=taxonomy term"} for i, v := range environ { environ[i] = strings.ReplaceAll(v, " ", delim) } b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Environ: environ, BuildCfg: BuildCfg{SkipRender: true}, }, ).Build() conf := b.H.Configs.Base b.Assert(conf.DisableLanguages, qt.DeepEquals, []string{"no", "sv"}) b.Assert(conf.DisableKinds, qt.DeepEquals, []string{"taxonomy", "term"}) } } func TestLoadMultiConfig(t *testing.T) { t.Parallel() c := qt.New(t) // Add a random config variable for testing. // side = page in Norwegian. configContentBase := ` [pagination] pagerSize = 32 path = "side" ` configContentSub := ` [pagination] path = "top" ` mm := afero.NewMemMapFs() writeToFs(t, mm, "base.toml", configContentBase) writeToFs(t, mm, "override.toml", configContentSub) all, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Fs: mm, Filename: "base.toml,override.toml"}) c.Assert(err, qt.IsNil) cfg := all.Base c.Assert(cfg.Pagination.Path, qt.Equals, "top") c.Assert(cfg.Pagination.PagerSize, qt.Equals, 32) } func TestLoadConfigFromThemes(t *testing.T) { t.Parallel() c := qt.New(t) mainConfigTemplate := ` theme = "test-theme" baseURL = "https://example.com/" [frontmatter] date = ["date","publishDate"] [params] MERGE_PARAMS p1 = "p1 main" [params.b] b1 = "b1 main" [params.b.c] bc1 = "bc1 main" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1main"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1main" [languages] [languages.en] languageName = "English" [languages.en.params] pl1 = "p1-en-main" [languages.nb] languageName = "Norsk" [languages.nb.params] pl1 = "p1-nb-main" [[menu.main]] name = "menu-main-main" [[menu.top]] name = "menu-top-main" ` themeConfig := ` baseURL = "http://bep.is/" # Can not be set in theme. disableKinds = ["taxonomy", "term"] # Can not be set in theme. [frontmatter] expiryDate = ["date"] [params] p1 = "p1 theme" p2 = "p2 theme" [params.b] b1 = "b1 theme" b2 = "b2 theme" [params.b.c] bc1 = "bc1 theme" bc2 = "bc2 theme" [params.b.c.d] bcd1 = "bcd1 theme" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1theme"] [mediaTypes."text/m2"] suffixes = ["m2theme"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1theme" [outputFormats.o2] mediaType = "text/m2" baseName = "o2theme" [languages] [languages.en] languageName = "English2" [languages.en.params] pl1 = "p1-en-theme" pl2 = "p2-en-theme" [[languages.en.menu.main]] name = "menu-lang-en-main" [[languages.en.menu.theme]] name = "menu-lang-en-theme" [languages.nb] languageName = "Norsk2" [languages.nb.params] pl1 = "p1-nb-theme" pl2 = "p2-nb-theme" top = "top-nb-theme" [[languages.nb.menu.main]] name = "menu-lang-nb-main" [[languages.nb.menu.theme]] name = "menu-lang-nb-theme" [[languages.nb.menu.top]] name = "menu-lang-nb-top" [[menu.main]] name = "menu-main-theme" [[menu.thememenu]] name = "menu-theme" ` buildForConfig := func(t testing.TB, mainConfig, themeConfig string) *IntegrationTestBuilder { files := "-- hugo.toml --\n" + mainConfig + "\n-- themes/test-theme/hugo.toml --\n" + themeConfig return Test(t, files) } buildForStrategy := func(t testing.TB, s string) *IntegrationTestBuilder { mainConfig := strings.ReplaceAll(mainConfigTemplate, "MERGE_PARAMS", s) return buildForConfig(t, mainConfig, themeConfig) } c.Run("Merge default", func(c *qt.C) { b := buildForStrategy(c, "") got := b.H.Configs.Base b.Assert(got.Params, qt.DeepEquals, maps.Params{ "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", "bc2": "bc2 theme", "d": maps.Params{"bcd1": string("bcd1 theme")}, }, "b2": "b2 theme", }, "p2": "p2 theme", "p1": "p1 main", }) c.Assert(got.BaseURL, qt.Equals, "https://example.com/") }) c.Run("Merge shallow", func(c *qt.C) { b := buildForStrategy(c, fmt.Sprintf("_merge=%q", "shallow")) got := b.H.Configs.Base.Params // Shallow merge, only add new keys to params. b.Assert(got, qt.DeepEquals, maps.Params{ "p1": "p1 main", "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", }, }, "p2": "p2 theme", }) }) c.Run("Merge no params in project", func(c *qt.C) { b := buildForConfig( c, "baseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", "[params]\np1 = \"p1 theme\"\n", ) got := b.H.Configs.Base.Params b.Assert(got, qt.DeepEquals, maps.Params{ "p1": "p1 theme", }) }) // Issue #8724 ##13643 for _, mergeStrategy := range []string{"none", "shallow"} { c.Run(fmt.Sprintf("Merge with sitemap config in theme, mergestrategy %s", mergeStrategy), func(c *qt.C) { smapConfigTempl := `[sitemap] changefreq = %q filename = "sitemap.xml" priority = 0.5` b := buildForConfig( c, fmt.Sprintf("_merge=%q\nbaseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", mergeStrategy), "baseURL=\"http://example.com\"\n"+fmt.Sprintf(smapConfigTempl, "monthly"), ) got := b.H.Configs.Base if mergeStrategy == "none" { b.Assert(got.Sitemap, qt.DeepEquals, config.SitemapConfig{ChangeFreq: "", Disable: false, Priority: -1, Filename: "sitemap.xml"}) b.AssertFileContent("public/sitemap.xml", "schemas/sitemap") } else { b.Assert(got.Sitemap, qt.DeepEquals, config.SitemapConfig{ChangeFreq: "monthly", Disable: false, Priority: 0.5, Filename: "sitemap.xml"}) b.AssertFileContent("public/sitemap.xml", "<changefreq>monthly</changefreq>") } }) } } func TestLoadConfigFromThemeDir(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- theme = "test-theme" [params] m1 = "mv1" -- themes/test-theme/hugo.toml -- [params] t1 = "tv1" t2 = "tv2" -- config/_default/config.toml -- [params] m2 = "mv2" -- themes/test-theme/config/_default/config.toml -- [params] t2 = "tv2d" t3 = "tv3d" -- themes/test-theme/config/production/config.toml -- [params] t3 = "tv3p" -- layouts/home.html -- m1: {{ .Site.Params.m1 }} m2: {{ .Site.Params.m2 }} t1: {{ .Site.Params.t1 }} t2: {{ .Site.Params.t2 }} t3: {{ .Site.Params.t3 }} ` b := Test(t, files) got := b.H.Configs.Base.Params b.Assert(got, qt.DeepEquals, maps.Params{ "m1": "mv1", "m2": "mv2", "t1": "tv1", "t2": "tv2d", "t3": "tv3p", }) } func TestPrivacyConfig(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- someOtherValue = "foo" [privacy.youtube] privacyEnhanced = true -- layouts/home.html -- Privacy Enhanced: {{ .Site.Config.Privacy.YouTube.PrivacyEnhanced }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "Privacy Enhanced: true") } func TestLoadConfigModules(t *testing.T) { t.Parallel() const ( o1t = ` name = "Component o1" license = "MIT" min_version = 0.38 ` o1c = ` theme = ["n2"] ` n1 = ` title = "Component n1" [module] description = "Component n1 description" [module.hugoVersion] min = "0.40.0" max = "0.50.0" extended = true [[module.imports]] path="o1" [[module.imports]] path="n3" ` n2 = ` title = "Component n2" ` n3 = ` title = "Component n3" ` n4 = ` title = "Component n4" ` ) files := ` -- hugo.toml -- [module] [[module.imports]] path="n1" [[module.imports]] path="n4" -- themes/n1/hugo.toml -- ` + n1 + ` -- themes/n2/hugo.toml -- ` + n2 + ` -- themes/n3/hugo.toml -- ` + n3 + ` -- themes/n4/hugo.toml -- ` + n4 + ` -- themes/o1/hugo.toml -- ` + o1c + ` -- themes/o1/theme.toml -- ` + o1t + ` -- themes/n1/data/module.toml -- name="n1" -- themes/n2/data/module.toml -- name="n2" -- themes/n3/data/module.toml -- name="n3" -- themes/n4/data/module.toml -- name="n4" -- themes/o1/data/module.toml -- name="o1" ` b := Test(t, files) modulesClient := b.H.Configs.ModulesClient var graphb bytes.Buffer modulesClient.Graph(&graphb) expected := "project n1\nn1 o1\no1 n2\nn1 n3\nproject n4\n" b.Assert(graphb.String(), qt.Equals, expected) } func TestInvalidDefaultMarkdownHandler(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup] defaultMarkdownHandler = 'blackfriday' -- content/_index.md -- ## Foo -- layouts/home.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "Configured defaultMarkdownHandler \"blackfriday\" not found. Did you mean to use goldmark? Blackfriday was removed in Hugo v0.100.0.") } // Issue 8979 func TestHugoConfig(t *testing.T) { filesTemplate := ` -- hugo.toml -- theme = "mytheme" [params] rootparam = "rootvalue" -- config/_default/hugo.toml -- [params] rootconfigparam = "rootconfigvalue" -- themes/mytheme/config/_default/hugo.toml -- [params] themeconfigdirparam = "themeconfigdirvalue" -- themes/mytheme/hugo.toml -- [params] themeparam = "themevalue" -- layouts/home.html -- rootparam: {{ site.Params.rootparam }} rootconfigparam: {{ site.Params.rootconfigparam }} themeparam: {{ site.Params.themeparam }} themeconfigdirparam: {{ site.Params.themeconfigdirparam }} ` for _, configName := range []string{"hugo.toml", "config.toml"} { t.Run(configName, func(t *testing.T) { t.Parallel() files := strings.ReplaceAll(filesTemplate, "hugo.toml", configName) b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNil) b.AssertFileContent("public/index.html", "rootparam: rootvalue", "rootconfigparam: rootconfigvalue", "themeparam: themevalue", "themeconfigdirparam: themeconfigdirvalue", ) }) } } // Issue #11089 func TestHugoConfigSliceOverrides(t *testing.T) { t.Parallel() filesTemplate := ` -- hugo.toml -- disableKinds = ["section"] [languages] [languages.en] disableKinds = [] title = "English" weigHt = WEIGHT_EN [languages.sv] title = "Swedish" wEight = WEIGHT_SV disableKinds = ["page"] -- layouts/home.html -- Home: {{ .Lang}}|{{ len site.RegularPages }}| -- layouts/single.html -- Single. -- content/p1.en.md -- -- content/p2.en.md -- -- content/p1.sv.md -- -- content/p2.sv.md -- ` t.Run("En first", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "WEIGHT_EN", "1") files = strings.ReplaceAll(files, "WEIGHT_SV", "2") cfg := config.New() b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BaseCfg: cfg, }, ).BuildE() b.Assert(err, qt.IsNil) b.AssertFileContent("public/index.html", "Home: en|2|") b.AssertFileContent("public/sv/index.html", "Home: sv|0|") }) t.Run("Sv first", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "WEIGHT_EN", "2") files = strings.ReplaceAll(files, "WEIGHT_SV", "1") for range 20 { cfg := config.New() b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BaseCfg: cfg, }, ).BuildE() b.Assert(err, qt.IsNil) b.AssertFileContent("public/index.html", "Home: en|2|") b.AssertFileContent("public/sv/index.html", "Home: sv|0|") } }) } func TestConfigOutputFormatDefinedInTheme(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- theme = "mytheme" [outputFormats] [outputFormats.myotherformat] baseName = 'myotherindex' mediaType = 'text/html' [outputs] home = ['myformat'] -- themes/mytheme/hugo.toml -- [outputFormats] [outputFormats.myformat] baseName = 'myindex' mediaType = 'text/html' -- layouts/home.html -- Home. ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNil) b.AssertFileContent("public/myindex.html", "Home.") } func TestConfigParamSetOnLanguageLevel(t *testing.T) { t.Skip("this has correctly started to fail now.") t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT"] [languages] [languages.en] title = "English Title" thisIsAParam = "thisIsAParamValue" [languages.en.params] myparam = "enParamValue" [languages.sv] title = "Svensk Title" [languages.sv.params] myparam = "svParamValue" -- layouts/home.html -- MyParam: {{ site.Params.myparam }} ThisIsAParam: {{ site.Params.thisIsAParam }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNil) b.AssertFileContent("public/index.html", ` MyParam: enParamValue ThisIsAParam: thisIsAParamValue `) } func TestReproCommentsIn10947(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT"] [languages] [languages.en] languageCode = "en-US" title = "English Title" [languages.en.params] myparam = "enParamValue" [languages.sv] title = "Svensk Title" [languages.sv.params] myparam = "svParamValue" -- content/mysection/_index.en.md -- --- title: "My English Section" --- -- content/mysection/_index.sv.md -- --- title: "My Swedish Section" --- -- layouts/home.html -- LanguageCode: {{ eq site.LanguageCode site.Language.LanguageCode }}|{{ site.Language.LanguageCode }}| {{ range $i, $e := (slice site .Site) }} {{ $i }}|AllPages: {{ len .AllPages }}|Sections: {{ if .Sections }}true{{ end }}|BuildDrafts: {{ .BuildDrafts }}|Param: {{ .Language.Params.myparam }}|Language string: {{ .Language }}|Languages: {{ .Languages }} {{ end }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, LogLevel: logg.LevelWarn, }, ).Build() b.Assert(b.H.Log.LoggCount(logg.LevelWarn), qt.Equals, 1) b.AssertFileContent("public/index.html", ` AllPages: 4| Sections: true| Param: enParamValue Param: enParamValue LanguageCode: true|en-US| `) b.AssertFileContent("public/sv/index.html", ` Param: svParamValue LanguageCode: true|sv| `) } func TestConfigEmptyMainSections(t *testing.T) { t.Parallel() files := ` -- hugo.yml -- params: mainSections: -- content/mysection/_index.md -- -- content/mysection/mycontent.md -- -- layouts/home.html -- mainSections: {{ site.Params.mainSections }} ` b := Test(t, files) b.AssertFileContent("public/index.html", ` mainSections: [] `) } func TestConfigHugoWorkingDir(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- layouts/home.html -- WorkingDir: {{ hugo.WorkingDir }}| ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, WorkingDir: "myworkingdir", }, ).Build() b.AssertFileContent("public/index.html", ` WorkingDir: myworkingdir| `) } func TestConfigMergeLanguageDeepEmptyLeftSide(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [params] p1 = "p1base" [languages.en] languageCode = 'en-US' languageName = 'English' weight = 1 [languages.en.markup.goldmark.extensions.typographer] leftDoubleQuote = '&ldquo;' # default &ldquo; rightDoubleQuote = '&rdquo;' # default &rdquo; [languages.de] languageCode = 'de-DE' languageName = 'Deutsch' weight = 2 [languages.de.params] p1 = "p1de" [languages.de.markup.goldmark.extensions.typographer] leftDoubleQuote = '&laquo;' # default &ldquo; rightDoubleQuote = '&raquo;' # default &rdquo; -- layouts/home.html -- {{ .Content }} p1: {{ site.Params.p1 }}| -- content/_index.en.md -- --- title: "English Title" --- A "quote" in English. -- content/_index.de.md -- --- title: "Deutsch Title" --- Ein "Zitat" auf Deutsch. ` b := Test(t, files) b.AssertFileContent("public/index.html", "p1: p1base", "<p>A &ldquo;quote&rdquo; in English.</p>") b.AssertFileContent("public/de/index.html", "p1: p1de", "<p>Ein &laquo;Zitat&raquo; auf Deutsch.</p>") } func TestConfigLegacyValues(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- # taxonomyTerm was renamed to taxonomy in Hugo 0.60.0. disableKinds = ["taxonomyTerm"] -- layouts/home.html -- Home ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNil) b.AssertFileContent("public/index.html", ` Home `) conf := b.H.Configs.Base b.Assert(conf.IsKindEnabled("taxonomy"), qt.Equals, false) } // Issue #11000 func TestConfigEmptyTOMLString(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [mediaTypes] [mediaTypes."text/htaccess"] suffixes = ["htaccess"] [outputFormats] [outputFormats.htaccess] mediaType = "text/htaccess" baseName = "" isPlainText = false notAlternative = true -- content/_index.md -- --- outputs: ["html", "htaccess"] --- -- layouts/home.html -- HTML. -- layouts/list.htaccess -- HTACCESS. ` b := Test(t, files) b.AssertFileContent("public/.htaccess", "HTACCESS") } func TestConfigLanguageCodeTopLevel(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- languageCode = "en-US" -- layouts/home.html -- LanguageCode: {{ .Site.LanguageCode }}|{{ site.Language.LanguageCode }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "LanguageCode: en-US|en-US|") } // See #11159 func TestConfigOutputFormatsPerLanguage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [languages] [languages.en] title = "English Title" [languages.sv] title = "Swedish Title" [languages.sv.outputFormats.html] path = "foo" [languages.sv.mediatypes."text/html"] suffixes = ["bar"] -- layouts/home.html -- Home. ` b := Test(t, files) b.AssertFileContent("public/index.html", "Home.") enConfig := b.H.Sites[0].conf m, _ := enConfig.MediaTypes.Config.GetByType("text/html") b.Assert(m.Suffixes(), qt.DeepEquals, []string{"html", "htm"}) svConfig := b.H.Sites[1].conf f, _ := svConfig.OutputFormats.Config.GetByName("html") b.Assert(f.Path, qt.Equals, "foo") m, _ = svConfig.MediaTypes.Config.GetByType("text/html") b.Assert(m.Suffixes(), qt.DeepEquals, []string{"bar"}) } func TestConfigMiscPanics(t *testing.T) { t.Parallel() // Issue 11047, t.Run("empty params", func(t *testing.T) { files := ` -- hugo.yaml -- params: -- layouts/home.html -- Foo: {{ site.Params.foo }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "Foo: |") }) // Issue 11046 t.Run("invalid language setup", func(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org" languageCode = "en-us" title = "Blog of me" defaultContentLanguage = "en" [languages] [en] lang = "en" languageName = "English" weight = 1 -- layouts/home.html -- Foo: {{ site.Params.foo }}| ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "invalid language configuration ") }) // Issue 11044 t.Run("invalid defaultContentLanguage", func(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org" defaultContentLanguage = "sv" [languages] [languages.en] languageCode = "en" languageName = "English" weight = 1 ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `defaultContentLanguage "sv" not found in languages configuration`) }) } // Issue #11040 func TestConfigModuleDefaultMountsInConfig(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" contentDir = "mycontent" -- layouts/home.html -- Home. ` b := Test(t, files) b.Assert(b.H.Configs.Base.Module.Mounts, qt.HasLen, 7) b.Assert(b.H.Configs.Base.Languages.Config.Sorted[0].Name, qt.Equals, "en") firstLang := b.H.Configs.Base.Languages.Config.Sorted[0].Name b.Assert(b.H.Configs.LanguageConfigMap[firstLang].Module.Mounts, qt.HasLen, 7) } func TestDefaultContentLanguageInSubdirOnlyOneLanguage(t *testing.T) { t.Run("One language, default in sub dir", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true disableKinds = ["taxonomy", "term", "page", "section"] -- content/foo/bar.txt -- Foo. -- layouts/home.html -- Home. ` b := Test(t, files) b.AssertFileContent("public/en/index.html", "Home.") b.AssertFileContent("public/en/foo/bar.txt", "Foo.") b.AssertFileContent("public/index.html", "refresh") b.AssertFileContent("public/sitemap.xml", "sitemapindex") b.AssertFileContent("public/en/sitemap.xml", "urlset") }) t.Run("Two languages, default in sub dir", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true disableKinds = ["taxonomy", "term", "page", "section"] [languages] [languages.en] title = "English Title" [languages.sv] title = "Swedish Title" -- content/foo/bar.txt -- Foo. -- layouts/home.html -- Home. ` b := Test(t, files) b.AssertFileContent("public/en/index.html", "Home.") b.AssertFileContent("public/en/foo/bar.txt", "Foo.") b.AssertFileContent("public/index.html", "refresh") b.AssertFileContent("public/sitemap.xml", "sitemapindex") b.AssertFileContent("public/en/sitemap.xml", "urlset") }) t.Run("Two languages, default in root", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = false disableKinds = ["taxonomy", "term", "page", "section"] [languages] [languages.en] title = "English Title" [languages.sv] title = "Swedish Title" -- content/foo/bar.txt -- Foo. -- layouts/home.html -- Home. ` b := Test(t, files) b.AssertFileContent("public/index.html", "Home.") b.AssertFileContent("public/foo/bar.txt", "Foo.") b.AssertFileContent("public/sitemap.xml", "sitemapindex") b.AssertFileContent("public/en/sitemap.xml", "urlset") }) } func TestLanguagesDisabled(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [languages] [languages.en] title = "English Title" [languages.sv] title = "Swedish Title" disabled = true -- layouts/home.html -- Home. ` b := Test(t, files) b.Assert(len(b.H.Sites), qt.Equals, 1) } func TestDisableDefaultLanguageRedirect(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- defaultContentLanguageInSubdir = true disableDefaultLanguageRedirect = true [languages] [languages.en] title = "English Title" [languages.sv] title = "Swedish Title" -- layouts/home.html -- Home. ` b := Test(t, files) b.Assert(len(b.H.Sites), qt.Equals, 2) b.AssertFileExists("public/index.html", false) } func TestLoadConfigYamlEnvVar(t *testing.T) { defaultEnv := []string{`HUGO_OUTPUTS=home: ['json']`} runVariant := func(t testing.TB, files string, env []string) *IntegrationTestBuilder { if env == nil { env = defaultEnv } b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Environ: env, BuildCfg: BuildCfg{SkipRender: true}, }, ).Build() outputs := b.H.Configs.Base.Outputs if env == nil { home := outputs["home"] b.Assert(home, qt.Not(qt.IsNil)) b.Assert(home, qt.DeepEquals, []string{"json"}) } return b } t.Run("with empty slice", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] [outputs] home = ["html"] ` b := runVariant(t, files, []string{`HUGO_OUTPUTS=section: []`}) outputs := b.H.Configs.Base.Outputs b.Assert(outputs, qt.DeepEquals, map[string][]string{ "home": {"html"}, "page": {"html"}, "rss": {"rss"}, "section": {}, "taxonomy": {"html", "rss"}, "term": {"html", "rss"}, }) }) t.Run("with existing outputs", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] [outputs] home = ["html"] ` runVariant(t, files, nil) }) { t.Run("with existing outputs direct", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] [outputs] home = ["html"] ` runVariant(t, files, []string{"HUGO_OUTPUTS_HOME=json"}) }) } t.Run("without existing outputs", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] ` runVariant(t, files, nil) }) t.Run("without existing outputs direct", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] ` runVariant(t, files, []string{"HUGO_OUTPUTS_HOME=json"}) }) } // Issue #11257 func TestDisableKindsTaxonomyTerm(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ['taxonomyTerm'] [taxonomies] category = 'categories' -- content/p1.md -- --- title: "P1" categories: ["c1"] --- -- layouts/home.html -- Home. -- layouts/list.html -- List. ` b := Test(t, files) b.AssertFileExists("public/index.html", true) b.AssertFileExists("public/categories/c1/index.html", true) b.AssertFileExists("public/categories/index.html", false) } func TestKindsUnknown(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['foo', 'home'] [outputs] foo = ['HTML', 'AMP', 'RSS'] -- layouts/list.html -- List. ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, LogLevel: logg.LevelWarn, }, ).Init() b.AssertLogContains("WARN Unknown kind \"foo\" in disableKinds configuration.\n") b.AssertLogContains("WARN Unknown kind \"foo\" in outputs configuration.\n") } func TestDeprecateTaxonomyTerm(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['taxonomyTerm'] [outputs] taxonomyterm = ['HTML', 'AMP', 'RSS'] -- layouts/list.html -- List. ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, LogLevel: logg.LevelWarn, BuildCfg: BuildCfg{SkipRender: true}, }, ).Init() b.AssertLogContains("WARN DEPRECATED: Kind \"taxonomyterm\" used in disableKinds is deprecated, use \"taxonomy\" instead.\n") b.AssertLogContains("WARN DEPRECATED: Kind \"taxonomyterm\" used in outputs configuration is deprecated, use \"taxonomy\" instead.\n") } func TestDisableKindsIssue12144(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["page"] defaultContentLanguage = "pt" [languages] [languages.en] weight = 1 title = "English" [languages.pt]
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/alias_test.go
hugolib/alias_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "path/filepath" "runtime" "strings" "testing" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config" ) func TestAlias(t *testing.T) { t.Parallel() tests := []struct { fileSuffix string urlPrefix string urlSuffix string settings map[string]any }{ {"/index.html", "http://example.com", "/", map[string]any{"baseURL": "http://example.com"}}, {"/index.html", "http://example.com/some/path", "/", map[string]any{"baseURL": "http://example.com/some/path"}}, {"/index.html", "http://example.com", "/", map[string]any{"baseURL": "http://example.com", "canonifyURLs": true}}, {"/index.html", "../..", "/", map[string]any{"relativeURLs": true}}, {".html", "", ".html", map[string]any{"uglyURLs": true}}, } for _, test := range tests { files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "taxonomy", "term"] CONFIG -- content/blog/page.md -- --- title: Has Alias aliases: ["/foo/bar/", "rel"] --- For some moments the old man did not reply. He stood with bowed head, buried in deep thought. But at last he spoke. -- layouts/all.html -- Title: {{ .Title }}|Content: {{ .Content }}| ` files = strings.Replace(files, "CONFIG", config.FromMapToTOMLString(test.settings), 1) b := Test(t, files) // the real page b.AssertFileContent("public/blog/page"+test.fileSuffix, "For some moments the old man") // the alias redirectors b.AssertFileContent("public/foo/bar"+test.fileSuffix, "<meta http-equiv=\"refresh\" content=\"0; url="+test.urlPrefix+"/blog/page"+test.urlSuffix+"\">") b.AssertFileContent("public/blog/rel"+test.fileSuffix, "<meta http-equiv=\"refresh\" content=\"0; url="+test.urlPrefix+"/blog/page"+test.urlSuffix+"\">") } } func TestAliasMultipleOutputFormats(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/single.html -- {{ .Content }} -- layouts/single.amp.html -- {{ .Content }} -- layouts/single.json -- {{ .Content }} -- content/blog/page.md -- --- title: Has Alias for HTML and AMP aliases: ["/foo/bar/"] outputs: ["html", "amp", "json"] --- For some moments the old man did not reply. He stood with bowed head, buried in deep thought. But at last he spoke. ` b := Test(t, files) // the real pages b.AssertFileContent("public/blog/page/index.html", "For some moments the old man") b.AssertFileContent("public/amp/blog/page/index.html", "For some moments the old man") b.AssertFileContent("public/blog/page/index.json", "For some moments the old man") // the alias redirectors b.AssertFileContent("public/foo/bar/index.html", "<meta http-equiv=\"refresh\" content=\"0; ") b.AssertFileContent("public/amp/foo/bar/index.html", "<meta http-equiv=\"refresh\" content=\"0; ") b.AssertFileExists("public/foo/bar/index.json", false) } func TestAliasTemplate(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/single.html -- Single. -- layouts/home.html -- Home. -- layouts/alias.html -- ALIASTEMPLATE -- content/page.md -- --- title: "Page" aliases: ["/foo/bar/"] --- ` b := Test(t, files) // the real page b.AssertFileContent("public/page/index.html", "Single.") // the alias redirector b.AssertFileContent("public/foo/bar/index.html", "ALIASTEMPLATE") } func TestTargetPathHTMLRedirectAlias(t *testing.T) { h := newAliasHandler(nil, loggers.NewDefault(), false) errIsNilForThisOS := runtime.GOOS != "windows" tests := []struct { value string expected string errIsNil bool }{ {"", "", false}, {"s", filepath.FromSlash("s/index.html"), true}, {"/", "", false}, {"alias 1", filepath.FromSlash("alias 1/index.html"), true}, {"alias 2/", filepath.FromSlash("alias 2/index.html"), true}, {"alias 3.html", "alias 3.html", true}, {"alias4.html", "alias4.html", true}, {"/alias 5.html", "alias 5.html", true}, {"/трям.html", "трям.html", true}, {"../../../../tmp/passwd", "", false}, {"/foo/../../../../tmp/passwd", filepath.FromSlash("tmp/passwd/index.html"), true}, {"foo/../../../../tmp/passwd", "", false}, {"C:\\Windows", filepath.FromSlash("C:\\Windows/index.html"), errIsNilForThisOS}, {"/trailing-space /", filepath.FromSlash("trailing-space /index.html"), errIsNilForThisOS}, {"/trailing-period./", filepath.FromSlash("trailing-period./index.html"), errIsNilForThisOS}, {"/tab\tseparated/", filepath.FromSlash("tab\tseparated/index.html"), errIsNilForThisOS}, {"/chrome/?p=help&ctx=keyboard#topic=3227046", filepath.FromSlash("chrome/?p=help&ctx=keyboard#topic=3227046/index.html"), errIsNilForThisOS}, {"/LPT1/Printer/", filepath.FromSlash("LPT1/Printer/index.html"), errIsNilForThisOS}, } for _, test := range tests { path, err := h.targetPathAlias(test.value) if (err == nil) != test.errIsNil { t.Errorf("Expected err == nil => %t, got: %t. err: %s", test.errIsNil, err == nil, err) continue } if err == nil && path != test.expected { t.Errorf("Expected: %q, got: %q", test.expected, path) } } } func TestAliasNIssue14053(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com" -- layouts/all.html -- All. -- content/page.md -- --- title: "Page" aliases: - n - y - no - yes --- ` b := Test(t, files) b.AssertPublishDir("n/index.html", "yes/index.html", "no/index.html", "yes/index.html") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__menus.go
hugolib/page__menus.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "sync" "github.com/gohugoio/hugo/navigation" ) type pageMenus struct { p *pageState q navigation.MenuQueryProvider pmInit sync.Once pm navigation.PageMenus } func (p *pageMenus) HasMenuCurrent(menuID string, me *navigation.MenuEntry) bool { _ = p.p.s.init.menus.Value(context.Background()) p.init() return p.q.HasMenuCurrent(menuID, me) } func (p *pageMenus) IsMenuCurrent(menuID string, inme *navigation.MenuEntry) bool { _ = p.p.s.init.menus.Value(context.Background()) p.init() return p.q.IsMenuCurrent(menuID, inme) } func (p *pageMenus) Menus() navigation.PageMenus { // There is a reverse dependency here. _ = p.p.s.init.menus.Value(context.Background()) return p.menus() } func (p *pageMenus) menus() navigation.PageMenus { p.init() return p.pm } func (p *pageMenus) init() { p.pmInit.Do(func() { p.q = navigation.NewMenuQueryProvider( p, p.p.s, p.p, ) params := p.p.Params() var menus any var ok bool if p.p.m.pageConfig.Menus != nil { menus = p.p.m.pageConfig.Menus } else { menus, ok = params["menus"] if !ok { menus = params["menu"] } } var err error p.pm, err = navigation.PageMenusFromPage(menus, p.p) if err != nil { p.p.s.Log.Errorln(p.p.wrapError(err)) } }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/hugo_sites_build_errors_test.go
hugolib/hugo_sites_build_errors_test.go
package hugolib import ( "fmt" "path/filepath" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/herrors" ) type testSiteBuildErrorAsserter struct { name string c *qt.C } func (t testSiteBuildErrorAsserter) getFileError(err error) herrors.FileError { t.c.Assert(err, qt.Not(qt.IsNil), qt.Commentf(t.name)) fe := herrors.UnwrapFileError(err) t.c.Assert(fe, qt.Not(qt.IsNil)) return fe } func (t testSiteBuildErrorAsserter) assertLineNumber(lineNumber int, err error) { t.c.Helper() fe := t.getFileError(err) t.c.Assert(fe.Position().LineNumber, qt.Equals, lineNumber, qt.Commentf(err.Error())) } func (t testSiteBuildErrorAsserter) assertErrorMessage(e1, e2 string) { // The error message will contain filenames with OS slashes. Normalize before compare. e1, e2 = filepath.ToSlash(e1), filepath.ToSlash(e2) t.c.Assert(e2, qt.Contains, e1) } func TestSiteBuildErrors(t *testing.T) { const ( yamlcontent = "yamlcontent" tomlcontent = "tomlcontent" jsoncontent = "jsoncontent" shortcode = "shortcode" base = "base" single = "single" ) type testCase struct { name string fileType string fileFixer func(content string) string assertErr func(a testSiteBuildErrorAsserter, err error) } createTestFiles := func(tc testCase) string { f := func(ftype, content string) string { if ftype != tc.fileType { return content } return tc.fileFixer(content) } return ` -- hugo.toml -- baseURL = "https://example.com" -- layouts/_shortcodes/sc.html -- ` + f(shortcode, `SHORTCODE L1 SHORTCODE L2 SHORTCODE L3: SHORTCODE L4: {{ .Page.Title }} `) + ` -- layouts/baseof.html -- ` + f(base, `BASEOF L1 BASEOF L2 BASEOF L3 BASEOF L4{{ if .Title }}{{ end }} {{block "main" .}}This is the main content.{{end}} BASEOF L6 `) + ` -- layouts/single.html -- ` + f(single, `{{ define "main" }} SINGLE L2: SINGLE L3: SINGLE L4: SINGLE L5: {{ .Title }} {{ .Content }} {{ end }} `) + ` -- layouts/foo/single.html -- ` + f(single, ` SINGLE L2: SINGLE L3: SINGLE L4: SINGLE L5: {{ .Title }} {{ .Content }} `) + ` -- content/myyaml.md -- ` + f(yamlcontent, `--- title: "The YAML" --- Some content. {{< sc >}} Some more text. The end. `) + ` -- content/mytoml.md -- ` + f(tomlcontent, `+++ title = "The TOML" p1 = "v" p2 = "v" p3 = "v" description = "Descriptioon" +++ Some content. `) + ` -- content/myjson.md -- ` + f(jsoncontent, `{ "title": "This is a title", "description": "This is a description." } Some content. `) } tests := []testCase{ { name: "Base template parse failed", fileType: base, fileFixer: func(content string) string { return strings.Replace(content, ".Title }}", ".Title }", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { a.assertLineNumber(4, err) }, }, { name: "Base template execute failed", fileType: base, fileFixer: func(content string) string { return strings.Replace(content, ".Title", ".Titles", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { a.assertLineNumber(4, err) }, }, { name: "Single template parse failed", fileType: single, fileFixer: func(content string) string { return strings.Replace(content, ".Title }}", ".Title }", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { fe := a.getFileError(err) a.c.Assert(fe.Position().LineNumber, qt.Equals, 5) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 1) a.assertErrorMessage("\"/layouts/foo/single.html:5:1\": parse of template failed: template: foo/single.html:5: unexpected \"}\" in operand", fe.Error()) }, }, { name: "Single template execute failed", fileType: single, fileFixer: func(content string) string { return strings.Replace(content, ".Title", ".Titles", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { fe := a.getFileError(err) a.c.Assert(fe.Position().LineNumber, qt.Equals, 5) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 14) a.assertErrorMessage("\"layouts/single.html:5:14\": execute of template failed", fe.Error()) }, }, { name: "Single template execute failed, long keyword", fileType: single, fileFixer: func(content string) string { return strings.Replace(content, ".Title", ".ThisIsAVeryLongTitle", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { fe := a.getFileError(err) a.c.Assert(fe.Position().LineNumber, qt.Equals, 5) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 14) a.assertErrorMessage("\"layouts/single.html:5:14\": execute of template failed", fe.Error()) }, }, { name: "Shortcode parse failed", fileType: shortcode, fileFixer: func(content string) string { return strings.Replace(content, ".Title }}", ".Title }", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { a.assertLineNumber(4, err) }, }, { name: "Shortcode execute failed", fileType: shortcode, fileFixer: func(content string) string { return strings.Replace(content, ".Title", ".Titles", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { fe := a.getFileError(err) // Make sure that it contains both the content file and template a.assertErrorMessage(`"content/myyaml.md:7:10": failed to render shortcode "sc": failed to process shortcode: "layouts/_shortcodes/sc.html:4:22": execute of template failed: template: shortcodes/sc.html:4:22: executing "shortcodes/sc.html" at <.Page.Titles>: can't evaluate field Titles in type page.Page`, fe.Error()) a.c.Assert(fe.Position().LineNumber, qt.Equals, 7) }, }, { name: "Shortode does not exist", fileType: yamlcontent, fileFixer: func(content string) string { return strings.Replace(content, "{{< sc >}}", "{{< nono >}}", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { fe := a.getFileError(err) a.c.Assert(fe.Position().LineNumber, qt.Equals, 7) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 10) a.assertErrorMessage(`"content/myyaml.md:7:10": failed to extract shortcode: template for shortcode "nono" not found`, fe.Error()) }, }, { name: "Invalid YAML front matter", fileType: yamlcontent, fileFixer: func(content string) string { return `--- title: "My YAML Content" foo bar --- ` }, assertErr: func(a testSiteBuildErrorAsserter, err error) { a.assertLineNumber(3, err) }, }, { name: "Invalid TOML front matter", fileType: tomlcontent, fileFixer: func(content string) string { return strings.Replace(content, "description = ", "description &", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { fe := a.getFileError(err) a.c.Assert(fe.Position().LineNumber, qt.Equals, 6) }, }, { name: "Invalid JSON front matter", fileType: jsoncontent, fileFixer: func(content string) string { return strings.Replace(content, "\"description\":", "\"description\"", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { fe := a.getFileError(err) a.c.Assert(fe.Position().LineNumber, qt.Equals, 3) }, }, { // See https://github.com/gohugoio/hugo/issues/5327 name: "Panic in template Execute", fileType: single, fileFixer: func(content string) string { return strings.Replace(content, ".Title", ".Parent.Parent.Parent", 1) }, assertErr: func(a testSiteBuildErrorAsserter, err error) { a.c.Assert(err, qt.Not(qt.IsNil)) fe := a.getFileError(err) a.c.Assert(fe.Position().LineNumber, qt.Equals, 5) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 21) }, }, } for _, test := range tests { test := test if test.name != "Base template parse failed" { continue } t.Run(test.name, func(t *testing.T) { t.Parallel() c := qt.New(t) errorAsserter := testSiteBuildErrorAsserter{ c: c, name: test.name, } files := createTestFiles(test) _, err := TestE(t, files) if test.assertErr != nil { test.assertErr(errorAsserter, err) } else { c.Assert(err, qt.IsNil) } }) } } // Issue 9852 func TestErrorMinify(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [minify] minifyOutput = true -- layouts/home.html -- <body> <script>=;</script> </body> ` b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) fes := herrors.UnwrapFileErrors(err) b.Assert(len(fes), qt.Equals, 1) fe := fes[0] b.Assert(fe, qt.IsNotNil) b.Assert(fe.Position().LineNumber, qt.Equals, 2) b.Assert(fe.Position().ColumnNumber, qt.Equals, 9) b.Assert(fe.Error(), qt.Contains, "unexpected = in expression on line 2 and column 9") b.Assert(filepath.ToSlash(fe.Position().Filename), qt.Contains, "hugo-transform-error") // os.Remove is not needed in txtar tests as the filesystem is ephemeral. // b.Assert(os.Remove(fe.Position().Filename), qt.IsNil) } func TestErrorNestedRender(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/_index.md -- --- title: "Home" --- -- layouts/home.html -- line 1 line 2 1{{ .Render "myview" }} -- layouts/myview.html -- line 1 12{{ partial "foo.html" . }} line 4 line 5 -- layouts/_partials/foo.html -- line 1 line 2 123{{ .ThisDoesNotExist }} line 4 ` b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) errors := herrors.UnwrapFileErrorsWithErrorContext(err) b.Assert(errors, qt.HasLen, 4) b.Assert(errors[0].Position().LineNumber, qt.Equals, 3) b.Assert(errors[0].Position().ColumnNumber, qt.Equals, 4) b.Assert(errors[0].Error(), qt.Contains, filepath.FromSlash(`"/layouts/home.html:3:4": execute of template failed`)) b.Assert(errors[0].ErrorContext().Lines, qt.DeepEquals, []string{"line 1", "line 2", "1{{ .Render \"myview\" }}"}) b.Assert(errors[2].Position().LineNumber, qt.Equals, 2) b.Assert(errors[2].Position().ColumnNumber, qt.Equals, 5) b.Assert(errors[2].ErrorContext().Lines, qt.DeepEquals, []string{"line 1", "12{{ partial \"foo.html\" . }}", "line 4", "line 5"}) b.Assert(errors[3].Position().LineNumber, qt.Equals, 3) b.Assert(errors[3].Position().ColumnNumber, qt.Equals, 6) b.Assert(errors[3].ErrorContext().Lines, qt.DeepEquals, []string{"line 1", "line 2", "123{{ .ThisDoesNotExist }}", "line 4"}) } func TestErrorNestedShortcode(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/_index.md -- --- title: "Home" --- ## Hello {{< hello >}} -- layouts/home.html -- line 1 line 2 {{ .Content }} line 5 -- layouts/_shortcodes/hello.html -- line 1 12{{ partial "foo.html" . }} line 4 line 5 -- layouts/_partials/foo.html -- line 1 line 2 123{{ .ThisDoesNotExist }} line 4 ` b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) errors := herrors.UnwrapFileErrorsWithErrorContext(err) b.Assert(errors, qt.HasLen, 4) b.Assert(errors[1].Position().LineNumber, qt.Equals, 6) b.Assert(errors[1].Position().ColumnNumber, qt.Equals, 1) b.Assert(errors[1].ErrorContext().ChromaLexer, qt.Equals, "md") b.Assert(errors[1].Error(), qt.Contains, filepath.FromSlash(`"/content/_index.md:6:1": failed to render shortcode "hello": failed to process shortcode: "/layouts/_shortcodes/hello.html:2:5":`)) b.Assert(errors[1].ErrorContext().Lines, qt.DeepEquals, []string{"", "## Hello", "{{< hello >}}", ""}) b.Assert(errors[2].ErrorContext().Lines, qt.DeepEquals, []string{"line 1", "12{{ partial \"foo.html\" . }}", "line 4", "line 5"}) b.Assert(errors[3].Position().LineNumber, qt.Equals, 3) b.Assert(errors[3].Position().ColumnNumber, qt.Equals, 6) b.Assert(errors[3].ErrorContext().Lines, qt.DeepEquals, []string{"line 1", "line 2", "123{{ .ThisDoesNotExist }}", "line 4"}) } func TestErrorRenderHookHeading(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/_index.md -- --- title: "Home" --- ## Hello -- layouts/home.html -- line 1 line 2 {{ .Content }} line 5 -- layouts/_markup/render-heading.html -- line 1 12{{ .Levels }} line 4 line 5 ` b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) errors := herrors.UnwrapFileErrorsWithErrorContext(err) b.Assert(errors, qt.HasLen, 3) b.Assert(errors[0].Error(), qt.Contains, filepath.FromSlash(`"/content/_index.md:2:5": "/layouts/_markup/render-heading.html:2:5": execute of template failed`)) } func TestErrorRenderHookCodeblock(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/_index.md -- --- title: "Home" --- ## Hello §§§ foo bar §§§ -- layouts/home.html -- line 1 line 2 {{ .Content }} line 5 -- layouts/_markup/render-codeblock-foo.html -- line 1 12{{ .Foo }} line 4 line 5 ` b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) errors := herrors.UnwrapFileErrorsWithErrorContext(err) b.Assert(errors, qt.HasLen, 3) first := errors[0] b.Assert(first.Error(), qt.Contains, filepath.FromSlash(`"/content/_index.md:7:1": "/layouts/_markup/render-codeblock-foo.html:2:5": execute of template failed`)) } func TestErrorInBaseTemplate(t *testing.T) { t.Parallel() filesTemplate := ` -- hugo.toml -- -- content/_index.md -- --- title: "Home" --- -- layouts/baseof.html -- line 1 base line 2 base {{ block "main" . }}empty{{ end }} line 4 base {{ block "toc" . }}empty{{ end }} -- layouts/home.html -- {{ define "main" }} line 2 index line 3 index line 4 index {{ end }} {{ define "toc" }} TOC: {{ partial "toc.html" . }} {{ end }} -- layouts/_partials/toc.html -- toc line 1 toc line 2 toc line 3 toc line 4 ` t.Run("base template", func(t *testing.T) { files := strings.Replace(filesTemplate, "line 4 base", "123{{ .ThisDoesNotExist \"abc\" }}", 1) b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `baseof.html:4:6`) }) t.Run("home template", func(t *testing.T) { files := strings.Replace(filesTemplate, "line 3 index", "1234{{ .ThisDoesNotExist \"abc\" }}", 1) b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `home.html:3:7"`) }) t.Run("partial from define", func(t *testing.T) { files := strings.Replace(filesTemplate, "toc line 2", "12345{{ .ThisDoesNotExist \"abc\" }}", 1) b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `toc.html:2:8"`) }) } // https://github.com/gohugoio/hugo/issues/5375 func TestSiteBuildTimeout(t *testing.T) { t.Parallel() var filesBuilder strings.Builder filesBuilder.WriteString(` -- hugo.toml -- timeout = 5 -- layouts/single.html -- {{ .WordCount }} -- layouts/_shortcodes/c.html -- {{ range .Page.Site.RegularPages }} {{ .WordCount }} {{ end }} `) for i := 1; i < 100; i++ { filesBuilder.WriteString(fmt.Sprintf(` -- content/page%d.md -- --- title: "A page" --- {{< c >}} `, i)) } _, err := TestE(t, filesBuilder.String()) qt.Assert(t, err, qt.Not(qt.IsNil)) qt.Assert(t, err.Error(), qt.Contains, "timed out rendering the page content") } func TestErrorTemplateRuntime(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- layouts/home.html -- Home. {{ .ThisDoesNotExist }} ` b, err := TestE(t, files) b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`/layouts/home.html:2:3`)) b.Assert(err.Error(), qt.Contains, `can't evaluate field ThisDoesNotExist`) } func TestErrorFrontmatterYAMLSyntax(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/_index.md -- --- line1: 'value1' x line2: 'value2' line3: 'value3' --- ` b, err := TestE(t, files) b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, "[2:1] non-map value is specified") fes := herrors.UnwrapFileErrors(err) b.Assert(len(fes), qt.Equals, 1) fe := fes[0] b.Assert(fe, qt.Not(qt.IsNil)) pos := fe.Position() b.Assert(pos.Filename, qt.Contains, filepath.FromSlash("content/_index.md")) b.Assert(fe.ErrorContext(), qt.Not(qt.IsNil)) b.Assert(pos.LineNumber, qt.Equals, 8) b.Assert(pos.ColumnNumber, qt.Equals, 1) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__content.go
hugolib/page__content.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "errors" "fmt" "html/template" "io" "strings" "sync/atomic" "unicode/utf8" maps0 "maps" "github.com/bep/helpers/contexthelpers" "github.com/bep/logg" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/predicate" "github.com/gohugoio/hugo/common/types/hstring" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/markup" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/markup/goldmark/hugocontext" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/tpl" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" ) const ( internalSummaryDividerBase = "HUGOMORE42" ) var ( internalSummaryDividerPreString = "\n\n" + internalSummaryDividerBase + "\n\n" internalSummaryDividerPre = []byte(internalSummaryDividerPreString) ) type pageContentReplacement struct { val []byte source pageparser.Item } func (m *pageMetaSource) parseFrontMatter( h *HugoSites, sid uint64, ) error { var filename string if m.f != nil { filename = m.f.Filename() } m.pi = &contentParseInfo{ h: h, sid: sid, openSource: m.openSource, shortcodeParseInfo: newShortcodeHandler(filename, h.Deps), } source, err := m.pi.contentSource(m) if err != nil { return err } items, err := pageparser.ParseBytes( source, pageparser.Config{ NoFrontMatter: m.noFrontMatter, }, ) if err != nil { return err } m.pi.itemsStep1 = items if err := m.pi.parseSource(source, m.noFrontMatter); err != nil { return err } return nil } func (m *pageMeta) newCachedContent(s *Site) (*cachedContent, error) { if m.pageMetaSource.pi == nil { panic("pageMeta.pageMetaSource.pi must be set before creating cachedContent") } c := &cachedContent{ pm: s.pageMap, StaleInfo: m, pi: m.pi, enableEmoji: s.conf.EnableEmoji, scopes: maps.NewCache[string, *cachedContentScope](), } var hasName predicate.P[string] = m.pi.shortcodeParseInfo.hasName c.hasShortcode.Store(&hasName) return c, nil } // Content cached for a page instance. type cachedContent struct { pm *pageMap resource.StaleInfo // Parsed content. pi *contentParseInfo enableEmoji bool // Whether the content has a given shortcode name. hasShortcode atomic.Pointer[predicate.P[string]] scopes *maps.Cache[string, *cachedContentScope] } func (c *cachedContent) getOrCreateScope(scope string, pco *pageContentOutput) *cachedContentScope { key := scope + pco.po.f.Name cs, _ := c.scopes.GetOrCreate(key, func() (*cachedContentScope, error) { return &cachedContentScope{ cachedContent: c, pco: pco, scope: scope, }, nil }) return cs } // contentParseInfo is shared between all Page instances created from the same source. type contentParseInfo struct { h *HugoSites sid uint64 // The source bytes. openSource hugio.OpenReadSeekCloser frontMatter map[string]any // Whether the parsed content contains a summary separator. hasSummaryDivider bool // Returns the position in bytes after any front matter. posMainContent int // Indicates whether we must do placeholder replacements. hasNonMarkdownShortcode bool // Items from the page parser. // These maps directly to the source itemsStep1 pageparser.Items // *shortcode, pageContentReplacement or pageparser.Item itemsStep2 []any // The shortcode handler. shortcodeParseInfo *shortcodeParseInfo } func (pi *contentParseInfo) AddBytes(item pageparser.Item) { pi.itemsStep2 = append(pi.itemsStep2, item) } func (pi *contentParseInfo) AddReplacement(val []byte, source pageparser.Item) { pi.itemsStep2 = append(pi.itemsStep2, pageContentReplacement{val: val, source: source}) } func (pi *contentParseInfo) AddShortcode(s *shortcode) { pi.itemsStep2 = append(pi.itemsStep2, s) if s.insertPlaceholder() { pi.hasNonMarkdownShortcode = true } } // contentToRenderForItems returns the content to be processed by Goldmark or similar. func (pi *contentParseInfo) contentToRender(ctx context.Context, source []byte, renderedShortcodes map[string]shortcodeRenderer) ([]byte, bool, error) { var hasVariants bool c := make([]byte, 0, len(source)+(len(source)/10)) for _, it := range pi.itemsStep2 { switch v := it.(type) { case pageparser.Item: c = append(c, source[v.Pos():v.Pos()+len(v.Val(source))]...) case pageContentReplacement: c = append(c, v.val...) case *shortcode: if !v.insertPlaceholder() { // Insert the rendered shortcode. renderedShortcode, found := renderedShortcodes[v.placeholder] if !found { // This should never happen. panic(fmt.Sprintf("rendered shortcode %q not found", v.placeholder)) } b, more, err := renderedShortcode.renderShortcode(ctx) if err != nil { return nil, false, fmt.Errorf("failed to render shortcode: %w", err) } hasVariants = hasVariants || more c = append(c, []byte(b)...) } else { // Insert the placeholder so we can insert the content after // markdown processing. c = append(c, []byte(v.placeholder)...) } default: panic(fmt.Sprintf("unknown item type %T", it)) } } return c, hasVariants, nil } func (c *cachedContent) IsZero() bool { return len(c.pi.itemsStep2) == 0 } func (pi *contentParseInfo) parseSource(source []byte, skipFrontMatter bool) error { if len(pi.itemsStep1) == 0 { return nil } s := pi.shortcodeParseInfo fail := func(err error, i pageparser.Item) error { if fe, ok := err.(herrors.FileError); ok { return fe } pos := posFromInput("", source, i.Pos()) return herrors.NewFileErrorFromPos(err, pos) } iter := pageparser.NewIterator(pi.itemsStep1) // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var ordinal int Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): if !skipFrontMatter { if err := pi.parseFrontMatter(it, iter, source); err != nil { return err } } next := iter.Peek() if !next.IsDone() { pi.posMainContent = next.Pos() } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos() } if item.IsNonWhitespace(source) { // Done return false } return true } iter.PeekWalk(f) pi.hasSummaryDivider = true // The content may be rendered by Goldmark or similar, // and we need to track the summary. pi.AddReplacement(internalSummaryDividerPre, it) // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, source, iter) if err != nil { return fail(err, it) } currShortcode.pos = it.Pos() currShortcode.length = iter.Current().Pos() - it.Pos() if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", pi.sid, uint64(currShortcode.ordinal)) } if currShortcode.name != "" { s.addName(currShortcode.name) } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", pi.sid, uint64(ordinal)) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) pi.AddShortcode(currShortcode) case it.IsEOF(): break Loop case it.IsError(): return fail(it.Err, it) default: pi.AddBytes(it) } } return nil } func (pi *contentParseInfo) parseFrontMatter(it pageparser.Item, iter *pageparser.Iterator, source []byte) error { if pi.frontMatter != nil { return nil } f := pageparser.FormatFromFrontMatterType(it.Type) var err error pi.frontMatter, err = metadecoders.Default.UnmarshalToMap(it.Val(source), f) if err != nil { fe := herrors.UnwrapFileError(err) if fe == nil { fe = herrors.NewFileError(err) } pos := fe.Position() // Offset the starting position of front matter. offset := iter.LineNumber(source) - 1 pos.LineNumber += offset fe.UpdatePosition(pos) fe.SetFilename("") // It will be set later. return fe } return nil } func (c *cachedContent) mustSource() []byte { source, err := c.pi.contentSource(c) if err != nil { panic(err) } return source } func (pi *contentParseInfo) contentSource(s resource.StaleInfo) ([]byte, error) { key := pi.sid versionv := s.StaleVersion() v, err := pi.h.cacheContentSource.GetOrCreate(key, func(uint64) (*resources.StaleValue[[]byte], error) { b, err := pi.readSourceAll() if err != nil { return nil, err } return &resources.StaleValue[[]byte]{ Value: b, StaleVersionFunc: func() uint32 { return s.StaleVersion() - versionv }, }, nil }) if err != nil { return nil, err } return v.Value, nil } func (pi *contentParseInfo) readSourceAll() ([]byte, error) { if pi.openSource == nil { return []byte{}, nil } r, err := pi.openSource() if err != nil { return nil, err } defer r.Close() return io.ReadAll(r) } type contentTableOfContents struct { // For Goldmark we split Parse and Render. astDoc any tableOfContents *tableofcontents.Fragments tableOfContentsHTML template.HTML // Temporary storage of placeholders mapped to their content. // These are shortcodes etc. Some of these will need to be replaced // after any markup is rendered, so they share a common prefix. contentPlaceholders map[string]shortcodeRenderer contentToRender []byte } type contentSummary struct { content template.HTML contentWithoutSummary template.HTML summary page.Summary } type contentPlainPlainWords struct { plain string plainWords []string wordCount int fuzzyWordCount int readingTime int } func (c *cachedContentScope) keyScope(ctx context.Context) string { return hugo.GetMarkupScope(ctx) + c.pco.po.f.Name + fmt.Sprintf("_%d", c.pi.sid) } func (c *cachedContentScope) contentRendered(ctx context.Context) (contentSummary, error) { cp := c.pco ctx = tpl.Context.DependencyScope.Set(ctx, pageDependencyScopeGlobal) key := c.keyScope(ctx) versionv := c.version(cp) v, err := c.pm.cacheContentRendered.GetOrCreate(key, func(string) (*resources.StaleValue[contentSummary], error) { cp.po.p.s.Log.Trace(logg.StringFunc(func() string { return fmt.Sprintln("contentRendered", key) })) cp.po.p.s.h.contentRenderCounter.Add(1) cp.contentRendered.Store(true) po := cp.po ct, err := c.contentToC(ctx) if err != nil { return nil, err } rs, err := func() (*resources.StaleValue[contentSummary], error) { rs := &resources.StaleValue[contentSummary]{ StaleVersionFunc: func() uint32 { return c.version(cp) - versionv }, } if len(c.pi.itemsStep2) == 0 { // Nothing to do. return rs, nil } var b []byte if ct.astDoc != nil { // The content is parsed, but not rendered. r, ok, err := po.contentRenderer.RenderContent(ctx, ct.contentToRender, ct.astDoc) if err != nil { return nil, err } if !ok { return nil, errors.New("invalid state: astDoc is set but RenderContent returned false") } b = r.Bytes() } else { // Copy the content to be rendered. b = make([]byte, len(ct.contentToRender)) copy(b, ct.contentToRender) } // There are one or more replacement tokens to be replaced. var hasShortcodeVariants bool tokenHandler := func(ctx context.Context, token string) ([]byte, error) { if token == tocShortcodePlaceholder { return []byte(ct.tableOfContentsHTML), nil } renderer, found := ct.contentPlaceholders[token] if found { repl, more, err := renderer.renderShortcode(ctx) if err != nil { return nil, err } hasShortcodeVariants = hasShortcodeVariants || more return repl, nil } // This should never happen. panic(fmt.Errorf("unknown shortcode token %q (number of tokens: %d)", token, len(ct.contentPlaceholders))) } b, err = expandShortcodeTokens(ctx, b, tokenHandler) if err != nil { return nil, err } if hasShortcodeVariants { cp.po.p.incrPageOutputTemplateVariation() } var result contentSummary if c.pi.hasSummaryDivider { s := string(b) summarized := page.ExtractSummaryFromHTMLWithDivider(cp.po.p.m.pageConfigSource.ContentMediaType, s, internalSummaryDividerBase) result.summary = page.Summary{ Text: template.HTML(summarized.Summary()), Type: page.SummaryTypeManual, Truncated: summarized.Truncated(), } result.contentWithoutSummary = template.HTML(summarized.ContentWithoutSummary()) result.content = template.HTML(summarized.Content()) } else { result.content = template.HTML(string(b)) } if !c.pi.hasSummaryDivider && cp.po.p.m.pageConfig.Summary == "" { numWords := cp.po.p.s.conf.SummaryLength isCJKLanguage := cp.po.p.m.pageConfig.IsCJKLanguage summary := page.ExtractSummaryFromHTML(cp.po.p.m.pageConfigSource.ContentMediaType, string(result.content), numWords, isCJKLanguage) result.summary = page.Summary{ Text: template.HTML(summary.Summary()), Type: page.SummaryTypeAuto, Truncated: summary.Truncated(), } result.contentWithoutSummary = template.HTML(summary.ContentWithoutSummary()) } rs.Value = result return rs, nil }() if err != nil { return rs, cp.po.p.wrapError(err) } if rs.Value.summary.IsZero() { b, err := cp.po.contentRenderer.ParseAndRenderContent(ctx, []byte(cp.po.p.m.pageConfig.Summary), false) if err != nil { return nil, err } html := cp.po.p.s.ContentSpec.TrimShortHTML(b.Bytes(), cp.po.p.m.pageConfigSource.Content.Markup) rs.Value.summary = page.Summary{ Text: helpers.BytesToHTML(html), Type: page.SummaryTypeFrontMatter, Truncated: rs.Value.summary.Truncated, } rs.Value.contentWithoutSummary = rs.Value.content } return rs, err }) if err != nil { return contentSummary{}, cp.po.p.wrapError(err) } return v.Value, nil } func (c *cachedContentScope) mustContentToC(ctx context.Context) contentTableOfContents { ct, err := c.contentToC(ctx) if err != nil { panic(err) } return ct } type contextKey uint8 const ( contextKeyContentCallback contextKey = iota ) var setGetContentCallbackInContext = contexthelpers.NewContextDispatcher[func(*pageContentOutput, contentTableOfContents)](contextKeyContentCallback) func (c *cachedContentScope) contentToC(ctx context.Context) (contentTableOfContents, error) { cp := c.pco key := c.keyScope(ctx) versionv := c.version(cp) v, err := c.pm.contentTableOfContents.GetOrCreate(key, func(string) (*resources.StaleValue[contentTableOfContents], error) { source, err := c.pi.contentSource(c) if err != nil { return nil, err } var ct contentTableOfContents if err := cp.initRenderHooks(); err != nil { return nil, err } po := cp.po p := po.p ct.contentPlaceholders, err = c.pi.shortcodeParseInfo.prepareShortcodesForPage(po, false) if err != nil { return nil, err } // Callback called from below (e.g. in .RenderString) ctxCallback := func(cp2 *pageContentOutput, ct2 contentTableOfContents) { cp.otherOutputs.Set(cp2.po.p.pid, cp2) // Merge content placeholders maps0.Copy(ct.contentPlaceholders, ct2.contentPlaceholders) if p.s.conf.Internal.Watch { for _, s := range cp2.po.p.m.content.pi.shortcodeParseInfo.shortcodes { cp.trackDependency(s.templ) } } // Transfer shortcode names so HasShortcode works for shortcodes from included pages. combined := cp.po.p.m.content.hasShortcode.Load().Or(*cp2.po.p.m.content.hasShortcode.Load()) cp.po.p.m.content.hasShortcode.Store(&combined) if cp2.po.p.pageOutputTemplateVariationsState.Load() > 0 { cp.po.p.incrPageOutputTemplateVariation() } } ctx = setGetContentCallbackInContext.Set(ctx, ctxCallback) var hasVariants bool ct.contentToRender, hasVariants, err = c.pi.contentToRender(ctx, source, ct.contentPlaceholders) if err != nil { return nil, err } if hasVariants { p.incrPageOutputTemplateVariation() } isHTML := cp.po.p.m.pageConfigSource.ContentMediaType.IsHTML() if !isHTML { createAndSetToC := func(tocProvider converter.TableOfContentsProvider) error { cfg := p.s.ContentSpec.Converters.GetMarkupConfig() ct.tableOfContents = tocProvider.TableOfContents() ct.tableOfContentsHTML, err = ct.tableOfContents.ToHTML( cfg.TableOfContents.StartLevel, cfg.TableOfContents.EndLevel, cfg.TableOfContents.Ordered, ) return err } // If the converter supports doing the parsing separately, we do that. parseResult, ok, err := po.contentRenderer.ParseContent(ctx, ct.contentToRender) if err != nil { return nil, err } if ok { // This is Goldmark. // Store away the parse result for later use. createAndSetToC(parseResult) ct.astDoc = parseResult.Doc() } else { // This is Asciidoctor etc. r, err := po.contentRenderer.ParseAndRenderContent(ctx, ct.contentToRender, true) if err != nil { return nil, err } ct.contentToRender = r.Bytes() if tocProvider, ok := r.(converter.TableOfContentsProvider); ok { createAndSetToC(tocProvider) } else { tmpContent, tmpTableOfContents := helpers.ExtractTOC(ct.contentToRender) ct.tableOfContentsHTML = helpers.BytesToHTML(tmpTableOfContents) ct.tableOfContents = tableofcontents.Empty ct.contentToRender = tmpContent } } } return &resources.StaleValue[contentTableOfContents]{ Value: ct, StaleVersionFunc: func() uint32 { return c.version(cp) - versionv }, }, nil }) if err != nil { return contentTableOfContents{}, err } return v.Value, nil } func (c *cachedContent) version(cp *pageContentOutput) uint32 { // Both of these gets incremented on change. return c.StaleVersion() + cp.contentRenderedVersion } func (c *cachedContentScope) contentPlain(ctx context.Context) (contentPlainPlainWords, error) { cp := c.pco key := c.keyScope(ctx) versionv := c.version(cp) v, err := c.pm.cacheContentPlain.GetOrCreateWitTimeout(key, cp.po.p.s.Conf.Timeout(), func(string) (*resources.StaleValue[contentPlainPlainWords], error) { var result contentPlainPlainWords rs := &resources.StaleValue[contentPlainPlainWords]{ StaleVersionFunc: func() uint32 { return c.version(cp) - versionv }, } rendered, err := c.contentRendered(ctx) if err != nil { return nil, err } result.plain = tpl.StripHTML(string(rendered.content)) result.plainWords = strings.Fields(result.plain) isCJKLanguage := cp.po.p.m.pageConfig.IsCJKLanguage if isCJKLanguage { result.wordCount = 0 for _, word := range result.plainWords { runeCount := utf8.RuneCountInString(word) if len(word) == runeCount { result.wordCount++ } else { result.wordCount += runeCount } } } else { result.wordCount = helpers.TotalWords(result.plain) } // TODO(bep) is set in a test. Fix that. if result.fuzzyWordCount == 0 { result.fuzzyWordCount = (result.wordCount + 100) / 100 * 100 } if isCJKLanguage { result.readingTime = (result.wordCount + 500) / 501 } else { result.readingTime = (result.wordCount + 212) / 213 } rs.Value = result return rs, nil }) if err != nil { if herrors.IsTimeoutError(err) { err = fmt.Errorf("timed out rendering the page content. Extend the `timeout` limit in your Hugo config file: %w", err) } return contentPlainPlainWords{}, err } return v.Value, nil } type cachedContentScope struct { *cachedContent pco *pageContentOutput scope string } func (c *cachedContentScope) prepareContext(ctx context.Context) context.Context { // A regular page's shortcode etc. may be rendered by e.g. the home page, // so we need to track any changes to this content's page. ctx = tpl.Context.DependencyManagerScopedProvider.Set(ctx, c.pco.po.p) // The markup scope is recursive, so if already set to a non zero value, preserve that value. if s := hugo.GetMarkupScope(ctx); s != "" || s == c.scope { return ctx } return hugo.SetMarkupScope(ctx, c.scope) } func (c *cachedContentScope) Render(ctx context.Context) (page.Content, error) { return c, nil } func (c *cachedContentScope) Content(ctx context.Context) (template.HTML, error) { ctx = c.prepareContext(ctx) cr, err := c.contentRendered(ctx) if err != nil { return "", err } return cr.content, nil } func (c *cachedContentScope) ContentWithoutSummary(ctx context.Context) (template.HTML, error) { ctx = c.prepareContext(ctx) cr, err := c.contentRendered(ctx) if err != nil { return "", err } return cr.contentWithoutSummary, nil } func (c *cachedContentScope) Summary(ctx context.Context) (page.Summary, error) { ctx = c.prepareContext(ctx) rendered, err := c.contentRendered(ctx) return rendered.summary, err } func (c *cachedContentScope) RenderString(ctx context.Context, args ...any) (template.HTML, error) { ctx = c.prepareContext(ctx) if len(args) < 1 || len(args) > 2 { return "", errors.New("want 1 or 2 arguments") } pco := c.pco var contentToRender string opts := defaultRenderStringOpts sidx := 1 if len(args) == 1 { sidx = 0 } else { m, ok := args[0].(map[string]any) if !ok { return "", errors.New("first argument must be a map") } if err := mapstructure.WeakDecode(m, &opts); err != nil { return "", fmt.Errorf("failed to decode options: %w", err) } if opts.Markup != "" { opts.Markup = markup.ResolveMarkup(opts.Markup) } } contentToRenderv := args[sidx] if _, ok := contentToRenderv.(hstring.HTML); ok { // This content is already rendered, this is potentially // a infinite recursion. return "", errors.New("text is already rendered, repeating it may cause infinite recursion") } var err error contentToRender, err = cast.ToStringE(contentToRenderv) if err != nil { return "", err } if err = pco.initRenderHooks(); err != nil { return "", err } conv := pco.po.p.getContentConverter() if opts.Markup != "" && opts.Markup != pco.po.p.m.pageConfigSource.ContentMediaType.SubType { var err error conv, err = pco.po.p.m.newContentConverter(pco.po.p, opts.Markup) if err != nil { return "", pco.po.p.wrapError(err) } } var rendered []byte parseInfo := &contentParseInfo{ h: pco.po.p.s.h, sid: pco.po.p.pid, } if pageparser.HasShortcode(contentToRender) { contentToRenderb := []byte(contentToRender) // String contains a shortcode. parseInfo.itemsStep1, err = pageparser.ParseBytes(contentToRenderb, pageparser.Config{ NoFrontMatter: true, NoSummaryDivider: true, }) if err != nil { return "", err } parseInfo.shortcodeParseInfo = newShortcodeHandler(pco.po.p.pathOrTitle(), pco.po.p.s.h.Deps) if err := parseInfo.parseSource(contentToRenderb, true); err != nil { return "", err } placeholders, err := parseInfo.shortcodeParseInfo.prepareShortcodesForPage(pco.po, true) if err != nil { return "", err } contentToRender, hasVariants, err := parseInfo.contentToRender(ctx, contentToRenderb, placeholders) if err != nil { return "", err } if hasVariants { pco.po.p.incrPageOutputTemplateVariation() } b, err := pco.renderContentWithConverter(ctx, conv, contentToRender, false) if err != nil { return "", pco.po.p.wrapError(err) } rendered = b.Bytes() if parseInfo.hasNonMarkdownShortcode { var hasShortcodeVariants bool tokenHandler := func(ctx context.Context, token string) ([]byte, error) { if token == tocShortcodePlaceholder { toc, err := c.contentToC(ctx) if err != nil { return nil, err } // The Page's TableOfContents was accessed in a shortcode. return []byte(toc.tableOfContentsHTML), nil } renderer, found := placeholders[token] if found { repl, more, err := renderer.renderShortcode(ctx) if err != nil { return nil, err } hasShortcodeVariants = hasShortcodeVariants || more return repl, nil } // This should not happen. return nil, fmt.Errorf("RenderString: unknown shortcode token %q", token) } rendered, err = expandShortcodeTokens(ctx, rendered, tokenHandler) if err != nil { return "", err } if hasShortcodeVariants { pco.po.p.incrPageOutputTemplateVariation() } } // We need a consolidated view in $page.HasShortcode combined := pco.po.p.m.content.hasShortcode.Load().Or(parseInfo.shortcodeParseInfo.hasName) pco.po.p.m.content.hasShortcode.Store(&combined) } else { c, err := pco.renderContentWithConverter(ctx, conv, []byte(contentToRender), false) if err != nil { return "", pco.po.p.wrapError(err) } rendered = c.Bytes() } if opts.Display == "inline" { markup := pco.po.p.m.pageConfigSource.Content.Markup if opts.Markup != "" { markup = pco.po.p.s.ContentSpec.ResolveMarkup(opts.Markup) } rendered = pco.po.p.s.ContentSpec.TrimShortHTML(rendered, markup) } return template.HTML(string(rendered)), nil } func (c *cachedContentScope) RenderShortcodes(ctx context.Context) (template.HTML, error) { ctx = c.prepareContext(ctx) pco := c.pco content := pco.po.p.m.content source, err := content.pi.contentSource(content) if err != nil { return "", err } ct, err := c.contentToC(ctx) if err != nil { return "", err } var insertPlaceholders bool var hasVariants bool cb := setGetContentCallbackInContext.Get(ctx) if cb != nil { insertPlaceholders = true } cc := make([]byte, 0, len(source)+(len(source)/10)) for _, it := range content.pi.itemsStep2 { switch v := it.(type) { case pageparser.Item: cc = append(cc, source[v.Pos():v.Pos()+len(v.Val(source))]...) case pageContentReplacement: // Ignore. case *shortcode: if !insertPlaceholders || !v.insertPlaceholder() { // Insert the rendered shortcode. renderedShortcode, found := ct.contentPlaceholders[v.placeholder] if !found { // This should never happen. panic(fmt.Sprintf("rendered shortcode %q not found", v.placeholder)) } b, more, err := renderedShortcode.renderShortcode(ctx) if err != nil { return "", fmt.Errorf("failed to render shortcode: %w", err) } hasVariants = hasVariants || more cc = append(cc, []byte(b)...) } else { // Insert the placeholder so we can insert the content after // markdown processing. cc = append(cc, []byte(v.placeholder)...) } default: panic(fmt.Sprintf("unknown item type %T", it)) } } if hasVariants { pco.po.p.incrPageOutputTemplateVariation() } if cb != nil { cb(pco, ct) } if tpl.Context.IsInGoldmark.Get(ctx) { // This content will be parsed and rendered by Goldmark. // Wrap it in a special Hugo markup to assign the correct Page from // the stack. return template.HTML(hugocontext.Wrap(cc, pco.po.p.pid)), nil } return helpers.BytesToHTML(cc), nil } func (c *cachedContentScope) Plain(ctx context.Context) string { ctx = c.prepareContext(ctx) return c.mustContentPlain(ctx).plain } func (c *cachedContentScope) PlainWords(ctx context.Context) []string { ctx = c.prepareContext(ctx) return c.mustContentPlain(ctx).plainWords } func (c *cachedContentScope) WordCount(ctx context.Context) int { ctx = c.prepareContext(ctx) return c.mustContentPlain(ctx).wordCount } func (c *cachedContentScope) FuzzyWordCount(ctx context.Context) int { ctx = c.prepareContext(ctx) return c.mustContentPlain(ctx).fuzzyWordCount } func (c *cachedContentScope) ReadingTime(ctx context.Context) int { ctx = c.prepareContext(ctx) return c.mustContentPlain(ctx).readingTime } func (c *cachedContentScope) Len(ctx context.Context) int { ctx = c.prepareContext(ctx) return len(c.mustContentRendered(ctx).content) } func (c *cachedContentScope) Fragments(ctx context.Context) *tableofcontents.Fragments { ctx = c.prepareContext(ctx) toc := c.mustContentToC(ctx).tableOfContents if toc == nil { return nil } return toc } func (c *cachedContentScope) fragmentsHTML(ctx context.Context) template.HTML { ctx = c.prepareContext(ctx) return c.mustContentToC(ctx).tableOfContentsHTML } func (c *cachedContentScope) mustContentPlain(ctx context.Context) contentPlainPlainWords { r, err := c.contentPlain(ctx) if err != nil { c.pco.fail(err) } return r } func (c *cachedContentScope) mustContentRendered(ctx context.Context) contentSummary { r, err := c.contentRendered(ctx) if err != nil { c.pco.fail(err) } return r }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/hugo_modules_test.go
hugolib/hugo_modules_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "testing" qt "github.com/frankban/quicktest" ) func TestModulesWithContent(t *testing.T) { t.Parallel() content := func(id string) string { return fmt.Sprintf(`--- title: Title %s --- Content %s `, id, id) } i18nContent := func(id, value string) string { return fmt.Sprintf(` [%s] other = %q `, id, value) } files := ` -- hugo.toml -- baseURL="https://example.org" defaultContentLanguage = "en" [module] [[module.imports]] path="a" [[module.imports.mounts]] source="myacontent" target="content/blog" lang="en" [[module.imports]] path="b" [[module.imports.mounts]] source="mybcontent" target="content/blog" lang="nn" [[module.imports]] path="c" [[module.imports]] path="d" [languages] [languages.en] title = "Title in English" languageName = "English" weight = 1 [languages.nn] languageName = "Nynorsk" weight = 2 title = "Tittel på nynorsk" [languages.nb] languageName = "Bokmål" weight = 3 title = "Tittel på bokmål" [languages.fr] languageName = "French" weight = 4 title = "French Title" -- layouts/home.html -- {{ range .Site.RegularPages }} |{{ .Title }}|{{ .RelPermalink }}|{{ .Plain }} {{ end }} {{ $data := .Site.Data }} Data Common: {{ $data.common.value }} Data C: {{ $data.c.value }} Data D: {{ $data.d.value }} All Data: {{ $data }} i18n hello1: {{ i18n "hello1" . }} i18n theme: {{ i18n "theme" . }} i18n theme2: {{ i18n "theme2" . }} -- themes/a/myacontent/page.md -- ` + content("theme-a-en") + ` -- themes/b/mybcontent/page.md -- ` + content("theme-b-nn") + ` -- themes/c/content/blog/c.md -- ` + content("theme-c-nn") + ` -- data/common.toml -- value="Project" -- themes/c/data/common.toml -- value="Theme C" -- themes/c/data/c.toml -- value="Hugo Rocks!" -- themes/d/data/c.toml -- value="Hugo Rodcks!" -- themes/d/data/d.toml -- value="Hugo Rodks!" -- i18n/en.toml -- ` + i18nContent("hello1", "Project") + ` -- themes/c/i18n/en.toml -- [hello1] other="Theme C Hello" [theme] other="Theme C" -- themes/d/i18n/en.toml -- ` + i18nContent("theme", "Theme D") + ` -- themes/d/i18n/en.toml -- ` + i18nContent("theme2", "Theme2 D") + ` -- themes/c/static/hello.txt -- Hugo Rocks!" ` b := Test(t, files) b.AssertFileContent("public/index.html", "|Title theme-a-en|/blog/page/|Content theme-a-en") b.AssertFileContent("public/nn/index.html", "|Title theme-b-nn|/nn/blog/page/|Content theme-b-nn") // Data b.AssertFileContent("public/index.html", "Data Common: Project", "Data C: Hugo Rocks!", "Data D: Hugo Rodks!", ) // i18n b.AssertFileContent("public/index.html", "i18n hello1: Project", "i18n theme: Theme C", "i18n theme2: Theme2 D", ) } func TestModulesIgnoreConfig(t *testing.T) { files := ` -- hugo.toml -- baseURL="https://example.org" [module] [[module.imports]] path="a" ignoreConfig=true -- themes/a/config.toml -- [params] a = "Should Be Ignored!" -- layouts/home.html -- Params: {{ .Site.Params }} ` Test(t, files).AssertFileContent("public/index.html", "! Ignored") } func TestModulesDisabled(t *testing.T) { files := ` -- hugo.toml -- baseURL="https://example.org" [module] [[module.imports]] path="a" [[module.imports]] path="b" disable=true -- themes/a/config.toml -- [params] a = "A param" -- themes/b/config.toml -- [params] b = "B param" -- layouts/home.html -- Params: {{ .Site.Params }} ` Test(t, files).AssertFileContent("public/index.html", "A param", "! B param") } func TestModulesIncompatible(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL="https://example.org" [module] [[module.imports]] path="ok" [[module.imports]] path="incompat1" [[module.imports]] path="incompat2" [[module.imports]] path="incompat3" -- themes/ok/data/ok.toml -- title = "OK" -- themes/incompat1/config.toml -- [module] [module.hugoVersion] min = "0.33.2" max = "0.45.0" -- themes/incompat2/theme.toml -- min_version = "5.0.0" -- themes/incompat3/theme.toml -- min_version = 0.55.0 ` b := Test(t, files, TestOptWarn()) b.AssertLogContains("is not compatible with this Hugo version") } func TestMountsProject(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL="https://example.org" [module] [[module.mounts]] source="mycontent" target="content" -- layouts/single.html -- Permalink: {{ .Permalink }}| -- mycontent/mypage.md -- --- title: "My Page" --- ` b := Test(t, files) b.AssertFileContent("public/mypage/index.html", "Permalink: https://example.org/mypage/|") } // https://github.com/gohugoio/hugo/issues/6684 func TestMountsContentFile(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] disableLiveReload = true [module] [[module.mounts]] source = "README.md" target = "content/_index.md" -- README.md -- # Hello World -- layouts/home.html -- Home: {{ .Title }}|{{ .Content }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "Home: |<h1 id=\"hello-world\">Hello World</h1>\n|") } // https://github.com/gohugoio/hugo/issues/6299 func TestSiteWithGoModButNoModules(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" -- go.mod -- ` b, err := TestE(t, files, TestOptOsFs()) b.Assert(err, qt.IsNil) } // Issue 9426 func TestMountSameSource(t *testing.T) { files := ` -- hugo.toml -- baseURL = 'https://example.org/' languageCode = 'en-us' title = 'Hugo GitHub Issue #9426' disableKinds = ['RSS','sitemap','taxonomy','term'] [[module.mounts]] source = "content" target = "content" [[module.mounts]] source = "extra-content" target = "content/resources-a" [[module.mounts]] source = "extra-content" target = "content/resources-b" -- layouts/single.html -- Single -- content/p1.md -- -- extra-content/_index.md -- -- extra-content/subdir/_index.md -- -- extra-content/subdir/about.md -- " ` b := Test(t, files) b.AssertFileContent("public/resources-a/subdir/about/index.html", "Single") b.AssertFileContent("public/resources-b/subdir/about/index.html", "Single") } func TestMountData(t *testing.T) { files := ` -- hugo.toml -- baseURL = 'https://example.org/' disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] [[module.mounts]] source = "data" target = "data" [[module.mounts]] source = "extra-data" target = "data/extra" -- extra-data/test.yaml -- message: Hugo Rocks -- layouts/home.html -- {{ site.Data.extra.test.message }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "Hugo Rocks") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/sitemap_test.go
hugolib/sitemap_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "reflect" "strings" "testing" "github.com/gohugoio/hugo/config" ) func TestSitemapBasic(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] -- content/sect/doc1.md -- --- title: doc1 --- Doc1 -- content/sect/doc2.md -- --- title: doc2 --- Doc2 ` b := Test(t, files) b.AssertFileContent("public/sitemap.xml", " <loc>https://example.com/sect/doc1/</loc>", "doc2") } func TestSitemapMultilingual(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] defaultContentLanguage = "en" [languages] [languages.en] weight = 1 languageName = "English" [languages.nn] weight = 2 languageName = "Nynorsk" -- content/sect/doc1.md -- --- title: doc1 --- Doc1 -- content/sect/doc2.md -- --- title: doc2 --- Doc2 -- content/sect/doc2.nn.md -- --- title: doc2 --- Doc2 ` b := Test(t, files) b.AssertFileContent("public/sitemap.xml", "<loc>https://example.com/en/sitemap.xml</loc>", "<loc>https://example.com/nn/sitemap.xml</loc>") b.AssertFileContent("public/en/sitemap.xml", " <loc>https://example.com/sect/doc1/</loc>", "doc2") b.AssertFileContent("public/nn/sitemap.xml", " <loc>https://example.com/nn/sect/doc2/</loc>") } // https://github.com/gohugoio/hugo/issues/5910 func TestSitemapOutputFormats(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] -- content/blog/html-amp.md -- --- Title: AMP and HTML outputs: [ "html", "amp" ] --- ` b := Test(t, files) // Should link to the HTML version. b.AssertFileContent("public/sitemap.xml", " <loc>https://example.com/blog/html-amp/</loc>") } func TestParseSitemap(t *testing.T) { t.Parallel() expected := config.SitemapConfig{ChangeFreq: "3", Disable: true, Filename: "doo.xml", Priority: 3.0} input := map[string]any{ "changefreq": "3", "disable": true, "filename": "doo.xml", "priority": 3.0, "unknown": "ignore", } result, err := config.DecodeSitemap(config.SitemapConfig{}, input) if err != nil { t.Fatalf("Failed to parse sitemap: %s", err) } if !reflect.DeepEqual(expected, result) { t.Errorf("Got \n%v expected \n%v", result, expected) } } func TestSitemapShouldNotUseListXML(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] [languages] [languages.en] weight = 1 languageName = "English" [languages.nn] weight = 2 -- layouts/list.xml -- Site: {{ .Site.Title }}| -- layouts/home -- Home. ` b := Test(t, files) b.AssertFileContent("public/sitemap.xml", "https://example.com/en/sitemap.xml") } func TestSitemapAndContentBundleNamedSitemap(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','taxonomy','term'] -- layouts/single.html -- layouts/_default/single.html -- layouts/sitemap/single.html -- layouts/sitemap/single.html -- content/sitemap/index.md -- --- title: My sitemap type: sitemap --- ` b := Test(t, files) b.AssertFileExists("public/sitemap.xml", true) } // Issue 12266 func TestSitemapIssue12266(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'https://example.org/' disableKinds = ['rss','taxonomy','term'] defaultContentLanguage = 'en' defaultContentLanguageInSubdir = true [languages.de] [languages.en] ` // Test A: multilingual with defaultContentLanguageInSubdir = true b := Test(t, files) b.AssertFileContent("public/sitemap.xml", "<loc>https://example.org/de/sitemap.xml</loc>", "<loc>https://example.org/en/sitemap.xml</loc>", ) b.AssertFileContent("public/de/sitemap.xml", "<loc>https://example.org/de/</loc>") b.AssertFileContent("public/en/sitemap.xml", "<loc>https://example.org/en/</loc>") // Test B: multilingual with defaultContentLanguageInSubdir = false files = strings.ReplaceAll(files, "defaultContentLanguageInSubdir = true", "defaultContentLanguageInSubdir = false") b = Test(t, files) b.AssertFileContent("public/sitemap.xml", "<loc>https://example.org/de/sitemap.xml</loc>", "<loc>https://example.org/en/sitemap.xml</loc>", ) b.AssertFileContent("public/de/sitemap.xml", "<loc>https://example.org/de/</loc>") b.AssertFileContent("public/en/sitemap.xml", "<loc>https://example.org/</loc>") // Test C: monolingual with defaultContentLanguageInSubdir = false files = strings.ReplaceAll(files, "[languages.de]", "") files = strings.ReplaceAll(files, "[languages.en]", "") b = Test(t, files) b.AssertFileExists("public/en/sitemap.xml", false) b.AssertFileContent("public/sitemap.xml", "<loc>https://example.org/</loc>") // Test D: monolingual with defaultContentLanguageInSubdir = true files = strings.ReplaceAll(files, "defaultContentLanguageInSubdir = false", "defaultContentLanguageInSubdir = true") b = Test(t, files) b.AssertFileContent("public/sitemap.xml", "<loc>https://example.org/en/sitemap.xml</loc>") b.AssertFileContent("public/en/sitemap.xml", "<loc>https://example.org/en/</loc>") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/integrationtest_builder.go
hugolib/integrationtest_builder.go
package hugolib import ( "bytes" "context" "encoding/base64" "errors" "fmt" "image" "io" "math/rand" "os" "path/filepath" "regexp" "runtime" "sort" "strings" "sync" "testing" "github.com/bep/logg" "github.com/yuin/goldmark/util" qt "github.com/frankban/quicktest" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/himage" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/allconfig" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/identity" "github.com/spf13/afero" "github.com/spf13/cast" "golang.org/x/text/unicode/norm" "golang.org/x/tools/txtar" ) type TestOpt func(*IntegrationTestConfig) // TestOptRunning will enable running in integration tests. func TestOptRunning() TestOpt { return func(c *IntegrationTestConfig) { c.Running = true } } // TestOptWatching will enable watching in integration tests. func TestOptWatching() TestOpt { return func(c *IntegrationTestConfig) { c.Watching = true } } // Enable tracing in integration tests. // THis should only be used during development and not committed to the repo. func TestOptTrace() TestOpt { return func(c *IntegrationTestConfig) { c.LogLevel = logg.LevelTrace } } // TestOptDebug will enable debug logging in integration tests. func TestOptDebug() TestOpt { return func(c *IntegrationTestConfig) { c.LogLevel = logg.LevelDebug } } // TestOptInfo will enable info logging in integration tests. func TestOptInfo() TestOpt { return func(c *IntegrationTestConfig) { c.LogLevel = logg.LevelInfo } } // TestOptWarn will enable warn logging in integration tests. func TestOptWarn() TestOpt { return func(c *IntegrationTestConfig) { c.LogLevel = logg.LevelWarn } } // TestOptSkipRender will skip the render phase in integration tests. func TestOptSkipRender() TestOpt { return func(c *IntegrationTestConfig) { c.BuildCfg = BuildCfg{ SkipRender: true, } } } // TestOptOsFs will enable the real file system in integration tests. func TestOptOsFs() TestOpt { return func(c *IntegrationTestConfig) { c.NeedsOsFS = true } } // TestOptWithNFDOnDarwin will normalize the Unicode filenames to NFD on Darwin. func TestOptWithNFDOnDarwin() TestOpt { return func(c *IntegrationTestConfig) { c.NFDFormOnDarwin = true } } // TestOptWithOSFs enables the real file system. func TestOptWithOSFs() TestOpt { return func(c *IntegrationTestConfig) { c.NeedsOsFS = true } } func TestOptWithPrintAndKeepTempDir(b bool) TestOpt { return func(c *IntegrationTestConfig) { c.PrintAndKeepTempDir = b } } // TestOptWithWorkingDir allows setting any config optiona as a function al option. func TestOptWithConfig(fn func(c *IntegrationTestConfig)) TestOpt { return func(c *IntegrationTestConfig) { fn(c) } } // Test is a convenience method to create a new IntegrationTestBuilder from some files and run a build. func Test(t testing.TB, files string, opts ...TestOpt) *IntegrationTestBuilder { cfg := IntegrationTestConfig{T: t, TxtarString: files} for _, o := range opts { o(&cfg) } return NewIntegrationTestBuilder(cfg).Build() } // TestE is the same as Test, but returns an error instead of failing the test. func TestE(t testing.TB, files string, opts ...TestOpt) (*IntegrationTestBuilder, error) { cfg := IntegrationTestConfig{T: t, TxtarString: files} for _, o := range opts { o(&cfg) } return NewIntegrationTestBuilder(cfg).BuildE() } // TestRunning is a convenience method to create a new IntegrationTestBuilder from some files with Running set to true and run a build. // Deprecated: Use Test with TestOptRunning instead. func TestRunning(t testing.TB, files string, opts ...TestOpt) *IntegrationTestBuilder { cfg := IntegrationTestConfig{T: t, TxtarString: files, Running: true} for _, o := range opts { o(&cfg) } return NewIntegrationTestBuilder(cfg).Build() } // In most cases you should not use this function directly, but the Test or TestRunning function. func NewIntegrationTestBuilder(conf IntegrationTestConfig) *IntegrationTestBuilder { // Code fences. conf.TxtarString = strings.ReplaceAll(conf.TxtarString, "§§§", "```") // Multiline strings. conf.TxtarString = strings.ReplaceAll(conf.TxtarString, "§§", "`") data := txtar.Parse([]byte(conf.TxtarString)) if conf.NFDFormOnDarwin { for i, f := range data.Files { data.Files[i].Name = norm.NFD.String(f.Name) } } c, ok := conf.T.(*qt.C) if !ok { c = qt.New(conf.T) } if conf.NeedsOsFS { if !filepath.IsAbs(conf.WorkingDir) { tempDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test") c.Assert(err, qt.IsNil) conf.WorkingDir = filepath.Join(tempDir, conf.WorkingDir) if !conf.PrintAndKeepTempDir { c.Cleanup(clean) } else { fmt.Println("\nUsing WorkingDir dir:", conf.WorkingDir) } } } else if conf.WorkingDir == "" { conf.WorkingDir = helpers.FilePathSeparator } return &IntegrationTestBuilder{ Cfg: conf, C: c, data: data, } } // IntegrationTestBuilder is a (partial) rewrite of sitesBuilder. // The main problem with the "old" one was that it was that the test data was often a little hidden, // so it became hard to look at a test and determine what it should do, especially coming back to the // test after a year or so. type IntegrationTestBuilder struct { *qt.C data *txtar.Archive fs *hugofs.Fs H *HugoSites Cfg IntegrationTestConfig changedFiles []string createdFiles []string removedFiles []string renamedFiles []string renamedDirs []string buildCount int GCCount int counters *buildCounters logBuff lockingBuffer lastBuildLog string builderInit sync.Once } type IntegrationTestSiteHelper struct { *qt.C b *IntegrationTestBuilder S *Site } type IntegrationTestPageHelper struct { *qt.C b *IntegrationTestBuilder p *pageState } func (s *IntegrationTestPageHelper) siteIntsToMap(matrix, complements sitesmatrix.VectorStore) map[string]map[string][]string { dconf := s.p.s.Conf.ConfiguredDimensions() intSetsToMap := func(intSets sitesmatrix.VectorStore) map[string][]string { var languages, versions, roles []string keys1, keys2, keys3 := intSets.KeysSorted() for _, v := range keys1 { languages = append(languages, dconf.ConfiguredLanguages.ResolveName(v)) } for _, v := range keys2 { versions = append(versions, dconf.ConfiguredVersions.ResolveName(v)) } for _, v := range keys3 { roles = append(roles, dconf.ConfiguredRoles.ResolveName(v)) } return map[string][]string{ "languages": languages, "versions": versions, "roles": roles, } } return map[string]map[string][]string{ "matrix": intSetsToMap(matrix), "complements": intSetsToMap(complements), } } func (s *IntegrationTestPageHelper) MatrixFromPageConfig() map[string]map[string][]string { pc := s.p.m.pageConfigSource return s.siteIntsToMap(pc.SitesMatrix, pc.SitesComplements) } func (s *IntegrationTestPageHelper) MatrixFromFile() map[string]map[string][]string { if s.p.m.f == nil { return nil } m := s.p.m.f.FileInfo().Meta() return s.siteIntsToMap(m.SitesMatrix, m.SitesComplements) } func (s *IntegrationTestSiteHelper) PageHelper(path string) *IntegrationTestPageHelper { p, err := s.S.GetPage(path) s.Assert(err, qt.IsNil) s.Assert(p, qt.Not(qt.IsNil), qt.Commentf("Page not found: %s", path)) ps, ok := p.(*pageState) s.Assert(ok, qt.IsTrue, qt.Commentf("Expected pageState, got %T", p)) return &IntegrationTestPageHelper{ C: s.C, b: s.b, p: ps, } } func (s *IntegrationTestSiteHelper) DimensionNames() types.Strings3 { return types.Strings3{ s.S.Language().Name(), s.S.Version().Name(), s.S.Role().Name(), } } type lockingBuffer struct { sync.Mutex buf bytes.Buffer } func (b *lockingBuffer) String() string { b.Lock() defer b.Unlock() return b.buf.String() } func (b *lockingBuffer) Reset() { b.Lock() defer b.Unlock() b.buf.Reset() } func (b *lockingBuffer) ReadFrom(r io.Reader) (n int64, err error) { b.Lock() n, err = b.buf.ReadFrom(r) b.Unlock() return } func (b *lockingBuffer) Write(p []byte) (n int, err error) { b.Lock() n, err = b.buf.Write(p) b.Unlock() return } // SiteHelper returns a helper for the given language, version and role. // Note that a blank value for an argument will use the default value for that dimension. func (s *IntegrationTestBuilder) SiteHelper(language, version, role string) *IntegrationTestSiteHelper { s.Helper() if s.H == nil { s.Fatal("SiteHelper: no sites available") } v := s.H.Conf.ConfiguredDimensions().ResolveVector(types.Strings3{language, version, role}) site, found := s.H.sitesVersionsRolesMap[v] if !found { s.Fatalf("SiteHelper: no site found for vector %v", v) } return &IntegrationTestSiteHelper{ C: s.C, b: s, S: site, } } // AssertLogContains asserts that the last build log contains the given strings. // Each string can be negated with a hglob.NegationPrefix prefix. func (s *IntegrationTestBuilder) AssertLogContains(els ...string) { s.Helper() for _, el := range els { var negate bool el, negate = s.negate(el) check := qt.Contains if negate { check = qt.Not(qt.Contains) } s.Assert(s.lastBuildLog, check, el) } } // AssertLogMatches asserts that the last build log matches the given regular expressions. // The regular expressions can be negated with a hglob.NegationPrefix prefix. func (s *IntegrationTestBuilder) AssertLogMatches(expression string) { s.Helper() var negate bool expression, negate = s.negate(expression) re := regexp.MustCompile(expression) checker := qt.IsTrue if negate { checker = qt.IsFalse } s.Assert(re.MatchString(s.lastBuildLog), checker, qt.Commentf(s.lastBuildLog)) } func (s *IntegrationTestBuilder) AssertFileCount(dirname string, expected int) { s.Helper() fs := s.fs.WorkingDirReadOnly count := 0 afero.Walk(fs, dirname, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } count++ return nil }) s.Assert(count, qt.Equals, expected) } func (s *IntegrationTestBuilder) negate(match string) (string, bool) { var negate bool if strings.HasPrefix(match, hglob.NegationPrefix) { negate = true match = strings.TrimPrefix(match, hglob.NegationPrefix) } return match, negate } func (s *IntegrationTestBuilder) AssertFileContent(filename string, matches ...string) { s.Helper() content := strings.TrimSpace(s.FileContent(filename)) for _, m := range matches { cm := qt.Commentf("File: %s Expect:\n%s Got:\n%s\nWith Space Visuals:\n%s", filename, m, content, util.VisualizeSpaces([]byte(content))) lines := strings.SplitSeq(m, "\n") for match := range lines { match = strings.TrimSpace(match) if match == "" || strings.HasPrefix(match, "#") { continue } var negate bool match, negate = s.negate(match) if negate { s.Assert(content, qt.Not(qt.Contains), match, cm) continue } s.Assert(content, qt.Contains, match, cm) } } } func (s *IntegrationTestBuilder) AssertFileContentEquals(filename string, match string) { s.Helper() content := s.FileContent(filename) s.Assert(content, qt.Equals, match, qt.Commentf(match)) } func (s *IntegrationTestBuilder) AssertFileContentExact(filename string, matches ...string) { s.Helper() content := s.FileContent(filename) for _, m := range matches { cm := qt.Commentf("File: %s Match %s\nContent:\n%s", filename, m, content) s.Assert(content, qt.Contains, m, cm) } } func (s *IntegrationTestBuilder) AssertNoRenderShortcodesArtifacts() { s.Helper() for _, p := range s.H.Pages() { content, err := p.Content(context.Background()) s.Assert(err, qt.IsNil) comment := qt.Commentf("Page: %s\n%s", p.Path(), content) s.Assert(strings.Contains(cast.ToString(content), "__hugo_ctx"), qt.IsFalse, comment) } } type IntegrationTestImageHelper struct { *qt.C b *IntegrationTestBuilder img image.Image formatName string congig image.Config } func (h *IntegrationTestImageHelper) AssertFormat(formatName string) *IntegrationTestImageHelper { h.Assert(h.formatName, qt.Equals, formatName, qt.Commentf("Expected format %q, got %q", formatName, h.formatName)) return h } func (h *IntegrationTestImageHelper) AssertFrameDurations(expect []int) *IntegrationTestImageHelper { anim, ok := h.img.(himage.AnimatedImage) h.Assert(ok, qt.IsTrue, qt.Commentf("Image is not animated")) h.Assert(anim.GetFrameDurations(), qt.DeepEquals, expect, qt.Commentf("Frame durations do not match")) return h } func (h *IntegrationTestImageHelper) AssertLoopCount(expect int) *IntegrationTestImageHelper { anim, ok := h.img.(himage.AnimatedImage) h.Assert(ok, qt.IsTrue, qt.Commentf("Image is not animated")) h.Assert(anim.GetLoopCount(), qt.Equals, expect, qt.Commentf("Loop count does not match")) return h } func (h *IntegrationTestImageHelper) AssertIsAnimated(b bool) *IntegrationTestImageHelper { _, ok := h.img.(himage.AnimatedImage) if b { h.Assert(ok, qt.IsTrue, qt.Commentf("Image is not animated")) return h } h.Assert(ok, qt.IsFalse, qt.Commentf("Image is animated")) return h } func (s *IntegrationTestBuilder) ImageHelper(filename string) *IntegrationTestImageHelper { filename = filepath.Clean(filename) fs := s.fs.WorkingDirReadOnly b, err := afero.ReadFile(fs, filename) s.Assert(err, qt.IsNil) conf, format, err := s.H.ResourceSpec.Imaging.Codec.DecodeConfig(bytes.NewReader(b)) s.Assert(err, qt.IsNil) img, err := s.H.ResourceSpec.Imaging.Codec.Decode(bytes.NewReader(b)) s.Assert(err, qt.IsNil) return &IntegrationTestImageHelper{ C: s.C, b: s, img: img, formatName: format, congig: conf, } } func (s *IntegrationTestBuilder) AssertPublishDir(matches ...string) { s.AssertFs(s.fs.PublishDir, matches...) } func (s *IntegrationTestBuilder) AssertFs(fs afero.Fs, matches ...string) { s.Helper() var buff bytes.Buffer s.Assert(s.printAndCheckFs(fs, "", &buff), qt.IsNil) printFsLines := strings.Split(buff.String(), "\n") sort.Strings(printFsLines) content := strings.TrimSpace((strings.Join(printFsLines, "\n"))) for _, m := range matches { cm := qt.Commentf("Match: %q\nIn:\n%s", m, content) lines := strings.SplitSeq(m, "\n") for match := range lines { match = strings.TrimSpace(match) var negate bool if strings.HasPrefix(match, hglob.NegationPrefix) { negate = true match = strings.TrimPrefix(match, hglob.NegationPrefix) } if negate { s.Assert(content, qt.Not(qt.Contains), match, cm) continue } s.Assert(content, qt.Contains, match, cm) } } } func (s *IntegrationTestBuilder) printAndCheckFs(fs afero.Fs, path string, w io.Writer) error { if fs == nil { return nil } return afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error { if err != nil { return fmt.Errorf("error: path %q: %s", path, err) } path = filepath.ToSlash(path) if path == "" { path = "." } var size int64 if !info.IsDir() { size = info.Size() f, err := fs.Open(path) if err != nil { return fmt.Errorf("error: path %q: %s", path, err) } defer f.Close() // This will panic if the file is a directory. var buf [1]byte io.ReadFull(f, buf[:]) } fmt.Fprintf(w, "%06d %s %t\n", size, path, info.IsDir()) return nil }) } func (s *IntegrationTestBuilder) AssertFileExists(filename string, b bool) { checker := qt.IsNil if !b { checker = qt.IsNotNil } _, err := s.fs.WorkingDirReadOnly.Stat(filename) if err != nil && !herrors.IsNotExist(err) { s.Assert(err, qt.IsNil) return } s.Assert(err, checker) } func (s *IntegrationTestBuilder) AssertRenderCountContent(count int) { s.Helper() s.Assert(s.counters.contentRenderCounter.Load(), qt.Equals, uint64(count)) } func (s *IntegrationTestBuilder) AssertRenderCountPage(count int) { s.Helper() s.Assert(s.counters.pageRenderCounter.Load(), qt.Equals, uint64(count)) } func (s *IntegrationTestBuilder) AssertRenderCountPageBetween(from, to int) { s.Helper() i := int(s.counters.pageRenderCounter.Load()) s.Assert(i >= from && i <= to, qt.IsTrue) } func (s *IntegrationTestBuilder) Build() *IntegrationTestBuilder { s.Helper() _, err := s.BuildE() if err != nil && strings.Contains(err.Error(), "error(s)") { err = fmt.Errorf("%w: %s", err, s.lastBuildLog) } if s.Cfg.Verbose || err != nil { if s.H != nil && err == nil { for s := range s.H.allSites(nil) { m := s.pageMap var buff bytes.Buffer fmt.Fprintf(&buff, "======= PageMap for site %q =======\n\n", s.resolveDimensionNames()) m.debugPrint("", 999, &buff) fmt.Println(buff.String()) } } } else if s.Cfg.LogLevel <= logg.LevelDebug { fmt.Println(s.lastBuildLog) } s.Assert(err, qt.IsNil) if s.Cfg.RunGC { s.GCCount, err = s.H.GC() s.Assert(err, qt.IsNil) } s.Cleanup(func() { if h := s.H; h != nil { s.Assert(h.Close(), qt.IsNil) } }) return s } func (s *IntegrationTestBuilder) BuildPartial(urls ...string) *IntegrationTestBuilder { if _, err := s.BuildPartialE(urls...); err != nil { s.Fatal(err) } return s } func (s *IntegrationTestBuilder) BuildPartialE(urls ...string) (*IntegrationTestBuilder, error) { if s.buildCount == 0 { panic("BuildPartial can only be used after a full build") } if !s.Cfg.Running { panic("BuildPartial can only be used in server mode") } visited := types.NewEvictingQueue[string](len(urls)) for _, url := range urls { visited.Add(url) } buildCfg := BuildCfg{RecentlyTouched: visited, PartialReRender: true} return s, s.build(buildCfg) } func (s *IntegrationTestBuilder) Close() { s.Helper() s.Assert(s.H.Close(), qt.IsNil) } func (s *IntegrationTestBuilder) LogString() string { return s.lastBuildLog } func (s *IntegrationTestBuilder) BuildE() (*IntegrationTestBuilder, error) { s.Helper() if err := s.initBuilder(); err != nil { return s, err } err := s.build(s.Cfg.BuildCfg) return s, err } func (s *IntegrationTestBuilder) Init() *IntegrationTestBuilder { if err := s.initBuilder(); err != nil { s.Fatalf("Failed to init builder: %s", err) } s.lastBuildLog = s.logBuff.String() return s } type IntegrationTestDebugConfig struct { Out io.Writer PrintDestinationFs bool PrintPagemap bool PrefixDestinationFs string PrefixPagemap string } func (s *IntegrationTestBuilder) EditFileReplaceAll(filename, old, new string) *IntegrationTestBuilder { return s.EditFileReplaceFunc(filename, func(s string) string { return strings.ReplaceAll(s, old, new) }) } func (s *IntegrationTestBuilder) EditFileReplaceFunc(filename string, replacementFunc func(s string) string) *IntegrationTestBuilder { absFilename := s.absFilename(filename) b, err := afero.ReadFile(s.fs.Source, absFilename) s.Assert(err, qt.IsNil) s.changedFiles = append(s.changedFiles, absFilename) oldContent := string(b) s.writeSource(absFilename, replacementFunc(oldContent)) return s } func (s *IntegrationTestBuilder) EditFileAppend(filename, contnt string) *IntegrationTestBuilder { absFilename := s.absFilename(filename) b, err := afero.ReadFile(s.fs.Source, absFilename) s.Assert(err, qt.IsNil) s.changedFiles = append(s.changedFiles, absFilename) oldContent := string(b) s.writeSource(absFilename, oldContent+contnt) return s } func (s *IntegrationTestBuilder) EditFiles(filenameContent ...string) *IntegrationTestBuilder { for i := 0; i < len(filenameContent); i += 2 { filename, content := filepath.FromSlash(filenameContent[i]), filenameContent[i+1] absFilename := s.absFilename(filename) s.changedFiles = append(s.changedFiles, absFilename) s.writeSource(absFilename, content) } return s } func (s *IntegrationTestBuilder) AddFiles(filenameContent ...string) *IntegrationTestBuilder { for i := 0; i < len(filenameContent); i += 2 { filename, content := filepath.FromSlash(filenameContent[i]), filenameContent[i+1] absFilename := s.absFilename(filename) s.createdFiles = append(s.createdFiles, absFilename) s.writeSource(absFilename, content) } return s } func (s *IntegrationTestBuilder) RemoveFiles(filenames ...string) *IntegrationTestBuilder { for _, filename := range filenames { absFilename := s.absFilename(filename) s.removedFiles = append(s.removedFiles, absFilename) s.Assert(s.fs.Source.Remove(absFilename), qt.IsNil) } return s } func (s *IntegrationTestBuilder) RemovePublishDir() *IntegrationTestBuilder { s.Helper() if err := s.fs.PublishDir.RemoveAll(""); err != nil && !herrors.IsNotExist(err) { s.Fatalf("Failed to remove publish dir: %s", err) } return s } func (s *IntegrationTestBuilder) RenameFile(old, new string) *IntegrationTestBuilder { absOldFilename := s.absFilename(old) absNewFilename := s.absFilename(new) s.renamedFiles = append(s.renamedFiles, absOldFilename) s.createdFiles = append(s.createdFiles, absNewFilename) s.Assert(s.fs.Source.MkdirAll(filepath.Dir(absNewFilename), 0o777), qt.IsNil) s.Assert(s.fs.Source.Rename(absOldFilename, absNewFilename), qt.IsNil) return s } func (s *IntegrationTestBuilder) RenameDir(old, new string) *IntegrationTestBuilder { absOldFilename := s.absFilename(old) absNewFilename := s.absFilename(new) s.renamedDirs = append(s.renamedDirs, absOldFilename) s.changedFiles = append(s.changedFiles, absNewFilename) afero.Walk(s.fs.Source, absOldFilename, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } s.createdFiles = append(s.createdFiles, strings.Replace(path, absOldFilename, absNewFilename, 1)) return nil }) s.Assert(s.fs.Source.MkdirAll(filepath.Dir(absNewFilename), 0o777), qt.IsNil) s.Assert(s.fs.Source.Rename(absOldFilename, absNewFilename), qt.IsNil) return s } func (s *IntegrationTestBuilder) FileContent(filename string) string { s.Helper() return s.readWorkingDir(s, s.fs, filepath.FromSlash(filename)) } func (s *IntegrationTestBuilder) initBuilder() error { var initErr error s.builderInit.Do(func() { var afs afero.Fs if s.Cfg.NeedsOsFS { afs = afero.NewOsFs() } else { afs = afero.NewMemMapFs() } if s.Cfg.LogLevel == 0 { s.Cfg.LogLevel = logg.LevelError } isBinaryRe := regexp.MustCompile(`^(.*)(\.png|\.jpg)$`) const dataSourceFilenamePrefix = "sourcefilename:" for _, f := range s.data.Files { filename := filepath.Join(s.Cfg.WorkingDir, f.Name) data := bytes.TrimSuffix(f.Data, []byte("\n")) datastr := strings.TrimSpace(string(data)) if strings.HasPrefix(datastr, dataSourceFilenamePrefix) { // Read from file relative to the current dir. var err error wd, _ := os.Getwd() filename := filepath.Join(wd, strings.TrimSpace(strings.TrimPrefix(datastr, dataSourceFilenamePrefix))) data, err = os.ReadFile(filename) s.Assert(err, qt.IsNil) } else if isBinaryRe.MatchString(filename) { var err error data, err = base64.StdEncoding.DecodeString(string(data)) s.Assert(err, qt.IsNil) } s.Assert(afs.MkdirAll(filepath.Dir(filename), 0o777), qt.IsNil) s.Assert(afero.WriteFile(afs, filename, data, 0o666), qt.IsNil) } configDir := "config" if _, err := afs.Stat(filepath.Join(s.Cfg.WorkingDir, "config")); err != nil { configDir = "" } var flags config.Provider if s.Cfg.BaseCfg != nil { flags = s.Cfg.BaseCfg } else { flags = config.New() } if s.Cfg.Running { flags.Set("internal", maps.Params{ "running": s.Cfg.Running, "watch": s.Cfg.Running, }) } else if s.Cfg.Watching { flags.Set("internal", maps.Params{ "watch": s.Cfg.Watching, }) } if s.Cfg.WorkingDir != "" { flags.Set("workingDir", s.Cfg.WorkingDir) } var w io.Writer if s.Cfg.Verbose || s.Cfg.LogLevel == logg.LevelTrace { w = io.MultiWriter(os.Stdout, &s.logBuff) } else { w = &s.logBuff } logger := loggers.New( loggers.Options{ StdOut: w, StdErr: w, Level: s.Cfg.LogLevel, DistinctLevel: logg.LevelWarn, }, ) res, err := allconfig.LoadConfig( allconfig.ConfigSourceDescriptor{ Flags: flags, ConfigDir: configDir, Fs: afs, Logger: logger, Environ: s.Cfg.Environ, }, ) if err != nil { initErr = err return } fs := hugofs.NewFrom(afs, res.LoadingInfo.BaseConfig) s.Assert(err, qt.IsNil) // changes received from Hugo in watch mode. // In the full setup, this channel is created in the commands package. changesFromBuild := make(chan []identity.Identity, 10) depsCfg := deps.DepsCfg{Configs: res, Fs: fs, LogLevel: logger.Level(), StdErr: logger.StdErr(), ChangesFromBuild: changesFromBuild, IsIntegrationTest: true} sites, err := NewHugoSites(depsCfg) if err != nil { initErr = err return } if sites == nil { initErr = errors.New("no sites") return } go func() { for id := range changesFromBuild { whatChanged := &WhatChanged{} for _, v := range id { whatChanged.Add(v) } bcfg := s.Cfg.BuildCfg bcfg.WhatChanged = whatChanged if err := s.build(bcfg); err != nil { s.Fatalf("Build failed after change: %s", err) } } }() s.H = sites s.fs = fs if s.Cfg.NeedsNpmInstall { wd, _ := os.Getwd() s.Assert(os.Chdir(s.Cfg.WorkingDir), qt.IsNil) s.C.Cleanup(func() { os.Chdir(wd) }) sc := security.DefaultConfig sc.Exec.Allow, err = security.NewWhitelist("npm") s.Assert(err, qt.IsNil) ex := hexec.New(sc, s.Cfg.WorkingDir, loggers.NewDefault()) command, err := ex.New("npm", "install") s.Assert(err, qt.IsNil) s.Assert(command.Run(), qt.IsNil) } }) return initErr } func (s *IntegrationTestBuilder) absFilename(filename string) string { filename = filepath.FromSlash(filename) if filepath.IsAbs(filename) { return filename } if s.Cfg.WorkingDir != "" && !strings.HasPrefix(filename, s.Cfg.WorkingDir) { filename = filepath.Join(s.Cfg.WorkingDir, filename) } return filename } func (s *IntegrationTestBuilder) reset() { s.changedFiles = nil s.createdFiles = nil s.removedFiles = nil s.renamedFiles = nil } func (s *IntegrationTestBuilder) build(cfg BuildCfg) error { s.Helper() defer func() { s.reset() s.lastBuildLog = s.logBuff.String() s.logBuff.Reset() }() changeEvents := s.changeEvents() s.counters = &buildCounters{} cfg.testCounters = s.counters s.buildCount++ err := s.H.Build(cfg, changeEvents...) if err != nil { return err } return nil } // We simulate the fsnotify events. // See the test output in https://github.com/bep/fsnotifyeventlister for what events gets produced // by the different OSes. func (s *IntegrationTestBuilder) changeEvents() []fsnotify.Event { var ( events []fsnotify.Event isLinux = runtime.GOOS == "linux" isMacOs = runtime.GOOS == "darwin" isWindows = runtime.GOOS == "windows" ) for _, v := range s.removedFiles { events = append(events, fsnotify.Event{ Name: v, Op: fsnotify.Remove, }) } for _, v := range s.renamedFiles { events = append(events, fsnotify.Event{ Name: v, Op: fsnotify.Rename, }) } for _, v := range s.renamedDirs { events = append(events, fsnotify.Event{ Name: v, // This is what we get on MacOS. Op: fsnotify.Remove | fsnotify.Rename, }) } for _, v := range s.changedFiles { events = append(events, fsnotify.Event{ Name: v, Op: fsnotify.Write, }) if isLinux || isWindows { // Duplicate write events, for some reason. events = append(events, fsnotify.Event{ Name: v, Op: fsnotify.Write, }) } if isMacOs { events = append(events, fsnotify.Event{ Name: v, Op: fsnotify.Chmod, }) } } for _, v := range s.createdFiles { events = append(events, fsnotify.Event{ Name: v, Op: fsnotify.Create, }) if isLinux || isWindows { events = append(events, fsnotify.Event{ Name: v, Op: fsnotify.Write, }) } } // Shuffle events. for i := range events { j := rand.Intn(i + 1) events[i], events[j] = events[j], events[i] } return events } func (s *IntegrationTestBuilder) readWorkingDir(t testing.TB, fs *hugofs.Fs, filename string) string { t.Helper() return s.readFileFromFs(t, fs.WorkingDirReadOnly, filename) } func (s *IntegrationTestBuilder) readFileFromFs(t testing.TB, fs afero.Fs, filename string) string { t.Helper() filename = filepath.Clean(filename) b, err := afero.ReadFile(fs, filename) if err != nil { // Print some debug info hadSlash := strings.HasPrefix(filename, helpers.FilePathSeparator) start := 0 if hadSlash { start = 1 } end := start + 1 parts := strings.Split(filename, helpers.FilePathSeparator) if parts[start] == "work" { end++ } s.Assert(err, qt.IsNil) } return string(b) } func (s *IntegrationTestBuilder) writeSource(filename, content string) { s.Helper() s.writeToFs(s.fs.Source, filename, content) } func (s *IntegrationTestBuilder) writeToFs(fs afero.Fs, filename, content string) { s.Helper() if err := afero.WriteFile(fs, filepath.FromSlash(filename), []byte(content), 0o755); err != nil { s.Fatalf("Failed to write file: %s", err) } } type IntegrationTestConfig struct { T testing.TB // The files to use on txtar format, see // https://pkg.go.dev/golang.org/x/exp/cmd/txtar // There are some contentions used in this test setup. // - §§§ can be used to wrap code fences. // - §§ can be used to wrap multiline strings. // - filenames prefixed with sourcefilename: will be read from the file system relative to the current dir. // - filenames with a .png or .jpg extension will be treated as binary and base64 decoded. TxtarString string // COnfig to use as the base. We will also read the config from the txtar. BaseCfg config.Provider // Environment variables passed to the config loader. Environ []string // Whether to simulate server mode. Running bool // Watch for changes. // This is (currently) always set to true when Running is set. // Note that the CLI for the server does allow for --watch=false, but that is not used in these test. Watching bool // Enable verbose logging. Verbose bool // The log level to use. LogLevel logg.Level // Whether it needs the real file system (e.g. for js.Build tests). NeedsOsFS bool // Whether to run GC after each build. RunGC bool // Do not remove the temp dir after the test. PrintAndKeepTempDir bool // Whether to run npm install before Build. NeedsNpmInstall bool // Whether to normalize the Unicode filenames to NFD on Darwin. NFDFormOnDarwin bool // The working dir to use. If not absolute, a temp dir will be created. WorkingDir string // The config to pass to Build. BuildCfg BuildCfg }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/language_content_dir_test.go
hugolib/language_content_dir_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) func TestLanguageContentRoot(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org/" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 10 contentDir = "content/en" [languages.nn] weight = 20 contentDir = "content/nn" -- content/en/_index.md -- --- title: "Home" --- -- content/nn/_index.md -- --- title: "Heim" --- -- content/en/myfiles/file1.txt -- file 1 en -- content/en/myfiles/file2.txt -- file 2 en -- content/nn/myfiles/file1.txt -- file 1 nn -- layouts/home.html -- Title: {{ .Title }}| Len Resources: {{ len .Resources }}| {{ range $i, $e := .Resources }} {{ $i }}|{{ .RelPermalink }}|{{ .Content }}| {{ end }} ` b := Test(t, files) b.AssertFileContent("public/en/index.html", "Home", "0|/en/myfiles/file1.txt|file 1 en|\n\n1|/en/myfiles/file2.txt|file 2 en|") b.AssertFileContent("public/nn/index.html", "Heim", "0|/nn/myfiles/file1.txt|file 1 nn|\n\n1|/en/myfiles/file2.txt|file 2 en|") } func TestContentMountMerge(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'https://example.org/' languageCode = 'en-us' title = 'Hugo Forum Topic #37225' theme = 'mytheme' disableKinds = ['sitemap','RSS','taxonomy','term'] defaultContentLanguage = 'en' defaultContentLanguageInSubdir = true [languages.en] languageName = 'English' weight = 1 [languages.de] languageName = 'Deutsch' weight = 2 [languages.nl] languageName = 'Nederlands' weight = 3 # EN content [[module.mounts]] source = 'content/en' target = 'content' lang = 'en' # DE content [[module.mounts]] source = 'content/de' target = 'content' lang = 'de' # This fills in the gaps in DE content with EN content [[module.mounts]] source = 'content/en' target = 'content' lang = 'de' # NL content [[module.mounts]] source = 'content/nl' target = 'content' lang = 'nl' # This should fill in the gaps in NL content with EN content [[module.mounts]] source = 'content/en' target = 'content' lang = 'nl' -- content/de/_index.md -- --- title: "home (de)" --- -- content/de/p1.md -- --- title: "p1 (de)" --- -- content/en/_index.md -- --- title: "home (en)" --- -- content/en/p1.md -- --- title: "p1 (en)" --- -- content/en/p2.md -- --- title: "p2 (en)" --- -- content/en/p3.md -- --- title: "p3 (en)" --- -- content/nl/_index.md -- --- title: "home (nl)" --- -- content/nl/p1.md -- --- title: "p1 (nl)" --- -- content/nl/p3.md -- --- title: "p3 (nl)" --- -- layouts/home.html -- {{ .Title }}: {{ site.Language.Lang }}: {{ range site.RegularPages }}{{ .Title }}|{{ end }}:END -- themes/mytheme/config.toml -- [[module.mounts]] source = 'content/nlt' target = 'content' lang = 'nl' -- themes/mytheme/content/nlt/p3.md -- --- title: "p3 theme (nl)" --- -- themes/mytheme/content/nlt/p4.md -- --- title: "p4 theme (nl)" --- ` b := Test(t, files) b.AssertFileContent("public/nl/index.html", `home (nl): nl: p1 (nl)|p2 (en)|p3 (nl)|p4 theme (nl)|:END`) b.AssertFileContent("public/de/index.html", `home (de): de: p1 (de)|p2 (en)|p3 (en)|:END`) b.AssertFileContent("public/en/index.html", `home (en): en: p1 (en)|p2 (en)|p3 (en)|:END`) } // Issue 13993 func TestIssue13993(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] printPathWarnings = true defaultContentLanguage = 'en' defaultContentLanguageInSubdir = true [languages.en] contentDir = "content/en" weight = 1 [languages.es] contentDir = "content/es" weight = 2 # Default content mounts [[module.mounts]] source = "content/en" target = "content" lang = "en" [[module.mounts]] source = "content/es" target = "content" lang = "es" # Populate the missing es content with en content [[module.mounts]] source = "content/en" target = "content" lang = "es" -- layouts/all.html -- {{ .Title }} -- content/en/p1.md -- --- title: p1 (en) --- -- content/en/p2.md -- --- title: p2 (en) --- -- content/es/p1.md -- --- title: p1 (es) --- ` b := Test(t, files, TestOptInfo()) b.AssertFileExists("public/en/p1/index.html", true) b.AssertFileExists("public/en/p2/index.html", true) b.AssertFileExists("public/es/p1/index.html", true) b.AssertFileExists("public/es/p2/index.html", true) // This assertion was changed for 0.152.0. It was no longer possible/practical to warn about duplicate content paths. b.AssertLogContains("! Duplicate") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/site.go
hugolib/site.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "errors" "fmt" "io" "mime" "net/url" "os" "path/filepath" "runtime" "slices" "sort" "strings" "sync" "time" "github.com/bep/logg" "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/common/hstore" "github.com/gohugoio/hugo/common/hsync" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/para" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/allconfig" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/hugolib/doctree" "github.com/gohugoio/hugo/hugolib/pagesfromdata" "github.com/gohugoio/hugo/hugolib/roles" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/hugolib/versions" "github.com/gohugoio/hugo/internal/js/esbuild" "github.com/gohugoio/hugo/internal/warpc" "github.com/gohugoio/hugo/langs/i18n" "github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/resources" xmaps "maps" "github.com/gohugoio/hugo/tpl/tplimpl" "github.com/gohugoio/hugo/tpl/tplimplinit" // Loads the template funcs namespaces. "golang.org/x/text/unicode/norm" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/publisher" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/gohugoio/hugo/resources/page/siteidentities" "github.com/gohugoio/hugo/resources/resource" "github.com/fsnotify/fsnotify" bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/navigation" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/tpl" ) var _ page.Site = (*Site)(nil) type siteState int const ( siteStateInit siteState = iota siteStateReady ) type Site struct { state siteState conf *allconfig.Config language *langs.Language store *hstore.Scratch siteWrapped page.Site // The owning container. h *HugoSites *deps.Deps *siteLanguageVersionRole relatedDocsHandler *page.RelatedDocsHandler publisher publisher.Publisher frontmatterHandler pagemeta.FrontMatterHandler } func (s Site) cloneForVersionAndRole(version, role int) (*Site, error) { s.siteLanguageVersionRole = s.siteLanguageVersionRole.cloneForVersionAndRole(version, role) d, err := s.Deps.Clone(&s, s.Conf) if err != nil { return nil, err } s.Deps = d ss := &s ss.siteWrapped = page.WrapSite(ss) return ss, nil } // For debugging purposes only. func (s *Site) resolveDimensionNames() types.Strings3 { return s.Conf.ConfiguredDimensions().ResolveNames(s.siteVector) } type siteLanguageVersionRole struct { siteVector sitesmatrix.Vector roleInternal roles.RoleInternal role roles.Role versionInternal versions.VersionInternal version versions.Version pageMap *pageMap // Page navigation. *pageFinder siteRefLinker siteRefLinker // Shortcut to the home page. Note that this may be nil if // home page, for some odd reason, is disabled. home *pageState // The last modification date of this site. lastmod time.Time // Lazily loaded site dependencies init *siteInit // The output formats that we need to render this site in. This slice // will be fixed once set. // This will be the union of Site.Pages' outputFormats. // This slice will be sorted. renderFormats output.Formats } func (s siteLanguageVersionRole) cloneForVersionAndRole(version, role int) *siteLanguageVersionRole { s.siteVector[sitesmatrix.Version] = version s.siteVector[sitesmatrix.Role] = role s.home = nil s.lastmod = time.Time{} s.init = &siteInit{} return &s } func (s siteLanguageVersionRole) Role() roles.Role { return s.role } func (s siteLanguageVersionRole) Version() versions.Version { return s.version } func (s *Site) Debug() { fmt.Println("Debugging site", s.Lang(), "=>") // fmt.Println(s.pageMap.testDump()) } // NewHugoSites creates HugoSites from the given config. func NewHugoSites(cfg deps.DepsCfg) (*HugoSites, error) { conf := cfg.Configs.GetFirstLanguageConfig() rolesSorted := cfg.Configs.Base.Roles.Config.Sorted versionsSorted := cfg.Configs.Base.Versions.Config.Sorted var logger loggers.Logger if cfg.TestLogger != nil { logger = cfg.TestLogger } else { var logHookLast func(e *logg.Entry) error if cfg.Configs.Base.PanicOnWarning { logHookLast = loggers.PanicOnWarningHook } if cfg.StdOut == nil { cfg.StdOut = os.Stdout } if cfg.StdErr == nil { cfg.StdErr = os.Stderr } if cfg.LogLevel == 0 { cfg.LogLevel = logg.LevelWarn } logOpts := loggers.Options{ Level: cfg.LogLevel, DistinctLevel: logg.LevelWarn, // This will drop duplicate log warning and errors. HandlerPost: logHookLast, StdOut: cfg.StdOut, StdErr: cfg.StdErr, StoreErrors: conf.Watching(), SuppressStatements: conf.IgnoredLogs(), } logger = loggers.New(logOpts) } memCache := dynacache.New(dynacache.Options{Watching: conf.Watching(), Log: logger}) var h *HugoSites onSignalRebuild := func(ids ...identity.Identity) { // This channel is buffered, but make sure we do this in a non-blocking way. if cfg.ChangesFromBuild != nil { go func() { cfg.ChangesFromBuild <- ids }() } } compilationCacheDir := filepath.Join(conf.Dirs().CacheDir, "_warpc") firstSiteDeps := &deps.Deps{ Fs: cfg.Fs, Log: logger, Conf: conf, BuildState: &deps.BuildState{ OnSignalRebuild: onSignalRebuild, }, Counters: &deps.Counters{}, MemCache: memCache, TranslationProvider: i18n.NewTranslationProvider(), WasmDispatchers: warpc.AllDispatchers( // Katex options. warpc.Options{ CompilationCacheDir: compilationCacheDir, // Katex is relatively slow. PoolSize: 8, Infof: logger.InfoCommand("katex").Logf, Warnf: logger.WarnCommand("katex").Logf, }, // WebP options. warpc.Options{ CompilationCacheDir: compilationCacheDir, PoolSize: 1, Memory: 384, // 384 MiB (4096 MiB Max) Infof: logger.InfoCommand("webp").Logf, Warnf: logger.WarnCommand("webp").Logf, }, ), } if err := firstSiteDeps.Init(); err != nil { return nil, err } // Prevent leaking goroutines in tests. if cfg.IsIntegrationTest && cfg.ChangesFromBuild != nil { firstSiteDeps.BuildClosers.Add(types.CloserFunc(func() error { close(cfg.ChangesFromBuild) return nil })) } batcherClient, err := esbuild.NewBatcherClient(firstSiteDeps) if err != nil { return nil, err } firstSiteDeps.JSBatcherClient = batcherClient confm := cfg.Configs if err := confm.Validate(logger); err != nil { return nil, err } var sites []*Site ns := &contentNodeShifter{ conf: conf, } treeConfig := doctree.Config[contentNode]{ Shifter: ns, TransformerRaw: &contentNodeTransformerRaw{}, } dimensionLengths := sitesmatrix.Vector{len(confm.Languages), len(versionsSorted), len(rolesSorted)} pageTrees := &pageTrees{ treePages: doctree.New( treeConfig, ), treeResources: doctree.New( treeConfig, ), treeTaxonomyEntries: doctree.NewTreeShiftTree[*weightedContentNode](dimensionLengths), treePagesFromTemplateAdapters: doctree.NewTreeShiftTree[*pagesfromdata.PagesFromTemplate](dimensionLengths), } pageTrees.createMutableTrees() for i, confp := range confm.ConfigLangs() { language := confp.Language().(*langs.Language) if language.Disabled { panic("cannot create site for disabled language: " + language.Lang) } k := language.Lang conf := confm.LanguageConfigMap[k] frontmatterHandler, err := pagemeta.NewFrontmatterHandler(firstSiteDeps.Log, conf.Frontmatter) if err != nil { return nil, err } langs.SetParams(language, conf.Params) s := &Site{ conf: conf, language: language, frontmatterHandler: frontmatterHandler, store: hstore.NewScratch(), siteLanguageVersionRole: &siteLanguageVersionRole{ siteVector: sitesmatrix.Vector{i, 0, 0}, }, } s.siteWrapped = page.WrapSite(s) if i == 0 { firstSiteDeps.Site = s s.Deps = firstSiteDeps } else { d, err := firstSiteDeps.Clone(s, confp) if err != nil { return nil, err } s.Deps = d } // Set up the main publishing chain. pub, err := publisher.NewDestinationPublisher( firstSiteDeps.ResourceSpec, s.conf.OutputFormats.Config, s.conf.MediaTypes.Config, ) if err != nil { return nil, err } s.publisher = pub s.relatedDocsHandler = page.NewRelatedDocsHandler(s.conf.Related) // Site deps end. sites = append(sites, s) } if len(sites) == 0 { return nil, errors.New("no sites to build") } sitesVersionsRoles := make([][][]*Site, len(sites)) for i := 0; i < len(sites); i++ { sitesVersionsRoles[i] = make([][]*Site, len(versionsSorted)) for j := range versionsSorted { sitesVersionsRoles[i][j] = make([]*Site, len(rolesSorted)) } } siteVersionRoles := map[types.Ints2][]roles.Role{} siteRoleVersions := map[types.Ints2][]versions.Version{} // i = site, j = version, k = role for i, v1 := range sitesVersionsRoles { for j, v2 := range v1 { for k := range v2 { var vrs *Site if j == 0 && k == 0 { vrs = sites[i] } else { prototype := sites[i] vrs, err = prototype.cloneForVersionAndRole(j, k) if err != nil { return nil, err } } vrs.roleInternal = rolesSorted[k] vrs.role = roles.NewRole(rolesSorted[k]) vrs.versionInternal = versionsSorted[j] vrs.version = versions.NewVersion(versionsSorted[j]) siteRoleVersions[types.Ints2{i, k}] = append(siteRoleVersions[types.Ints2{i, k}], vrs.version) siteVersionRoles[types.Ints2{i, j}] = append(siteVersionRoles[types.Ints2{i, j}], vrs.role) vrs.pageMap = newPageMap(vrs, memCache, pageTrees) vrs.pageFinder = newPageFinder(vrs.pageMap) vrs.siteRefLinker = newSiteRefLinker(vrs) vrs.prepareInits() v2[k] = vrs } } } h, err = newHugoSites(cfg, firstSiteDeps, pageTrees, sitesVersionsRoles) if err == nil && h == nil { panic("hugo: newHugoSitesNew returned nil error and nil HugoSites") } return h, err } func newHugoSites( cfg deps.DepsCfg, d *deps.Deps, pageTrees *pageTrees, sitesVersionsRoles [][][]*Site, ) (*HugoSites, error) { first := make([]*Site, len(sitesVersionsRoles)) for i, v := range sitesVersionsRoles { first[i] = v[0][0] } sitesVersionsRolesMap := map[sitesmatrix.Vector]*Site{} for _, v1 := range sitesVersionsRoles { for _, v2 := range v1 { for _, s := range v2 { sitesVersionsRolesMap[s.siteVector] = s } } } numWorkers := config.GetNumWorkerMultiplier() numWorkersSite := min(numWorkers, len(sitesVersionsRolesMap)) workersSite := para.New(numWorkersSite) var sitesLanguages []*Site for _, v := range sitesVersionsRoles { sitesLanguages = append(sitesLanguages, v[0][0]) } h := &HugoSites{ Sites: first, sitesVersionsRoles: sitesVersionsRoles, sitesVersionsRolesMap: sitesVersionsRolesMap, sitesLanguages: sitesLanguages, Deps: first[0].Deps, Configs: cfg.Configs, workersSite: workersSite, numWorkersSites: numWorkers, numWorkers: numWorkers, pageTrees: pageTrees, cachePages: dynacache.GetOrCreatePartition[string, page.Pages](d.MemCache, "/pags/all", dynacache.OptionsPartition{Weight: 10, ClearWhen: dynacache.ClearOnRebuild}, ), cacheContentSource: dynacache.GetOrCreatePartition[uint64, *resources.StaleValue[[]byte]](d.MemCache, "/cont/src", dynacache.OptionsPartition{Weight: 70, ClearWhen: dynacache.ClearOnChange}), translationKeyPages: maps.NewSliceCache[page.Page](), currentSite: first[0], skipRebuildForFilenames: make(map[string]bool), init: &hugoSitesInit{}, progressReporter: &progressReporter{}, } // Assemble dependencies to be used in hugo.Deps. var dependencies []*hugo.Dependency var depFromMod func(m modules.Module) *hugo.Dependency depFromMod = func(m modules.Module) *hugo.Dependency { dep := &hugo.Dependency{ Path: m.Path(), Version: m.Version(), Time: m.Time(), Vendor: m.Vendor(), } // These are pointers, but this all came from JSON so there's no recursive navigation, // so just create new values. if m.Replace() != nil { dep.Replace = depFromMod(m.Replace()) } if m.Owner() != nil { dep.Owner = depFromMod(m.Owner()) } return dep } for _, m := range d.Paths.AllModules() { dependencies = append(dependencies, depFromMod(m)) } h.hugoInfo = hugo.NewInfo(h.Configs.GetFirstLanguageConfig(), dependencies) var prototype *deps.Deps var i int for _, v := range sitesVersionsRoles { for _, r := range v { for _, s := range r { s.h = h // The template store needs to be initialized after the h container is set on s. if i == 0 { templateStore, err := tplimpl.NewStore( tplimpl.StoreOptions{ Fs: s.BaseFs.Layouts.Fs, Log: s.Log, Watching: s.Conf.Watching(), PathParser: s.Conf.PathParser(), Metrics: d.Metrics, OutputFormats: s.conf.OutputFormats.Config, MediaTypes: s.conf.MediaTypes.Config, DefaultOutputFormat: s.conf.DefaultOutputFormat, TaxonomySingularPlural: s.conf.Taxonomies, RenderHooks: s.conf.Markup.Goldmark.RenderHooks, }, tplimpl.SiteOptions{ Site: s, TemplateFuncs: tplimplinit.CreateFuncMap(s.Deps), }) if err != nil { return nil, err } s.Deps.TemplateStore = templateStore } else { s.Deps.TemplateStore = prototype.TemplateStore.WithSiteOpts( tplimpl.SiteOptions{ Site: s, TemplateFuncs: tplimplinit.CreateFuncMap(s.Deps), }) } if err := s.Deps.Compile(prototype); err != nil { return nil, err } if i == 0 { prototype = s.Deps } i++ } } } h.fatalErrorHandler = &fatalErrorHandler{ h: h, donec: make(chan bool), } h.init.data = hsync.OnceMoreFunc(func(ctx context.Context) error { return h.loadData() }) h.init.gitInfo = hsync.OnceMoreFunc(func(ctx context.Context) error { return h.loadGitInfo() }) return h, nil } // GetSiteDimension returns the value of the specified site dimension (such as language, version, or role) // based on the provided dimension name string. If the dimension name is unknown, it panics. func (s *Site) Dimension(d string) page.SiteDimension { switch d { case sitesmatrix.DimensionName(sitesmatrix.Language): return s.language case sitesmatrix.DimensionName(sitesmatrix.Version): return s.version case sitesmatrix.DimensionName(sitesmatrix.Role): return s.role default: panic(fmt.Sprintf("unknown dimension %q", d)) } } // Returns the server port. func (s *Site) ServerPort() int { return s.conf.C.BaseURL.Port() } // Returns the configured title for this Site. func (s *Site) Title() string { return s.conf.Title } func (s *Site) Copyright() string { return s.conf.Copyright } func (s *Site) Lang() string { return s.language.Lang } func (s *Site) Config() page.SiteConfig { return page.SiteConfig{ Privacy: s.conf.Privacy, Services: s.conf.Services, } } func (s *Site) LanguageCode() string { return s.Language().LanguageCode() } // Returns all Sites for all languages. func (s *Site) Sites() page.Sites { sites := make(page.Sites, len(s.h.Sites)) for i, s := range s.h.Sites { sites[i] = s.Site() } return sites } // Returns Site currently rendering. func (s *Site) Current() page.Site { return s.h.currentSite } // MainSections returns the list of main sections. func (s *Site) MainSections() []string { s.CheckReady() return s.conf.C.MainSections } // Returns a struct with some information about the build. func (s *Site) Hugo() hugo.HugoInfo { if s.h == nil { panic("site: hugo: h not initialized") } if s.h.hugoInfo.Environment == "" { panic("site: hugo: hugoInfo not initialized") } return s.h.hugoInfo } // Returns the BaseURL for this Site. func (s *Site) BaseURL() string { return s.conf.C.BaseURL.WithPath } // Deprecated: Use .Site.Lastmod instead. func (s *Site) LastChange() time.Time { s.CheckReady() hugo.Deprecate(".Site.LastChange", "Use .Site.Lastmod instead.", "v0.123.0") return s.lastmod } // Returns the last modification date of the content. func (s *Site) Lastmod() time.Time { return s.lastmod } // Returns the Params configured for this site. func (s *Site) Params() maps.Params { return s.conf.Params } // Deprecated: Use taxonomies instead. func (s *Site) Author() map[string]any { if len(s.conf.Author) != 0 { hugo.Deprecate(".Site.Author", "Implement taxonomy 'author' or use .Site.Params.Author instead.", "v0.124.0") } return s.conf.Author } // Deprecated: Use taxonomies instead. func (s *Site) Authors() page.AuthorList { hugo.Deprecate(".Site.Authors", "Implement taxonomy 'authors' or use .Site.Params.Author instead.", "v0.124.0") return page.AuthorList{} } // Deprecated: Use .Site.Params instead. func (s *Site) Social() map[string]string { hugo.Deprecate(".Site.Social", "Implement taxonomy 'social' or use .Site.Params.Social instead.", "v0.124.0") return s.conf.Social } func (s *Site) Param(key any) (any, error) { return resource.Param(s, nil, key) } // Returns a map of all the data inside /data. func (s *Site) Data() map[string]any { return s.h.Data() } func (s *Site) BuildDrafts() bool { return s.conf.BuildDrafts } // Deprecated: Use hugo.IsMultilingual instead. func (s *Site) IsMultiLingual() bool { hugo.Deprecate(".Site.IsMultiLingual", "Use hugo.IsMultilingual instead.", "v0.124.0") return s.h.isMultilingual() } func (s *Site) LanguagePrefix() string { prefix := s.GetLanguagePrefix() if prefix == "" { return "" } return "/" + prefix } func (s *Site) Site() page.Site { return page.WrapSite(s) } func (s *Site) ForEeachIdentityByName(name string, f func(identity.Identity) bool) { if id, found := siteidentities.FromString(name); found { if f(id) { return } } } // Pages returns all pages. // This is for the current language only. func (s *Site) Pages() page.Pages { s.CheckReady() return s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ Path: "", KeyPart: "global", Include: pagePredicates.ShouldListGlobal.BoolFunc(), }, Recursive: true, IncludeSelf: true, }, ) } // RegularPages returns all the regular pages. // This is for the current language only. func (s *Site) RegularPages() page.Pages { s.CheckReady() return s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ Path: "", KeyPart: "global", Include: pagePredicates.ShouldListGlobal.And(pagePredicates.KindPage).BoolFunc(), }, Recursive: true, }, ) } // AllPages returns all pages for all sites. func (s *Site) AllPages() page.Pages { s.CheckReady() return s.h.Pages() } // AllRegularPages returns all regular pages for all sites. func (s *Site) AllRegularPages() page.Pages { s.CheckReady() return s.h.RegularPages() } func (s *Site) Store() *hstore.Scratch { return s.store } func (s *Site) CheckReady() { if s.state != siteStateReady { panic("this method cannot be called before the site is fully initialized") } } func (s *Site) Taxonomies() page.TaxonomyList { s.CheckReady() return s.init.taxonomies.Value(context.Background()) } type ( taxonomiesConfig map[string]string taxonomiesConfigValues struct { views []viewName viewsByTreeKey map[string]viewName } ) func (t taxonomiesConfig) Values() taxonomiesConfigValues { var views []viewName for k, v := range t { views = append(views, viewName{singular: k, plural: v, pluralTreeKey: cleanTreeKey(v)}) } sort.Slice(views, func(i, j int) bool { return views[i].plural < views[j].plural }) viewsByTreeKey := make(map[string]viewName) for _, v := range views { viewsByTreeKey[v.pluralTreeKey] = v } return taxonomiesConfigValues{ views: views, viewsByTreeKey: viewsByTreeKey, } } // Lazily loaded site dependencies. type siteInit struct { prevNext hsync.FuncResetter prevNextInSection hsync.FuncResetter menus hsync.ValueResetter[navigation.Menus] taxonomies hsync.ValueResetter[page.TaxonomyList] } func (init *siteInit) Reset() { init.prevNext.Reset() init.prevNextInSection.Reset() init.menus.Reset() init.taxonomies.Reset() } func (s *Site) prepareInits() { s.init = &siteInit{} s.init.prevNext = hsync.OnceMoreFunc(func(ctx context.Context) error { regularPages := s.RegularPages() if s.conf.Page.NextPrevSortOrder == "asc" { regularPages = regularPages.Reverse() } for i, p := range regularPages { np, ok := p.(nextPrevProvider) if !ok { continue } pos := np.getNextPrev() if pos == nil { continue } pos.nextPage = nil pos.prevPage = nil if i > 0 { pos.nextPage = regularPages[i-1] } if i < len(regularPages)-1 { pos.prevPage = regularPages[i+1] } } return nil }) s.init.prevNextInSection = hsync.OnceMoreFunc(func(ctx context.Context) error { setNextPrev := func(pas page.Pages) { for i, p := range pas { np, ok := p.(nextPrevInSectionProvider) if !ok { continue } pos := np.getNextPrevInSection() if pos == nil { continue } pos.nextPage = nil pos.prevPage = nil if i > 0 { pos.nextPage = pas[i-1] } if i < len(pas)-1 { pos.prevPage = pas[i+1] } } } sections := s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ Path: "", KeyPart: "sectionorhome", Include: pagePredicates.KindSection.Or(pagePredicates.KindHome).BoolFunc(), }, IncludeSelf: true, Recursive: true, }, ) for _, section := range sections { ps := section.RegularPages() if s.conf.Page.NextPrevInSectionSortOrder == "asc" { ps = ps.Reverse() } setNextPrev(ps) } return nil }) s.init.menus = hsync.OnceMoreValue(func(ctx context.Context) navigation.Menus { m, err := s.assembleMenus() if err != nil { panic(err) } return m }) s.init.taxonomies = hsync.OnceMoreValue(func(ctx context.Context) page.TaxonomyList { taxonomies, err := s.pageMap.CreateSiteTaxonomies(ctx) if err != nil { panic(err) } return taxonomies }) } func (s *Site) Menus() navigation.Menus { s.CheckReady() return s.init.menus.Value(context.Background()) } func (s *Site) initRenderFormats() { formatSet := make(map[string]bool) formats := output.Formats{} w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: s.pageMap.treePages, Handle: func(key string, n contentNode) (radix.WalkFlag, error) { if p, ok := n.(*pageState); ok { for _, f := range p.m.pageConfig.ConfiguredOutputFormats { if !formatSet[f.Name] { formats = append(formats, f) formatSet[f.Name] = true } } } return radix.WalkContinue, nil }, } if err := w.Walk(context.TODO()); err != nil { panic(err) } // Add the per kind configured output formats for _, kind := range kinds.AllKindsInPages { if siteFormats, found := s.conf.C.KindOutputFormats[kind]; found { for _, f := range siteFormats { if !formatSet[f.Name] { formats = append(formats, f) formatSet[f.Name] = true } } } } sort.Sort(formats) s.renderFormats = formats } func (s *Site) GetInternalRelatedDocsHandler() *page.RelatedDocsHandler { return s.relatedDocsHandler } func (s *Site) Language() *langs.Language { return s.language } func (s *Site) Languages() langs.Languages { return s.h.Configs.Languages } type siteRefLinker struct { s *Site errorLogger logg.LevelLogger notFoundURL string } func newSiteRefLinker(s *Site) siteRefLinker { logger := s.Log.Error() notFoundURL := s.conf.RefLinksNotFoundURL errLevel := s.conf.RefLinksErrorLevel if strings.EqualFold(errLevel, "warning") { logger = s.Log.Warn() } return siteRefLinker{s: s, errorLogger: logger, notFoundURL: notFoundURL} } func (s siteRefLinker) logNotFound(ref, what string, p page.Page, position text.Position) { if position.IsValid() { s.errorLogger.Logf("[%s] REF_NOT_FOUND: Ref %q: %s: %s", s.s.Lang(), ref, position.String(), what) } else if p == nil { s.errorLogger.Logf("[%s] REF_NOT_FOUND: Ref %q: %s", s.s.Lang(), ref, what) } else { s.errorLogger.Logf("[%s] REF_NOT_FOUND: Ref %q from page %q: %s", s.s.Lang(), ref, p.Path(), what) } } func (s *siteRefLinker) refLink(ref string, source any, relative bool, outputFormat string) (string, error) { p, err := unwrapPage(source) if err != nil { return "", err } var refURL *url.URL ref = filepath.ToSlash(ref) refURL, err = url.Parse(ref) if err != nil { return s.notFoundURL, err } var target page.Page var link string if refURL.Path != "" { var err error target, err = s.s.getPageRef(p, refURL.Path) var pos text.Position if err != nil || target == nil { if p, ok := source.(text.Positioner); ok { pos = p.Position() } } if err != nil { s.logNotFound(refURL.Path, err.Error(), p, pos) return s.notFoundURL, nil } if target == nil { s.logNotFound(refURL.Path, "page not found", p, pos) return s.notFoundURL, nil } var permalinker Permalinker = target if outputFormat != "" { o := target.OutputFormats().Get(outputFormat) if o == nil { s.logNotFound(refURL.Path, fmt.Sprintf("output format %q", outputFormat), p, pos) return s.notFoundURL, nil } permalinker = o } if relative { link = permalinker.RelPermalink() } else { link = permalinker.Permalink() } } if refURL.Fragment != "" { _ = target link = link + "#" + refURL.Fragment if pctx, ok := target.(pageContext); ok { if refURL.Path != "" { if di, ok := pctx.getContentConverter().(converter.DocumentInfo); ok { link = link + di.AnchorSuffix() } } } else if pctx, ok := p.(pageContext); ok { if di, ok := pctx.getContentConverter().(converter.DocumentInfo); ok { link = link + di.AnchorSuffix() } } } return link, nil } func (s *Site) watching() bool { return s.h != nil && s.h.Configs.Base.Internal.Watch } type WhatChanged struct { mu sync.Mutex needsPagesAssembly bool ids map[identity.Identity]bool } func (w *WhatChanged) init() { if w.ids == nil { w.ids = make(map[identity.Identity]bool) } } func (w *WhatChanged) Add(ids ...identity.Identity) { w.mu.Lock() defer w.mu.Unlock() w.init() for _, id := range ids { w.ids[id] = true } } func (w *WhatChanged) Clear() { w.mu.Lock() defer w.mu.Unlock() w.clear() } func (w *WhatChanged) clear() { w.ids = nil } func (w *WhatChanged) Changes() []identity.Identity { if w == nil || w.ids == nil { return nil } return slices.Collect(xmaps.Keys(w.ids)) } func (w *WhatChanged) Drain() []identity.Identity { w.mu.Lock() defer w.mu.Unlock() ids := w.Changes() w.clear() return ids } // RegisterMediaTypes will register the Site's media types in the mime // package, so it will behave correctly with Hugo's built-in server. func (s *Site) RegisterMediaTypes() { for _, mt := range s.conf.MediaTypes.Config { for _, suffix := range mt.Suffixes() { _ = mime.AddExtensionType(mt.Delimiter+suffix, mt.Type) } } } func (h *HugoSites) fileEventsFilter(events []fsnotify.Event) []fsnotify.Event { seen := make(map[fsnotify.Event]bool) n := 0 for _, ev := range events { // Avoid processing the same event twice. if seen[ev] { continue } seen[ev] = true if h.SourceSpec.IgnoreFile(ev.Name) { continue } if runtime.GOOS == "darwin" { // When a file system is HFS+, its filepath is in NFD form. ev.Name = norm.NFC.String(ev.Name) } events[n] = ev n++ } events = events[:n] eventOrdinal := func(e fsnotify.Event) int { // Pull the structural changes to the top. if e.Op.Has(fsnotify.Create) { return 1 } if e.Op.Has(fsnotify.Remove) { return 2 } if e.Op.Has(fsnotify.Rename) { return 3 } if e.Op.Has(fsnotify.Write) { return 4 } return 5 } sort.Slice(events, func(i, j int) bool { // First sort by event type. if eventOrdinal(events[i]) != eventOrdinal(events[j]) { return eventOrdinal(events[i]) < eventOrdinal(events[j]) } // Then sort by name. return events[i].Name < events[j].Name }) return events } type fileEventInfo struct { fsnotify.Event fi os.FileInfo added bool removed bool isChangedDir bool } func (h *HugoSites) fileEventsApplyInfo(events []fsnotify.Event) []fileEventInfo { var infos []fileEventInfo for _, ev := range events { removed := false added := false if ev.Op&fsnotify.Remove == fsnotify.Remove { removed = true } fi, statErr := h.Fs.Source.Stat(ev.Name) // Some editors (Vim) sometimes issue only a Rename operation when writing an existing file // Sometimes a rename operation means that file has been renamed other times it means // it's been updated. if ev.Op.Has(fsnotify.Rename) { // If the file is still on disk, it's only been updated, if it's not, it's been moved if statErr != nil { removed = true } } if ev.Op.Has(fsnotify.Create) { added = true } isChangedDir := statErr == nil && fi.IsDir() infos = append(infos, fileEventInfo{ Event: ev, fi: fi, added: added, removed: removed, isChangedDir: isChangedDir, }) } n := 0 for _, ev := range infos { // Remove any directories that's also represented by a file. keep := true if ev.isChangedDir { for _, ev2 := range infos { if ev2.fi != nil && !ev2.fi.IsDir() && filepath.Dir(ev2.Name) == ev.Name { keep = false break } } } if keep { infos[n] = ev n++ } } infos = infos[:n] return infos } func (h *HugoSites) fileEventsTrim(events []fsnotify.Event) []fsnotify.Event { seen := make(map[string]bool) n := 0 for _, ev := range events { if seen[ev.Name] { continue } seen[ev.Name] = true events[n] = ev n++ } return events } func (h *HugoSites) fileEventsContentPaths(p []pathChange) []pathChange { var bundles []pathChange var dirs []pathChange var regular []pathChange var others []pathChange for _, p := range p { if p.isDir { dirs = append(dirs, p) } else { others = append(others, p) } } // Remove all files below dir. if len(dirs) > 0 { n := 0 for _, d := range dirs { dir := d.p.Path() + "/" for _, o := range others { if !strings.HasPrefix(o.p.Path(), dir) { others[n] = o n++ } } } others = others[:n] } for _, p := range others { if p.p.IsBundle() { bundles = append(bundles, p) } else { regular = append(regular, p) } } // Remove any files below leaf bundles. // Remove any files in the same folder as branch bundles. var keepers []pathChange for _, o := range regular { keep := true for _, b := range bundles { prefix := b.p.Base() + "/" if b.p.IsLeafBundle() && strings.HasPrefix(o.p.Path(), prefix) { keep = false break } else if b.p.IsBranchBundle() && o.p.Dir() == b.p.Dir() { keep = false break } } if keep { keepers = append(keepers, o) } } keepers = append(dirs, keepers...)
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page_test.go
hugolib/page_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "fmt" "html/template" "path/filepath" "strings" "testing" "time" "github.com/bep/clocks" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/markup/asciidocext" "github.com/gohugoio/hugo/markup/rst" "github.com/gohugoio/hugo/tpl" "github.com/spf13/cast" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" qt "github.com/frankban/quicktest" ) const ( homePage = "---\ntitle: Home\n---\nHome Page Content\n" simplePage = "---\ntitle: Simple\n---\nSimple Page\n" simplePageRFC3339Date = "---\ntitle: RFC3339 Date\ndate: \"2013-05-17T16:59:30Z\"\n---\nrfc3339 content" simplePageWithoutSummaryDelimiter = `--- title: SimpleWithoutSummaryDelimiter --- [Lorem ipsum](https://lipsum.com/) dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Additional text. Further text. ` simplePageWithSummaryDelimiter = `--- title: Simple --- Summary Next Line <!--more--> Some more text ` simplePageWithSummaryParameter = `--- title: SimpleWithSummaryParameter summary: "Page with summary parameter and [a link](http://www.example.com/)" --- Some text. Some more text. ` simplePageWithSummaryDelimiterAndMarkdownThatCrossesBorder = `--- title: Simple --- The [best static site generator][hugo].[^1] <!--more--> [hugo]: http://gohugo.io/ [^1]: Many people say so. ` simplePageWithSummaryDelimiterSameLine = `--- title: Simple --- Summary Same Line<!--more--> Some more text ` simplePageWithAllCJKRunes = `--- title: Simple --- € € € € € 你好 도형이 カテゴリー ` simplePageWithMainEnglishWithCJKRunes = `--- title: Simple --- In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. In Chinese, 好 means good. More then 70 words. ` simplePageWithIsCJKLanguageFalse = `--- title: Simple isCJKLanguage: false --- In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. In Chinese, 好的啊 means good. In Chinese, 好的呀 means good. In Chinese, 好的啊 means good. In Chinese, 好的呀呀 means good enough. More then 70 words. ` simplePageWithLongContent = `--- title: Simple --- Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.` pageWithToC = `--- title: TOC --- For some moments the old man did not reply. He stood with bowed head, buried in deep thought. But at last he spoke. ## AA I have no idea, of course, how long it took me to reach the limit of the plain, but at last I entered the foothills, following a pretty little canyon upward toward the mountains. Beside me frolicked a laughing brooklet, hurrying upon its noisy way down to the silent sea. In its quieter pools I discovered many small fish, of four-or five-pound weight I should imagine. In appearance, except as to size and color, they were not unlike the whale of our own seas. As I watched them playing about I discovered, not only that they suckled their young, but that at intervals they rose to the surface to breathe as well as to feed upon certain grasses and a strange, scarlet lichen which grew upon the rocks just above the water line. ### AAA I remember I felt an extraordinary persuasion that I was being played with, that presently, when I was upon the very verge of safety, this mysterious death--as swift as the passage of light--would leap after me from the pit about the cylinder and strike me down. ## BB ### BBB "You're a great Granser," he cried delightedly, "always making believe them little marks mean something." ` simplePageWithURL = `--- title: Simple url: simple/url/ --- Simple Page With URL` simplePageWithSlug = `--- title: Simple slug: simple-slug --- Simple Page With Slug` simplePageWithDate = `--- title: Simple date: '2013-10-15T06:16:13' --- Simple Page With Date` UTF8Page = `--- title: ラーメン --- UTF8 Page` UTF8PageWithURL = `--- title: ラーメン url: ラーメン/url/ --- UTF8 Page With URL` UTF8PageWithSlug = `--- title: ラーメン slug: ラーメン-slug --- UTF8 Page With Slug` UTF8PageWithDate = `--- title: ラーメン date: '2013-10-15T06:16:13' --- UTF8 Page With Date` ) func checkPageTitle(t *testing.T, page page.Page, title string) { if page.Title() != title { t.Fatalf("Page title is: %s. Expected %s", page.Title(), title) } } func checkPageContent(t *testing.T, page page.Page, expected string, msg ...any) { t.Helper() a := normalizeContent(expected) b := normalizeContent(content(page)) if a != b { t.Fatalf("Page content is:\n%q\nExpected:\n%q (%q)", b, a, msg) } } func normalizeContent(c string) string { norm := c norm = strings.Replace(norm, "\n", " ", -1) norm = strings.Replace(norm, " ", " ", -1) norm = strings.Replace(norm, " ", " ", -1) norm = strings.Replace(norm, " ", " ", -1) norm = strings.Replace(norm, "p> ", "p>", -1) norm = strings.Replace(norm, "> <", "> <", -1) return strings.TrimSpace(norm) } func checkPageTOC(t *testing.T, page page.Page, toc string) { t.Helper() if page.TableOfContents(context.Background()) != template.HTML(toc) { t.Fatalf("Page TableOfContents is:\n%q.\nExpected %q", page.TableOfContents(context.Background()), toc) } } func checkPageSummary(t *testing.T, page page.Page, summary string, msg ...any) { s := string(page.Summary(context.Background())) a := normalizeContent(s) b := normalizeContent(summary) if a != b { t.Fatalf("Page summary is:\n%q.\nExpected\n%q (%q)", a, b, msg) } } func checkPageType(t *testing.T, page page.Page, pageType string) { if page.Type() != pageType { t.Fatalf("Page type is: %s. Expected: %s", page.Type(), pageType) } } func checkPageDate(t *testing.T, page page.Page, time time.Time) { if page.Date() != time { t.Fatalf("Page date is: %s. Expected: %s", page.Date(), time) } } func normalizeExpected(ext, str string) string { str = normalizeContent(str) switch ext { default: return str case "html": return strings.Trim(tpl.StripHTML(str), " ") case "ad": paragraphs := strings.Split(str, "</p>") expected := "" for _, para := range paragraphs { if para == "" { continue } expected += fmt.Sprintf("<div class=\"paragraph\">\n%s</p></div>\n", para) } return expected case "rst": if str == "" { return "<div class=\"document\"></div>" } return fmt.Sprintf("<div class=\"document\">\n\n\n%s</div>", str) } } func testAllMarkdownEnginesForPages(t *testing.T, assertFunc func(t *testing.T, ext string, pages page.Pages), settings map[string]any, pageSources ...string, ) { engines := []struct { ext string shouldExecute func() bool }{ {"md", func() bool { return true }}, {"ad", func() bool { ok, _ := asciidocext.Supports(); return ok }}, {"rst", func() bool { return !htesting.IsRealCI() && rst.Supports() }}, } for _, e := range engines { if !e.shouldExecute() { continue } t.Run(e.ext, func(t *testing.T) { cfg := config.New() for k, v := range settings { cfg.Set(k, v) } if s := cfg.GetString("contentDir"); s != "" && s != "content" { panic("contentDir must be set to 'content' for this test") } files := ` -- hugo.toml -- [security] [security.exec] allow = ['^python$', '^rst2html.*', '^asciidoctor$'] ` for i, source := range pageSources { files += fmt.Sprintf("-- content/p%d.%s --\n%s\n", i, e.ext, source) } homePath := fmt.Sprintf("_index.%s", e.ext) files += fmt.Sprintf("-- content/%s --\n%s\n", homePath, homePage) b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, BaseCfg: cfg, }, ).Build() s := b.H.Sites[0] b.Assert(len(s.RegularPages()), qt.Equals, len(pageSources)) assertFunc(t, e.ext, s.RegularPages()) home := s.Home() b.Assert(home, qt.Not(qt.IsNil)) b.Assert(home.File().Path(), qt.Equals, homePath) b.Assert(content(home), qt.Contains, "Home Page Content") }) } } // Issue #1076 func TestPageWithDelimiterForMarkdownThatCrossesBorder(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/simple.md -- ` + simplePageWithSummaryDelimiterAndMarkdownThatCrossesBorder + ` ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{SkipRender: true}, }, ).Build() b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 1) p := b.H.Sites[0].RegularPages()[0] b.Assert(p.Summary(context.Background()), qt.Equals, template.HTML( "<p>The <a href=\"http://gohugo.io/\">best static site generator</a>.<sup id=\"fnref:1\"><a href=\"#fn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup></p>")) cnt := content(p) b.Assert(cnt, qt.Equals, "<p>The <a href=\"http://gohugo.io/\">best static site generator</a>.<sup id=\"fnref:1\"><a href=\"#fn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup></p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n<hr>\n<ol>\n<li id=\"fn:1\">\n<p>Many people say so.&#160;<a href=\"#fnref:1\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n</ol>\n</div>") } func TestPageDatesTerms(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/p1.md -- --- title: p1 date: 2022-01-15 lastMod: 2022-01-16 tags: ["a", "b"] categories: ["c", "d"] --- p1 -- content/p2.md -- --- title: p2 date: 2017-01-16 lastMod: 2017-01-17 tags: ["a", "c"] categories: ["c", "e"] --- p2 -- layouts/list.html -- {{ .Title }}|Date: {{ .Date.Format "2006-01-02" }}|Lastmod: {{ .Lastmod.Format "2006-01-02" }}| ` b := Test(t, files) b.AssertFileContent("public/categories/index.html", "Categories|Date: 2022-01-15|Lastmod: 2022-01-16|") b.AssertFileContent("public/categories/c/index.html", "C|Date: 2022-01-15|Lastmod: 2022-01-16|") b.AssertFileContent("public/categories/e/index.html", "E|Date: 2017-01-16|Lastmod: 2017-01-17|") b.AssertFileContent("public/tags/index.html", "Tags|Date: 2022-01-15|Lastmod: 2022-01-16|") b.AssertFileContent("public/tags/a/index.html", "A|Date: 2022-01-15|Lastmod: 2022-01-16|") b.AssertFileContent("public/tags/c/index.html", "C|Date: 2017-01-16|Lastmod: 2017-01-17|") } func TestPageDatesAllKinds(t *testing.T) { t.Parallel() pageContent := ` --- title: Page date: 2017-01-15 tags: ["hugo"] categories: ["cool stuff"] --- ` files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/page.md -- ` + pageContent + ` -- content/blog/page.md -- ` + pageContent + ` ` b := Test(t, files) b.Assert(len(b.H.Sites), qt.Equals, 1) s := b.H.Sites[0] checkDate := func(t time.Time, msg string) { b.Helper() b.Assert(t.Year(), qt.Equals, 2017, qt.Commentf(msg)) } checkDated := func(d resource.Dated, msg string) { b.Helper() checkDate(d.Date(), "date: "+msg) checkDate(d.Lastmod(), "lastmod: "+msg) } for _, p := range s.Pages() { checkDated(p, p.Kind()) } checkDate(s.Lastmod(), "site") } func TestPageDatesSections(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/no-index/page.md -- --- title: Page date: 2017-01-15 --- -- content/with-index-no-date/_index.md -- --- title: No Date --- -- content/with-index-date/_index.md -- --- title: Date date: 2018-01-15 --- -- content/with-index-date/p1.md -- --- title: Date date: 2018-01-15 --- -- content/with-index-date/p2.md -- --- title: Date date: 2018-01-15 --- ` for i := 1; i <= 20; i++ { files += fmt.Sprintf(` -- content/main-section/p%d.md -- --- title: Date date: 2012-01-12 --- `, i) } b := Test(t, files) b.Assert(len(b.H.Sites), qt.Equals, 1) s := b.H.Sites[0] checkDate := func(p page.Page, year int) { b.Assert(p.Date().Year(), qt.Equals, year) b.Assert(p.Lastmod().Year(), qt.Equals, year) } checkDate(s.getPageOldVersion("/"), 2018) checkDate(s.getPageOldVersion("/no-index"), 2017) b.Assert(s.getPageOldVersion("/with-index-no-date").Date().IsZero(), qt.Equals, true) checkDate(s.getPageOldVersion("/with-index-date"), 2018) b.Assert(s.Site().Lastmod().Year(), qt.Equals, 2018) } func TestPageSummary(t *testing.T) { t.Parallel() assertFunc := func(t *testing.T, ext string, pages page.Pages) { p := pages[0] checkPageTitle(t, p, "SimpleWithoutSummaryDelimiter") // Source is not AsciiDoc- or RST-compatible so don't test them if ext != "ad" && ext != "rst" { checkPageContent(t, p, normalizeExpected(ext, "<p><a href=\"https://lipsum.com/\">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n\n<p>Additional text.</p>\n\n<p>Further text.</p>\n"), ext) checkPageSummary(t, p, normalizeExpected(ext, "<p><a href=\"https://lipsum.com/\">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><p>Additional text.</p>"), ext) } checkPageType(t, p, "page") } testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithoutSummaryDelimiter) } func TestPageWithDelimiter(t *testing.T) { t.Parallel() assertFunc := func(t *testing.T, ext string, pages page.Pages) { p := pages[0] checkPageTitle(t, p, "Simple") checkPageContent(t, p, normalizeExpected(ext, "<p>Summary Next Line</p>\n\n<p>Some more text</p>\n"), ext) checkPageSummary(t, p, normalizeExpected(ext, "<p>Summary Next Line</p>"), ext) checkPageType(t, p, "page") } testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithSummaryDelimiter) } func TestPageWithSummaryParameter(t *testing.T) { t.Parallel() assertFunc := func(t *testing.T, ext string, pages page.Pages) { p := pages[0] checkPageTitle(t, p, "SimpleWithSummaryParameter") checkPageContent(t, p, normalizeExpected(ext, "<p>Some text.</p>\n\n<p>Some more text.</p>\n"), ext) // Summary is not AsciiDoc- or RST-compatible so don't test them if ext != "ad" && ext != "rst" { checkPageSummary(t, p, normalizeExpected(ext, "Page with summary parameter and <a href=\"http://www.example.com/\">a link</a>"), ext) } checkPageType(t, p, "page") } testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithSummaryParameter) } // Issue #3854 // Also see https://github.com/gohugoio/hugo/issues/3977 func TestPageWithDateFields(t *testing.T) { c := qt.New(t) pageWithDate := `--- title: P%d weight: %d %s: 2017-10-13 --- Simple Page With Some Date` hasDate := func(p page.Page) bool { return p.Date().Year() == 2017 } datePage := func(field string, weight int) string { return fmt.Sprintf(pageWithDate, weight, weight, field) } t.Parallel() assertFunc := func(t *testing.T, ext string, pages page.Pages) { c.Assert(len(pages) > 0, qt.Equals, true) for _, p := range pages { c.Assert(hasDate(p), qt.Equals, true) } } fields := []string{"date", "publishdate", "pubdate", "published"} pageContents := make([]string, len(fields)) for i, field := range fields { pageContents[i] = datePage(field, i+1) } testAllMarkdownEnginesForPages(t, assertFunc, nil, pageContents...) } func TestPageRawContent(t *testing.T) { files := ` -- hugo.toml -- -- content/basic.md -- --- title: "basic" --- **basic** -- content/empty.md -- --- title: "empty" --- -- layouts/single.html -- |{{ .RawContent }}| ` b := Test(t, files) b.AssertFileContent("public/basic/index.html", "|**basic**|") b.AssertFileContent("public/empty/index.html", "! title") } func TestTableOfContents(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/tocpage.md -- ` + pageWithToC + ` ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{SkipRender: true}, }, ).Build() b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 1) p := b.H.Sites[0].RegularPages()[0] checkPageContent(t, p, "<p>For some moments the old man did not reply. He stood with bowed head, buried in deep thought. But at last he spoke.</p><h2 id=\"aa\">AA</h2> <p>I have no idea, of course, how long it took me to reach the limit of the plain, but at last I entered the foothills, following a pretty little canyon upward toward the mountains. Beside me frolicked a laughing brooklet, hurrying upon its noisy way down to the silent sea. In its quieter pools I discovered many small fish, of four-or five-pound weight I should imagine. In appearance, except as to size and color, they were not unlike the whale of our own seas. As I watched them playing about I discovered, not only that they suckled their young, but that at intervals they rose to the surface to breathe as well as to feed upon certain grasses and a strange, scarlet lichen which grew upon the rocks just above the water line.</p><h3 id=\"aaa\">AAA</h3> <p>I remember I felt an extraordinary persuasion that I was being played with, that presently, when I was upon the very verge of safety, this mysterious death&ndash;as swift as the passage of light&ndash;would leap after me from the pit about the cylinder and strike me down. ## BB</p><h3 id=\"bbb\">BBB</h3> <p>&ldquo;You&rsquo;re a great Granser,&rdquo; he cried delightedly, &ldquo;always making believe them little marks mean something.&rdquo;</p>") checkPageTOC(t, p, "<nav id=\"TableOfContents\">\n <ul>\n <li><a href=\"#aa\">AA</a>\n <ul>\n <li><a href=\"#aaa\">AAA</a></li>\n <li><a href=\"#bbb\">BBB</a></li>\n </ul>\n </li>\n </ul>\n</nav>") } func TestPageWithMoreTag(t *testing.T) { t.Parallel() assertFunc := func(t *testing.T, ext string, pages page.Pages) { p := pages[0] checkPageTitle(t, p, "Simple") checkPageContent(t, p, normalizeExpected(ext, "<p>Summary Same Line</p>\n\n<p>Some more text</p>\n")) checkPageSummary(t, p, normalizeExpected(ext, "<p>Summary Same Line</p>")) checkPageType(t, p, "page") } testAllMarkdownEnginesForPages(t, assertFunc, nil, simplePageWithSummaryDelimiterSameLine) } func TestSummaryInFrontMatter(t *testing.T) { t.Parallel() Test(t, ` -- hugo.toml -- -- content/simple.md -- --- title: Simple summary: "Front **matter** summary" --- Simple Page -- layouts/single.html -- Summary: {{ .Summary }}|Truncated: {{ .Truncated }}| `).AssertFileContent("public/simple/index.html", "Summary: Front <strong>matter</strong> summary|", "Truncated: false") } func TestSummaryManualSplit(t *testing.T) { t.Parallel() Test(t, ` -- hugo.toml -- -- content/simple.md -- --- title: Simple --- This is **summary**. <!--more--> This is **content**. -- layouts/single.html -- Summary: {{ .Summary }}|Truncated: {{ .Truncated }}| Content: {{ .Content }}| `).AssertFileContent("public/simple/index.html", "Summary: <p>This is <strong>summary</strong>.</p>|", "Truncated: true|", "Content: <p>This is <strong>summary</strong>.</p>\n<p>This is <strong>content</strong>.</p>|", ) } func TestSummaryManualSplitHTML(t *testing.T) { t.Parallel() Test(t, ` -- hugo.toml -- -- content/simple.html -- --- title: Simple --- <div> This is <b>summary</b>. </div> <!--more--> <div> This is <b>content</b>. </div> -- layouts/single.html -- Summary: {{ .Summary }}|Truncated: {{ .Truncated }}| Content: {{ .Content }}| `).AssertFileContent("public/simple/index.html", "Summary: <div>\nThis is <b>summary</b>.\n</div>\n|Truncated: true|\nContent: \n\n<div>\nThis is <b>content</b>.\n</div>|") } func TestSummaryAuto(t *testing.T) { t.Parallel() Test(t, ` -- hugo.toml -- summaryLength = 10 -- content/simple.md -- --- title: Simple --- This is **summary**. This is **more summary**. This is *even more summary**. This is **more summary**. This is **content**. -- layouts/single.html -- Summary: {{ .Summary }}|Truncated: {{ .Truncated }}| Content: {{ .Content }}| `).AssertFileContent("public/simple/index.html", "Summary: <p>This is <strong>summary</strong>.\nThis is <strong>more summary</strong>.\nThis is <em>even more summary</em>*.\nThis is <strong>more summary</strong>.</p>|", "Truncated: true|", "Content: <p>This is <strong>summary</strong>.") } // #2973 func TestSummaryWithHTMLTagsOnNextLine(t *testing.T) { assertFunc := func(t *testing.T, ext string, pages page.Pages) { c := qt.New(t) p := pages[0] s := string(p.Summary(context.Background())) c.Assert(s, qt.Contains, "Happy new year everyone!") c.Assert(s, qt.Not(qt.Contains), "User interface") } testAllMarkdownEnginesForPages(t, assertFunc, nil, `--- title: Simple --- Happy new year everyone! Here is the last report for commits in the year 2016. It covers hrev50718-hrev50829. <!--more--> <h3>User interface</h3> `) } // Issue 9383 func TestRenderStringForRegularPageTranslations(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseurl = "https://example.org/" title = "My Site" defaultContentLanguage = "ru" defaultContentLanguageInSubdir = true [languages.ru] contentDir = 'content/ru' weight = 1 [languages.en] weight = 2 contentDir = 'content/en' [outputs] home = ["HTML", "JSON"] -- layouts/home.html -- {{- range .Site.Home.Translations -}} <p>{{- .RenderString "foo" -}}</p> {{- end -}} {{- range .Site.Home.AllTranslations -}} <p>{{- .RenderString "bar" -}}</p> {{- end -}} -- layouts/single.html -- {{ .Content }} -- layouts/index.json -- {"Title": "My Site"} -- content/ru/a.md -- -- content/en/a.md -- ` b := Test(t, files) b.AssertFileContent("public/ru/index.html", ` <p>foo</p> <p>foo</p> <p>bar</p> <p>bar</p> `) b.AssertFileContent("public/en/index.html", ` <p>foo</p> <p>foo</p> <p>bar</p> <p>bar</p> `) } // Issue 8919 func TestContentProviderWithCustomOutputFormat(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'http://example.org/' title = 'My New Hugo Site' timeout = 600000 # ten minutes in case we want to pause and debug defaultContentLanguage = "en" [languages] [languages.en] title = "Repro" languageName = "English" contentDir = "content/en" [languages.zh_CN] title = "Repro" languageName = "简体中文" contentDir = "content/zh_CN" [outputFormats] [outputFormats.metadata] baseName = "metadata" mediaType = "text/html" isPlainText = true notAlternative = true [outputs] home = ["HTML", "metadata"] -- layouts/home.metadata.html -- <h2>Translations metadata</h2> <ul> {{ $p := .Page }} {{ range $p.Translations}} <li>Title: {{ .Title }}, {{ .Summary }}</li> <li>Content: {{ .Content }}</li> <li>Plain: {{ .Plain }}</li> <li>PlainWords: {{ .PlainWords }}</li> <li>Summary: {{ .Summary }}</li> <li>Truncated: {{ .Truncated }}</li> <li>FuzzyWordCount: {{ .FuzzyWordCount }}</li> <li>ReadingTime: {{ .ReadingTime }}</li> <li>Len: {{ .Len }}</li> {{ end }} </ul> -- layouts/baseof.html -- <html> <body> {{ block "main" . }}{{ end }} </body> </html> -- layouts/home.html -- {{ define "main" }} <h2>Translations</h2> <ul> {{ $p := .Page }} {{ range $p.Translations}} <li>Title: {{ .Title }}, {{ .Summary }}</li> <li>Content: {{ .Content }}</li> <li>Plain: {{ .Plain }}</li> <li>PlainWords: {{ .PlainWords }}</li> <li>Summary: {{ .Summary }}</li> <li>Truncated: {{ .Truncated }}</li> <li>FuzzyWordCount: {{ .FuzzyWordCount }}</li> <li>ReadingTime: {{ .ReadingTime }}</li> <li>Len: {{ .Len }}</li> {{ end }} </ul> {{ end }} -- content/en/_index.md -- --- title: Title (en) summary: Summary (en) --- Here is some content. -- content/zh_CN/_index.md -- --- title: Title (zh) summary: Summary (zh) --- 这是一些内容 ` b := Test(t, files) b.AssertFileContent("public/index.html", `<html> <body> <h2>Translations</h2> <ul> <li>Title: Title (zh), Summary (zh)</li> <li>Content: <p>这是一些内容</p> </li> <li>Plain: 这是一些内容 </li> <li>PlainWords: [这是一些内容]</li> <li>Summary: Summary (zh)</li> <li>Truncated: false</li> <li>FuzzyWordCount: 100</li> <li>ReadingTime: 1</li> <li>Len: 26</li> </ul> </body> </html>`) b.AssertFileContent("public/metadata.html", `<h2>Translations metadata</h2> <ul> <li>Title: Title (zh), Summary (zh)</li> <li>Content: <p>这是一些内容</p> </li> <li>Plain: 这是一些内容 </li> <li>PlainWords: [这是一些内容]</li> <li>Summary: Summary (zh)</li> <li>Truncated: false</li> <li>FuzzyWordCount: 100</li> <li>ReadingTime: 1</li> <li>Len: 26</li> </ul>`) b.AssertFileContent("public/zh_cn/index.html", `<html> <body> <h2>Translations</h2> <ul> <li>Title: Title (en), Summary (en)</li> <li>Content: <p>Here is some content.</p> </li> <li>Plain: Here is some content. </li> <li>PlainWords: [Here is some content.]</li> <li>Summary: Summary (en)</li> <li>Truncated: false</li> <li>FuzzyWordCount: 100</li> <li>ReadingTime: 1</li> <li>Len: 29</li> </ul> </body> </html>`) b.AssertFileContent("public/zh_cn/metadata.html", `<h2>Translations metadata</h2> <ul> <li>Title: Title (en), Summary (en)</li> <li>Content: <p>Here is some content.</p> </li> <li>Plain: Here is some content. </li> <li>PlainWords: [Here is some content.]</li> <li>Summary: Summary (en)</li> <li>Truncated: false</li> <li>FuzzyWordCount: 100</li> <li>ReadingTime: 1</li> <li>Len: 29</li> </ul>`) } func TestPageWithDate(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/simple.md -- ` + simplePageRFC3339Date + ` ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{SkipRender: true}, }, ).Build() b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 1) p := b.H.Sites[0].RegularPages()[0] d, _ := time.Parse(time.RFC3339, "2013-05-17T16:59:30Z") checkPageDate(t, p, d) } func TestPageWithFrontMatterConfig(t *testing.T) { for _, dateHandler := range []string{":filename", ":fileModTime"} { t.Run(fmt.Sprintf("dateHandler=%q", dateHandler), func(t *testing.T) { t.Parallel() pageTemplate := ` --- title: Page weight: %d lastMod: 2018-02-28 %s --- Content ` files := ` -- hugo.toml -- baseURL = "http://example.com/" [frontmatter] date = ["` + dateHandler + `", "date"] -- content/section/2012-02-21-noslug.md -- ` + fmt.Sprintf(pageTemplate, 1, "") + ` -- content/section/2012-02-22-slug.md -- ` + fmt.Sprintf(pageTemplate, 2, "slug: aslug") + ` ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, // Needed for fileModTime }, ).Build() s := b.H.Sites[0] b.Assert(len(s.RegularPages()), qt.Equals, 2) noSlug := s.RegularPages()[0] slug := s.RegularPages()[1] b.Assert(noSlug.Lastmod().Day(), qt.Equals, 28) switch strings.ToLower(dateHandler) { case ":filename": b.Assert(noSlug.Date().IsZero(), qt.Equals, false) b.Assert(slug.Date().IsZero(), qt.Equals, false) b.Assert(noSlug.Date().Year(), qt.Equals, 2012) b.Assert(slug.Date().Year(), qt.Equals, 2012) b.Assert(noSlug.Slug(), qt.Equals, "noslug") b.Assert(slug.Slug(), qt.Equals, "aslug") case ":filemodtime": // For fileModTime, we need to get the actual file mod time. // The IntegrationTestBuilder creates a temporary directory. // We need to get the path to the created files. // The `b.Fs` field gives access to the file system. c1Path := filepath.Join(b.Cfg.WorkingDir, "content", "section", "2012-02-21-noslug.md") c2Path := filepath.Join(b.Cfg.WorkingDir, "content", "section", "2012-02-22-slug.md") c1fi, err := b.fs.Source.Stat(c1Path) b.Assert(err, qt.IsNil)
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/content_map_page_contentnodeshifter.go
hugolib/content_map_page_contentnodeshifter.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/resources/resource" ) type contentNodeShifter struct { conf config.AllProvider // Used for logging/debugging. } func (s *contentNodeShifter) Delete(n contentNode, vec sitesmatrix.Vector) (contentNode, bool, bool) { switch v := n.(type) { case contentNodesMap: deleted, wasDeleted := v[vec] if wasDeleted { delete(v, vec) resource.MarkStale(deleted) } return deleted, wasDeleted, len(v) == 0 case contentNodeForSite: if v.siteVector() != vec { return nil, false, false } resource.MarkStale(v) return v, true, true default: v = v.(contentNodeSingle) // Ensure single node. resource.MarkStale(v) return v, true, true } } func (s *contentNodeShifter) DeleteFunc(v contentNode, f func(n contentNode) bool) bool { switch ss := v.(type) { case contentNodeSingle: if f(ss) { resource.MarkStale(ss) return true } return false case contentNodes: for i, n := range ss { if f(n) { resource.MarkStale(n) ss = append(ss[:i], ss[i+1:]...) } } return len(ss) == 0 case contentNodesMap: for k, n := range ss { if f(n) { resource.MarkStale(n) delete(ss, k) } } return len(ss) == 0 default: panic(fmt.Sprintf("DeleteFunc: unknown type %T", v)) } } func (s *contentNodeShifter) ForEeachInAllDimensions(n contentNode, f func(contentNode) bool) { if n == nil { return } if v, ok := n.(interface { // Implemented by all the list nodes. ForEeachInAllDimensions(f func(contentNode) bool) }); ok { v.ForEeachInAllDimensions(f) return } f(n) } func (s *contentNodeShifter) ForEeachInDimension(n contentNode, vec sitesmatrix.Vector, d int, f func(contentNode) bool) { LOOP1: for vec2, v := range contentNodeToSeq2(n) { for i, v := range vec2 { if i != d && v != vec[i] { continue LOOP1 } } if !f(v) { return } } } func (s *contentNodeShifter) Insert(old, new contentNode) (contentNode, contentNode, bool) { new = new.(contentNodeSingle) // Ensure single node. switch vv := old.(type) { case contentNodeSingle: return contentNodes{vv, new}, old, false case contentNodes: s := make(contentNodes, 0, len(vv)+1) s = append(s, vv...) s = append(s, new) return s, old, false case contentNodesMap: switch new := new.(type) { case contentNodeForSite: oldp := vv[new.siteVector()] updated := oldp != new if updated { resource.MarkStale(oldp) } vv[new.siteVector()] = new return vv, oldp, updated default: s := make(contentNodes, 0, len(vv)+1) for _, v := range vv { s = append(s, v) } s = append(s, new) return s, vv, false } default: panic(fmt.Sprintf("Insert: unknown type %T", old)) } } func (s *contentNodeShifter) Shift(n contentNode, siteVector sitesmatrix.Vector, fallback bool) (contentNode, bool) { switch v := n.(type) { case contentNodeLookupContentNode: if vv := v.lookupContentNode(siteVector); vv != nil { return vv, true } default: panic(fmt.Sprintf("Shift: unknown type %T for %q", n, n.Path())) } if !fallback { // Done return nil, false } if vvv := cnh.findContentNodeForSiteVector(siteVector, fallback, contentNodeToSeq(n)); vvv != nil { return vvv, true } return nil, false }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/content_factory.go
hugolib/content_factory.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "fmt" "io" "path/filepath" "strings" "time" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/source" "github.com/gohugoio/hugo/resources/page" "github.com/spf13/afero" ) // ContentFactory creates content files from archetype templates. type ContentFactory struct { h *HugoSites // We parse the archetype templates as Go templates, so we need // to replace any shortcode with a temporary placeholder. shortcodeReplacerPre *strings.Replacer shortcodeReplacerPost *strings.Replacer } // ApplyArchetypeFilename archetypeFilename to w as a template using the given Page p as the foundation for the data context. func (f ContentFactory) ApplyArchetypeFi(w io.Writer, p page.Page, archetypeKind string, fi hugofs.FileMetaInfo) error { if fi.IsDir() { return fmt.Errorf("archetype directory (%q) not supported", fi.Meta().Filename) } templateSource, err := fi.Meta().ReadAll() if err != nil { return fmt.Errorf("failed to read archetype file %q: %s: %w", fi.Meta().Filename, err, err) } return f.ApplyArchetypeTemplate(w, p, archetypeKind, string(templateSource)) } // ApplyArchetypeTemplate templateSource to w as a template using the given Page p as the foundation for the data context. func (f ContentFactory) ApplyArchetypeTemplate(w io.Writer, p page.Page, archetypeKind, templateSource string) error { ps := p.(*pageState) if archetypeKind == "" { archetypeKind = p.Type() } d := &archetypeFileData{ Type: archetypeKind, Date: htime.Now().Format(time.RFC3339), Page: p, File: p.File(), } templateSource = f.shortcodeReplacerPre.Replace(templateSource) templ, err := ps.s.TemplateStore.TextParse("archetype.md", templateSource) if err != nil { return fmt.Errorf("failed to parse archetype template: %s: %w", err, err) } result, err := executeToString(context.Background(), ps.s.GetTemplateStore(), templ, d) if err != nil { return fmt.Errorf("failed to execute archetype template: %s: %w", err, err) } _, err = io.WriteString(w, f.shortcodeReplacerPost.Replace(result)) return err } func (f ContentFactory) SectionFromFilename(filename string) (string, error) { filename = filepath.Clean(filename) rel, _, err := f.h.AbsProjectContentDir(filename) if err != nil { return "", err } parts := strings.Split(paths.ToSlashTrimLeading(rel), "/") if len(parts) < 2 { return "", nil } return parts[0], nil } // CreateContentPlaceHolder creates a content placeholder file inside the // best matching content directory. func (f ContentFactory) CreateContentPlaceHolder(filename string, force bool) (string, error) { filename = filepath.Clean(filename) _, abs, err := f.h.AbsProjectContentDir(filename) if err != nil { return "", err } // This will be overwritten later, just write a placeholder to get // the paths correct. placeholder := `--- title: "Content Placeholder" build: render: never list: never publishResources: false --- ` if force { return abs, afero.WriteReader(f.h.Fs.Source, abs, strings.NewReader(placeholder)) } return abs, afero.SafeWriteReader(f.h.Fs.Source, abs, strings.NewReader(placeholder)) } // NewContentFactory creates a new ContentFactory for h. func NewContentFactory(h *HugoSites) ContentFactory { return ContentFactory{ h: h, shortcodeReplacerPre: strings.NewReplacer( "{{<", "{x{<", "{{%", "{x{%", ">}}", ">}x}", "%}}", "%}x}"), shortcodeReplacerPost: strings.NewReplacer( "{x{<", "{{<", "{x{%", "{{%", ">}x}", ">}}", "%}x}", "%}}"), } } // archetypeFileData represents the data available to an archetype template. type archetypeFileData struct { // The archetype content type, either given as --kind option or extracted // from the target path's section, i.e. "blog/mypost.md" will resolve to // "blog". Type string // The current date and time as a RFC3339 formatted string, suitable for use in front matter. Date string // The temporary page. Note that only the file path information is relevant at this stage. Page page.Page // File is the same as Page.File, embedded here for historic reasons. // TODO(bep) make this a method. *source.File } func (f *archetypeFileData) Site() page.Site { return f.Page.Site() } func (f *archetypeFileData) Name() string { return f.Page.File().ContentBaseName() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/embedded_templates_test.go
hugolib/embedded_templates_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) func TestInternalTemplatesImage(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org" [params] images=["siteimg1.jpg", "siteimg2.jpg"] -- content/mybundle/index.md -- --- title: My Bundle date: 2021-02-26T18:02:00-01:00 lastmod: 2021-05-22T19:25:00-01:00 --- -- content/mypage/index.md -- --- title: My Page images: ["pageimg1.jpg", "pageimg2.jpg", "https://example.local/logo.png", "sample.jpg"] date: 2021-02-26T18:02:00+01:00 lastmod: 2021-05-22T19:25:00+01:00 --- -- content/mysite.md -- --- title: My Site --- -- layouts/single.html -- {{ template "_internal/twitter_cards.html" . }} {{ template "_internal/opengraph.html" . }} {{ template "_internal/schema.html" . }} -- content/mybundle/featured-sunset.jpg -- /9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAD/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AAT8AAAAA//Z -- content/mypage/sample.jpg -- /9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAD/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AAT8AAAAA//Z ` b := Test(t, files) b.AssertFileContent("public/mybundle/index.html", ` <meta name="twitter:image" content="https://example.org/mybundle/featured-sunset.jpg"> <meta name="twitter:title" content="My Bundle"> <meta property="og:title" content="My Bundle"> <meta property="og:url" content="https://example.org/mybundle/"> <meta property="og:image" content="https://example.org/mybundle/featured-sunset.jpg"> <meta property="article:published_time" content="2021-02-26T18:02:00-01:00"> <meta property="article:modified_time" content="2021-05-22T19:25:00-01:00"> <meta itemprop="name" content="My Bundle"> <meta itemprop="image" content="https://example.org/mybundle/featured-sunset.jpg"> <meta itemprop="datePublished" content="2021-02-26T18:02:00-01:00"> <meta itemprop="dateModified" content="2021-05-22T19:25:00-01:00"> `) b.AssertFileContent("public/mypage/index.html", ` <meta name="twitter:image" content="https://example.org/pageimg1.jpg"> <meta property="og:image" content="https://example.org/pageimg1.jpg"> <meta property="og:image" content="https://example.org/pageimg2.jpg"> <meta property="og:image" content="https://example.local/logo.png"> <meta property="og:image" content="https://example.org/mypage/sample.jpg"> <meta property="article:published_time" content="2021-02-26T18:02:00+01:00"> <meta property="article:modified_time" content="2021-05-22T19:25:00+01:00"> <meta itemprop="image" content="https://example.org/pageimg1.jpg"> <meta itemprop="image" content="https://example.org/pageimg2.jpg"> <meta itemprop="image" content="https://example.local/logo.png"> <meta itemprop="image" content="https://example.org/mypage/sample.jpg"> <meta itemprop="datePublished" content="2021-02-26T18:02:00+01:00"> <meta itemprop="dateModified" content="2021-05-22T19:25:00+01:00"> `) b.AssertFileContent("public/mysite/index.html", ` <meta name="twitter:image" content="https://example.org/siteimg1.jpg"> <meta property="og:image" content="https://example.org/siteimg1.jpg"> <meta itemprop="image" content="https://example.org/siteimg1.jpg"> `) } func TestEmbeddedPaginationTemplate(t *testing.T) { t.Parallel() test := func(variant string, expectedOutput string) { files := ` -- hugo.toml -- pagination.pagerSize = 1 -- content/s1/p01.md -- --- title: p01 --- -- content/s1/p02.md -- --- title: p02 --- -- content/s1/p03.md -- --- title: p03 --- -- content/s1/p04.md -- --- title: p04 --- -- content/s1/p05.md -- --- title: p05 --- -- content/s1/p06.md -- --- title: p06 --- -- content/s1/p07.md -- --- title: p07 --- -- content/s1/p08.md -- --- title: p08 --- -- content/s1/p09.md -- --- title: p09 --- -- content/s1/p10.md -- --- title: p10 --- -- layouts/home.html -- {{ .Paginate (where site.RegularPages "Section" "s1") }}` + variant + ` ` b := Test(t, files) b.AssertFileContent("public/index.html", expectedOutput) } expectedOutputDefaultFormat := "Pager 1\n <ul class=\"pagination pagination-default\">\n <li class=\"page-item disabled\">\n <a aria-disabled=\"true\" aria-label=\"First\" class=\"page-link\" role=\"button\" tabindex=\"-1\"><span aria-hidden=\"true\">&laquo;&laquo;</span></a>\n </li>\n <li class=\"page-item disabled\">\n <a aria-disabled=\"true\" aria-label=\"Previous\" class=\"page-link\" role=\"button\" tabindex=\"-1\"><span aria-hidden=\"true\">&laquo;</span></a>\n </li>\n <li class=\"page-item active\">\n <a aria-current=\"page\" aria-label=\"Page 1\" class=\"page-link\" role=\"button\">1</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Page 2\" class=\"page-link\" role=\"button\">2</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/3/\" aria-label=\"Page 3\" class=\"page-link\" role=\"button\">3</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/4/\" aria-label=\"Page 4\" class=\"page-link\" role=\"button\">4</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/5/\" aria-label=\"Page 5\" class=\"page-link\" role=\"button\">5</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Next\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;</span></a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/10/\" aria-label=\"Last\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;&raquo;</span></a>\n </li>\n </ul>" expectedOutputTerseFormat := "Pager 1\n <ul class=\"pagination pagination-terse\">\n <li class=\"page-item active\">\n <a aria-current=\"page\" aria-label=\"Page 1\" class=\"page-link\" role=\"button\">1</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Page 2\" class=\"page-link\" role=\"button\">2</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/3/\" aria-label=\"Page 3\" class=\"page-link\" role=\"button\">3</a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/2/\" aria-label=\"Next\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;</span></a>\n </li>\n <li class=\"page-item\">\n <a href=\"/page/10/\" aria-label=\"Last\" class=\"page-link\" role=\"button\"><span aria-hidden=\"true\">&raquo;&raquo;</span></a>\n </li>\n </ul>" variant := `{{ template "_internal/pagination.html" . }}` test(variant, expectedOutputDefaultFormat) variant = `{{ template "_internal/pagination.html" (dict "page" .) }}` test(variant, expectedOutputDefaultFormat) variant = `{{ template "_internal/pagination.html" (dict "page" . "format" "default") }}` test(variant, expectedOutputDefaultFormat) variant = `{{ template "_internal/pagination.html" (dict "page" . "format" "terse") }}` test(variant, expectedOutputTerseFormat) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/params_test.go
hugolib/params_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" qt "github.com/frankban/quicktest" ) func TestFrontMatterParamsInItsOwnSection(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org/" -- content/_index.md -- +++ title = "Home" [[cascade]] background = 'yosemite.jpg' [cascade.params] a = "home-a" b = "home-b" [cascade._target] kind = 'page' +++ -- content/p1.md -- --- title: "P1" summary: "frontmatter.summary" params: a: "p1-a" summary: "params.summary" --- -- layouts/single.html -- Params: {{ range $k, $v := .Params }}{{ $k }}: {{ $v }}|{{ end }}$ Summary: {{ .Summary }}| ` b := Test(t, files) b.AssertFileContent("public/p1/index.html", "Params: a: p1-a|b: home-b|background: yosemite.jpg|draft: false|iscjklanguage: false|summary: params.summary|title: P1|$", "Summary: frontmatter.summary|", ) } // Issue 11970. func TestFrontMatterBuildIsHugoKeyword(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org/" -- content/p1.md -- --- title: "P1" build: "foo" --- -- layouts/single.html -- Params: {{ range $k, $v := .Params }}{{ $k }}: {{ $v }}|{{ end }}$ ` b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "We renamed the _build keyword") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/resource_chain_test.go
hugolib/resource_chain_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "encoding/base64" "io" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" ) func TestResourceChainBasic(t *testing.T) { failIfHandler := func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/fail.jpg" { http.Error(w, "{ msg: failed }", http.StatusNotImplemented) return } h.ServeHTTP(w, r) }) } ts := httptest.NewServer( failIfHandler(http.FileServer(http.Dir("testdata/"))), ) t.Cleanup(func() { ts.Close() }) files := ` -- hugo.toml -- baseURL = "http://example.com/" -- assets/images/sunset.jpg -- ` + getTestSunset(t) + ` -- layouts/home.html -- {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | fingerprint "sha512" | minify | fingerprint }} {{ $cssFingerprinted1 := "body { background-color: lightblue; }" | resources.FromString "styles.css" | minify | fingerprint }} {{ $cssFingerprinted2 := "body { background-color: orange; }" | resources.FromString "styles2.css" | minify | fingerprint }} HELLO: {{ $hello.Name }}|{{ $hello.RelPermalink }}|{{ $hello.Content | safeHTML }} {{ $img := resources.Get "images/sunset.jpg" }} {{ $fit := $img.Fit "200x200" }} {{ $fit2 := $fit.Fit "100x200" }} {{ $img = $img | fingerprint }} SUNSET: {{ $img.Name }}|{{ $img.RelPermalink }}|{{ $img.Width }}|{{ len $img.Content }} FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }} CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }} CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }} {{ $failedImg := try (resources.GetRemote "HTTPTEST_SERVER_URL/fail.jpg") }} {{ $rimg := resources.GetRemote "HTTPTEST_SERVER_URL/sunset.jpg" }} {{ $remotenotfound := resources.GetRemote "HTTPTEST_SERVER_URL/notfound.jpg" }} {{ $localnotfound := resources.Get "images/notfound.jpg" }} {{ $gopherprotocol := try (resources.GetRemote "gopher://example.org") }} {{ $rfit := $rimg.Fit "200x200" }} {{ $rfit2 := $rfit.Fit "100x200" }} {{ $rimg = $rimg | fingerprint }} SUNSET REMOTE: {{ $rimg.Name }}|{{ $rimg.RelPermalink }}|{{ $rimg.Width }}|{{ len $rimg.Content }} FIT REMOTE: {{ $rfit.Name }}|{{ $rfit.RelPermalink }}|{{ $rfit.Width }} REMOTE NOT FOUND: {{ if $remotenotfound }}FAILED{{ else}}OK{{ end }} LOCAL NOT FOUND: {{ if $localnotfound }}FAILED{{ else}}OK{{ end }} PRINT PROTOCOL ERROR1: {{ with $gopherprotocol }}{{ .Value | safeHTML }}{{ end }} PRINT PROTOCOL ERROR2: {{ with $gopherprotocol }}{{ .Err | safeHTML }}{{ end }} PRINT PROTOCOL ERROR DETAILS: {{ with $gopherprotocol }}{{ with .Err }}Err: {{ . | safeHTML }}{{ with .Cause }}|{{ with .Data }}Body: {{ .Body }}|StatusCode: {{ .StatusCode }}{{ end }}|{{ end }}{{ end }}{{ end }} FAILED REMOTE ERROR DETAILS CONTENT: {{ with $failedImg }}{{ with .Err }}{{ with .Cause }}{{ . }}|{{ with .Data }}Body: {{ .Body }}|StatusCode: {{ .StatusCode }}|ContentLength: {{ .ContentLength }}|ContentType: {{ .ContentType }}{{ end }}{{ end }}{{ end }}{{ end }}| ` files = strings.ReplaceAll(files, "HTTPTEST_SERVER_URL", ts.URL) b := Test(t, files) b.AssertFileContent("public/index.html", "HELLO: /hello.html") b.AssertFileContent("public/index.html", "SUNSET: /images/sunset.jpg") b.AssertFileContent("public/index.html", "FIT: /images/sunset.jpg") b.AssertFileContent("public/index.html", "CSS integrity Data first:") b.AssertFileContent("public/index.html", "CSS integrity Data last:") b.AssertFileContent("public/index.html", "SUNSET REMOTE:") b.AssertFileContent("public/index.html", "FIT REMOTE:") b.AssertFileContent("public/index.html", "REMOTE NOT FOUND: OK") b.AssertFileContent("public/index.html", "LOCAL NOT FOUND: OK") b.AssertFileContent("public/index.html", "PRINT PROTOCOL ERROR DETAILS:") b.AssertFileContent("public/index.html", "FAILED REMOTE ERROR DETAILS CONTENT:") b.AssertFileContent("public/styles.min.a1df58687c3c9cc38bf26532f7b4b2f2c2b0315dcde212376959995c04f11fef.css", "body{background-color:#add8e6}") b.AssertFileContent("public//styles2.min.1cfc52986836405d37f9998a63fd6dd8608e8c410e5e3db1daaa30f78bc273ba.css", "body{background-color:orange}") } // getTestSunset reads the sunset.jpg file from testdata and returns its content as a string. // This is used to embed the image content directly into the txtar string. func getTestSunset(t testing.TB) string { t.Helper() b, err := os.ReadFile("testdata/sunset.jpg") if err != nil { t.Fatal(err) } return base64.StdEncoding.EncodeToString(b) } func TestResourceChainPostProcess(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true [minify] minifyOutput = true [minify.tdewolff] [minify.tdewolff.html] keepQuotes = false keepWhitespace = false -- content/page1.md -- --- title: Page1 --- -- content/page2.md -- --- title: Page2 --- -- layouts/single.html -- {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }} -- layouts/home.html -- Start. {{ $hello := "<h1> Hello World! </h1>" | resources.FromString "hello.html" | minify | fingerprint "md5" | resources.PostProcess }} HELLO: {{ $hello.RelPermalink }}|Integrity: {{ $hello.Data.Integrity }}|MediaType: {{ $hello.MediaType.Type }} HELLO2: Name: {{ $hello.Name }}|Content: {{ $hello.Content }}|Title: {{ $hello.Title }}|ResourceType: {{ $hello.ResourceType }} // Issue #10269 {{ $m := dict "relPermalink" $hello.RelPermalink "integrity" $hello.Data.Integrity "mediaType" $hello.MediaType.Type }} {{ $json := jsonify (dict "indent" " ") $m | resources.FromString "hello.json" -}} JSON: {{ $json.RelPermalink }} // Issue #8884 <a href="hugo.rocks">foo</a> <a href="{{ $hello.RelPermalink }}" integrity="{{ $hello.Data.Integrity}}">Hello</a> a b a b a b End. ` b := Test(t, files) b.AssertFileContent("public/index.html", `Start. HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html|Integrity: md5-otHLJPJLMip9rVIEFMUj6Q==|MediaType: text/html HELLO2: Name: /hello.html|Content: <h1>Hello World!</h1>|Title: /hello.html|ResourceType: text <a href=hugo.rocks>foo</a> <a href="/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" integrity="md5-otHLJPJLMip9rVIEFMUj6Q==">Hello</a> a b a b a b End.`) b.AssertFileContent("public/page1/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/page2/index.html", `HELLO: /hello.min.a2d1cb24f24b322a7dad520414c523e9.html`) b.AssertFileContent("public/hello.json", ` integrity": "md5-otHLJPJLMip9rVIEFMUj6Q== mediaType": "text/html relPermalink": "/hello.min.a2d1cb24f24b322a7dad520414c523e9.html" `) } func TestResourceChains(t *testing.T) { t.Parallel() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/css/styles1.css": w.Header().Set("Content-Type", "text/css") w.Write([]byte(`h1 { font-style: bold; }`)) return case "/js/script1.js": w.Write([]byte(`var x; x = 5, document.getElementById("demo").innerHTML = x * 10`)) return case "/mydata/json1.json": w.Write([]byte(`{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }`)) return case "/mydata/xml1.xml": w.Write([]byte(` <hello> <world>Hugo Rocks!</<world> </hello>`)) return case "/mydata/svg1.svg": w.Header().Set("Content-Disposition", `attachment; filename="image.svg"`) w.Write([]byte(` <svg height="100" width="100"> <path d="M1e2 1e2H3e2 2e2z"/> </svg>`)) return case "/mydata/html1.html": w.Write([]byte(` <html> <a href=#>Cool</a> </html>`)) return case "/authenticated/": w.Header().Set("Content-Type", "text/plain") if r.Header.Get("Authorization") == "Bearer abcd" { w.Write([]byte(`Welcome`)) return } http.Error(w, "Forbidden", http.StatusForbidden) return case "/post": w.Header().Set("Content-Type", "text/plain") if r.Method == http.MethodPost { body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Write(body) return } http.Error(w, "Bad request", http.StatusBadRequest) return } http.Error(w, "Not found", http.StatusNotFound) })) t.Cleanup(func() { ts.Close() }) tests := []struct { name string shouldRun func() bool files string assert func(b *IntegrationTestBuilder) }{ {"tocss", func() bool { return scss.Supports() }, ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- {{ $scss := resources.Get "scss/styles2.scss" | toCSS }} {{ $sass := resources.Get "sass/styles3.sass" | toCSS }} {{ $scssCustomTarget := resources.Get "scss/styles2.scss" | toCSS (dict "targetPath" "styles/main.css") }} {{ $scssCustomTargetString := resources.Get "scss/styles2.scss" | toCSS "styles/main.css" }} {{ $scssMin := resources.Get "scss/styles2.scss" | toCSS | minify }} {{ $scssFromTempl := ".{{ .Kind }} { color: blue; }" | resources.FromString "kindofblue.templ" | resources.ExecuteAsTemplate "kindofblue.scss" . | toCSS (dict "targetPath" "styles/templ.css") | minify }} {{ $bundle1 := slice $scssFromTempl $scssMin | resources.Concat "styles/bundle1.css" }} T1: Len Content: {{ len $scss.Content }}|RelPermalink: {{ $scss.RelPermalink }}|Permalink: {{ $scss.Permalink }}|MediaType: {{ $scss.MediaType.Type }} T2: Content: {{ $scssMin.Content }}|RelPermalink: {{ $scssMin.RelPermalink }} T3: Content: {{ len $scssCustomTarget.Content }}|RelPermalink: {{ $scssCustomTarget.RelPermalink }}|MediaType: {{ $scssCustomTarget.MediaType.Type }} T4: Content: {{ len $scssCustomTargetString.Content }}|RelPermalink: {{ $scssCustomTargetString.RelPermalink }}|MediaType: {{ $scssCustomTargetString.MediaType.Type }} T5: Content: {{ $sass.Content }}|T5 RelPermalink: {{ $sass.RelPermalink }}| T6: {{ $bundle1.Permalink }} `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", `T1: Len Content: 24|RelPermalink: /scss/styles2.css|Permalink: http://example.com/scss/styles2.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T2: Content: body{color:#333}|RelPermalink: /scss/styles2.min.css`) b.AssertFileContent("public/index.html", `T3: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T4: Content: 24|RelPermalink: /styles/main.css|MediaType: text/css`) b.AssertFileContent("public/index.html", `T5: Content: .content-navigation {`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) b.AssertFileExists("public/styles/templ.min.css", false) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) }}, {"minify", func() bool { return true }, ` -- hugo.toml -- baseURL = "http://example.com/" [minify] [minify.tdewolff] [minify.tdewolff.html] keepWhitespace = false -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }} Min CSS Remote: {{ ( resources.GetRemote "HTTPTEST_SERVER_URL/css/styles1.css" | minify ).Content }} Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }} Min JS Remote: {{ ( resources.GetRemote "HTTPTEST_SERVER_URL/js/script1.js" | minify ).Content }} Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min JSON Remote: {{ ( resources.GetRemote "HTTPTEST_SERVER_URL/mydata/json1.json" | resources.Minify ).Content | safeHTML }} Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min XML Remote: {{ ( resources.GetRemote "HTTPTEST_SERVER_URL/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }} Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG Remote: {{ ( resources.GetRemote "HTTPTEST_SERVER_URL/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }} Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }} Min HTML Remote: {{ ( resources.GetRemote "HTTPTEST_SERVER_URL/mydata/html1.html" | resources.Minify ).Content | safeHTML }} `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min CSS Remote: h1{font-style:bold}`) b.AssertFileContent("public/index.html", `Min JS: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JS Remote: var x=5;document.getElementById(&#34;demo&#34;).innerHTML=x*10`) b.AssertFileContent("public/index.html", `Min JSON: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min JSON Remote: {"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}`) b.AssertFileContent("public/index.html", `Min XML: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min XML Remote: <hello><world>Hugo Rocks!</<world></hello>`) b.AssertFileContent("public/index.html", `Min SVG: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG Remote: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min SVG again: <svg height="100" width="100"><path d="M1e2 1e2H3e2 2e2z"/></svg>`) b.AssertFileContent("public/index.html", `Min HTML: <html><a href=#>Cool</a></html>`) b.AssertFileContent("public/index.html", `Min HTML Remote: <html><a href=#>Cool</a></html>`) }}, {"remote", func() bool { return true }, ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- {{$js := resources.GetRemote "HTTPTEST_SERVER_URL/js/script1.js" }} Remote Filename: {{ $js.RelPermalink }} {{$svg := resources.GetRemote "HTTPTEST_SERVER_URL/mydata/svg1.svg" }} Remote Content-Disposition: {{ $svg.RelPermalink }} {{$auth := resources.GetRemote "HTTPTEST_SERVER_URL/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }} Remote Authorization: {{ $auth.Content }} {{$post := resources.GetRemote "HTTPTEST_SERVER_URL/post" (dict "method" "post" "body" "Request body") }} Remote POST: {{ $post.Content }} `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", `Remote Filename: /script1_`) b.AssertFileContent("public/index.html", `Remote Content-Disposition: /image_`) b.AssertFileContent("public/index.html", `Remote Authorization: Welcome`) b.AssertFileContent("public/index.html", `Remote POST: Request body`) }}, {"concat", func() bool { return true }, ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $textResources := .Resources.Match "*.txt" }} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} T1: Content: {{ $combined.Content }}|RelPermalink: {{ $combined.RelPermalink }}|Permalink: {{ $combined.Permalink }}|MediaType: {{ $combined.MediaType.Type }} {{ with $textResources }} {{ $combinedText := . | resources.Concat "bundle/concattxt.txt" }} T2: Content: {{ $combinedText.Content }}|{{ $combinedText.RelPermalink }} {{ end }} {{/* https://github.com/gohugoio/hugo/issues/5269 */}} {{ $css := "body { color: blue; }" | resources.FromString "styles.css" }} {{ $minified := resources.Get "css/styles1.css" | minify }} {{ slice $css $minified | resources.Concat "bundle/mixed.css" }} {{/* https://github.com/gohugoio/hugo/issues/5403 */}} {{ $d := "function D {} // A comment" | resources.FromString "d.js"}} {{ $e := "(function E {})" | resources.FromString "e.js"}} {{ $f := "(function F {})()" | resources.FromString "f.js"}} {{ $jsResources := .Resources.Match "*.js" }} {{ $combinedJs := slice $d $e $f | resources.Concat "bundle/concatjs.js" }} T3: Content: {{ $combinedJs.Content }}|{{ $combinedJs.RelPermalink }} `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", `T1: Content: ABC|RelPermalink: /bundle/concat.txt|Permalink: http://example.com/bundle/concat.txt|MediaType: text/plain`) b.AssertFileContent("public/bundle/concat.txt", "ABC") b.AssertFileContent("public/index.html", `T2: Content: t1t|t2t|`) b.AssertFileContent("public/bundle/concattxt.txt", "t1t|t2t|") b.AssertFileContent("public/index.html", `T3: Content: function D {} // A comment ; (function E {}) ; (function F {})()|`) b.AssertFileContent("public/bundle/concatjs.js", `function D {} // A comment ; (function E {}) ; (function F {})()`) }}, { "concat and fingerprint", func() bool { return true }, ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- {{ $a := "A" | resources.FromString "a.txt"}} {{ $b := "B" | resources.FromString "b.txt"}} {{ $c := "C" | resources.FromString "c.txt"}} {{ $combined := slice $a $b $c | resources.Concat "bundle/concat.txt" }} {{ $fingerprinted := $combined | fingerprint }} Fingerprinted: {{ $fingerprinted.RelPermalink }} `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", "Fingerprinted: /bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt") b.AssertFileContent("public/bundle/concat.b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78.txt", "ABC") }, }, {"fromstring", func() bool { return true }, ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- {{ $r := "Hugo Rocks!" | resources.FromString "rocks/hugo.txt" }} {{ $r.Content }}|{{ $r.RelPermalink }}|{{ $r.Permalink }}|{{ $r.MediaType.Type }} `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", `Hugo Rocks!|/rocks/hugo.txt|http://example.com/rocks/hugo.txt|text/plain`) b.AssertFileContent("public/rocks/hugo.txt", "Hugo Rocks!") }}, {"execute-as-template", func() bool { return true }, ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- {{ $var := "Hugo Page" }} {{ if .IsHome }} {{ $var = "Hugo Home" }} {{ end }} T1: {{ $var }} {{ $result := "{{ .Kind | upper }}" | resources.FromString "mytpl.txt" | resources.ExecuteAsTemplate "result.txt" . }} T2: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }} `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", `T2: HOME|/result.txt|text/plain`, `T1: Hugo Home`) }}, {"fingerprint", func() bool { return true }, ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- {{ $r := "ab" | resources.FromString "rocks/hugo.txt" }} {{ $result := $r | fingerprint }} {{ $result512 := $r | fingerprint "sha512" }} {{ $resultMD5 := $r | fingerprint "md5" }} T1: {{ $result.Content }}|{{ $result.RelPermalink}}|{{$result.MediaType.Type }}|{{ $result.Data.Integrity }}| T2: {{ $result512.Content }}|{{ $result512.RelPermalink}}|{{$result512.MediaType.Type }}|{{ $result512.Data.Integrity }}| T3: {{ $resultMD5.Content }}|{{ $resultMD5.RelPermalink}}|{{$resultMD5.MediaType.Type }}|{{ $resultMD5.Data.Integrity }}| {{ $r2 := "bc" | resources.FromString "rocks/hugo2.txt" | fingerprint }} {{/* https://github.com/gohugoio/hugo/issues/5296 */}} T4: {{ $r2.Data.Integrity }}| `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", `T1: ab|/rocks/hugo.fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603.txt|text/plain|sha256-&#43;44g/C5MPySMYMOb1lLzwTRymLuXe4tNWQO4UFViBgM=|`) b.AssertFileContent("public/index.html", `T2: ab|/rocks/hugo.2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d.txt|text/plain|sha512-LUCKBxfsGIFYJ4p5bGiQRDYdxv3eKNbwSXO4CJbhgjl1zb8S62P54FkTKO4jXYDptb8apqRPRhf/PK9kAOsXLQ==|`) b.AssertFileContent("public/index.html", `T3: ab|/rocks/hugo.187ef4436122d1cc2f40dc2b92f0eba0.txt|text/plain|md5-GH70Q2Ei0cwvQNwrkvDroA==|`) b.AssertFileContent("public/index.html", `T4: sha256-Hgu9bGhroFC46wP/7txk/cnYCUf86CGrvl1tyNJSxaw=|`) }}, // https://github.com/gohugoio/hugo/issues/5226 {"baseurl-path", func() bool { return true }, ` -- hugo.toml -- baseURL = "https://example.com/hugo/" -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- {{ $r1 := "ab" | resources.FromString "rocks/hugo.txt" }} T1: {{ $r1.Permalink }}|{{ $r1.RelPermalink }} `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", `T1: https://example.com/hugo/rocks/hugo.txt|/hugo/rocks/hugo.txt`) }}, // https://github.com/gohugoio/hugo/issues/4944 {"Prevent resource publish on .Content only", func() bool { return true }, ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: Home --- Home. -- content/page1.md -- --- title: Hello1 --- Hello1 -- content/page2.md -- --- title: Hello2 --- Hello2 -- content/t1.txt -- t1t| -- content/t2.txt -- t2t| -- assets/css/styles1.css -- h1 { font-style: bold; } -- assets/js/script1.js -- var x; x = 5; document.getElementById("demo").innerHTML = x * 10; -- assets/mydata/json1.json -- { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } -- assets/mydata/svg1.svg -- <svg height="100" width="100"> <path d="M 100 100 L 300 100 L 200 100 z"/> </svg> -- assets/mydata/xml1.xml -- <hello> <world>Hugo Rocks!</<world> </hello> -- assets/mydata/html1.html -- <html> <a href="#"> Cool </a > </html> -- assets/scss/styles2.scss -- $color: #333; body { color: $color; } -- assets/sass/styles3.sass -- $color: #333; .content-navigation border-color: $color -- layouts/home.html -- {{ $cssInline := "body { color: green; }" | resources.FromString "inline.css" | minify }} {{ $cssPublish1 := "body { color: blue; }" | resources.FromString "external1.css" | minify }} {{ $cssPublish2 := "body { color: orange; }" | resources.FromString "external2.css" | minify }} Inline: {{ $cssInline.Content }} Publish 1: {{ $cssPublish1.Content }} {{ $cssPublish1.RelPermalink }} Publish 2: {{ $cssPublish2.Permalink }} `, func(b *IntegrationTestBuilder) { b.AssertFileContent("public/index.html", `Inline: body{color:green}`, "Publish 1: body{color:blue} /external1.min.css", "Publish 2: http://example.com/external2.min.css", ) b.AssertFileExists("public/external2.css", false) b.AssertFileExists("public/external1.css", false) b.AssertFileExists("public/external2.min.css", true) b.AssertFileExists("public/external1.min.css", true)
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/mount_filters_test.go
hugolib/mount_filters_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) func TestMountFilters(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" [module] [[module.mounts]] source = 'content' target = 'content' excludeFiles = "/a/c/**" [[module.mounts]] source = 'static' target = 'static' [[module.mounts]] source = 'layouts' target = 'layouts' excludeFiles = "/**/foo.html" [[module.mounts]] source = 'data' target = 'data' includeFiles = "/mydata/**" [[module.mounts]] source = 'assets' target = 'assets' excludeFiles = ["/**exclude.*", "/moooo.*"] [[module.mounts]] source = 'i18n' target = 'i18n' [[module.mounts]] source = 'archetypes' target = 'archetypes' -- layouts/single.html -- Single page. -- content/a/b/p1.md -- --- title: Include --- -- content/a/c/p2.md -- --- title: Exclude --- -- data/mydata/b.toml -- b1='bval' -- data/nodata/c.toml -- c1='bval' -- layouts/_partials/foo.html -- foo -- assets/exclude.txt -- foo -- assets/js/exclude.js -- foo -- assets/js/include.js -- foo -- layouts/home.html -- Data: {{ site.Data }}:END Template: {{ templates.Exists "partials/foo.html" }}:END Resource1: {{ resources.Get "js/include.js" }}:END Resource2: {{ resources.Get "js/exclude.js" }}:END Resource3: {{ resources.Get "exclude.txt" }}:END Resources: {{ resources.Match "**.js" }} ` b := Test(t, files) b.AssertFileExists("public/a/b/p1/index.html", true) b.AssertFileExists("public/a/c/p2/index.html", false) b.AssertFileContent("public/index.html", ` Data: map[mydata:map[b:map[b1:bval]]]:END Template: false Resource1: /js/include.js:END Resource2: :END Resource3: :END Resources: [/js/include.js] `) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/prune_resources.go
hugolib/prune_resources.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib // GC requires a build first and must run on it's own. It is not thread safe. func (h *HugoSites) GC() (int, error) { return h.Deps.ResourceSpec.FileCaches.Prune() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/template_test.go
hugolib/template_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "strings" "testing" ) // https://github.com/gohugoio/hugo/issues/4895 func TestTemplateBOM(t *testing.T) { t.Parallel() bom := "\ufeff" files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/baseof.html -- ` + bom + ` Base: {{ block "main" . }}base main{{ end }} -- layouts/single.html -- ` + bom + `{{ define "main" }}Hi!?{{ end }} -- content/page.md -- --- title: "Page" --- Page Content ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/page/index.html", "Base: Hi!?") } func TestTemplateManyBaseTemplates(t *testing.T) { t.Parallel() numPages := 100 var b strings.Builder b.WriteString("-- hugo.toml --\n") b.WriteString("baseURL = \"http://example.com/\"\n") for i := range numPages { id := i + 1 b.WriteString(fmt.Sprintf("-- content/page%d.md --\n", id)) b.WriteString(fmt.Sprintf(`--- title: "Page %d" layout: "layout%d" --- Content. `, id, id)) b.WriteString(fmt.Sprintf("-- layouts/layout%d.html --\n", id)) b.WriteString(fmt.Sprintf(` {{ define "main" }}%d{{ end }} `, id)) b.WriteString(fmt.Sprintf("-- layouts/layout%d-baseof.html --\n", id)) b.WriteString(fmt.Sprintf(` Base %d: {{ block "main" . }}FOO{{ end }} `, id)) } files := b.String() builder := Test(t, files) for i := range numPages { id := i + 1 builder.AssertFileContent(fmt.Sprintf("public/page%d/index.html", id), fmt.Sprintf(`Base %d: %d`, id, id)) } } // https://github.com/gohugoio/hugo/issues/6790 func TestTemplateNoBasePlease(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/list.html -- {{ define "main" }} Bonjour {{ end }} {{ printf "list" }} -- layouts/single.html -- {{ printf "single" }} {{ define "main" }} Bonjour {{ end }} -- content/blog/p1.md -- --- title: The Page --- ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/blog/p1/index.html", `single`) b.AssertFileContent("public/blog/index.html", `list`) } // https://github.com/gohugoio/hugo/issues/6816 func TestTemplateBaseWithComment(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/baseof.html -- Base: {{ block "main" . }}{{ end }} -- layouts/home.html -- {{/* A comment */}} {{ define "main" }} Bonjour {{ end }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", `Base: Bonjour`) } func TestTemplateLookupSite(t *testing.T) { t.Run("basic", func(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/single.html -- Single: {{ .Title }} -- layouts/list.html -- List: {{ .Title }} -- content/_index.md -- --- title: Home Sweet Home --- -- content/p1.md -- --- title: P1 --- ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", `List: Home Sweet Home`) b.AssertFileContent("public/p1/index.html", `Single: P1`) }) } func TestTemplateLookupSitBaseOf(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/blog" disablePathToLower = true defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 10 [languages.fr] weight = 20 -- layouts/home.html -- {{ define "main" }}Main Home En{{ end }} -- layouts/home.fr.html -- {{ define "main" }}Main Home Fr{{ end }} -- layouts/baseof.html -- Baseof en: {{ block "main" . }}main block{{ end }} -- layouts/baseof.fr.html -- Baseof fr: {{ block "main" . }}main block{{ end }} -- layouts/mysection/baseof.html -- Baseof mysection: {{ block "main" . }}mysection block{{ end }} -- layouts/single.html -- {{ define "main" }}Main Default Single{{ end }} -- layouts/list.html -- {{ define "main" }}Main Default List{{ end }} -- content/mysection/p1.md -- --- title: My Page --- ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/en/index.html", `Baseof en: Main Home En`) b.AssertFileContent("public/fr/index.html", `Baseof fr: Main Home Fr`) b.AssertFileContent("public/en/mysection/index.html", `Baseof mysection: Main Default List`) b.AssertFileContent("public/en/mysection/p1/index.html", `Baseof mysection: Main Default Single`) } func TestTemplateFuncs(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/blog" disablePathToLower = true defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 10 [languages.fr] weight = 20 -- layouts/home.html -- Site: {{ site.Language.Lang }} / {{ .Site.Language.Lang }} / {{ site.BaseURL }} Sites: {{ site.Sites.Default.Home.Language.Lang }} Hugo: {{ hugo.Generator }} -- layouts/home.fr.html -- Site: {{ site.Language.Lang }} / {{ .Site.Language.Lang }} / {{ site.BaseURL }} Sites: {{ site.Sites.Default.Home.Language.Lang }} Hugo: {{ hugo.Generator }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/en/index.html", "Site: en / en / http://example.com/blog", "Sites: en", "Hugo: <meta name=\"generator\" content=\"Hugo") b.AssertFileContent("public/fr/index.html", "Site: fr / fr / http://example.com/blog", "Sites: en", "Hugo: <meta name=\"generator\" content=\"Hugo", ) } func TestPartialWithReturn(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/_partials/add42.tpl -- {{ $v := add . 42 }} {{ return $v }} -- layouts/_partials/dollarContext.tpl -- {{ $v := add $ 42 }} {{ return $v }} -- layouts/_partials/dict.tpl -- {{ $v := add $.adder 42 }} {{ return $v }} -- layouts/_partials/complex.tpl -- {{ return add . 42 }} -- layouts/_partials/hello.tpl -- {{ $v := printf "hello %s" . }} {{ return $v }} -- layouts/home.html -- Test Partials With Return Values: add42: 50: {{ partial "add42.tpl" 8 }} hello world: {{ partial "hello.tpl" "world" }} dollarContext: 60: {{ partial "dollarContext.tpl" 18 }} adder: 70: {{ partial "dict.tpl" (dict "adder" 28) }} complex: 80: {{ partial "complex.tpl" 38 }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` add42: 50: 50 hello world: hello world dollarContext: 60: 60 adder: 70: 70 complex: 80: 80 `) } // Issue 7528 func TestPartialWithZeroedArgs(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/home.html -- X{{ partial "retval" dict }}X X{{ partial "retval" slice }}X X{{ partial "retval" "" }}X X{{ partial "retval" false }}X X{{ partial "retval" 0 }}X {{ define "partials/retval" }} {{ return 123 }} {{ end }} -- content/p.md -- ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` X123X X123X X123X X123X X123X `) } func TestPartialCached(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/home.html -- {{ $key1 := (dict "a" "av" ) }} {{ $key2 := (dict "a" "av2" ) }} Partial cached1: {{ partialCached "p1" "input1" $key1 }} Partial cached2: {{ partialCached "p1" "input2" $key1 }} Partial cached3: {{ partialCached "p1" "input3" $key2 }} -- layouts/_partials/p1.html -- partial: {{ . }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` Partial cached1: partial: input1 Partial cached2: partial: input1 Partial cached3: partial: input3 `) } // https://github.com/gohugoio/hugo/issues/6615 func TestTemplateTruth(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/home.html -- {{ $p := index site.RegularPages 0 }} {{ $zero := $p.ExpiryDate }} {{ $notZero := time.Now }} if: Zero: {{ if $zero }}FAIL{{ else }}OK{{ end }} if: Not Zero: {{ if $notZero }}OK{{ else }}Fail{{ end }} not: Zero: {{ if not $zero }}OK{{ else }}FAIL{{ end }} not: Not Zero: {{ if not $notZero }}FAIL{{ else }}OK{{ end }} with: Zero {{ with $zero }}FAIL{{ else }}OK{{ end }} -- content/p1.md -- --- title: p1 --- ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` if: Zero: OK if: Not Zero: OK not: Zero: OK not: Not Zero: OK with: Zero OK `) } func TestTemplateGoIssues(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/home.html -- {{ $title := "a & b" }} <script type="application/ld+json">{"@type":"WebPage","headline":"{{$title}}"}</script> {{/* Action/commands newlines, from Go 1.16, see https://github.com/golang/go/issues/29770 */}} {{ $norway := dict "country" "Norway" "population" "5 millions" "language" "Norwegian" "language_code" "nb" "weather" "freezing cold" "capitol" "Oslo" "largest_city" "Oslo" "currency" "Norwegian krone" "dialing_code" "+47" }} Population in Norway is {{ $norway.population | lower | upper }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` <script type="application/ld+json">{"@type":"WebPage","headline":"a \u0026 b"}</script> Population in Norway is 5 MILLIONS `) } func TestPartialInline(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/p1.md -- -- layouts/home.html -- {{ $p1 := partial "p1" . }} {{ $p2 := partial "p2" . }} P1: {{ $p1 }} P2: {{ $p2 }} {{ define "partials/p1" }}Inline: p1{{ end }} {{ define "partials/p2" }} {{ $value := 32 }} {{ return $value }} {{ end }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` P1: Inline: p1 P2: 32`, ) } func TestPartialInlineBase(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/p1.md -- -- layouts/baseof.html -- {{ $p3 := partial "p3" . }}P3: {{ $p3 }} {{ block "main" . }}{{ end }}{{ define "partials/p3" }}Inline: p3{{ end }} -- layouts/home.html -- {{ define "main" }} {{ $p1 := partial "p1" . }} {{ $p2 := partial "p2" . }} P1: {{ $p1 }} P2: {{ $p2 }} {{ end }} {{ define "partials/p1" }}Inline: p1{{ end }} {{ define "partials/p2" }} {{ $value := 32 }} {{ return $value }} {{ end }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` P1: Inline: p1 P2: 32 P3: Inline: p3 `, ) } // https://github.com/gohugoio/hugo/issues/7478 func TestBaseWithAndWithoutDefine(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/p1.md -- --- title: P --- Content -- layouts/baseof.html -- ::Header Start:{{ block "header" . }}{{ end }}:Header End: ::{{ block "main" . }}Main{{ end }}:: -- layouts/home.html -- {{ define "header" }} Home Header {{ end }} {{ define "main" }} This is home main {{ end }} -- layouts/single.html -- {{ define "main" }} This is single main {{ end }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", ` Home Header This is home main `, ) b.AssertFileContent("public/p1/index.html", ` ::Header Start::Header End: This is single main `, ) } // Issue 9393. func TestApplyWithNamespace(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/p1.md -- -- layouts/home.html -- {{ $b := slice " a " " b " " c" }} {{ $a := apply $b "strings.Trim" "." " " }} a: {{ $a }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{}, }, ).Build() b.AssertFileContent("public/index.html", `a: [a b c]`) } // Legacy behavior for internal templates. func TestOverrideInternalTemplate(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org" -- layouts/home.html -- {{ template "_internal/google_analytics_async.html" . }} -- layouts/_internal/google_analytics_async.html -- Overridden. ` b := Test(t, files) b.AssertFileContent("public/index.html", "Overridden.") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page_unwrap.go
hugolib/page_unwrap.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/resources/page" ) // Wraps a Page. type pageWrapper interface { page() page.Page } // unwrapPage is used in equality checks and similar. func unwrapPage(in any) (page.Page, error) { switch v := in.(type) { case *pageState: return v, nil case pageWrapper: return v.page(), nil case types.Unwrapper: return unwrapPage(v.Unwrapv()) case page.Page: return v, nil case nil: return nil, nil default: return nil, fmt.Errorf("unwrapPage: %T not supported", in) } } func mustUnwrapPage(in any) page.Page { p, err := unwrapPage(in) if err != nil { panic(err) } return p }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/shortcode_page.go
hugolib/shortcode_page.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "html/template" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/resources/page" ) // A placeholder for the TableOfContents markup. This is what we pass to the Goldmark etc. renderers. var tocShortcodePlaceholder = createShortcodePlaceholder("TOC", 0, 0) // shortcodeRenderer is typically used to delay rendering of inner shortcodes // marked with placeholders in the content. type shortcodeRenderer interface { renderShortcode(context.Context) ([]byte, bool, error) renderShortcodeString(context.Context) (string, bool, error) } type shortcodeRenderFunc func(context.Context) ([]byte, bool, error) func (f shortcodeRenderFunc) renderShortcode(ctx context.Context) ([]byte, bool, error) { return f(ctx) } func (f shortcodeRenderFunc) renderShortcodeString(ctx context.Context) (string, bool, error) { b, has, err := f(ctx) return string(b), has, err } type prerenderedShortcode struct { s string hasVariants bool } func (p prerenderedShortcode) renderShortcode(context.Context) ([]byte, bool, error) { return []byte(p.s), p.hasVariants, nil } func (p prerenderedShortcode) renderShortcodeString(context.Context) (string, bool, error) { return p.s, p.hasVariants, nil } var zeroShortcode = prerenderedShortcode{} // This is sent to the shortcodes. They cannot access the content // they're a part of. It would cause an infinite regress. // // Go doesn't support virtual methods, so this careful dance is currently (I think) // the best we can do. type pageForShortcode struct { page.PageWithoutContent page.TableOfContentsProvider page.MarkupProvider page.ContentProvider // We need to replace it after we have rendered it, so provide a // temporary placeholder. toc template.HTML p *pageState } var _ types.Unwrapper = (*pageForShortcode)(nil) func newPageForShortcode(p *pageState) page.Page { return &pageForShortcode{ PageWithoutContent: p, TableOfContentsProvider: p, MarkupProvider: page.NopPage, ContentProvider: page.NopPage, toc: template.HTML(tocShortcodePlaceholder), p: p, } } // For internal use. func (p *pageForShortcode) Unwrapv() any { return p.PageWithoutContent.(page.Page) } func (p *pageForShortcode) String() string { return p.p.String() } func (p *pageForShortcode) TableOfContents(context.Context) template.HTML { return p.toc } var _ types.Unwrapper = (*pageForRenderHooks)(nil) // This is what is sent into the content render hooks (link, image). type pageForRenderHooks struct { page.PageWithoutContent page.TableOfContentsProvider page.MarkupProvider page.ContentProvider p *pageState } func newPageForRenderHook(p *pageState) page.Page { return &pageForRenderHooks{ PageWithoutContent: p, MarkupProvider: page.NopPage, ContentProvider: page.NopPage, TableOfContentsProvider: p, p: p, } } func (p *pageForRenderHooks) Unwrapv() any { return p.p } func (p *pageForRenderHooks) String() string { return p.p.String() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/content_map.go
hugolib/content_map.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "fmt" "iter" "path" "path/filepath" "strings" "unicode" "github.com/bep/logg" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugolib/pagesfromdata" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/hugofs" ) // Used to mark ambiguous keys in reverse index lookups. var ambiguousContentNode = &pageState{} var trimCutsetDotSlashSpace = func(r rune) bool { return r == '.' || r == '/' || unicode.IsSpace(r) } type contentMapConfig struct { lang string taxonomyConfig taxonomiesConfigValues taxonomyDisabled bool taxonomyTermDisabled bool pageDisabled bool isRebuild bool } type resourceSourceState int const ( resourceStateNew resourceSourceState = iota resourceStateAssigned ) type resourceSource struct { state resourceSourceState sv sitesmatrix.Vector path *paths.Path opener hugio.OpenReadSeekCloser fi hugofs.FileMetaInfo rc *pagemeta.ResourceConfig r resource.Resource } func (r *resourceSource) assignSiteVector(vec sitesmatrix.Vector) *resourceSource { if r.state == resourceStateAssigned { panic("cannot assign site vector to a resourceSource that is already assigned") } r.sv = vec r.state = resourceStateAssigned return r } func (r resourceSource) clone() *resourceSource { r.state = resourceStateNew r.r = nil return &r } func (r *resourceSource) forEeachContentNode(f func(v sitesmatrix.Vector, n contentNode) bool) bool { return f(r.sv, r) } func (r *resourceSource) nodeCategorySingle() { // Marker method. } func (r *resourceSource) String() string { var sb strings.Builder if r.fi != nil { sb.WriteString("filename: " + r.fi.Meta().Filename) sb.WriteString(fmt.Sprintf(" matrix: %v", r.fi.Meta().SitesMatrix)) sb.WriteString(fmt.Sprintf(" complements: %v", r.fi.Meta().SitesComplements)) } if r.rc != nil { sb.WriteString(fmt.Sprintf("rc matrix: %v", r.rc.SitesMatrix)) sb.WriteString(fmt.Sprintf("rc complements: %v", r.rc.SitesComplements)) } sb.WriteString(fmt.Sprintf(" sv: %v", r.sv)) return sb.String() } func (r *resourceSource) siteVector() sitesmatrix.Vector { return r.sv } func (r *resourceSource) MarkStale() { resource.MarkStale(r.r) } func (r *resourceSource) resetBuildState() { if rr, ok := r.r.(contentNodeBuildStateResetter); ok { rr.resetBuildState() } } func (r *resourceSource) GetIdentity() identity.Identity { if r.r != nil { return r.r.(identity.IdentityProvider).GetIdentity() } return r.path } func (p *resourceSource) nodeSourceEntryID() any { if p.rc != nil { return p.rc.ContentAdapterSourceEntryHash } if p.fi != nil { return p.fi.Meta().Filename } return p.path } func (p *resourceSource) lookupContentNode(v sitesmatrix.Vector) contentNode { if p.state >= resourceStateAssigned { if p.sv == v { return p } return nil } // A site has not been assigned yet. if p.rc != nil && p.rc.MatchSiteVector(v) { return p } if p.rc != nil && p.rc.SitesMatrix.LenVectors() > 0 { // Do not consider file mount matrix if the resource config has its own. return nil } if p.fi != nil && p.fi.Meta().SitesMatrix.HasVector(v) { return p } return nil } func (p *resourceSource) lookupContentNodes(siteVector sitesmatrix.Vector, fallback bool) iter.Seq[contentNodeForSite] { if siteVector == p.sv { return func(yield func(n contentNodeForSite) bool) { yield(p) } } pc := p.rc var found bool if !fallback { if pc != nil && pc.MatchSiteVector(siteVector) { found = true } else { return nil } } if !found && pc != nil { if !pc.MatchLanguageCoarse(siteVector) { return nil } if !pc.MatchVersionCoarse(siteVector) { return nil } if !pc.MatchRoleCoarse(siteVector) { return nil } } if !found && !fallback { return nil } return func(yield func(n contentNodeForSite) bool) { if !yield(p) { return } } } func (r *resourceSource) Path() string { return r.path.Base() } func (r *resourceSource) PathInfo() *paths.Path { return r.path } func (cfg contentMapConfig) getTaxonomyConfig(s string) (v viewName) { for _, n := range cfg.taxonomyConfig.views { if strings.HasPrefix(s, n.pluralTreeKey) { return n } } return } func (m *pageMap) AddFi(fi hugofs.FileMetaInfo, buildConfig *BuildCfg) (pageSourceCount uint64, resourceSourceCount uint64, addErr error) { if fi.IsDir() { return } if m == nil { panic("nil pageMap") } h := m.s.h insertResource := func(fim hugofs.FileMetaInfo) error { resourceSourceCount++ pi := fi.Meta().PathInfo key := pi.Base() tree := m.treeResources tree.Lock(true) defer tree.Unlock(true) if pi.IsContent() { pm, err := h.newPageMetaSourceFromFile(fi) if err != nil { return fmt.Errorf("failed to create page from file %q: %w", fi.Meta().Filename, err) } pm.bundled = true m.treeResources.Insert(key, pm) } else { r := func() (hugio.ReadSeekCloser, error) { return fim.Meta().Open() } // Create one dimension now, the rest later on demand. rs := &resourceSource{path: pi, opener: r, fi: fim, sv: fim.Meta().SitesMatrix.VectorSample()} m.treeResources.Insert(key, rs) } return nil } meta := fi.Meta() pi := meta.PathInfo switch pi.Type() { case paths.TypeFile, paths.TypeContentResource: m.s.Log.Trace(logg.StringFunc( func() string { return fmt.Sprintf("insert resource: %q", fi.Meta().Filename) }, )) if err := insertResource(fi); err != nil { addErr = err return } case paths.TypeContentData: pc, rc, err := m.addPagesFromGoTmplFi(fi, buildConfig) pageSourceCount += pc resourceSourceCount += rc if err != nil { addErr = err return } default: m.s.Log.Trace(logg.StringFunc( func() string { return fmt.Sprintf("insert bundle: %q", fi.Meta().Filename) }, )) pageSourceCount++ pm, err := h.newPageMetaSourceFromFile(fi) if err != nil { addErr = fmt.Errorf("failed to create page meta from file %q: %w", fi.Meta().Filename, err) return } m.treePages.InsertWithLock(pm.pathInfo.Base(), pm) } return } func (m *pageMap) addPagesFromGoTmplFi(fi hugofs.FileMetaInfo, buildConfig *BuildCfg) (pageCount uint64, resourceCount uint64, addErr error) { meta := fi.Meta() pi := meta.PathInfo m.s.Log.Trace(logg.StringFunc( func() string { return fmt.Sprintf("insert pages from data file: %q", fi.Meta().Filename) }, )) if !files.IsGoTmplExt(pi.Ext()) { addErr = fmt.Errorf("unsupported data file extension %q", pi.Ext()) return } sitesMatrix := fi.Meta().SitesMatrix s := m.s.h.resolveFirstSite(sitesMatrix) h := s.h contentAdapter := s.pageMap.treePagesFromTemplateAdapters.Get(pi.Base()) var rebuild bool if contentAdapter != nil { // Rebuild contentAdapter = contentAdapter.CloneForGoTmpl(fi) rebuild = true } else { contentAdapter = pagesfromdata.NewPagesFromTemplate( pagesfromdata.PagesFromTemplateOptions{ GoTmplFi: fi, Site: s, DepsFromSite: func(s page.Site) pagesfromdata.PagesFromTemplateDeps { ss := s.(*Site) return pagesfromdata.PagesFromTemplateDeps{ TemplateStore: ss.GetTemplateStore(), } }, DependencyManager: s.Conf.NewIdentityManager(), Watching: s.Conf.Watching(), HandlePage: func(pt *pagesfromdata.PagesFromTemplate, pe *pagemeta.PageConfigEarly) error { s := pt.Site.(*Site) if err := pe.CompileForPagesFromDataPre(pt.GoTmplFi.Meta().PathInfo.Base(), m.s.Log, s.conf.MediaTypes.Config); err != nil { return err } ps, err := s.h.newPageMetaSourceForContentAdapter(fi, s.siteVector, pe) if err != nil { return err } if ps == nil { // Disabled page. return nil } u, n, replaced := s.pageMap.treePages.InsertWithLock(ps.pathInfo.Base(), ps) if h.isRebuild() { if replaced { pt.AddChange(cnh.GetIdentity(n)) } else { pt.AddChange(cnh.GetIdentity(u)) // New content not in use anywhere. // To make sure that these gets listed in any site.RegularPages ranges or similar // we could invalidate everything, but first try to collect a sample set // from the surrounding pages. var surroundingIDs []identity.Identity ids := h.pageTrees.collectIdentitiesSurrounding(pi.Base(), 10) if len(ids) > 0 { surroundingIDs = append(surroundingIDs, ids...) } else { // No surrounding pages found, so invalidate everything. surroundingIDs = []identity.Identity{identity.GenghisKhan} } for _, id := range surroundingIDs { pt.AddChange(id) } } } return nil }, HandleResource: func(pt *pagesfromdata.PagesFromTemplate, rc *pagemeta.ResourceConfig) error { s := pt.Site.(*Site) if err := rc.Compile( pt.GoTmplFi.Meta().PathInfo.Base(), pt.GoTmplFi, s.Conf, s.conf.MediaTypes.Config, ); err != nil { return err } // Create one dimension now, the rest later on demand. rs := &resourceSource{path: rc.PathInfo, rc: rc, opener: nil, fi: pt.GoTmplFi, sv: s.siteVector} _, n, updated := s.pageMap.treeResources.InsertWithLock(rs.path.Base(), rs) if h.isRebuild() && updated { pt.AddChange(cnh.GetIdentity(n)) } return nil }, }, ) s.pageMap.treePagesFromTemplateAdapters.Insert(pi.Base(), contentAdapter) } handleBuildInfo := func(s *Site, bi pagesfromdata.BuildInfo) { resourceCount += bi.NumResourcesAdded pageCount += bi.NumPagesAdded s.handleContentAdapterChanges(bi, buildConfig) } bi, err := contentAdapter.Execute(context.Background()) if err != nil { addErr = err return } handleBuildInfo(s, bi) if !rebuild && (bi.EnableAllLanguages || bi.EnableAllDimensions) { // Clone and insert the adapter for the other sites. var iter iter.Seq[*Site] if bi.EnableAllLanguages { include := func(ss *Site) bool { return s.siteVector.Language() != ss.siteVector.Language() } iter = h.allSiteLanguages(include) } else { include := func(ss *Site) bool { return s.siteVector != ss.siteVector } iter = h.allSites(include) } for ss := range iter { clone := contentAdapter.CloneForSite(ss) // Make sure it gets executed for the first time. bi, err := clone.Execute(context.Background()) if err != nil { addErr = err return } handleBuildInfo(ss, bi) // Insert into the correct language tree so it get rebuilt on changes. ss.pageMap.treePagesFromTemplateAdapters.Insert(pi.Base(), clone) } } return } // The home page is represented with the zero string. // All other keys starts with a leading slash. No trailing slash. // Slashes are Unix-style. func cleanTreeKey(elem ...string) string { var s string if len(elem) > 0 { s = elem[0] if len(elem) > 1 { s = path.Join(elem...) } } s = strings.TrimFunc(s, trimCutsetDotSlashSpace) s = filepath.ToSlash(strings.ToLower(paths.Sanitize(s))) if s == "" || s == "/" { return "" } if s[0] != '/' { s = "/" + s } return s }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/hugo_smoke_test.go
hugolib/hugo_smoke_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "math/rand" "strings" "testing" "github.com/bep/logg" qt "github.com/frankban/quicktest" ) // The most basic build test. func TestHello(t *testing.T) { files := ` -- hugo.toml -- title = "Hello" baseURL="https://example.org" disableKinds = ["term", "taxonomy", "section", "page"] -- content/p1.md -- --- title: Page --- -- layouts/home.html -- Home: {{ .Title }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, // LogLevel: logg.LevelTrace, }, ).Build() b.Assert(b.H.Log.LoggCount(logg.LevelWarn), qt.Equals, 0) b.AssertFileContent("public/index.html", `Hello`) } func TestSmoke202509(t *testing.T) { t.Parallel() // Test variants: // Site with two languages, one with home page content and one without. // A common translated page bundle but with different dates. // A text resource in one of the languages. // Date aggregation. // A content resource in one of the languages. // Basic shortcode usage with templates in both languages. // Test Rotate the language dimension. // The same content page mounted for all languages. // RenderString with shortcode. files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages.en] title = "Site title en" weight = 200 [languages.nn] title = "Site title nn" weight = 100 [[module.mounts]] source = 'content/en' target = 'content' lang = 'en' [[module.mounts]] source = 'content/nn' target = 'content' lang = 'nn' [[module.mounts]] source = 'content/all' target = 'content' [module.mounts.sites.matrix] languages = ["**"] -- content/en/_index.md -- --- title: "Home in English" --- Home Content. -- content/en/mysection/p1/mytext.txt -- This is a text resource in English. -- content/en/mysection/p1/mypage.md -- --- title: "mypage en" --- mypage en content. -- content/en/mysection/p1/index.md -- --- title: "p1 en" date: 2023-10-01 --- Content p1 en. {{< myshortcode >}} -- content/nn/mysection/p1/index.md -- --- title: "p1 nn" date: 2024-10-01 --- Content p1 nn. {{< myshortcode >}} -- content/all/mysection/p2/index.md -- --- title: "p2 all" date: 2022-10-01 --- Content p2 all. {{< myshortcode >}} -- layouts/all.html -- All. {{ .Title }}|Lastmod: {{ .Lastmod.Format "2006-01-02" }}| Kind: {{ .Kind }}| Content: {{ .Content }}| CurrentSection: {{ .CurrentSection.PathInfo.Path }}| Parent: {{ with .Parent }}{{ .RelPermalink }}{{ end }}| Home: {{ .Site.Home.Title }}| Rotate(language): {{ range .Rotate "language" }}{{ .Lang }}|{{ .Title }}|{{ end }}| mytext.txt: {{ with .Resources.GetMatch "**.txt" }}{{ .Content }}|{{ .RelPermalink }}{{ end }}| mypage.md: {{ with .Resources.GetMatch "**.md" }}{{ .Content }}|{{ .RelPermalink }}{{ end }}| RenderString with shortcode: {{ .RenderString "{{< myshortcode >}}" }}| -- layouts/_shortcodes/myshortcode.html -- myshortcode.html -- layouts/_shortcodes/myshortcode.en.html -- myshortcode.en.html ` b := Test(t, files) b.AssertFileContent("public/en/index.html", "All. Home in English|", // from content file. "Kind: home|", "Lastmod: 2023-10-01", "RenderString with shortcode: myshortcode.en.html", "Parent: |", ) b.AssertFileContent("public/nn/index.html", "Site title nn|", // from site config. "Lastmod: 2024-10-01", "RenderString with shortcode: myshortcode.html", ) b.AssertFileContent("public/nn/mysection/p1/index.html", "p1 nn|Lastmod: 2024-10-01|\nRotate(language): nn|p1 nn|en|p1 en||", "mytext.txt: This is a text resource in English.|/en/mysection/p1/mytext.txt|", "Content p1 nn.", "mypage.md: |", "myshortcode.html", ) b.AssertFileContent("public/en/mysection/p1/index.html", "p1 en|Lastmod: 2023-10-01|\nRotate(language): nn|p1 nn|en|p1 en||", "mytext.txt: This is a text resource in English.|/en/mysection/p1/mytext.txt|", "mypage.md: <p>mypage en content.</p>", "Content p1 en.", "myshortcode.en.html", "RenderString with shortcode: myshortcode.en.html", ) b.AssertFileContent("public/nn/mysection/p2/index.html", "myshortcode.html", "RenderString with shortcode: myshortcode.html", ) b.AssertFileContent("public/en/mysection/p2/index.html", "myshortcode.en.html", "RenderString with shortcode: myshortcode.en.html", ) } func TestSmokeTaxonomies202509(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "robotsTXT"] baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [taxonomies] category = "categories" tag = "tags" [languages.en] title = "Site title en" weight = 200 [languages.nn] title = "Site title nn" weight = 100 [languages.nn.taxonomies] tag = "tags" foo = "foos" [module] [[module.mounts]] source = 'content/en' target = 'content' [module.mounts.sites.matrix] languages = 'en' [[module.mounts]] source = 'content/nn' target = 'content' [module.mounts.sites.matrix] languages = 'nn' -- content/en/p1.md -- --- title: "p1 en" date: 2023-10-01 tags: ["tag1", "tag2"] categories: ["cat1"] foos: ["foo2"] --- Content p1 en. -- content/nn/p1.md -- --- title: "p1 nn" date: 2024-10-01 tags: ["tag1", "tag3"] categories: ["cat1", "cat2"] foos: ["foo1"] --- -- layouts/all.html -- All. {{ .Title }}|{{ .Kind }}| GetTerms tags: {{ range .GetTerms "tags" }}{{ .Name }}|{{ end }}$ GetTerms categories: {{ range .GetTerms "categories" }}{{ .Name }}|{{ end }}$ GetTerms foos: {{ range .GetTerms "foos" }}{{ .Name }}|{{ end }}$ ` b := Test(t, files) b.AssertFileContent("public/en/p1/index.html", "p1 en", "GetTerms tags: tag1|tag2|$", "GetTerms categories: cat1|$", "GetTerms foos: $") b.AssertFileContent("public/nn/p1/index.html", "p1 nn", "GetTerms tags: tag1|tag3|$", "GetTerms categories: $", "GetTerms foos: foo1|$") b.AssertFileContent("public/en/tags/index.html", "All. Tags|taxonomy|") b.AssertFileContent("public/nn/tags/tag1/index.html", "All. Tag1|term|") b.AssertFileContent("public/en/tags/tag1/index.html", "All. Tag1|term|") } func TestSmokeEdits202509(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["term", "taxonomy"] disableLiveReload = true defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages.en] title = "Site title en" weight = 200 [languages.nn] title = "Site title nn" weight = 100 [module] [[module.mounts]] source = 'content/en' target = 'content' [module.mounts.sites.matrix] languages = ['en'] [[module.mounts]] source = 'content/nn' target = 'content' [module.mounts.sites.matrix] languages = ['nn'] -- content/en/p1/index.md -- --- title: "p1 en" date: 2023-10-01 --- Content p1 en. -- content/nn/p1/index.md -- --- title: "p1 nn" date: 2024-10-01 --- Content p1 nn. -- layouts/all.html -- All. {{ .Title }}|Lastmod: {{ .Lastmod.Format "2006-01-02" }}|Content: {{ .Content }}| ` b := TestRunning(t, files) // b.AssertPublishDir("sDF") b.AssertFileContent("public/en/p1/index.html", "All. p1 en|") b.AssertFileContent("public/nn/p1/index.html", "All. p1 nn|") b.EditFileReplaceAll("public/en/p1/index.html", "p1 en", "p1 en edited").Build() b.AssertFileContent("public/en/p1/index.html", "All. p1 en edited") b.EditFileReplaceAll("public/nn/p1/index.html", "p1 nn", "p1 nn|").Build() } func TestSmokeOutputFormats(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/" defaultContentLanguage = "en" disableKinds = ["term", "taxonomy", "robotsTXT", "sitemap"] [outputs] home = ["html", "rss"] section = ["html", "rss"] page = ["html"] -- content/p1.md -- --- title: Page --- Page. -- layouts/list.html -- List: {{ .Title }}|{{ .RelPermalink}}|{{ range .OutputFormats }}{{ .Name }}: {{ .RelPermalink }}|{{ end }}$ -- layouts/list.xml -- List xml: {{ .Title }}|{{ .RelPermalink}}|{{ range .OutputFormats }}{{ .Name }}: {{ .RelPermalink }}|{{ end }}$ -- layouts/single.html -- Single: {{ .Title }}|{{ .RelPermalink}}|{{ range .OutputFormats }}{{ .Name }}: {{ .RelPermalink }}|{{ end }}$ ` for range 2 { b := Test(t, files) b.AssertFileContent("public/index.html", `List: |/|html: /|rss: /index.xml|$`) b.AssertFileContent("public/index.xml", `List xml: |/|html: /|rss: /index.xml|$`) b.AssertFileContent("public/p1/index.html", `Single: Page|/p1/|html: /p1/|$`) b.AssertFileExists("public/p1/index.xml", false) } } func TestSmoke(t *testing.T) { t.Parallel() // Basic test cases. // OK translations // OK page collections // OK next, prev in section // OK GetPage // OK Pagination // OK RenderString with shortcode // OK cascade // OK site last mod, section last mod. // OK main sections // OK taxonomies // OK GetTerms // OK Resource page // OK Resource txt const files = ` -- hugo.toml -- baseURL = "https://example.com" title = "Smoke Site" rssLimit = 3 defaultContentLanguage = "en" defaultContentLanguageInSubdir = true enableRobotsTXT = true [pagination] pagerSize = 1 [taxonomies] category = 'categories' tag = 'tags' [languages] [languages.en] weight = 1 title = "In English" [languages.no] weight = 2 title = "På norsk" [params] hugo = "Rules!" [outputs] home = ["html", "json", "rss"] -- layouts/home.html -- Home: {{ .Lang}}|{{ .Kind }}|{{ .RelPermalink }}|{{ .Title }}|{{ .Content }}|Len Resources: {{ len .Resources }}|HTML Resources: {{ range .Resources }}{{ .ResourceType }}|{{ .RelPermalink }}|{{ .MediaType }} - {{ end }}| Site last mod: {{ site.Lastmod.Format "2006-02-01" }}| Home last mod: {{ .Lastmod.Format "2006-02-01" }}| Len Translations: {{ len .Translations }}| Len home.RegularPagesRecursive: {{ len .RegularPagesRecursive }}| RegularPagesRecursive: {{ range .RegularPagesRecursive }}{{ .RelPermalink }}|{{ end }}@ Len site.RegularPages: {{ len site.RegularPages }}| Len site.Pages: {{ len site.Pages }}| Len site.AllPages: {{ len site.AllPages }}| GetPage: {{ with .Site.GetPage "posts/p1" }}{{ .RelPermalink }}|{{ .Title }}{{ end }}| RenderString with shortcode: {{ .RenderString "{{% hello %}}" }}| Paginate: {{ .Paginator.PageNumber }}/{{ .Paginator.TotalPages }}| -- layouts/index.json -- Home:{{ .Lang}}|{{ .Kind }}|{{ .RelPermalink }}|{{ .Title }}|{{ .Content }}|Len Resources: {{ len .Resources }}|JSON -- layouts/list.html -- List: {{ .Lang}}|{{ .Kind }}|{{ .RelPermalink }}|{{ .Title }}|{{ .Content }}|Len Resources: {{ len .Resources }}| Resources: {{ range .Resources }}{{ .ResourceType }}|{{ .RelPermalink }}|{{ .MediaType }} - {{ end }} Pages Length: {{ len .Pages }} RegularPages Length: {{ len .RegularPages }} RegularPagesRecursive Length: {{ len .RegularPagesRecursive }} List last mod: {{ .Lastmod.Format "2006-02-01" }} Background: {{ .Params.background }}| Kind: {{ .Kind }} Type: {{ .Type }} Paginate: {{ .Paginator.PageNumber }}/{{ .Paginator.TotalPages }}| -- layouts/single.html -- Single: {{ .Lang}}|{{ .Kind }}|{{ .RelPermalink }}|{{ .Title }}|{{ .Content }}|Len Resources: {{ len .Resources }}|Background: {{ .Params.background }}| Resources: {{ range .Resources }}{{ .ResourceType }}|{{ .RelPermalink }}|{{ .MediaType }}|{{ .Params }} - {{ end }} {{ $textResource := .Resources.GetMatch "**.txt" }} {{ with $textResource }} Icon: {{ .Params.icon }}| {{ $textResourceFingerprinted := . | fingerprint }} Icon fingerprinted: {{ with $textResourceFingerprinted }}{{ .Params.icon }}|{{ .RelPermalink }}{{ end }}| {{ end }} NextInSection: {{ with .NextInSection }}{{ .RelPermalink }}|{{ .Title }}{{ end }}| PrevInSection: {{ with .PrevInSection }}{{ .RelPermalink }}|{{ .Title }}{{ end }}| GetTerms: {{ range .GetTerms "tags" }}name: {{ .Name }}, title: {{ .Title }}|{{ end }} -- layouts/_shortcodes/hello.html -- Hello. -- content/_index.md -- --- title: Home in English --- Home Content. -- content/_index.no.md -- --- title: Hjem cascade: - _target: kind: page path: /posts/** background: post.jpg - _target: kind: term background: term.jpg --- Hjem Innhold. -- content/posts/f1.txt -- posts f1 text. -- content/posts/sub/f1.txt -- posts sub f1 text. -- content/posts/p1/index.md -- +++ title = "Post 1" lastMod = "2001-01-01" tags = ["tag1"] [[resources]] src = '**' [resources.params] icon = 'enicon' +++ Content 1. -- content/posts/p1/index.no.md -- +++ title = "Post 1 no" lastMod = "2002-02-02" tags = ["tag1", "tag2"] [[resources]] src = '**' [resources.params] icon = 'noicon' +++ Content 1 no. -- content/posts/_index.md -- --- title: Posts --- -- content/posts/p1/f1.txt -- posts p1 f1 text. -- content/posts/p1/sub/ps1.md -- --- title: Post Sub 1 --- Content Sub 1. -- content/posts/p2.md -- --- title: Post 2 tags: ["tag1", "tag3"] --- Content 2. -- content/posts/p2.no.md -- --- title: Post 2 No --- Content 2 No. -- content/tags/_index.md -- --- title: Tags --- Content Tags. -- content/tags/tag1/_index.md -- --- title: Tag 1 --- Content Tag 1. ` b := NewIntegrationTestBuilder(IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, // Verbose: true, // LogLevel: logg.LevelTrace, }).Build() b.AssertFileContent("public/en/index.html", "Home: en|home|/en/|Home in English|<p>Home Content.</p>\n|HTML", "Site last mod: 2001-01-01", "Home last mod: 2001-01-01", "Translations: 1|", "Len home.RegularPagesRecursive: 2|", "Len site.RegularPages: 2|", "Len site.Pages: 8|", "Len site.AllPages: 16|", "GetPage: /en/posts/p1/|Post 1|", "RenderString with shortcode: Hello.|", "Paginate: 1/2|", ) b.AssertFileContent("public/en/page/2/index.html", "Paginate: 2/2|") b.AssertFileContent("public/no/index.html", "Home: no|home|/no/|Hjem|<p>Hjem Innhold.</p>\n|HTML", "Site last mod: 2002-02-02", "Home last mod: 2002-02-02", "Translations: 1", "GetPage: /no/posts/p1/|Post 1 no|", ) b.AssertFileContent("public/en/index.json", "Home:en|home|/en/|Home in English|<p>Home Content.</p>\n|JSON") b.AssertFileContent("public/no/index.json", "Home:no|home|/no/|Hjem|<p>Hjem Innhold.</p>\n|JSON") b.AssertFileContent("public/en/posts/p1/index.html", "Single: en|page|/en/posts/p1/|Post 1|<p>Content 1.</p>\n|Len Resources: 2|", "Resources: text|/en/posts/p1/f1.txt|text/plain|map[icon:enicon] - page||application/octet-stream|map[draft:false iscjklanguage:false title:Post Sub 1] -", "Icon: enicon", "Icon fingerprinted: enicon|/en/posts/p1/f1.e5746577af5cbfc4f34c558051b7955a9a5a795a84f1c6ab0609cb3473a924cb.txt|", "NextInSection: |\nPrevInSection: /en/posts/p2/|Post 2|", "GetTerms: name: tag1, title: Tag 1|", ) b.AssertFileContent("public/no/posts/p1/index.html", "Resources: 1", "Resources: text|/en/posts/p1/f1.txt|text/plain|map[icon:noicon] -", "Icon: noicon", "Icon fingerprinted: noicon|/en/posts/p1/f1.e5746577af5cbfc4f34c558051b7955a9a5a795a84f1c6ab0609cb3473a924cb.txt|", "Background: post.jpg", "NextInSection: |\nPrevInSection: /no/posts/p2/|Post 2 No|", ) b.AssertFileContent("public/en/posts/index.html", "List: en|section|/en/posts/|Posts||Len Resources: 2|", "Resources: text|/en/posts/f1.txt|text/plain - text|/en/posts/sub/f1.txt|text/plain -", "List last mod: 2001-01-01", ) b.AssertFileContent("public/no/posts/index.html", "List last mod: 2002-02-02", ) b.AssertFileContent("public/en/posts/p2/index.html", "Single: en|page|/en/posts/p2/|Post 2|<p>Content 2.</p>\n|", "|Len Resources: 0", "GetTerms: name: tag1, title: Tag 1|name: tag3, title: Tag3|", ) b.AssertFileContent("public/no/posts/p2/index.html", "Single: no|page|/no/posts/p2/|Post 2 No|<p>Content 2 No.</p>\n|") b.AssertFileContent("public/no/categories/index.html", "Kind: taxonomy", "Type: categories", ) b.AssertFileContent("public/no/tags/index.html", "Kind: taxonomy", "Type: tags", ) b.AssertFileContent("public/no/tags/tag1/index.html", "Background: term.jpg", "Kind: term", "Type: tags", "Paginate: 1/1|", ) b.AssertFileContent("public/en/tags/tag1/index.html", "Kind: term", "Type: tags", "Paginate: 1/2|", ) } // Basic tests that verifies that the different file systems work as expected. func TestSmokeFilesystems(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] title = "In English" [languages.nn] title = "På nynorsk" [module] [[module.mounts]] source = "i18n" target = "i18n" [[module.mounts]] source = "data" target = "data" [[module.mounts]] source = "content/en" target = "content" lang = "en" [[module.mounts]] source = "content/nn" target = "content" lang = "nn" [[module.imports]] path = "mytheme" -- layouts/home.html -- i18n s1: {{ i18n "s1" }}| i18n s2: {{ i18n "s2" }}| data s1: {{ site.Data.d1.s1 }}| data s2: {{ site.Data.d1.s2 }}| title: {{ .Title }}| -- themes/mytheme/hugo.toml -- [[module.mounts]] source = "i18n" target = "i18n" [[module.mounts]] source = "data" target = "data" # i18n files both project and theme. -- i18n/en.toml -- [s1] other = 's1project' -- i18n/nn.toml -- [s1] other = 's1prosjekt' -- themes/mytheme/i18n/en.toml -- [s1] other = 's1theme' [s2] other = 's2theme' # data files both project and theme. -- data/d1.yaml -- s1: s1project -- themes/mytheme/data/d1.yaml -- s1: s1theme s2: s2theme # Content -- content/en/_index.md -- --- title: "Home" --- -- content/nn/_index.md -- --- title: "Heim" --- ` b := Test(t, files) b.AssertFileContent("public/en/index.html", "i18n s1: s1project", "i18n s2: s2theme", "data s1: s1project", "data s2: s2theme", "title: Home", ) b.AssertFileContent("public/nn/index.html", "i18n s1: s1prosjekt", "i18n s2: s2theme", "data s1: s1project", "data s2: s2theme", "title: Heim", ) } // https://github.com/golang/go/issues/30286 func TestDataRace(t *testing.T) { var filesBuilder strings.Builder filesBuilder.WriteString(` -- hugo.toml -- baseURL = "https://example.org" defaultContentLanguage = "en" [outputs] home = ["HTML", "JSON", "CSV", "RSS"] page = ["HTML", "JSON"] [mediaTypes] [mediaTypes."application/json"] suffixes = ["json"] [mediaTypes."text/csv"] suffixes = ["csv"] [outputFormats.JSON] mediaType = "application/json" isPlainText = true isHTML = false [outputFormats.CSV] mediaType = "text/csv" isPlainText = true isHTML = false -- layouts/single.html -- HTML Single: {{ .Data.Pages }} -- layouts/list.html -- HTML List: {{ .Data.Pages }} -- content/_index.md -- --- title: "The Home" outputs: ["HTML", "JSON", "CSV", "RSS"] --- The content. `) const pageContent = ` --- title: "The Page" outputs: ["HTML", "JSON"] --- The content. ` for i := 1; i <= 50; i++ { filesBuilder.WriteString(fmt.Sprintf("\n-- content/blog/page%d.md --\n%s", i, pageContent)) } files := filesBuilder.String() _ = Test(t, files) // Assertions can be added here if needed, but the original test only builds. // The primary purpose of TestDataRace is to check for race conditions during the build process. // If the build completes without race detector errors, the test passes. } // This is just a test to verify that BenchmarkBaseline is working as intended. func TestBenchmarkBaseline(t *testing.T) { cfg := IntegrationTestConfig{ T: t, TxtarString: benchmarkBaselineFiles(true), } b := NewIntegrationTestBuilder(cfg).Build() b.Assert(len(b.H.Sites), qt.Equals, 4) b.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 161) b.Assert(len(b.H.Sites[0].Pages()), qt.Equals, 197) b.Assert(len(b.H.Sites[2].RegularPages()), qt.Equals, 158) b.Assert(len(b.H.Sites[2].Pages()), qt.Equals, 194) } func BenchmarkBaseline(b *testing.B) { cfg := IntegrationTestConfig{ T: b, TxtarString: benchmarkBaselineFiles(false), } for b.Loop() { b.StopTimer() builder := NewIntegrationTestBuilder(cfg) b.StartTimer() builder.Build() } } func benchmarkBaselineFiles(leafBundles bool) string { rnd := rand.New(rand.NewSource(32)) files := ` -- hugo.toml -- baseURL = "https://example.com" defaultContentLanguage = 'en' [module] [[module.mounts]] source = 'content/en' target = 'content/en' lang = 'en' [[module.mounts]] source = 'content/nn' target = 'content/nn' lang = 'nn' [[module.mounts]] source = 'content/no' target = 'content/no' lang = 'no' [[module.mounts]] source = 'content/sv' target = 'content/sv' lang = 'sv' [[module.mounts]] source = 'layouts' target = 'layouts' [languages] [languages.en] title = "English" weight = 1 [languages.nn] title = "Nynorsk" weight = 2 [languages.no] title = "Norsk" weight = 3 [languages.sv] title = "Svenska" weight = 4 -- layouts/list.html -- {{ .Title }} {{ .Content }} -- layouts/single.html -- {{ .Title }} {{ .Content }} -- layouts/_shortcodes/myshort.html -- {{ .Inner }} ` contentTemplate := ` --- title: "Page %d" date: "2018-01-01" weight: %d --- ## Heading 1 Duis nisi reprehenderit nisi cupidatat cillum aliquip ea id eu esse commodo et. ## Heading 2 Aliqua labore enim et sint anim amet excepteur ea dolore. {{< myshort >}} Hello, World! {{< /myshort >}} Aliqua labore enim et sint anim amet excepteur ea dolore. ` for _, lang := range []string{"en", "nn", "no", "sv"} { files += fmt.Sprintf("\n-- content/%s/_index.md --\n"+contentTemplate, lang, 1, 1, 1) for i, root := range []string{"", "foo", "bar", "baz"} { for j, section := range []string{"posts", "posts/funny", "posts/science", "posts/politics", "posts/world", "posts/technology", "posts/world/news", "posts/world/news/europe"} { n := i + j + 1 files += fmt.Sprintf("\n-- content/%s/%s/%s/_index.md --\n"+contentTemplate, lang, root, section, n, n, n) for k := 1; k < rnd.Intn(30)+1; k++ { n := n + k ns := fmt.Sprintf("%d", n) if leafBundles { ns = fmt.Sprintf("%d/index", n) } file := fmt.Sprintf("\n-- content/%s/%s/%s/p%s.md --\n"+contentTemplate, lang, root, section, ns, n, n) files += file } } } } return files }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/robotstxt_test.go
hugolib/robotstxt_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) func TestRobotsTXTOutput(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://auth/bub/" enableRobotsTXT = true -- layouts/robots.txt -- User-agent: Googlebot {{ range .Data.Pages }} Disallow: {{.RelPermalink}} {{ end }} ` b := Test(t, files) b.AssertFileContent("public/robots.txt", "User-agent: Googlebot") } func TestRobotsTXTDefaultTemplate(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://auth/bub/" enableRobotsTXT = true ` b := Test(t, files) b.AssertFileContent("public/robots.txt", "User-agent: *") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/site_url_test.go
hugolib/site_url_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) func TestSectionsEntries(t *testing.T) { files := ` -- hugo.toml -- -- content/withfile/_index.md -- -- content/withoutfile/p1.md -- -- layouts/list.html -- SectionsEntries: {{ .SectionsEntries }} ` b := Test(t, files) b.AssertFileContent("public/withfile/index.html", "SectionsEntries: [withfile]") b.AssertFileContent("public/withoutfile/index.html", "SectionsEntries: [withoutfile]") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/dates_test.go
hugolib/dates_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" ) func TestDateFormatMultilingual(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] weight=10 [languages.nn] weight=20 -- content/_index.en.md -- --- title: Page date: 2021-07-18 --- -- content/_index.nn.md -- --- title: Page date: 2021-07-18 --- -- layouts/home.html -- Date: {{ .Date | time.Format ":date_long" }} ` b := Test(t, files) b.AssertFileContent("public/en/index.html", `Date: July 18, 2021`) b.AssertFileContent("public/nn/index.html", `Date: 18. juli 2021`) } func TestTimeZones(t *testing.T) { t.Parallel() const ( pageTemplYaml = `--- title: Page date: %s lastMod: %s publishDate: %s expiryDate: %s --- ` pageTemplTOML = `+++ title="Page" date=%s lastMod=%s publishDate=%s expiryDate=%s +++ ` shortDateTempl = `%d-07-%d` longDateTempl = `%d-07-%d 15:28:01` ) createPageContent := func(pageTempl, dateTempl string, quoted bool) string { createDate := func(year, i int) string { d := fmt.Sprintf(dateTempl, year, i) if quoted { return fmt.Sprintf("%q", d) } return d } return fmt.Sprintf( pageTempl, createDate(2021, 10), createDate(2021, 11), createDate(2021, 12), createDate(2099, 13), // This test will fail in 2099 :-) ) } files := ` -- hugo.toml -- baseURL = "https://example.org" defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] timeZone="UTC" weight=10 [languages.nn] timeZone="America/Antigua" weight=20 -- layouts/single.html -- Date: {{ .Date | safeHTML }} Lastmod: {{ .Lastmod | safeHTML }} PublishDate: {{ .PublishDate | safeHTML }} ExpiryDate: {{ .ExpiryDate | safeHTML }} -- content/short-date-yaml-unqouted.en.md -- ` + createPageContent(pageTemplYaml, shortDateTempl, false) + ` -- content/short-date-yaml-unqouted.nn.md -- ` + createPageContent(pageTemplYaml, shortDateTempl, false) + ` -- content/short-date-yaml-qouted.en.md -- ` + createPageContent(pageTemplYaml, shortDateTempl, true) + ` -- content/short-date-yaml-qouted.nn.md -- ` + createPageContent(pageTemplYaml, shortDateTempl, true) + ` -- content/long-date-yaml-unqouted.en.md -- ` + createPageContent(pageTemplYaml, longDateTempl, false) + ` -- content/long-date-yaml-unqouted.nn.md -- ` + createPageContent(pageTemplYaml, longDateTempl, false) + ` -- content/short-date-toml-unqouted.en.md -- ` + createPageContent(pageTemplTOML, shortDateTempl, false) + ` -- content/short-date-toml-unqouted.nn.md -- ` + createPageContent(pageTemplTOML, shortDateTempl, false) + ` -- content/short-date-toml-qouted.en.md -- ` + createPageContent(pageTemplTOML, shortDateTempl, true) + ` -- content/short-date-toml-qouted.nn.md -- ` + createPageContent(pageTemplTOML, shortDateTempl, true) + ` ` b := Test(t, files) expectShortDateEn := ` Date: 2021-07-10 00:00:00 +0000 UTC Lastmod: 2021-07-11 00:00:00 +0000 UTC PublishDate: 2021-07-12 00:00:00 +0000 UTC ExpiryDate: 2099-07-13 00:00:00 +0000 UTC` expectShortDateNn := strings.ReplaceAll(expectShortDateEn, "+0000 UTC", "-0400 AST") expectLongDateEn := ` Date: 2021-07-10 15:28:01 +0000 UTC Lastmod: 2021-07-11 15:28:01 +0000 UTC PublishDate: 2021-07-12 15:28:01 +0000 UTC ExpiryDate: 2099-07-13 15:28:01 +0000 UTC` expectLongDateNn := strings.ReplaceAll(expectLongDateEn, "+0000 UTC", "-0400 AST") // YAML b.AssertFileContent("public/en/short-date-yaml-unqouted/index.html", expectShortDateEn) b.AssertFileContent("public/nn/short-date-yaml-unqouted/index.html", expectShortDateNn) b.AssertFileContent("public/en/short-date-yaml-qouted/index.html", expectShortDateEn) b.AssertFileContent("public/nn/short-date-yaml-qouted/index.html", expectShortDateNn) b.AssertFileContent("public/en/long-date-yaml-unqouted/index.html", expectLongDateEn) b.AssertFileContent("public/nn/long-date-yaml-unqouted/index.html", expectLongDateNn) // TOML b.AssertFileContent("public/en/short-date-toml-unqouted/index.html", expectShortDateEn) b.AssertFileContent("public/nn/short-date-toml-unqouted/index.html", expectShortDateNn) b.AssertFileContent("public/en/short-date-toml-qouted/index.html", expectShortDateEn) b.AssertFileContent("public/nn/short-date-toml-qouted/index.html", expectShortDateNn) } // Issue 8832 func TestTimeZoneInvalid(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- timeZone = "America/LosAngeles" # Should be America/Los_Angeles ` b, err := TestE(t, files) b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, `invalid timeZone for language "en": unknown time zone America/LosAngeles`) } // Issue 8835 func TestTimeOnError(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- layouts/home.html -- time: {{ time "2020-10-20" "invalid-timezone" }} -- content/p1.md -- ` b, err := TestE(t, files) b.Assert(err, qt.Not(qt.IsNil)) } func TestTOMLDates(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- timeZone = "America/Los_Angeles" -- content/_index.md -- --- date: "2020-10-20" --- -- content/p1.md -- +++ title = "TOML Date with UTC offset" date = 2021-08-16T06:00:00+00:00 +++ ## Foo -- data/mydata.toml -- date = 2020-10-20 talks = [ { date = 2017-01-23, name = "Past talk 1" }, { date = 2017-01-24, name = "Past talk 2" }, { date = 2017-01-26, name = "Past talk 3" }, { date = 2050-02-12, name = "Future talk 1" }, { date = 2050-02-13, name = "Future talk 2" }, ] -- layouts/home.html -- {{ $futureTalks := where site.Data.mydata.talks "date" ">" now }} {{ $pastTalks := where site.Data.mydata.talks "date" "<" now }} {{ $homeDate := site.Home.Date }} {{ $p1Date := (site.GetPage "p1").Date }} Future talks: {{ len $futureTalks }} Past talks: {{ len $pastTalks }} Home's Date should be greater than past: {{ gt $homeDate (index $pastTalks 0).date }} Home's Date should be less than future: {{ lt $homeDate (index $futureTalks 0).date }} Home's Date should be equal mydata date: {{ eq $homeDate site.Data.mydata.date }} Home date: {{ $homeDate }} mydata.date: {{ site.Data.mydata.date }} Full time: {{ $p1Date | time.Format ":time_full" }} ` b := Test(t, files) b.AssertFileContent("public/index.html", ` Future talks: 2 Past talks: 3 Home's Date should be greater than past: true Home's Date should be less than future: true Home's Date should be equal mydata date: true Full time: 6:00:00 am UTC `) } func TestPublisDateRollupIssue12438(t *testing.T) { t.Parallel() // To future Hugo maintainers, this test will start to fail in 2099. files := ` -- hugo.toml -- disableKinds = ['home','rss','sitemap'] [taxonomies] tag = 'tags' -- layouts/list.html -- Date: {{ .Date.Format "2006-01-02" }} PublishDate: {{ .PublishDate.Format "2006-01-02" }} Lastmod: {{ .Lastmod.Format "2006-01-02" }} -- layouts/single.html -- {{ .Title }} -- content/s1/p1.md -- --- title: p1 date: 2024-03-01 lastmod: 2024-03-02 tags: [t1] --- -- content/s1/p2.md -- --- title: p2 date: 2024-04-03 lastmod: 2024-04-04 tags: [t1] --- -- content/s1/p3.md -- --- title: p3 lastmod: 2099-05-06 tags: [t1] --- ` // Test without publishDate in front matter. b := Test(t, files) b.AssertFileContent("public/s1/index.html", ` Date: 2024-04-03 PublishDate: 2024-04-03 Lastmod: 2024-04-04 `) b.AssertFileContent("public/tags/index.html", ` Date: 2024-04-03 PublishDate: 2024-04-03 Lastmod: 2024-04-04 `) b.AssertFileContent("public/tags/t1/index.html", ` Date: 2024-04-03 PublishDate: 2024-04-03 Lastmod: 2024-04-04 `) // Test with publishDate in front matter. files = strings.ReplaceAll(files, "lastmod", "publishDate") b = Test(t, files) b.AssertFileContent("public/s1/index.html", ` Date: 2024-04-03 PublishDate: 2024-04-04 Lastmod: 2024-04-03 `) b.AssertFileContent("public/tags/index.html", ` Date: 2024-04-03 PublishDate: 2024-04-04 Lastmod: 2024-04-03 `) b.AssertFileContent("public/tags/t1/index.html", ` Date: 2024-04-03 PublishDate: 2024-04-04 Lastmod: 2024-04-03 `) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/paginator_test.go
hugolib/paginator_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "testing" qt "github.com/frankban/quicktest" ) func TestPaginator(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com/foo/" [pagination] pagerSize = 3 path = "thepage" [languages.en] weight = 1 contentDir = "content/en" [languages.nn] weight = 2 contentDir = "content/nn" ` // Manually generate content files for the txtar string for i := 0; i < 9; i++ { files += fmt.Sprintf(` -- content/en/blog/page%d.md -- --- title: Page %d --- Content. `, i, i) files += fmt.Sprintf(` -- content/nn/blog/page%d.md -- --- title: Page %d --- Content. `, i, i) } files += ` -- layouts/home.html -- {{ $pag := $.Paginator }} Total: {{ $pag.TotalPages }} First: {{ $pag.First.URL }} Page Number: {{ $pag.PageNumber }} URL: {{ $pag.URL }} {{ with $pag.Next }}Next: {{ .URL }}{{ end }} {{ with $pag.Prev }}Prev: {{ .URL }}{{ end }} {{ range $i, $e := $pag.Pagers }} {{ printf "%d: %d/%d %t" $i $pag.PageNumber .PageNumber (eq . $pag) -}} {{ end }} -- layouts/index.xml -- {{ $pag := $.Paginator }} Total: {{ $pag.TotalPages }} First: {{ $pag.First.URL }} Page Number: {{ $pag.PageNumber }} URL: {{ $pag.URL }} {{ with $pag.Next }}Next: {{ .URL }}{{ end }} {{ with $pag.Prev }}Prev: {{ .URL }}{{ end }} {{ range $i, $e := $pag.Pagers }} {{ printf "%d: %d/%d %t" $i $pag.PageNumber .PageNumber (eq . $pag) -}} {{ end }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "Page Number: 1", "0: 1/1 true") b.AssertFileContent("public/thepage/2/index.html", "Total: 3", "Page Number: 2", "URL: /foo/thepage/2/", "Next: /foo/thepage/3/", "Prev: /foo/", "1: 2/2 true", ) b.AssertFileContent("public/index.xml", "Page Number: 1", "0: 1/1 true") b.AssertFileContent("public/thepage/2/index.xml", "Page Number: 2", "1: 2/2 true") b.AssertFileContent("public/nn/index.html", "Page Number: 1", "0: 1/1 true") b.AssertFileContent("public/nn/index.xml", "Page Number: 1", "0: 1/1 true") } // Issue 6023 func TestPaginateWithSort(t *testing.T) { files := ` -- hugo.toml -- -- content/a/a.md -- -- content/z/b.md -- -- content/x/b.md -- -- content/x/a.md -- -- layouts/home.html -- Paginate: {{ range (.Paginate (sort .Site.RegularPages ".File.Filename" "desc")).Pages }}|{{ .Path }}{{ end }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "Paginate: |/z/b|/x/b|/x/a|/a/a") } // https://github.com/gohugoio/hugo/issues/6797 func TestPaginateOutputFormat(t *testing.T) { files := ` -- hugo.toml -- baseURL = "http://example.com/" -- content/_index.md -- --- title: "Home" cascade: outputs: - JSON --- ` for i := 0; i < 22; i++ { files += fmt.Sprintf(` -- content/p%d.md -- --- title: "Page" weight: %d --- `, i+1, i+1) } files += ` -- layouts/index.json -- JSON: {{ .Paginator.TotalNumberOfElements }}: {{ range .Paginator.Pages }}|{{ .RelPermalink }}{{ end }}:DONE ` b := Test(t, files) b.AssertFileContent("public/index.json", `JSON: 22 |/p1/index.json|/p2/index.json| `) // This looks odd, so are most bugs. b.AssertFileExists("public/page/1/index.json/index.html", false) b.AssertFileExists("public/page/1/index.json", false) b.AssertFileContent("public/page/2/index.json", `JSON: 22: |/p11/index.json|/p12/index.json`) } // Issue 10802 func TestPaginatorEmptyPageGroups(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/" -- content/p1.md -- -- content/p2.md -- -- layouts/home.html -- {{ $empty := site.RegularPages | complement site.RegularPages }} Len: {{ len $empty }}: Type: {{ printf "%T" $empty }} {{ $pgs := $empty.GroupByPublishDate "January 2006" }} {{ $pag := .Paginate $pgs }} Len Pag: {{ len $pag.Pages }} ` b := Test(t, files) b.AssertFileContent("public/index.html", "Len: 0", "Len Pag: 0") } func TestPaginatorNodePagesOnly(t *testing.T) { files := ` -- hugo.toml -- [pagination] pagerSize = 1 -- content/p1.md -- -- layouts/single.html -- Paginator: {{ .Paginator }} ` b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `error calling Paginator: pagination not supported for this page`) } func TestNilPointerErrorMessage(t *testing.T) { files := ` -- hugo.toml -- -- content/p1.md -- -- layouts/single.html -- Home Filename: {{ site.Home.File.Filename }} ` b, err := TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `single.html:1:22: executing "single.html" – File is nil; wrap it in if or with: {{ with site.Home.File }}{{ .Filename }}{{ end }}`) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/content_map_page.go
hugolib/content_map_page.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "fmt" "io" "path" "sort" "strconv" "strings" "sync/atomic" "github.com/bep/logg" "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/cache/dynacache" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/predicate" "github.com/gohugoio/hugo/common/rungroup" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/hugolib/doctree" "github.com/gohugoio/hugo/hugolib/pagesfromdata" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var pagePredicates = struct { KindPage predicate.PR[*pageState] KindSection predicate.PR[*pageState] KindHome predicate.PR[*pageState] KindTerm predicate.PR[*pageState] ShouldListLocal predicate.PR[*pageState] ShouldListGlobal predicate.PR[*pageState] ShouldListAny predicate.PR[*pageState] ShouldLink predicate.PR[page.Page] }{ KindPage: func(p *pageState) predicate.Match { return predicate.BoolMatch(p.Kind() == kinds.KindPage) }, KindSection: func(p *pageState) predicate.Match { return predicate.BoolMatch(p.Kind() == kinds.KindSection) }, KindHome: func(p *pageState) predicate.Match { return predicate.BoolMatch(p.Kind() == kinds.KindHome) }, KindTerm: func(p *pageState) predicate.Match { return predicate.BoolMatch(p.Kind() == kinds.KindTerm) }, ShouldListLocal: func(p *pageState) predicate.Match { return predicate.BoolMatch(p.m.shouldList(false)) }, ShouldListGlobal: func(p *pageState) predicate.Match { return predicate.BoolMatch(p.m.shouldList(true)) }, ShouldListAny: func(p *pageState) predicate.Match { return predicate.BoolMatch(p.m.shouldListAny()) }, ShouldLink: func(p page.Page) predicate.Match { return predicate.BoolMatch(!p.(*pageState).m.noLink()) }, } type pageMap struct { i int s *Site // Main storage for all pages. *pageTrees // Used for simple page lookups by name, e.g. "mypage.md" or "mypage". pageReverseIndex *contentTreeReverseIndex cachePages1 *dynacache.Partition[string, page.Pages] cachePages2 *dynacache.Partition[string, page.Pages] cacheResources *dynacache.Partition[string, resource.Resources] cacheGetTerms *dynacache.Partition[string, map[string]page.Pages] cacheContentRendered *dynacache.Partition[string, *resources.StaleValue[contentSummary]] cacheContentPlain *dynacache.Partition[string, *resources.StaleValue[contentPlainPlainWords]] contentTableOfContents *dynacache.Partition[string, *resources.StaleValue[contentTableOfContents]] contentDataFileSeenItems *maps.Cache[string, map[uint64]bool] cfg contentMapConfig } // Invoked on rebuilds. func (m *pageMap) Reset() { m.pageReverseIndex.Reset() } // pageTrees holds pages and resources in a tree structure for all sites/languages. // Each site gets its own tree set via the Shape method. type pageTrees struct { // This tree contains all Pages. // This include regular pages, sections, taxonomies and so on. // Note that all of these trees share the same key structure, // so you can take a leaf Page key and do a prefix search // with key + "/" to get all of its resources. treePages *doctree.NodeShiftTree[contentNode] // This tree contains Resources bundled in pages. treeResources *doctree.NodeShiftTree[contentNode] // All pages and resources. treePagesResources doctree.WalkableTrees[contentNode] // This tree contains all taxonomy entries, e.g "/tags/blue/page1" treeTaxonomyEntries *doctree.TreeShiftTreeSlice[*weightedContentNode] // Stores the state for _content.gotmpl files. // Mostly releveant for rebuilds. treePagesFromTemplateAdapters *doctree.TreeShiftTreeSlice[*pagesfromdata.PagesFromTemplate] // A slice of the resource trees. resourceTrees doctree.MutableTrees } // collectAndMarkStaleIdentities collects all identities from in all trees matching the given key. // We currently re-read all page/resources for all languages that share the same path, // so we mark all entries as stale (which will trigger cache invalidation), then // return the first. func (t *pageTrees) collectAndMarkStaleIdentities(p *paths.Path) []identity.Identity { key := p.Base() var ids []identity.Identity // We need only one identity sample per dimension. nCount := 0 cb := func(n contentNode) bool { if n == nil { return false } cnh.markStale(n) if nCount > 0 { return true } nCount++ cnh.toForEachIdentityProvider(n).ForEeachIdentity(func(id identity.Identity) bool { ids = append(ids, id) return false }) return false } tree := t.treePages nCount = 0 tree.ForEeachInAllDimensions(key, cb) tree = t.treeResources nCount = 0 tree.ForEeachInAllDimensions(key, cb) if p.Component() == files.ComponentFolderContent { // It may also be a bundled content resource. key := p.ForType(paths.TypeContentResource).Base() tree = t.treeResources nCount = 0 tree.ForEeachInAllDimensions(key, cb) } return ids } // collectIdentitiesSurrounding collects all identities surrounding the given key. func (t *pageTrees) collectIdentitiesSurrounding(key string, maxSamplesPerTree int) []identity.Identity { ids := t.collectIdentitiesSurroundingIn(key, maxSamplesPerTree, t.treePages) ids = append(ids, t.collectIdentitiesSurroundingIn(key, maxSamplesPerTree, t.treeResources)...) return ids } func (t *pageTrees) collectIdentitiesSurroundingIn(key string, maxSamples int, tree *doctree.NodeShiftTree[contentNode]) []identity.Identity { var ids []identity.Identity section, ok := tree.LongestPrefixRaw(path.Dir(key)) if ok { count := 0 prefix := section + "/" level := strings.Count(prefix, "/") tree.WalkPrefixRaw(prefix, func(s string, n contentNode) (radix.WalkFlag, contentNode, error) { if level != strings.Count(s, "/") { return radix.WalkContinue, nil, nil } cnh.toForEachIdentityProvider(n).ForEeachIdentity(func(id identity.Identity) bool { ids = append(ids, id) return false }) count++ if count > maxSamples { return radix.WalkStop, nil, nil } return radix.WalkContinue, nil, nil }) } return ids } func (t *pageTrees) DeletePageAndResourcesBelow(ss ...string) { t.resourceTrees.Lock(true) defer t.resourceTrees.Unlock(true) t.treePages.Lock(true) defer t.treePages.Unlock(true) for _, s := range ss { t.resourceTrees.DeletePrefix(paths.AddTrailingSlash(s)) t.treePages.Delete(s) } } func (t pageTrees) Shape(v sitesmatrix.Vector) *pageTrees { t.treePages = t.treePages.Shape(v) t.treeResources = t.treeResources.Shape(v) t.treeTaxonomyEntries = t.treeTaxonomyEntries.Shape(v) t.treePagesFromTemplateAdapters = t.treePagesFromTemplateAdapters.Shape(v) t.createMutableTrees() return &t } func (t *pageTrees) createMutableTrees() { t.treePagesResources = doctree.WalkableTrees[contentNode]{ t.treePages, t.treeResources, } t.resourceTrees = doctree.MutableTrees{ t.treeResources, } } var ( _ resource.Identifier = pageMapQueryPagesInSection{} _ resource.Identifier = pageMapQueryPagesBelowPath{} ) type pageMapQueryPagesInSection struct { pageMapQueryPagesBelowPath Recursive bool IncludeSelf bool } func (q pageMapQueryPagesInSection) Key() string { return "gagesInSection" + "/" + q.pageMapQueryPagesBelowPath.Key() + "/" + strconv.FormatBool(q.Recursive) + "/" + strconv.FormatBool(q.IncludeSelf) } // This needs to be hashable. type pageMapQueryPagesBelowPath struct { Path string // Additional identifier for this query. // Used as part of the cache key. KeyPart string // Page inclusion filter. // May be nil. Include predicate.P[*pageState] } func (q pageMapQueryPagesBelowPath) Key() string { return q.Path + "/" + q.KeyPart } // Apply fn to all pages in m matching the given predicate. // fn may return true to stop the walk. func (m *pageMap) forEachPage(include predicate.PR[*pageState], fn func(p *pageState) (bool, error)) error { if include == nil { include = func(p *pageState) predicate.Match { return predicate.True } } w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: m.treePages, LockType: doctree.LockTypeRead, Handle: func(key string, n contentNode) (radix.WalkFlag, error) { if p, ok := n.(*pageState); ok && include(p).OK() { if terminate, err := fn(p); terminate || err != nil { return radix.WalkStop, err } } return radix.WalkContinue, nil }, } return w.Walk(context.Background()) } func (m *pageMap) forEeachPageIncludingBundledPages(include predicate.PR[*pageState], fn func(p *pageState) (bool, error)) error { if include == nil { include = func(p *pageState) predicate.Match { return predicate.True } } if err := m.forEachPage(include, fn); err != nil { return err } w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: m.treeResources, LockType: doctree.LockTypeRead, Handle: func(key string, n contentNode) (radix.WalkFlag, error) { if p, ok := n.(*pageState); ok && include(p).OK() { if terminate, err := fn(p); terminate || err != nil { return radix.WalkStop, err } } return radix.WalkContinue, nil }, } return w.Walk(context.Background()) } func (m *pageMap) getOrCreatePagesFromCache( cache *dynacache.Partition[string, page.Pages], key string, create func(string) (page.Pages, error), ) (page.Pages, error) { if cache == nil { cache = m.cachePages1 } return cache.GetOrCreate(key, create) } func (m *pageMap) getPagesInSection(q pageMapQueryPagesInSection) page.Pages { cacheKey := q.Key() pages, err := m.getOrCreatePagesFromCache(nil, cacheKey, func(string) (page.Pages, error) { prefix := paths.AddTrailingSlash(q.Path) var ( pas page.Pages otherBranch string ) include := q.Include if include == nil { include = pagePredicates.ShouldListLocal.BoolFunc() } w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: m.treePages, Prefix: prefix, Fallback: true, } w.Handle = func(key string, n contentNode) (radix.WalkFlag, error) { if q.Recursive { if p, ok := n.(*pageState); ok && include(p) { pas = append(pas, p) } return radix.WalkContinue, nil } if p, ok := n.(*pageState); ok && include(p) { pas = append(pas, p) } if cnh.isBranchNode(n) { currentBranch := key + "/" if otherBranch == "" || otherBranch != currentBranch { w.SkipPrefix(currentBranch) } otherBranch = currentBranch } return radix.WalkContinue, nil } err := w.Walk(context.Background()) if err == nil { if q.IncludeSelf { if n := m.treePages.Get(q.Path); n != nil { if p, ok := n.(*pageState); ok && include(p) { pas = append(pas, p) } } } page.SortByDefault(pas) } return pas, err }) if err != nil { panic(err) } return pages } func (m *pageMap) getPagesWithTerm(q pageMapQueryPagesBelowPath) page.Pages { key := q.Key() v, err := m.cachePages1.GetOrCreate(key, func(string) (page.Pages, error) { var pas page.Pages include := q.Include if include == nil { include = pagePredicates.ShouldListLocal.BoolFunc() } err := m.treeTaxonomyEntries.WalkPrefix( doctree.LockTypeNone, paths.AddTrailingSlash(q.Path), func(s string, n *weightedContentNode) (bool, error) { p := n.n.(*pageState) if !include(p) { return false, nil } pas = append(pas, pageWithWeight0{n.weight, p}) return false, nil }, ) if err != nil { return nil, err } page.SortByDefault(pas) return pas, nil }) if err != nil { panic(err) } return v } func (m *pageMap) getTermsForPageInTaxonomy(path, taxonomy string) page.Pages { prefix := paths.AddLeadingSlash(taxonomy) termPages, err := m.cacheGetTerms.GetOrCreate(prefix, func(string) (map[string]page.Pages, error) { mm := make(map[string]page.Pages) err := m.treeTaxonomyEntries.WalkPrefix( doctree.LockTypeNone, paths.AddTrailingSlash(prefix), func(s string, n *weightedContentNode) (bool, error) { mm[n.n.Path()] = append(mm[n.n.Path()], n.term) return false, nil }, ) if err != nil { return nil, err } // Sort the terms. for _, v := range mm { page.SortByDefault(v) } return mm, nil }) if err != nil { panic(err) } return termPages[path] } func (m *pageMap) forEachResourceInPage( ps *pageState, lockType doctree.LockType, fallback bool, transform func(resourceKey string, n contentNode) (n2 contentNode, ns doctree.NodeTransformState, err error), handle func(resourceKey string, n contentNode) (bool, error), ) error { keyPage := ps.Path() if keyPage == "/" { keyPage = "" } prefix := paths.AddTrailingSlash(ps.Path()) isBranch := ps.IsNode() rwr := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: m.treeResources, Prefix: prefix, LockType: lockType, Fallback: fallback, } shouldSkipOrTerminate := func(resourceKey string) (ns doctree.NodeTransformState) { if !isBranch { return } // A resourceKey always represents a filename with extension. // A page key points to the logical path of a page, which when sourced from the filesystem // may represent a directory (bundles) or a single content file (e.g. p1.md). // So, to avoid any overlapping ambiguity, we start looking from the owning directory. s := resourceKey for { s = path.Dir(s) ownerKey, found := m.treePages.LongestPrefixRaw(s) if !found { return doctree.NodeTransformStateTerminate } if ownerKey == keyPage { break } if s != ownerKey && strings.HasPrefix(s, ownerKey) { // Keep looking continue } // Stop walking downwards, someone else owns this resource. rwr.SkipPrefix(ownerKey + "/") return doctree.NodeTransformStateSkip } return } if transform != nil { rwr.Transform = func(resourceKey string, n contentNode) (n2 contentNode, ns doctree.NodeTransformState, err error) { if ns = shouldSkipOrTerminate(resourceKey); ns >= doctree.NodeTransformStateSkip { return } return transform(resourceKey, n) } } rwr.Handle = func(resourceKey string, n contentNode) (radix.WalkFlag, error) { if transform == nil { if ns := shouldSkipOrTerminate(resourceKey); ns >= doctree.NodeTransformStateSkip { if ns == doctree.NodeTransformStateTerminate { return radix.WalkStop, nil } return radix.WalkContinue, nil } } b, err := handle(resourceKey, n) if b || err != nil { return radix.WalkStop, err } return radix.WalkContinue, nil } return rwr.Walk(context.Background()) } func (m *pageMap) getResourcesForPage(ps *pageState) (resource.Resources, error) { var res resource.Resources m.forEachResourceInPage(ps, doctree.LockTypeNone, true, nil, func(resourceKey string, n contentNode) (bool, error) { switch n := n.(type) { case *resourceSource: r := n.r if r == nil { panic(fmt.Sprintf("getResourcesForPage: resource %q for page %q has no resource, sites matrix %v/%v", resourceKey, ps.Path(), ps.siteVector(), n.sv)) } res = append(res, r) case *pageState: res = append(res, n) default: panic(fmt.Sprintf("getResourcesForPage: unknown type %T", n)) } return false, nil }) return res, nil } func (m *pageMap) getOrCreateResourcesForPage(ps *pageState) resource.Resources { keyPage := ps.Path() if keyPage == "/" { keyPage = "" } key := keyPage + "/get-resources-for-page" v, err := m.cacheResources.GetOrCreate(key, func(string) (resource.Resources, error) { res, err := m.getResourcesForPage(ps) if err != nil { return nil, err } if translationKey := ps.m.pageConfig.TranslationKey; translationKey != "" { // This this should not be a very common case. // Merge in resources from the other languages. translatedPages, _ := m.s.h.translationKeyPages.Get(translationKey) for _, tp := range translatedPages { if tp == ps { continue } tps := tp.(*pageState) // Make sure we query from the correct language root. res2, err := tps.s.pageMap.getResourcesForPage(tps) if err != nil { return nil, err } // Add if Name not already in res. for _, r := range res2 { var found bool for _, r2 := range res { if resource.NameNormalizedOrName(r2) == resource.NameNormalizedOrName(r) { found = true break } } if !found { res = append(res, r) } } } } lessFunc := func(i, j int) bool { ri, rj := res[i], res[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { // Pull pages behind other resources. return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() } sort.SliceStable(res, lessFunc) if len(ps.m.pageConfig.ResourcesMeta) > 0 { for i, r := range res { res[i] = resources.CloneWithMetadataFromMapIfNeeded(ps.m.pageConfig.ResourcesMeta, r) } sort.SliceStable(res, lessFunc) } return res, nil }) if err != nil { panic(err) } return v } var _ doctree.Transformer[contentNode] = (*contentNodeTransformerRaw)(nil) type contentNodeTransformerRaw struct{} func (t *contentNodeTransformerRaw) Append(n contentNode, ns ...contentNode) (contentNode, bool) { if n == nil { if len(ns) == 1 { return ns[0], true } var ss contentNodes = ns return ss, true } switch v := n.(type) { case contentNodes: v = append(v, ns...) return v, true default: ss := make(contentNodes, 0, 1+len(ns)) ss = append(ss, v) ss = append(ss, ns...) return ss, true } } func newPageMap(s *Site, mcache *dynacache.Cache, pageTrees *pageTrees) *pageMap { var m *pageMap vec := s.siteVector languageVersionRole := fmt.Sprintf("s%d/%d&%d", vec.Language(), vec.Version(), vec.Role()) var taxonomiesConfig taxonomiesConfig = s.conf.Taxonomies m = &pageMap{ pageTrees: pageTrees.Shape(vec), cachePages1: dynacache.GetOrCreatePartition[string, page.Pages](mcache, fmt.Sprintf("/pag1/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 10, ClearWhen: dynacache.ClearOnRebuild}), cachePages2: dynacache.GetOrCreatePartition[string, page.Pages](mcache, fmt.Sprintf("/pag2/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 10, ClearWhen: dynacache.ClearOnRebuild}), cacheGetTerms: dynacache.GetOrCreatePartition[string, map[string]page.Pages](mcache, fmt.Sprintf("/gett/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 5, ClearWhen: dynacache.ClearOnRebuild}), cacheResources: dynacache.GetOrCreatePartition[string, resource.Resources](mcache, fmt.Sprintf("/ress/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 60, ClearWhen: dynacache.ClearOnRebuild}), cacheContentRendered: dynacache.GetOrCreatePartition[string, *resources.StaleValue[contentSummary]](mcache, fmt.Sprintf("/cont/ren/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 70, ClearWhen: dynacache.ClearOnChange}), cacheContentPlain: dynacache.GetOrCreatePartition[string, *resources.StaleValue[contentPlainPlainWords]](mcache, fmt.Sprintf("/cont/pla/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 70, ClearWhen: dynacache.ClearOnChange}), contentTableOfContents: dynacache.GetOrCreatePartition[string, *resources.StaleValue[contentTableOfContents]](mcache, fmt.Sprintf("/cont/toc/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 70, ClearWhen: dynacache.ClearOnChange}), contentDataFileSeenItems: maps.NewCache[string, map[uint64]bool](), cfg: contentMapConfig{ lang: s.Lang(), taxonomyConfig: taxonomiesConfig.Values(), taxonomyDisabled: !s.conf.IsKindEnabled(kinds.KindTaxonomy), taxonomyTermDisabled: !s.conf.IsKindEnabled(kinds.KindTerm), pageDisabled: !s.conf.IsKindEnabled(kinds.KindPage), }, i: s.siteVector.Language(), s: s, } m.pageReverseIndex = newContentTreeTreverseIndex(func(get func(key any) (contentNode, bool), set func(key any, val contentNode)) { add := func(k string, n contentNode) { existing, found := get(k) if found && existing != ambiguousContentNode { set(k, ambiguousContentNode) } else if !found { set(k, n) } } w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: m.treePages, LockType: doctree.LockTypeRead, Handle: func(s string, n contentNode) (radix.WalkFlag, error) { p := n.(*pageState) if p.PathInfo() != nil { add(p.PathInfo().BaseNameNoIdentifier(), p) } return radix.WalkContinue, nil }, } if err := w.Walk(context.Background()); err != nil { panic(err) } }) return m } func newContentTreeTreverseIndex(init func(get func(key any) (contentNode, bool), set func(key any, val contentNode))) *contentTreeReverseIndex { return &contentTreeReverseIndex{ initFn: init, mm: maps.NewCache[any, contentNode](), } } type contentTreeReverseIndex struct { initFn func(get func(key any) (contentNode, bool), set func(key any, val contentNode)) mm *maps.Cache[any, contentNode] } func (c *contentTreeReverseIndex) Reset() { c.mm.Reset() } func (c *contentTreeReverseIndex) Get(key any) contentNode { v, _ := c.mm.InitAndGet(key, func(get func(key any) (contentNode, bool), set func(key any, val contentNode)) error { c.initFn(get, set) return nil }) return v } func (m *pageMap) debugPrint(prefix string, maxLevel int, w io.Writer) { noshift := false pageWalker := &doctree.NodeShiftTreeWalker[contentNode]{ NoShift: noshift, Tree: m.treePages, Prefix: prefix, WalkContext: &doctree.WalkContext[contentNode]{}, } resourceWalker := pageWalker.Extend() resourceWalker.Tree = m.treeResources pageWalker.Handle = func(keyPage string, n contentNode) (radix.WalkFlag, error) { level := strings.Count(keyPage, "/") if level > maxLevel { return radix.WalkContinue, nil } const indentStr = " " p := n.(*pageState) lenIndent := 0 info := fmt.Sprintf("%s lm: %s (%s)", keyPage, p.Lastmod().Format("2006-01-02"), p.Kind()) fmt.Fprintln(w, info) switch p.Kind() { case kinds.KindTerm: m.treeTaxonomyEntries.WalkPrefix( doctree.LockTypeNone, keyPage+"/", func(s string, n *weightedContentNode) (bool, error) { fmt.Fprint(w, strings.Repeat(indentStr, lenIndent+4)) fmt.Fprintln(w, s) return false, nil }, ) } isBranch := cnh.isBranchNode(n) resourceWalker.Prefix = keyPage + "/" resourceWalker.Handle = func(ss string, n contentNode) (radix.WalkFlag, error) { if isBranch { ownerKey, _ := pageWalker.Tree.LongestPrefix(ss, false, nil) if ownerKey != keyPage { // Stop walking downwards, someone else owns this resource. pageWalker.SkipPrefix(ownerKey + "/") return radix.WalkContinue, nil } } fmt.Fprint(w, strings.Repeat(indentStr, lenIndent+8)) fmt.Fprintln(w, ss+" (resource)") return radix.WalkContinue, nil } if err := resourceWalker.Walk(context.Background()); err != nil { return radix.WalkStop, err } return radix.WalkContinue, nil } err := pageWalker.Walk(context.Background()) if err != nil { panic(err) } } func (h *HugoSites) dynacacheGCFilenameIfNotWatchedAndDrainMatching(filename string) { cpss := h.BaseFs.ResolvePaths(filename) if len(cpss) == 0 { return } // Compile cache busters. var cacheBusters []func(string) bool for _, cps := range cpss { if cps.Watch { continue } np := hglob.NormalizePath(path.Join(cps.Component, cps.Path)) g, err := h.ResourceSpec.BuildConfig().MatchCacheBuster(h.Log, np) if err == nil && g != nil { cacheBusters = append(cacheBusters, g) } } if len(cacheBusters) == 0 { return } cacheBusterOr := func(s string) bool { for _, cb := range cacheBusters { if cb(s) { return true } } return false } h.dynacacheGCCacheBuster(cacheBusterOr) // We want to avoid that evicted items in the above is considered in the next step server change. _ = h.MemCache.DrainEvictedIdentitiesMatching(func(ki dynacache.KeyIdentity) bool { return cacheBusterOr(ki.Key.(string)) }) } func (h *HugoSites) dynacacheGCCacheBuster(cachebuster func(s string) bool) { if cachebuster == nil { return } shouldDelete := func(k, v any) bool { var b bool if s, ok := k.(string); ok { b = cachebuster(s) } return b } h.MemCache.ClearMatching(nil, shouldDelete) } func (h *HugoSites) resolveAndClearStateForIdentities( ctx context.Context, l logg.LevelLogger, cachebuster func(s string) bool, changes []identity.Identity, ) error { // Drain the cache eviction stack to start fresh. evictedStart := h.Deps.MemCache.DrainEvictedIdentities() h.Log.Debug().Log(logg.StringFunc( func() string { var sb strings.Builder for _, change := range changes { var key string if kp, ok := change.(resource.Identifier); ok { key = " " + kp.Key() } sb.WriteString(fmt.Sprintf("Direct dependencies of %q (%T%s) =>\n", change.IdentifierBase(), change, key)) seen := map[string]bool{ change.IdentifierBase(): true, } // Print the top level dependencies. identity.WalkIdentitiesDeep(change, func(level int, id identity.Identity) bool { if level > 1 { return true } if !seen[id.IdentifierBase()] { sb.WriteString(fmt.Sprintf(" %s%s\n", strings.Repeat(" ", level), id.IdentifierBase())) } seen[id.IdentifierBase()] = true return false }) } return sb.String() }), ) for _, id := range changes { if staler, ok := id.(resource.Staler); ok { var msgDetail string if p, ok := id.(*pageState); ok && p.File() != nil { msgDetail = fmt.Sprintf(" (%s)", p.File().Filename()) } h.Log.Trace(logg.StringFunc(func() string { return fmt.Sprintf("Marking stale: %s (%T)%s\n", id, id, msgDetail) })) staler.MarkStale() } } // The order matters here: // 1. Then GC the cache, which may produce changes. // 2. Then reset the page outputs, which may mark some resources as stale. if err := loggers.TimeTrackfn(func() (logg.LevelLogger, error) { ll := l.WithField("substep", "gc dynacache") predicate := func(k any, v any) bool { if cachebuster != nil { if s, ok := k.(string); ok { return cachebuster(s) } } return false } h.MemCache.ClearOnRebuild(predicate, changes...) h.Log.Trace(logg.StringFunc(func() string { var sb strings.Builder sb.WriteString("dynacache keys:\n") for _, key := range h.MemCache.Keys(nil) { sb.WriteString(fmt.Sprintf(" %s\n", key)) } return sb.String() })) return ll, nil }); err != nil { return err } // Drain the cache eviction stack. evicted := h.Deps.MemCache.DrainEvictedIdentities() if len(evicted) < 200 { for _, c := range evicted { changes = append(changes, c.Identity) } if len(evictedStart) > 0 { // In low memory situations and/or very big sites, there can be a lot of unrelated evicted items, // but there's a chance that some of them are related to the changes we are about to process, // so check. depsFinder := identity.NewFinder(identity.FinderConfig{}) var addends []identity.Identity for _, ev := range evictedStart { for _, id := range changes { if cachebuster != nil && cachebuster(ev.Key.(string)) { addends = append(addends, ev.Identity) break } if r := depsFinder.Contains(id, ev.Identity, -1); r > 0 { addends = append(addends, ev.Identity) break } } } changes = append(changes, addends...) } } else { // Mass eviction, we might as well invalidate everything. changes = []identity.Identity{identity.GenghisKhan} } // Remove duplicates seen := make(map[identity.Identity]bool) var n int for _, id := range changes { if !seen[id] { seen[id] = true changes[n] = id n++ } } changes = changes[:n] if h.pageTrees.treePagesFromTemplateAdapters.LenRaw() > 0 { if err := loggers.TimeTrackfn(func() (logg.LevelLogger, error) { ll := l.WithField("substep", "resolve content adapter change set").WithField("changes", len(changes)) checkedCount := 0 matchCount := 0 depsFinder := identity.NewFinder(identity.FinderConfig{}) h.pageTrees.treePagesFromTemplateAdapters.WalkPrefixRaw(doctree.LockTypeRead, "", func(s string, n *pagesfromdata.PagesFromTemplate) (bool, error) { for _, id := range changes { checkedCount++ if r := depsFinder.Contains(id, n.DependencyManager, 2); r > identity.FinderNotFound { n.MarkStale() matchCount++ break } } return false, nil }) ll = ll.WithField("checked", checkedCount).WithField("matches", matchCount) return ll, nil }); err != nil { return err } } if err := loggers.TimeTrackfn(func() (logg.LevelLogger, error) { // changesLeft: The IDs that the pages is dependent on. // changesRight: The IDs that the pages depend on. ll := l.WithField("substep", "resolve page output change set").WithField("changes", len(changes)) checkedCount, matchCount, err := h.resolveAndResetDependententPageOutputs(ctx, changes) ll = ll.WithField("checked", checkedCount).WithField("matches", matchCount) return ll, err }); err != nil { return err } return nil } // The left change set is the IDs that the pages is dependent on. // The right change set is the IDs that the pages depend on. func (h *HugoSites) resolveAndResetDependententPageOutputs(ctx context.Context, changes []identity.Identity) (int, int, error) { if changes == nil { return 0, 0, nil } // This can be shared (many of the same IDs are repeated). depsFinder := identity.NewFinder(identity.FinderConfig{}) h.Log.Trace(logg.StringFunc(func() string { var sb strings.Builder sb.WriteString("resolve page dependencies: ") for _, id := range changes { sb.WriteString(fmt.Sprintf(" %T: %s|", id, id.IdentifierBase())) } return sb.String() })) var ( resetCounter atomic.Int64 checkedCounter atomic.Int64 ) resetPo := func(po *pageOutput, rebuildContent bool, r identity.FinderResult) { if rebuildContent && po.pco != nil { po.pco.Reset() // Will invalidate content cache. } po.renderState = 0 if r == identity.FinderFoundOneOfMany || po.f.Name == output.HTTPStatus404HTMLFormat.Name { // Will force a re-render even in fast render mode. po.renderOnce = false } resetCounter.Add(1) h.Log.Trace(logg.StringFunc(func() string { p := po.p return fmt.Sprintf("%s Resetting page output %q for %q for output %q\n", p.s.resolveDimensionNames(), p.Kind(), p.Path(), po.f.Name) })) } // This can be a relativeley expensive operations, so we do it in parallel. g := rungroup.Run(ctx, rungroup.Config[*pageState]{ NumWorkers: h.numWorkers, Handle: func(ctx context.Context, p *pageState) error { if !p.isRenderedAny() { // This needs no reset, so no need to check it. return nil } // First check the top level dependency manager. for _, id := range changes { checkedCounter.Add(1) if r := depsFinder.Contains(id, p.dependencyManager, 2); r > identity.FinderFoundOneOfManyRepetition { for _, po := range p.pageOutputs { // Note that p.dependencyManager is used when rendering content, so reset that. resetPo(po, true, r) } // Done. return nil } } // Then do a more fine grained reset for each output format. OUTPUTS: for _, po := range p.pageOutputs { if !po.isRendered() { continue } for _, id := range changes { checkedCounter.Add(1)
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__per_output.go
hugolib/page__per_output.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "bytes" "context" "errors" "fmt" "html/template" "sync" "sync/atomic" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/tpl/tplimpl" "github.com/spf13/cast" "github.com/gohugoio/hugo/markup/converter/hooks" gc "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/gohugoio/hugo/markup/converter" bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( nopTargetPath = targetPathsHolder{} nopPagePerOutput = struct { resource.ResourceLinksProvider page.ContentProvider page.PageRenderProvider page.PaginatorProvider page.TableOfContentsProvider page.AlternativeOutputFormatsProvider targetPather }{ page.NopPage, page.NopPage, page.NopPage, page.NopPage, page.NopPage, page.NopPage, nopTargetPath, } ) func newPageContentOutput(po *pageOutput) (*pageContentOutput, error) { cp := &pageContentOutput{ po: po, renderHooks: &renderHooks{}, otherOutputs: maps.NewCache[uint64, *pageContentOutput](), } return cp, nil } type renderHooks struct { getRenderer hooks.GetRendererFunc init sync.Once } // pageContentOutput represents the Page content for a given output format. type pageContentOutput struct { po *pageOutput // Other pages involved in rendering of this page, // typically included with .RenderShortcodes. otherOutputs *maps.Cache[uint64, *pageContentOutput] contentRenderedVersion uint32 // Incremented on reset. contentRendered atomic.Bool // Set on content render. // Renders Markdown hooks. renderHooks *renderHooks } func (pco *pageContentOutput) trackDependency(idp identity.IdentityProvider) { pco.po.p.dependencyManagerOutput.AddIdentity(idp.GetIdentity()) } func (pco *pageContentOutput) Reset() { if pco == nil { return } pco.contentRenderedVersion++ pco.contentRendered.Store(false) pco.renderHooks = &renderHooks{} } func (pco *pageContentOutput) Render(ctx context.Context, layout ...string) (template.HTML, error) { if len(layout) == 0 { return "", errors.New("no layout given") } templ, found, err := pco.po.p.resolveTemplate(layout...) if err != nil { return "", pco.po.p.wrapError(err) } if !found { return "", nil } // Make sure to send the *pageState and not the *pageContentOutput to the template. res, err := executeToString(ctx, pco.po.p.s.GetTemplateStore(), templ, pco.po.p) if err != nil { return "", pco.po.p.wrapError(fmt.Errorf("failed to execute template %s: %w", templ.Name(), err)) } return template.HTML(res), nil } func (pco *pageContentOutput) Fragments(ctx context.Context) *tableofcontents.Fragments { return pco.c().Fragments(ctx) } func (pco *pageContentOutput) RenderShortcodes(ctx context.Context) (template.HTML, error) { return pco.c().RenderShortcodes(ctx) } func (pco *pageContentOutput) Markup(opts ...any) page.Markup { if len(opts) > 1 { panic("too many arguments, expected 0 or 1") } var scope string if len(opts) == 1 { scope = cast.ToString(opts[0]) } return pco.po.p.m.content.getOrCreateScope(scope, pco) } func (pco *pageContentOutput) c() page.Markup { return pco.po.p.m.content.getOrCreateScope("", pco) } func (pco *pageContentOutput) Content(ctx context.Context) (any, error) { r, err := pco.c().Render(ctx) if err != nil { return nil, err } return r.Content(ctx) } func (pco *pageContentOutput) ContentWithoutSummary(ctx context.Context) (template.HTML, error) { r, err := pco.c().Render(ctx) if err != nil { return "", err } return r.ContentWithoutSummary(ctx) } func (pco *pageContentOutput) TableOfContents(ctx context.Context) template.HTML { return pco.c().(*cachedContentScope).fragmentsHTML(ctx) } func (pco *pageContentOutput) Len(ctx context.Context) int { return pco.mustRender(ctx).Len(ctx) } func (pco *pageContentOutput) mustRender(ctx context.Context) page.Content { c, err := pco.c().Render(ctx) if err != nil { pco.fail(err) } return c } func (pco *pageContentOutput) fail(err error) { pco.po.p.s.h.FatalError(pco.po.p.wrapError(err)) } func (pco *pageContentOutput) Plain(ctx context.Context) string { return pco.mustRender(ctx).Plain(ctx) } func (pco *pageContentOutput) PlainWords(ctx context.Context) []string { return pco.mustRender(ctx).PlainWords(ctx) } func (pco *pageContentOutput) ReadingTime(ctx context.Context) int { return pco.mustRender(ctx).ReadingTime(ctx) } func (pco *pageContentOutput) WordCount(ctx context.Context) int { return pco.mustRender(ctx).WordCount(ctx) } func (pco *pageContentOutput) FuzzyWordCount(ctx context.Context) int { return pco.mustRender(ctx).FuzzyWordCount(ctx) } func (pco *pageContentOutput) Summary(ctx context.Context) template.HTML { summary, err := pco.mustRender(ctx).Summary(ctx) if err != nil { pco.fail(err) } return summary.Text } func (pco *pageContentOutput) Truncated(ctx context.Context) bool { summary, err := pco.mustRender(ctx).Summary(ctx) if err != nil { pco.fail(err) } return summary.Truncated } func (pco *pageContentOutput) RenderString(ctx context.Context, args ...any) (template.HTML, error) { return pco.c().RenderString(ctx, args...) } func (pco *pageContentOutput) initRenderHooks() error { if pco == nil { return nil } pco.renderHooks.init.Do(func() { if pco.po.p.pageOutputTemplateVariationsState.Load() == 0 { pco.po.p.pageOutputTemplateVariationsState.Store(1) } type cacheKey struct { tp hooks.RendererType id any f output.Format } renderCache := make(map[cacheKey]any) var renderCacheMu sync.Mutex resolvePosition := func(ctx any) text.Position { source := pco.po.p.m.content.mustSource() var offset int switch v := ctx.(type) { case hooks.PositionerSourceTargetProvider: offset = bytes.Index(source, v.PositionerSourceTarget()) } pos := pco.po.p.posFromInput(source, offset) if pos.LineNumber > 0 { // Move up to the code fence delimiter. // This is in line with how we report on shortcodes. pos.LineNumber = pos.LineNumber - 1 } return pos } pco.renderHooks.getRenderer = func(tp hooks.RendererType, id any) any { renderCacheMu.Lock() defer renderCacheMu.Unlock() key := cacheKey{tp: tp, id: id, f: pco.po.f} if r, ok := renderCache[key]; ok { return r } // Inherit the descriptor from the page/current output format. // This allows for fine-grained control of the template used for // rendering of e.g. links. base, layoutDescriptor := pco.po.p.GetInternalTemplateBasePathAndDescriptor() switch tp { case hooks.LinkRendererType: layoutDescriptor.Variant1 = "link" case hooks.ImageRendererType: layoutDescriptor.Variant1 = "image" case hooks.HeadingRendererType: layoutDescriptor.Variant1 = "heading" case hooks.PassthroughRendererType: layoutDescriptor.Variant1 = "passthrough" if id != nil { layoutDescriptor.Variant2 = id.(string) } case hooks.BlockquoteRendererType: layoutDescriptor.Variant1 = "blockquote" if id != nil { layoutDescriptor.Variant2 = id.(string) } case hooks.TableRendererType: layoutDescriptor.Variant1 = "table" case hooks.CodeBlockRendererType: layoutDescriptor.Variant1 = "codeblock" if id != nil { layoutDescriptor.Variant2 = id.(string) } } renderHookConfig := pco.po.p.s.conf.Markup.Goldmark.RenderHooks var ignoreEmbedded bool // For multilingual single-host sites, "auto" becomes "fallback" // earlier in the process. switch layoutDescriptor.Variant1 { case "link": ignoreEmbedded = renderHookConfig.Link.UseEmbedded == gc.RenderHookUseEmbeddedNever || renderHookConfig.Link.UseEmbedded == gc.RenderHookUseEmbeddedAuto case "image": ignoreEmbedded = renderHookConfig.Image.UseEmbedded == gc.RenderHookUseEmbeddedNever || renderHookConfig.Image.UseEmbedded == gc.RenderHookUseEmbeddedAuto } candidates := pco.po.p.s.renderFormats var numCandidatesFound int consider := func(candidate *tplimpl.TemplInfo) bool { if layoutDescriptor.Variant1 != candidate.D.Variant1 { return false } if layoutDescriptor.Variant2 != "" && candidate.D.Variant2 != "" && layoutDescriptor.Variant2 != candidate.D.Variant2 { return false } if ignoreEmbedded && candidate.SubCategory() == tplimpl.SubCategoryEmbedded { // Don't consider the embedded hook templates. return false } if pco.po.p.pageOutputTemplateVariationsState.Load() > 1 { return true } if candidate.D.OutputFormat == "" { numCandidatesFound++ } else if _, found := candidates.GetByName(candidate.D.OutputFormat); found { numCandidatesFound++ } return true } getHookTemplate := func() (*tplimpl.TemplInfo, bool) { q := tplimpl.TemplateQuery{ Path: base, Category: tplimpl.CategoryMarkup, Desc: layoutDescriptor, Sites: pco.po.p.s.siteVector, Consider: consider, } v := pco.po.p.s.TemplateStore.LookupPagesLayout(q) return v, v != nil } templ, found1 := getHookTemplate() if found1 && templ == nil { panic("found1 is true, but templ is nil") } if !found1 && layoutDescriptor.OutputFormat == pco.po.p.s.conf.DefaultOutputFormat { numCandidatesFound++ } if numCandidatesFound > 1 { // More than one output format candidate found for this hook temoplate, // so we cannot reuse the same rendered content. pco.po.p.incrPageOutputTemplateVariation() } if !found1 { if tp == hooks.CodeBlockRendererType { // No user provided template for code blocks, so we use the native Go version -- which is also faster. r := pco.po.p.s.ContentSpec.Converters.GetHighlighter() renderCache[key] = r return r } return nil } r := hookRendererTemplate{ templateHandler: pco.po.p.s.GetTemplateStore(), templ: templ, resolvePosition: resolvePosition, } renderCache[key] = r return r } }) return nil } func (pco *pageContentOutput) getContentConverter() (converter.Converter, error) { if err := pco.initRenderHooks(); err != nil { return nil, err } return pco.po.p.getContentConverter(), nil } func (cp *pageContentOutput) ParseAndRenderContent(ctx context.Context, content []byte, renderTOC bool) (converter.ResultRender, error) { c, err := cp.getContentConverter() if err != nil { return nil, err } return cp.renderContentWithConverter(ctx, c, content, renderTOC) } func (pco *pageContentOutput) ParseContent(ctx context.Context, content []byte) (converter.ResultParse, bool, error) { c, err := pco.getContentConverter() if err != nil { return nil, false, err } p, ok := c.(converter.ParseRenderer) if !ok { return nil, ok, nil } rctx := converter.RenderContext{ Ctx: ctx, Src: content, RenderTOC: true, GetRenderer: pco.renderHooks.getRenderer, } r, err := p.Parse(rctx) return r, ok, err } func (pco *pageContentOutput) RenderContent(ctx context.Context, content []byte, doc any) (converter.ResultRender, bool, error) { c, err := pco.getContentConverter() if err != nil { return nil, false, err } p, ok := c.(converter.ParseRenderer) if !ok { return nil, ok, nil } rctx := converter.RenderContext{ Ctx: ctx, Src: content, RenderTOC: true, GetRenderer: pco.renderHooks.getRenderer, } r, err := p.Render(rctx, doc) return r, ok, err } func (pco *pageContentOutput) renderContentWithConverter(ctx context.Context, c converter.Converter, content []byte, renderTOC bool) (converter.ResultRender, error) { r, err := c.Convert( converter.RenderContext{ Ctx: ctx, Src: content, RenderTOC: renderTOC, GetRenderer: pco.renderHooks.getRenderer, }) return r, err } // these will be shifted out when rendering a given output format. type pagePerOutputProviders interface { targetPather page.PaginatorProvider resource.ResourceLinksProvider } type targetPather interface { targetPaths() page.TargetPaths getRelURL() string } type targetPathsHolder struct { // relURL is usually the same as OutputFormat.RelPermalink, but can be different // for non-permalinkable output formats. These shares RelPermalink with the main (first) output format. relURL string paths page.TargetPaths page.OutputFormat } func (t targetPathsHolder) getRelURL() string { return t.relURL } func (t targetPathsHolder) targetPaths() page.TargetPaths { return t.paths } func executeToString(ctx context.Context, h *tplimpl.TemplateStore, templ *tplimpl.TemplInfo, data any) (string, error) { b := bp.GetBuffer() defer bp.PutBuffer(b) if err := h.ExecuteWithContext(ctx, templ, b, data); err != nil { return "", err } return b.String(), nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__position.go
hugolib/page__position.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "github.com/gohugoio/hugo/common/hsync" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/resources/page" ) func newPagePosition(n *nextPrev) pagePosition { return pagePosition{nextPrev: n} } func newPagePositionInSection(n *nextPrev) pagePositionInSection { return pagePositionInSection{nextPrev: n} } type nextPrev struct { init hsync.FuncResetter prevPage page.Page nextPage page.Page } func (n *nextPrev) next() page.Page { n.init.Do(context.Background()) return n.nextPage } func (n *nextPrev) prev() page.Page { n.init.Do(context.Background()) return n.prevPage } type pagePosition struct { *nextPrev } func (p pagePosition) Next() page.Page { return p.next() } // Deprecated: Use Next instead. func (p pagePosition) NextPage() page.Page { hugo.Deprecate(".Page.NextPage", "Use .Page.Next instead.", "v0.123.0") return p.Next() } func (p pagePosition) Prev() page.Page { return p.prev() } // Deprecated: Use Prev instead. func (p pagePosition) PrevPage() page.Page { hugo.Deprecate(".Page.PrevPage", "Use .Page.Prev instead.", "v0.123.0") return p.Prev() } type pagePositionInSection struct { *nextPrev } func (p pagePositionInSection) NextInSection() page.Page { return p.next() } func (p pagePositionInSection) PrevInSection() page.Page { return p.prev() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/site_render.go
hugolib/site_render.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "fmt" "path" "strings" "sync" "github.com/bep/logg" "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/hugolib/doctree" "github.com/gohugoio/hugo/tpl/tplimpl" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" ) type siteRenderContext struct { cfg *BuildCfg infol logg.LevelLogger // languageIdx is the zero based index of the site. languageIdx int // Zero based index for all output formats combined. sitesOutIdx int // Zero based index of the output formats configured within a Site. // Note that these outputs are sorted. outIdx int multihost bool } // Whether to render 404.html, robotsTXT.txt and similar. // These are usually rendered once in the root of public. func (s siteRenderContext) shouldRenderStandalonePage(kind string) bool { if s.multihost || kind == kinds.KindSitemap { // 1 per site return s.outIdx == 0 } if kind == kinds.KindTemporary || kind == kinds.KindStatus404 { // 1 for all output formats return s.outIdx == 0 } // 1 for all sites and output formats. return s.languageIdx == 0 && s.outIdx == 0 } // renderPages renders pages concurrently. func (s *Site) renderPages(ctx *siteRenderContext) error { numWorkers := config.GetNumWorkerMultiplier() results := make(chan error) pages := make(chan *pageState, numWorkers) // buffered for performance errs := make(chan error) go s.errorCollator(results, errs) wg := &sync.WaitGroup{} for range numWorkers { wg.Add(1) go pageRenderer(ctx, s, pages, results, wg) } cfg := ctx.cfg w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: s.pageMap.treePages, Handle: func(key string, n contentNode) (radix.WalkFlag, error) { if p, ok := n.(*pageState); ok { if cfg.shouldRender(ctx.infol, p) { select { case <-s.h.Done(): return radix.WalkStop, nil default: pages <- p } } } return radix.WalkContinue, nil }, } if err := w.Walk(context.Background()); err != nil { return err } close(pages) wg.Wait() close(results) err := <-errs if err != nil { return fmt.Errorf("%v failed to render pages: %w", s.resolveDimensionNames(), err) } return nil } func pageRenderer( ctx *siteRenderContext, s *Site, pages <-chan *pageState, results chan<- error, wg *sync.WaitGroup, ) { defer wg.Done() sendErr := func(err error) bool { select { case results <- err: return true case <-s.h.Done(): return false } } for p := range pages { if p.m.isStandalone() && !ctx.shouldRenderStandalonePage(p.Kind()) { continue } if p.m.pageConfig.Build.PublishResources { if err := p.renderResources(); err != nil { if sendErr(p.errorf(err, "failed to render resources")) { continue } else { return } } } if !p.render { // Nothing more to do for this page. continue } templ, found, err := p.resolveTemplate() if err != nil { if sendErr(p.errorf(err, "failed to resolve template")) { continue } else { return } } if !found { s.Log.Trace( func() string { return fmt.Sprintf("no layout for kind %q found", p.Kind()) }, ) // Don't emit warning for missing 404 etc. pages. if !p.m.isStandalone() { s.logMissingLayout("", p.Layout(), p.Kind(), p.f.Name) } continue } targetPath := p.targetPaths().TargetFilename s.Log.Trace( func() string { return fmt.Sprintf("rendering outputFormat %q kind %q using layout %q to %q", p.pageOutput.f.Name, p.Kind(), templ.Name(), targetPath) }, ) var d any = p switch p.Kind() { case kinds.KindSitemapIndex: d = s.h.Sites } if err := s.renderAndWritePage(&s.PathSpec.ProcessingStats.Pages, targetPath, p, d, templ); err != nil { if sendErr(err) { continue } else { return } } if p.paginator != nil && p.paginator.current != nil { if err := s.renderPaginator(p, templ); err != nil { if sendErr(err) { continue } else { return } } } } } func (s *Site) logMissingLayout(name, layout, kind, outputFormat string) { log := s.Log.Warn() if name != "" && infoOnMissingLayout[name] { log = s.Log.Info() } errMsg := "You should create a template file which matches Hugo Layouts Lookup Rules for this combination." var args []any msg := "found no layout file for" if outputFormat != "" { msg += " %q" args = append(args, outputFormat) } if layout != "" { msg += " for layout %q" args = append(args, layout) } if kind != "" { msg += " for kind %q" args = append(args, kind) } if name != "" { msg += " for %q" args = append(args, name) } msg += ": " + errMsg log.Logf(msg, args...) } // renderPaginator must be run after the owning Page has been rendered. func (s *Site) renderPaginator(p *pageState, templ *tplimpl.TemplInfo) error { paginatePath := s.Conf.Pagination().Path d := p.targetPathDescriptor f := p.outputFormat() d.Type = f if p.paginator.current == nil || p.paginator.current != p.paginator.current.First() { panic(fmt.Sprintf("invalid paginator state for %q", p.pathOrTitle())) } if f.IsHTML && !s.Conf.Pagination().DisableAliases { // Write alias for page 1 d.Addends = fmt.Sprintf("/%s/%d", paginatePath, 1) targetPaths := page.CreateTargetPaths(d) if err := s.writeDestAlias(targetPaths.TargetFilename, p.Permalink(), f, p); err != nil { return err } } // Render pages for the rest for current := p.paginator.current.Next(); current != nil; current = current.Next() { p.paginator.current = current d.Addends = fmt.Sprintf("/%s/%d", paginatePath, current.PageNumber()) targetPaths := page.CreateTargetPaths(d) if err := s.renderAndWritePage( &s.PathSpec.ProcessingStats.PaginatorPages, targetPaths.TargetFilename, p, p, templ); err != nil { return err } } return nil } // renderAliases renders shell pages that simply have a redirect in the header. func (s *Site) renderAliases() error { w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: s.pageMap.treePages, Handle: func(key string, n contentNode) (radix.WalkFlag, error) { p := n.(*pageState) // We cannot alias a page that's not rendered. if p.m.noLink() || p.skipRender() { return radix.WalkContinue, nil } if len(p.Aliases()) == 0 { return radix.WalkContinue, nil } pathSeen := make(map[string]bool) for _, of := range p.OutputFormats() { if !of.Format.IsHTML { continue } f := of.Format if pathSeen[f.Path] { continue } pathSeen[f.Path] = true plink := of.Permalink() for _, a := range p.Aliases() { isRelative := !strings.HasPrefix(a, "/") if isRelative { // Make alias relative, where "." will be on the // same directory level as the current page. basePath := path.Join(p.targetPaths().SubResourceBaseLink, "..") a = path.Join(basePath, a) } else { // Make sure AMP and similar doesn't clash with regular aliases. a = path.Join(f.Path, a) } if s.conf.C.IsUglyURLSection(p.Section()) && !strings.HasSuffix(a, ".html") { a += ".html" } lang := p.Language().Lang if s.h.Configs.IsMultihost && !strings.HasPrefix(a, "/"+lang) { // These need to be in its language root. a = path.Join(lang, a) } err := s.writeDestAlias(a, plink, f, p) if err != nil { return radix.WalkStop, err } } } return radix.WalkContinue, nil }, } return w.Walk(context.TODO()) } // renderMainLanguageRedirect creates a redirect to the main language home, // depending on if it lives in sub folder (e.g. /en) or not. func (s *Site) renderMainLanguageRedirect() error { if s.conf.DisableDefaultLanguageRedirect { return nil } if s.h.Conf.IsMultihost() || !(s.h.Conf.DefaultContentLanguageInSubdir() || s.h.Conf.IsMultilingual()) { // No need for a redirect return nil } html, found := s.conf.OutputFormats.Config.GetByName("html") if found { mainLang := s.conf.DefaultContentLanguage if s.conf.DefaultContentLanguageInSubdir { mainLangURL := s.PathSpec.AbsURL(mainLang+"/", false) s.Log.Debugf("Write redirect to main language %s: %s", mainLang, mainLangURL) if err := s.publishDestAlias(true, "/", mainLangURL, html, nil); err != nil { return err } } else { mainLangURL := s.PathSpec.AbsURL("", false) s.Log.Debugf("Write redirect to main language %s: %s", mainLang, mainLangURL) if err := s.publishDestAlias(true, mainLang, mainLangURL, html, nil); err != nil { return err } } } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/pages_language_merge_test.go
hugolib/pages_language_merge_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/resources/resource" "github.com/google/go-cmp/cmp" ) var deepEqualsPages = qt.CmpEquals(cmp.Comparer(func(p1, p2 *pageState) bool { return p1 == p2 })) func TestMergeLanguages(t *testing.T) { t.Parallel() c := qt.New(t) files := generateLanguageMergeTxtar(30) b := Test(t, files) h := b.H enSite := h.Sites[0] frSite := h.Sites[1] nnSite := h.Sites[2] c.Assert(len(enSite.RegularPages()), qt.Equals, 31) c.Assert(len(frSite.RegularPages()), qt.Equals, 6) c.Assert(len(nnSite.RegularPages()), qt.Equals, 12) for range 2 { mergedNN := nnSite.RegularPages().MergeByLanguage(enSite.RegularPages()) c.Assert(len(mergedNN), qt.Equals, 31) for i := 1; i <= 31; i++ { expectedLang := "en" if i == 2 || i%3 == 0 || i == 31 { expectedLang = "nn" } p := mergedNN[i-1] c.Assert(p.Language().Lang, qt.Equals, expectedLang) } } mergedFR := frSite.RegularPages().MergeByLanguage(enSite.RegularPages()) c.Assert(len(mergedFR), qt.Equals, 31) for i := 1; i <= 31; i++ { expectedLang := "en" if i%5 == 0 { expectedLang = "fr" } p := mergedFR[i-1] c.Assert(p.Language().Lang, qt.Equals, expectedLang) } firstNN := nnSite.RegularPages()[0] c.Assert(len(firstNN.Sites()), qt.Equals, 4) c.Assert(firstNN.Sites().Default().Language().Lang, qt.Equals, "en") nnBundle := nnSite.getPageOldVersion("page", "bundle") enBundle := enSite.getPageOldVersion("page", "bundle") c.Assert(len(enBundle.Resources()), qt.Equals, 6) c.Assert(len(nnBundle.Resources()), qt.Equals, 2) var ri any = nnBundle.Resources() // This looks less ugly in the templates ... mergedNNResources := ri.(resource.ResourcesLanguageMerger).MergeByLanguage(enBundle.Resources()) c.Assert(len(mergedNNResources), qt.Equals, 6) unchanged, err := nnSite.RegularPages().MergeByLanguageInterface(nil) c.Assert(err, qt.IsNil) c.Assert(unchanged, deepEqualsPages, nnSite.RegularPages()) } func TestMergeLanguagesTemplate(t *testing.T) { t.Parallel() files := generateLanguageMergeTxtar(15) + ` -- layouts/home.html -- {{ $pages := .Site.RegularPages }} {{ .Scratch.Set "pages" $pages }} {{ $enSite := index .Sites 0 }} {{ $frSite := index .Sites 1 }} {{ if eq .Language.Lang "nn" }}: {{ $nnBundle := .Site.GetPage "page" "bundle" }} {{ $enBundle := $enSite.GetPage "page" "bundle" }} {{ .Scratch.Set "pages" ($pages | lang.Merge $frSite.RegularPages| lang.Merge $enSite.RegularPages) }} {{ .Scratch.Set "pages2" (sort ($nnBundle.Resources | lang.Merge $enBundle.Resources) "Title") }} {{ end }} {{ $pages := .Scratch.Get "pages" }} {{ $pages2 := .Scratch.Get "pages2" }} Pages1: {{ range $i, $p := $pages }}{{ add $i 1 }}: {{ .File.Path }} {{ .Language.Lang }} | {{ end }} Pages2: {{ range $i, $p := $pages2 }}{{ add $i 1 }}: {{ .Title }} {{ .Language.Lang }} | {{ end }} {{ $nil := resources.Get "asdfasdfasdf" }} Pages3: {{ $frSite.RegularPages | lang.Merge $nil }} Pages4: {{ $nil | lang.Merge $frSite.RegularPages }} -- layouts/_shortcodes/shortcode.html -- MyShort -- layouts/_shortcodes/lingo.html -- MyLingo ` b := Test(t, files) b.AssertFileContent("public/nn/index.html", "Pages1: 1: p1.md en | 2: p2.nn.md nn | 3: p3.nn.md nn | 4: p4.md en | 5: p5.fr.md fr | 6: p6.nn.md nn | 7: p7.md en | 8: p8.md en | 9: p9.nn.md nn | 10: p10.fr.md fr | 11: p11.md en | 12: p12.nn.md nn | 13: p13.md en | 14: p14.md en | 15: p15.nn.md nn") b.AssertFileContent("public/nn/index.html", "Pages2: 1: doc100 en | 2: doc101 nn | 3: doc102 nn | 4: doc103 en | 5: doc104 en | 6: doc105 en") b.AssertFileContent("public/nn/index.html", ` Pages3: Pages(3) Pages4: Pages(3) `) } func generateLanguageMergeTxtar(count int) string { var b strings.Builder // hugo.toml for multisite configuration b.WriteString(` -- hugo.toml -- baseURL = "https://example.org" defaultContentLanguage = "en" [languages] [languages.en] title = "English" weight = 1 [languages.fr] title = "French" weight = 2 [languages.nn] title = "Nynorsk" weight = 3 [languages.no] title = "Norwegian" weight = 4 `) contentTemplate := `--- title: doc%d weight: %d date: "2018-02-28" --- # doc *some "content"* {{< shortcode >}} {{< lingo >}} ` // Generate content files for i := 1; i <= count; i++ { content := fmt.Sprintf(contentTemplate, i, i) b.WriteString(fmt.Sprintf("\n-- content/p%d.md --\n%s", i, content)) if i == 2 || i%3 == 0 { b.WriteString(fmt.Sprintf("\n-- content/p%d.nn.md --\n%s", i, content)) } if i%5 == 0 { b.WriteString(fmt.Sprintf("\n-- content/p%d.fr.md --\n%s", i, content)) } } // Add a bundles j := 100 b.WriteString(fmt.Sprintf("\n-- content/bundle/index.md --\n%s", fmt.Sprintf(contentTemplate, j, j))) for i := range 6 { b.WriteString(fmt.Sprintf("\n-- content/bundle/pb%d.md --\n%s", i, fmt.Sprintf(contentTemplate, i+j, i+j))) } b.WriteString(fmt.Sprintf("\n-- content/bundle/index.nn.md --\n%s", fmt.Sprintf(contentTemplate, j, j))) for i := 1; i < 3; i++ { b.WriteString(fmt.Sprintf("\n-- content/bundle/pb%d.nn.md --\n%s", i, fmt.Sprintf(contentTemplate, i+j, i+j))) } // Add shortcode templates b.WriteString(` -- layouts/_shortcodes/shortcode.html -- MyShort -- layouts/_shortcodes/lingo.html -- MyLingo `) return b.String() } func BenchmarkMergeByLanguage(b *testing.B) { const count = 100 files := generateLanguageMergeTxtar(count - 1) builder := Test(b, files) h := builder.H enSite := h.Sites[0] nnSite := h.Sites[2] for b.Loop() { merged := nnSite.RegularPages().MergeByLanguage(enSite.RegularPages()) if len(merged) != count { b.Fatal("Count mismatch") } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/pages_test.go
hugolib/pages_test.go
package hugolib import ( "fmt" "math/rand" "testing" "github.com/gohugoio/hugo/resources/page" qt "github.com/frankban/quicktest" ) func newPagesPrevNextTestSite(t testing.TB, numPages int) *IntegrationTestBuilder { categories := []string{"blue", "green", "red", "orange", "indigo", "amber", "lime"} cat1, cat2 := categories[rand.Intn(len(categories))], categories[rand.Intn(len(categories))] categoriesSlice := fmt.Sprintf("[%q,%q]", cat1, cat2) pageTemplate := ` --- title: "Page %d" weight: %d categories: %s --- ` files := ` -- hugo.toml -- baseURL = "http://example.com/" ` for i := 1; i <= numPages; i++ { files += fmt.Sprintf("-- content/page%d.md --%s\n", i, fmt.Sprintf(pageTemplate, i, rand.Intn(numPages), categoriesSlice)) } return Test(t, files, TestOptSkipRender()) } func TestPagesPrevNext(t *testing.T) { b := newPagesPrevNextTestSite(t, 100) pages := b.H.Sites[0].RegularPages() b.Assert(pages, qt.HasLen, 100) for _, p := range pages { msg := qt.Commentf("w=%d", p.Weight()) b.Assert(pages.Next(p), qt.Equals, p.Next(), msg) b.Assert(pages.Prev(p), qt.Equals, p.Prev(), msg) } } func BenchmarkPagesPrevNext(b *testing.B) { type Variant struct { name string preparePages func(pages page.Pages) page.Pages run func(p page.Page, pages page.Pages) } shufflePages := func(pages page.Pages) page.Pages { rand.Shuffle(len(pages), func(i, j int) { pages[i], pages[j] = pages[j], pages[i] }) return pages } for _, variant := range []Variant{ {".Next", nil, func(p page.Page, pages page.Pages) { p.Next() }}, {".Prev", nil, func(p page.Page, pages page.Pages) { p.Prev() }}, {"Pages.Next", nil, func(p page.Page, pages page.Pages) { pages.Next(p) }}, {"Pages.Prev", nil, func(p page.Page, pages page.Pages) { pages.Prev(p) }}, {"Pages.Shuffled.Next", shufflePages, func(p page.Page, pages page.Pages) { pages.Next(p) }}, {"Pages.Shuffled.Prev", shufflePages, func(p page.Page, pages page.Pages) { pages.Prev(p) }}, {"Pages.ByTitle.Next", func(pages page.Pages) page.Pages { return pages.ByTitle() }, func(p page.Page, pages page.Pages) { pages.Next(p) }}, } { for _, numPages := range []int{300, 5000} { b.Run(fmt.Sprintf("%s-pages-%d", variant.name, numPages), func(b *testing.B) { b.StopTimer() builder := newPagesPrevNextTestSite(b, numPages) pages := builder.H.Sites[0].RegularPages() if variant.preparePages != nil { pages = variant.preparePages(pages) } b.StartTimer() for b.Loop() { p := pages[rand.Intn(len(pages))] variant.run(p, pages) } }) } } } func BenchmarkPagePageCollections(b *testing.B) { type Variant struct { name string run func(p page.Page) } for _, variant := range []Variant{ {".Pages", func(p page.Page) { p.Pages() }}, {".RegularPages", func(p page.Page) { p.RegularPages() }}, {".RegularPagesRecursive", func(p page.Page) { p.RegularPagesRecursive() }}, } { for _, numPages := range []int{300, 5000} { b.Run(fmt.Sprintf("%s-%d", variant.name, numPages), func(b *testing.B) { b.StopTimer() builder := newPagesPrevNextTestSite(b, numPages) builder.Build() var pages page.Pages for _, p := range builder.H.Sites[0].Pages() { if !p.IsPage() { pages = append(pages, p) } } b.StartTimer() for b.Loop() { p := pages[rand.Intn(len(pages))] variant.run(p) } }) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/gitinfo.go
hugolib/gitinfo.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "io" "path/filepath" "strings" "github.com/bep/gitmap" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/source" ) type gitInfo struct { contentDir string repo *gitmap.GitRepo } func (g *gitInfo) forPage(p page.Page) *source.GitInfo { name := strings.TrimPrefix(filepath.ToSlash(p.File().Filename()), g.contentDir) name = strings.TrimPrefix(name, "/") gi, found := g.repo.Files[name] if !found { return nil } return gi } func newGitInfo(d *deps.Deps) (*gitInfo, error) { opts := gitmap.Options{ Repository: d.Conf.BaseConfig().WorkingDir, GetGitCommandFunc: func(stdout, stderr io.Writer, args ...string) (gitmap.Runner, error) { var argsv []any for _, arg := range args { argsv = append(argsv, arg) } argsv = append( argsv, hexec.WithStdout(stdout), hexec.WithStderr(stderr), ) return d.ExecHelper.New("git", argsv...) }, } gitRepo, err := gitmap.Map(opts) if err != nil { return nil, err } return &gitInfo{contentDir: gitRepo.TopLevelAbsPath, repo: gitRepo}, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/rss_test.go
hugolib/rss_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) // Before Hugo 0.49 we set the pseudo page kind RSS on the page when output to RSS. // This had some unintended side effects, esp. when the only output format for that page // was RSS. // For the page kinds that can have multiple output formats, the Kind should be one of the // standard home, page etc. // This test has this single purpose: Check that the Kind is that of the source page. // See https://github.com/gohugoio/hugo/issues/5138 func TestRSSKind(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/index.rss.xml -- RSS Kind: {{ .Kind }} ` b := Test(t, files) b.AssertFileContent("public/index.xml", "RSS Kind: home") } func TestRSSCanonifyURLs(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "http://example.com/" -- layouts/index.rss.xml -- <rss>{{ range .Pages }}<item>{{ .Content | html }}</item>{{ end }}</rss> -- content/page.md -- --- Title: My Page --- Figure: {{< figure src="/images/sunset.jpg" title="Sunset" >}} ` b := Test(t, files) b.AssertFileContent("public/index.xml", "img src=&#34;http://example.com/images/sunset.jpg") } // Issue 13332. func TestRSSCanonifyURLsSubDir(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = 'https://example.org/subdir' disableKinds = ['section','sitemap','taxonomy','term'] [markup.goldmark.renderHooks.image] enableDefault = true [markup.goldmark.renderHooks.link] enableDefault = true -- layouts/_markup/render-image.html -- {{- $u := urls.Parse .Destination -}} {{- $src := $u.String | relURL -}} <img srcset="{{ $src }}" src="{{ $src }} 2x"> <img src="{{ $src }}"> {{- /**/ -}} -- layouts/home.html -- {{ .Content }}| -- layouts/single.html -- {{ .Content }}| -- layouts/rss.xml -- {{ with site.GetPage "/s1/p2" }} {{ .Content | transform.XMLEscape | safeHTML }} {{ end }} -- content/s1/p1.md -- --- title: p1 --- -- content/s1/p2/index.md -- --- title: p2 --- ![alt](a.jpg) [p1](/s1/p1) -- content/s1/p2/a.jpg -- ` b := Test(t, files) b.AssertFileContent("public/index.xml", "https://example.org/subdir/s1/p1/") b.AssertFileContent("public/index.xml", "img src=&#34;https://example.org/subdir/a.jpg", "img srcset=&#34;https://example.org/subdir/a.jpg&#34; src=&#34;https://example.org/subdir/a.jpg 2x") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/site_sections_test.go
hugolib/site_sections_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) func TestNextInSectionNested(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/" -- content/blog/page1.md -- --- weight: 1 --- -- content/blog/page2.md -- --- weight: 2 --- -- content/blog/cool/_index.md -- --- weight: 1 --- -- content/blog/cool/cool1.md -- --- weight: 1 --- -- content/blog/cool/cool2.md -- --- weight: 2 --- -- content/root1.md -- --- weight: 1 --- -- content/root2.md -- --- weight: 2 --- -- layouts/single.html -- Prev: {{ with .PrevInSection }}{{ .RelPermalink }}{{ end }}| Next: {{ with .NextInSection }}{{ .RelPermalink }}{{ end }}| ` b := Test(t, files) b.AssertFileContent("public/root1/index.html", "Prev: /root2/|", "Next: |") b.AssertFileContent("public/root2/index.html", "Prev: |", "Next: /root1/|") b.AssertFileContent("public/blog/page1/index.html", "Prev: /blog/page2/|", "Next: |") b.AssertFileContent("public/blog/page2/index.html", "Prev: |", "Next: /blog/page1/|") b.AssertFileContent("public/blog/cool/cool1/index.html", "Prev: /blog/cool/cool2/|", "Next: |") b.AssertFileContent("public/blog/cool/cool2/index.html", "Prev: |", "Next: /blog/cool/cool1/|") } func TestSectionEntries(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/" -- content/myfirstsection/p1.md -- --- title: "P1" --- P1 -- content/a/b/c/_index.md -- --- title: "C" --- C -- content/a/b/c/mybundle/index.md -- --- title: "My Bundle" --- -- layouts/list.html -- Kind: {{ .Kind }}|RelPermalink: {{ .RelPermalink }}|SectionsPath: {{ .SectionsPath }}|SectionsEntries: {{ .SectionsEntries }}|Len: {{ len .SectionsEntries }}| -- layouts/single.html -- Kind: {{ .Kind }}|RelPermalink: {{ .RelPermalink }}|SectionsPath: {{ .SectionsPath }}|SectionsEntries: {{ .SectionsEntries }}|Len: {{ len .SectionsEntries }}| ` b := Test(t, files) b.AssertFileContent("public/myfirstsection/p1/index.html", "RelPermalink: /myfirstsection/p1/|SectionsPath: /myfirstsection|SectionsEntries: [myfirstsection]|Len: 1") b.AssertFileContent("public/a/b/c/index.html", "RelPermalink: /a/b/c/|SectionsPath: /a/b/c|SectionsEntries: [a b c]|Len: 3") b.AssertFileContent("public/a/b/c/mybundle/index.html", "Kind: page|RelPermalink: /a/b/c/mybundle/|SectionsPath: /a/b/c|SectionsEntries: [a b c]|Len: 3") b.AssertFileContent("public/index.html", "Kind: home|RelPermalink: /|SectionsPath: /|SectionsEntries: []|Len: 0") } func TestParentWithPageOverlap(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com/" -- content/docs/_index.md -- -- content/docs/logs/_index.md -- -- content/docs/logs/sdk.md -- -- content/docs/logs/sdk_exporters/stdout.md -- -- layouts/list.html -- {{ .RelPermalink }}|{{ with .Parent}}{{ .RelPermalink }}{{ end }}| -- layouts/single.html -- {{ .RelPermalink }}|{{ with .Parent}}{{ .RelPermalink }}{{ end }}| ` b := Test(t, files) b.AssertFileContent("public/index.html", "/||") b.AssertFileContent("public/docs/index.html", "/docs/|/|") b.AssertFileContent("public/docs/logs/index.html", "/docs/logs/|/docs/|") b.AssertFileContent("public/docs/logs/sdk/index.html", "/docs/logs/sdk/|/docs/logs/|") b.AssertFileContent("public/docs/logs/sdk_exporters/stdout/index.html", "/docs/logs/sdk_exporters/stdout/|/docs/logs/|") } func TestNestedSectionsEmpty(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com/" -- content/a/b/c/_index.md -- --- title: "C" --- -- layouts/all.html -- All: {{ .Title }}|{{ .Kind }}| ` b := Test(t, files) b.AssertFileContent("public/a/index.html", "All: As|section|") b.AssertFileExists("public/a/b/index.html", false) b.AssertFileContent("public/a/b/c/index.html", "All: C|section|") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__new.go
hugolib/page__new.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "strings" "sync" "sync/atomic" "github.com/gohugoio/hugo/common/constants" "github.com/gohugoio/hugo/common/hstore" "github.com/gohugoio/hugo/resources/page" ) var ( pageIDCounter atomic.Uint64 pageSourceIDCounter atomic.Uint64 ) func (s *Site) newPageFromPageMeta(m *pageMeta, cascades *page.PageMatcherParamsConfigs) (*pageState, error) { p, err := s.doNewPageFromPageMeta(m, cascades) if err != nil { return nil, m.wrapError(err, s.SourceFs) } return p, nil } func (s *Site) doNewPageFromPageMeta(m *pageMeta, cascades *page.PageMatcherParamsConfigs) (*pageState, error) { if err := m.initLate(s); err != nil { return nil, err } pid := pageIDCounter.Add(1) // Parse the rest of the page content. var err error m.content, err = m.newCachedContent(s) if err != nil { return nil, m.wrapError(err, s.SourceFs) } ps := &pageState{ pid: pid, s: s, pageOutput: nopPageOutput, Staler: m, dependencyManager: s.Conf.NewIdentityManager(), pageCommon: &pageCommon{ store: sync.OnceValue(func() *hstore.Scratch { return hstore.NewScratch() }), // Rarely used. Positioner: page.NopPage, InSectionPositioner: page.NopPage, ResourceNameTitleProvider: m, ResourceParamsProvider: m, PageMetaProvider: m, PageMetaInternalProvider: m, FileProvider: m, OutputFormatsProvider: page.NopPage, ResourceTypeProvider: pageTypesProvider, MediaTypeProvider: pageTypesProvider, RefProvider: page.NopPage, ShortcodeInfoProvider: page.NopPage, LanguageProvider: s, RelatedDocsHandlerProvider: s, m: m, s: s, }, } if ps.IsHome() && ps.PathInfo().IsLeafBundle() { msg := "Using %s in your content's root directory is usually incorrect for your home page. " msg += "You should use %s instead. If you don't rename this file, your home page will be " msg += "treated as a leaf bundle, meaning it won't be able to have any child pages or sections." ps.s.Log.Warnidf(constants.WarnHomePageIsLeafBundle, msg, ps.PathInfo().PathNoLeadingSlash(), strings.ReplaceAll(ps.PathInfo().PathNoLeadingSlash(), "index", "_index")) } if m.f != nil { gi, err := s.h.gitInfoForPage(ps) if err != nil { return nil, fmt.Errorf("failed to load Git data: %w", err) } ps.gitInfo = gi owners, err := s.h.codeownersForPage(ps) if err != nil { return nil, fmt.Errorf("failed to load CODEOWNERS: %w", err) } ps.codeowners = owners } ps.pageMenus = &pageMenus{p: ps} ps.PageMenusProvider = ps.pageMenus ps.GetPageProvider = pageSiteAdapter{s: s, p: ps} ps.GitInfoProvider = ps ps.TranslationsProvider = ps ps.ResourceDataProvider = newDataFunc(ps) ps.RawContentProvider = ps ps.ChildCareProvider = ps ps.TreeProvider = pageTree{p: ps} ps.Eqer = ps ps.TranslationKeyProvider = ps ps.ShortcodeInfoProvider = ps ps.AlternativeOutputFormatsProvider = ps // Combine the cascade map with front matter. if err = ps.setMetaPost(cascades); err != nil { return nil, err } return ps, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/breaking_changes_test.go
hugolib/breaking_changes_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/cascade_test.go
hugolib/cascade_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "fmt" "testing" "github.com/gohugoio/hugo/hugolib/sitesmatrix" qt "github.com/frankban/quicktest" ) func BenchmarkCascadeTarget(b *testing.B) { files := ` -- content/_index.md -- background = 'yosemite.jpg' [cascade._target] kind = '{section,term}' -- content/posts/_index.md -- -- content/posts/funny/_index.md -- ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n", i+1) } for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/funny/pf%d.md --\n", i+1) } b.Run("Kind", func(b *testing.B) { cfg := IntegrationTestConfig{ T: b, TxtarString: files, } b.ResetTimer() for b.Loop() { b.StopTimer() builder := NewIntegrationTestBuilder(cfg) b.StartTimer() builder.Build() } }) } func TestCascadeBuildOptionsTaxonomies(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL="https://example.org" [taxonomies] tag = "tags" [[cascade]] [cascade._build] render = "never" list = "never" publishResources = false [cascade._target] path = '/hidden/**' -- content/p1.md -- --- title: P1 --- -- content/hidden/p2.md -- --- title: P2 tags: [t1, t2] --- -- layouts/list.html -- List: {{ len .Pages }}| -- layouts/single.html -- Single: Tags: {{ site.Taxonomies.tags }}| ` b := Test(t, files) b.AssertFileContent("public/p1/index.html", "Single: Tags: map[]|") b.AssertFileContent("public/tags/index.html", "List: 0|") b.AssertFileExists("public/hidden/p2/index.html", false) b.AssertFileExists("public/tags/t2/index.html", false) } func TestCascadeEditIssue12449(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ['sitemap','rss', 'home', 'taxonomy','term'] disableLiveReload = true -- layouts/list.html -- Title: {{ .Title }}|{{ .Content }}|cascadeparam: {{ .Params.cascadeparam }}| -- layouts/single.html -- Title: {{ .Title }}|{{ .Content }}|cascadeparam: {{ .Params.cascadeparam }}| -- content/mysect/_index.md -- --- title: mysect cascade: description: descriptionvalue params: cascadeparam: cascadeparamvalue --- mysect-content| -- content/mysect/p1/index.md -- --- slug: p1 --- p1-content| -- content/mysect/subsect/_index.md -- --- slug: subsect --- subsect-content| ` b := TestRunning(t, files) // Make the cascade set the title. b.EditFileReplaceAll("content/mysect/_index.md", "description: descriptionvalue", "title: cascadetitle").Build() b.AssertFileContent("public/mysect/subsect/index.html", "Title: cascadetitle|") // Edit cascade title. b.EditFileReplaceAll("content/mysect/_index.md", "title: cascadetitle", "title: cascadetitle-edit").Build() b.AssertFileContent("public/mysect/subsect/index.html", "Title: cascadetitle-edit|") // Revert title change. // The step below failed in #12449. b.EditFileReplaceAll("content/mysect/_index.md", "title: cascadetitle-edit", "description: descriptionvalue").Build() b.AssertFileContent("public/mysect/subsect/index.html", "Title: |") } func TestCascadeIssue12172(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','sitemap','taxonomy','term'] [[cascade]] headless = true [cascade._target] path = '/s1**' -- content/s1/p1.md -- --- title: p1 --- -- layouts/single.html -- {{ .Title }}| -- layouts/list.html -- {{ .Title }}| ` b := Test(t, files) b.AssertFileExists("public/index.html", true) b.AssertFileExists("public/s1/index.html", false) b.AssertFileExists("public/s1/p1/index.html", false) } // Issue 12594. func TestCascadeOrder(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','sitemap','taxonomy','term', 'home'] -- content/_index.md -- --- title: Home cascade: - _target: path: "**" params: background: yosemite.jpg - _target: params: background: goldenbridge.jpg --- -- content/p1.md -- --- title: p1 --- -- layouts/single.html -- Background: {{ .Params.background }}| -- layouts/list.html -- {{ .Title }}| ` for range 10 { b := Test(t, files) b.AssertFileContent("public/p1/index.html", "Background: yosemite.jpg") } } // Issue #12465. func TestCascadeOverlap(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','sitemap','taxonomy','term'] -- layouts/list.html -- {{ .Title }} -- layouts/single.html -- {{ .Title }} -- content/s/_index.md -- --- title: s cascade: build: render: never --- -- content/s/p1.md -- --- title: p1 --- -- content/sx/_index.md -- --- title: sx --- -- content/sx/p2.md -- --- title: p2 --- ` b := Test(t, files) b.AssertFileExists("public/s/index.html", false) b.AssertFileExists("public/s/p1/index.html", false) b.AssertFileExists("public/sx/index.html", true) // failing b.AssertFileExists("public/sx/p2/index.html", true) // failing } func TestCascadeGotmplIssue13743(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] [cascade.params] foo = 'bar' [cascade.target] path = '/p1' -- content/_content.gotmpl -- {{ .AddPage (dict "title" "p1" "path" "p1") }} -- layouts/all.html -- {{ .Title }}|{{ .Params.foo }} ` b := Test(t, files) b.AssertFileContent("public/p1/index.html", "p1|bar") // actual content is "p1|" } func TestSitesMatrixCascadeConfig(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [languages.sv] weight = 3 [versions] [versions."v1.0.0"] [versions."v2.0.0"] [versions."v2.1.0"] [roles] [roles.guest] [roles.member] [cascade] [cascade.sites.matrix] languages = ["en"] versions = ["v2**"] roles = ["member"] [cascade.sites.complements] languages = ["nn"] versions = ["v1.0.*"] roles = ["guest"] -- content/_index.md -- --- title: "Home" sites: matrix: roles: ["guest"] --- -- layouts/all.html -- All. ` b := Test(t, files) s0 := b.H.sitesVersionsRolesMap[sitesmatrix.Vector{0, 0, 0}] // en, v2.1.0, guest b.Assert(s0.home, qt.IsNotNil) b.Assert(s0.home.File(), qt.IsNotNil) b.Assert(s0.language.Name(), qt.Equals, "en") b.Assert(s0.version.Name(), qt.Equals, "v2.1.0") b.Assert(s0.role.Name(), qt.Equals, "guest") s0Pconfig := s0.Home().(*pageState).m.pageConfigSource b.Assert(s0Pconfig.SitesMatrix.Vectors(), qt.DeepEquals, []sitesmatrix.Vector{{0, 0, 0}, {0, 1, 0}}) // en, v2.1.0, guest + en, v2.0.0, guest s1 := b.H.sitesVersionsRolesMap[sitesmatrix.Vector{1, 2, 0}] b.Assert(s1.home, qt.IsNotNil) b.Assert(s1.home.File(), qt.IsNil) b.Assert(s1.language.Name(), qt.Equals, "nn") b.Assert(s1.version.Name(), qt.Equals, "v1.0.0") b.Assert(s1.role.Name(), qt.Equals, "guest") s1Pconfig := s1.Home().(*pageState).m.pageConfigSource b.Assert(s1Pconfig.SitesMatrix.HasVector(sitesmatrix.Vector{1, 2, 0}), qt.IsTrue) // nn, v1.0.0, guest // Every site needs a home page. This matrix adds the missing ones, (3 * 3 * 2) - 2 = 16 b.Assert(s1Pconfig.SitesMatrix.LenVectors(), qt.Equals, 16) } func TestCascadeBundledPage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org" -- content/_index.md -- --- title: Home cascade: params: p1: v1 --- -- content/b1/index.md -- --- title: b1 --- -- content/b1/p2.md -- --- title: p2 --- -- layouts/all.html -- Title: {{ .Title }}|p1: {{ .Params.p1 }}| {{ range .Resources }} Resource: {{ .Name }}|p1: {{ .Params.p1 }}| {{ end }} ` b := Test(t, files) b.AssertFileContent("public/b1/index.html", "Title: b1|p1: v1|", "Resource: p2.md|p1: v1|") } // Issue 14310 // Issue 14321 func TestCascadeIssue14310(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home', 'rss', 'sitemap', 'taxonomy', 'term'] defaultContentLanguage = 'en' defaultContentLanguageInSubdir = true [languages.en] weight = 1 [languages.de] weight = 2 [[cascade]] [cascade.params] size = 'medium' [cascade.target] kind = 'page' -- layouts/all.html -- |color: {{ .Params.color }}|size: {{ .Params.size }}| -- content/s1/_index.de.md -- --- title: s1 (de) cascade: params: color: red (de) --- -- content/s1/_index.en.md -- --- title: s1 (en) cascade: params: color: red (en) --- -- content/s1/p1.de.md -- --- title: p1 (de) --- -- content/s1/p1.en.md -- --- title: p1 (en) --- ` b := Test(t, files) b.AssertFileContent("public/en/s1/p1/index.html", "|color: red (en)|size: medium|") // fails: file contains "|color: red (en)|size: |" b.AssertFileContent("public/de/s1/p1/index.html", "|color: red (de)|size: medium|") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page_kinds.go
hugolib/page_kinds.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib const ( pageResourceType = "page" )
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__tree.go
hugolib/page__tree.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "context" "fmt" "strings" "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/hugolib/doctree" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" ) // pageTree holds the treen navigational method for a Page. type pageTree struct { p *pageState } func (pt pageTree) IsAncestor(other any) bool { n, ok := other.(contentNode) if !ok { return false } if n.Path() == pt.p.Path() { return false } return strings.HasPrefix(n.Path(), paths.AddTrailingSlash(pt.p.Path())) } func (pt pageTree) IsDescendant(other any) bool { n, ok := other.(contentNode) if !ok { return false } if n.Path() == pt.p.Path() { return false } return strings.HasPrefix(pt.p.Path(), paths.AddTrailingSlash(n.Path())) } func (pt pageTree) CurrentSection() page.Page { if kinds.IsBranch(pt.p.Kind()) { return pt.p } dir := pt.p.m.pathInfo.Dir() if dir == "/" { if pt.p.s.home == nil { panic(fmt.Sprintf("[%v] home page is nil for %q", pt.p.s.siteVector, pt.p.Path())) } return pt.p.s.home } _, n := pt.p.s.pageMap.treePages.LongestPrefix(dir, false, func(n contentNode) bool { return cnh.isBranchNode(n) }) if n != nil { return n.(page.Page) } panic(fmt.Sprintf("CurrentSection not found for %q for %s", pt.p.Path(), pt.p.s.resolveDimensionNames())) } func (pt pageTree) FirstSection() page.Page { s := pt.p.m.pathInfo.Dir() if s == "/" { return pt.p.s.home } for { k, n := pt.p.s.pageMap.treePages.LongestPrefix(s, false, func(n contentNode) bool { return cnh.isBranchNode(n) }) if n == nil { return nil } // /blog if strings.Count(k, "/") < 2 { return n.(page.Page) } if s == "" { return nil } s = paths.Dir(s) } } func (pt pageTree) InSection(other any) bool { if pt.p == nil || types.IsNil(other) { return false } p, ok := other.(page.Page) if !ok { return false } return pt.CurrentSection() == p.CurrentSection() } func (pt pageTree) Parent() page.Page { if pt.p.IsHome() { return nil } dir := pt.p.m.pathInfo.ContainerDir() if dir == "" { return pt.p.s.home } for { _, n := pt.p.s.pageMap.treePages.LongestPrefix(dir, false, nil) if n == nil { return pt.p.s.home } if pt.p.m.bundled || cnh.isBranchNode(n) { return n.(page.Page) } dir = paths.Dir(dir) } } func (pt pageTree) Ancestors() page.Pages { var ancestors page.Pages parent := pt.Parent() for parent != nil { ancestors = append(ancestors, parent) parent = parent.Parent() } return ancestors } func (pt pageTree) Sections() page.Pages { var ( pages page.Pages currentBranchPrefix string s = pt.p.Path() prefix = paths.AddTrailingSlash(s) tree = pt.p.s.pageMap.treePages ) w := &doctree.NodeShiftTreeWalker[contentNode]{ Tree: tree, Prefix: prefix, } w.Handle = func(ss string, n contentNode) (radix.WalkFlag, error) { if !cnh.isBranchNode(n) { return radix.WalkContinue, nil } if currentBranchPrefix == "" || !strings.HasPrefix(ss, currentBranchPrefix) { if p, ok := n.(*pageState); ok && p.IsSection() && p.m.shouldList(false) && p.Parent() == pt.p { pages = append(pages, p) } else { w.SkipPrefix(ss + "/") } } currentBranchPrefix = ss + "/" return radix.WalkContinue, nil } if err := w.Walk(context.Background()); err != nil { panic(err) } page.SortByDefault(pages) return pages } func (pt pageTree) Page() page.Page { return pt.p } func (p pageTree) SectionsEntries() []string { sp := p.SectionsPath() if sp == "/" { return nil } entries := strings.Split(sp[1:], "/") if len(entries) == 0 { return nil } return entries } func (p pageTree) SectionsPath() string { return p.CurrentSection().Path() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/page__paths.go
hugolib/page__paths.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "net/url" "path" "strings" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/page" ) func newPagePaths(ps *pageState) (pagePaths, error) { s := ps.s pm := ps.m targetPathDescriptor, err := createTargetPathDescriptor(ps) if err != nil { return pagePaths{}, err } var outputFormats output.Formats if ps.m.isStandalone() { outputFormats = output.Formats{ps.m.standaloneOutputFormat} } else { outputFormats = ps.outputFormats() if len(outputFormats) == 0 { return pagePaths{}, nil } if pm.noRender() { outputFormats = outputFormats[:1] } } pageOutputFormats := make(page.OutputFormats, len(outputFormats)) targets := make(map[string]targetPathsHolder) for i, f := range outputFormats { desc := targetPathDescriptor desc.Type = f paths := page.CreateTargetPaths(desc) var relPermalink, permalink string // If a page is headless or bundled in another, // it will not get published on its own and it will have no links. // We also check the build options if it's set to not render or have // a link. if !pm.noLink() && !pm.bundled { relPermalink = paths.RelPermalink(s.PathSpec) permalink = paths.PermalinkForOutputFormat(s.PathSpec, f) } pageOutputFormats[i] = page.NewOutputFormat(relPermalink, permalink, len(outputFormats) == 1, f) // Use the main format for permalinks, usually HTML. permalinksIndex := 0 if f.Permalinkable { // Unless it's permalinkable. permalinksIndex = i } targets[f.Name] = targetPathsHolder{ relURL: relPermalink, paths: paths, OutputFormat: pageOutputFormats[permalinksIndex], } } var out page.OutputFormats if !pm.noLink() { out = pageOutputFormats } return pagePaths{ outputFormats: out, firstOutputFormat: pageOutputFormats[0], targetPaths: targets, targetPathDescriptor: targetPathDescriptor, }, nil } type pagePaths struct { outputFormats page.OutputFormats firstOutputFormat page.OutputFormat targetPaths map[string]targetPathsHolder targetPathDescriptor page.TargetPathDescriptor } func (l pagePaths) OutputFormats() page.OutputFormats { return l.outputFormats } func createTargetPathDescriptor(p *pageState) (page.TargetPathDescriptor, error) { s := p.s d := s.Deps pm := p.m alwaysInSubDir := p.Kind() == kinds.KindSitemap pageInfoPage := p.PathInfo() pageInfoCurrentSection := p.CurrentSection().PathInfo() if p.s.Conf.DisablePathToLower() { pageInfoPage = pageInfoPage.Unnormalized() pageInfoCurrentSection = pageInfoCurrentSection.Unnormalized() } desc := page.TargetPathDescriptor{ PathSpec: d.PathSpec, Kind: p.Kind(), Path: pageInfoPage, Section: pageInfoCurrentSection, UglyURLs: s.h.Conf.IsUglyURLs(p.Section()), ForcePrefix: s.h.Conf.IsMultihost() || alwaysInSubDir, URL: pm.pageConfig.URL, } if pm.Slug() != "" { desc.BaseName = pm.Slug() } else if pm.isStandalone() && pm.standaloneOutputFormat.BaseName != "" { desc.BaseName = pm.standaloneOutputFormat.BaseName } else { desc.BaseName = pageInfoPage.BaseNameNoIdentifier() } addPrefix := func(filePath, link string) { if filePath != "" { if desc.PrefixFilePath != "" { desc.PrefixFilePath += "/" + filePath } else { desc.PrefixFilePath += filePath } } if link != "" { if desc.PrefixLink != "" { desc.PrefixLink += "/" + link } else { desc.PrefixLink += link } } } // Add path prefixes. // Add any role first, as that is a natural candidate for external ACL checks. rolePrefix := s.getPrefixRole() addPrefix(rolePrefix, rolePrefix) versionPrefix := s.getPrefixVersion() addPrefix(versionPrefix, versionPrefix) addPrefix(s.getLanguageTargetPathLang(alwaysInSubDir), s.getLanguagePermalinkLang(alwaysInSubDir)) if desc.URL != "" && strings.IndexByte(desc.URL, ':') >= 0 { // Attempt to parse and expand an url opath, err := d.ResourceSpec.Permalinks.ExpandPattern(desc.URL, p) if err != nil { return desc, err } if opath != "" { opath, _ = url.QueryUnescape(opath) desc.URL = opath } } opath, err := d.ResourceSpec.Permalinks.Expand(p.Section(), p) if err != nil { return desc, err } if opath != "" { opath, _ = url.QueryUnescape(opath) opath = path.Clean(opath) desc.ExpandedPermalink = opath if p.File() != nil { s.Log.Debugf("Set expanded permalink path for %s %s to %#v", p.Kind(), p.File().Path(), opath) } else { s.Log.Debugf("Set expanded permalink path for %s in %v to %#v", p.Kind(), desc.Section.Path(), opath) } } return desc, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/hugo_sites_build_test.go
hugolib/hugo_sites_build_test.go
package hugolib import ( "fmt" "path/filepath" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/resources/kinds" "github.com/spf13/afero" ) func TestMultiSitesMainLangInRoot(t *testing.T) { files := ` -- hugo.toml -- defaultContentLanguage = "fr" defaultContentLanguageInSubdir = false disableKinds = ["taxonomy", "term"] [languages] [languages.en] weight = 1 [languages.fr] weight = 2 -- content/sect/doc1.en.md -- --- title: doc1 en --- -- content/sect/doc1.fr.md -- --- title: doc1 fr slug: doc1-fr --- -- layouts/single.html -- Single: {{ .Title }}|{{ .Lang }}|{{ .RelPermalink }}| ` b := Test(t, files) b.AssertFileContent("public/sect/doc1-fr/index.html", "Single: doc1 fr|fr|/sect/doc1-fr/|") b.AssertFileContent("public/en/sect/doc1/index.html", "Single: doc1 en|en|/en/sect/doc1/|") } func TestMultiSitesWithTwoLanguages(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- defaultContentLanguage = "nn" [languages] [languages.nn] languageName = "Nynorsk" weight = 1 title = "Tittel på Nynorsk" [languages.nn.params] p1 = "p1nn" [languages.en] title = "Title in English" languageName = "English" weight = 2 [languages.en.params] p1 = "p1en" ` b := Test(t, files, TestOptSkipRender()) sites := b.H.Sites c := qt.New(t) c.Assert(len(sites), qt.Equals, 2) nnSite := sites[0] nnHome := nnSite.getPageOldVersion(kinds.KindHome) c.Assert(len(nnHome.AllTranslations()), qt.Equals, 2) c.Assert(len(nnHome.Translations()), qt.Equals, 1) c.Assert(nnHome.IsTranslated(), qt.Equals, true) enHome := sites[1].getPageOldVersion(kinds.KindHome) p1, err := enHome.Param("p1") c.Assert(err, qt.IsNil) c.Assert(p1, qt.Equals, "p1en") p1, err = nnHome.Param("p1") c.Assert(err, qt.IsNil) c.Assert(p1, qt.Equals, "p1nn") } func writeToFs(t testing.TB, fs afero.Fs, filename, content string) { t.Helper() if err := afero.WriteFile(fs, filepath.FromSlash(filename), []byte(content), 0o755); err != nil { t.Fatalf("Failed to write file: %s", err) } } func TestBenchmarkAssembleDeepSiteWithManySections(t *testing.T) { t.Parallel() b := createBenchmarkAssembleDeepSiteWithManySectionsBuilder(t, false, 2, 3, 4).Build() b.AssertFileContent("public/index.html", "Num regular pages recursive: 48|") } func createBenchmarkAssembleDeepSiteWithManySectionsBuilder(t testing.TB, skipRender bool, sectionDepth, sectionsPerLevel, pagesPerSection int) *IntegrationTestBuilder { t.Helper() const contentTemplate = `--- title: P%d --- ## A title Some content with a shortcode: {{< foo >}}. Some more content and then another shortcode: {{< foo >}}. Some final content. ` const filesTemplate = ` -- hugo.toml -- baseURL = "http://example.org/" disableKinds = ["taxonomy", "term", "rss", "sitemap", "robotsTXT", "404"] -- layouts/all.html -- All.{{ .Title }}|{{ .Content }}|Num pages: {{ len .Pages }}|Num sections: {{ len .Sections }}|Num regular pages recursive: {{ len .RegularPagesRecursive }}| Sections: {{ range .Sections }}{{ .Title }}|{{ end }}| RegularPagesRecursive: {{ range .RegularPagesRecursive }}{{ .RelPermalink }}|{{ end }}| -- layouts/_shortcodes/foo.html -- ` page := func(section string, i int) string { return fmt.Sprintf("\n-- content/%s/p%d.md --\n"+contentTemplate, section, i, i) } section := func(section string, i int) string { if section != "" { section = paths.AddTrailingSlash(section) } return fmt.Sprintf("\n-- content/%ss%d/_index.md --\n"+contentTemplate, section, i, i) } var sb strings.Builder // s0 // s0/s0 // s0/s1 // etc. var ( pageCount int sectionCount int ) var createSections func(currentSection string, currentDepth int) createSections = func(currentSection string, currentDepth int) { if currentDepth > sectionDepth { return } for i := 0; i < sectionsPerLevel; i++ { sectionCount++ sectionName := fmt.Sprintf("s%d", i) sectionPath := sectionName if currentSection != "" { sectionPath = currentSection + "/" + sectionName } sb.WriteString(section(currentSection, i)) // Pages in this section for j := 0; j < pagesPerSection; j++ { pageCount++ sb.WriteString(page(sectionPath, j)) } // Recurse createSections(sectionPath, currentDepth+1) } } createSections("", 1) sb.WriteString(filesTemplate) files := sb.String() return NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: BuildCfg{ SkipRender: skipRender, }, }, ) } func BenchmarkAssembleDeepSiteWithManySections(b *testing.B) { runOne := func(sectionDepth, sectionsPerLevel, pagesPerSection int) { name := fmt.Sprintf("depth=%d/sectionsPerLevel=%d/pagesPerSection=%d", sectionDepth, sectionsPerLevel, pagesPerSection) b.Run(name, func(b *testing.B) { for b.Loop() { b.StopTimer() bt := createBenchmarkAssembleDeepSiteWithManySectionsBuilder(b, true, sectionDepth, sectionsPerLevel, pagesPerSection) b.StartTimer() bt.Build() } }) } runOne(1, 1, 50) runOne(1, 6, 100) runOne(1, 6, 500) runOne(2, 6, 100) runOne(4, 2, 100) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/collections.go
hugolib/collections.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/resources/page" ) var ( _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) // collections.Slicer implementations below. We keep these bridge implementations // here as it makes it easier to get an idea of "type coverage". These // implementations have no value on their own. // Slice is for internal use. func (ps *pageState) Slice(items any) (any, error) { return page.ToPages(items) } // collections.Grouper implementations below // Group creates a PageGroup from a key and a Pages object // This method is not meant for external use. It got its non-typed arguments to satisfy // a very generic interface in the tpl package. func (ps *pageState) Group(key any, in any) (any, error) { pages, err := page.ToPages(in) if err != nil { return nil, err } return page.PageGroup{Key: key, Pages: pages}, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/segments/segments.go
hugolib/segments/segments.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package segments import ( "fmt" "strings" "github.com/gobwas/glob" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/predicate" "github.com/gohugoio/hugo/config" hglob "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/mitchellh/mapstructure" ) // Segments is a collection of named segments. type Segments struct { builder *segmentsBuilder // SegmentFilter is the compiled filter for all segments to render. SegmentFilter SegmentFilter } type SegmentFilter interface { // ShouldExcludeCoarse returns whether the given fields should be excluded on a coarse level. ShouldExcludeCoarse(SegmentQuery) bool // ShouldExcludeFine returns whether the given fields should be excluded on a fine level. ShouldExcludeFine(SegmentQuery) bool } type segmentFilter struct { exclude predicate.PR[SegmentQuery] include predicate.PR[SegmentQuery] } func (f segmentFilter) ShouldExcludeCoarse(q SegmentQuery) bool { return f.exclude(q).OK() } func (f segmentFilter) ShouldExcludeFine(q SegmentQuery) bool { return f.exclude(q).OK() || !f.include(q).OK() } type segmentsBuilder struct { logger loggers.Logger isConfigInit bool configuredDimensions *sitesmatrix.ConfiguredDimensions segmentCfg map[string]SegmentConfig segmentsToRender []string } func (b *Segments) compile() error { filter, err := b.builder.build() if err != nil { return err } b.SegmentFilter = filter b.builder = nil return nil } func (s *segmentsBuilder) buildOne(f []SegmentMatcherFields) (predicate.PR[SegmentQuery], error) { if f == nil { return matchNothing, nil } var ( result predicate.PR[SegmentQuery] section predicate.PR[SegmentQuery] ) addSectionMatcher := func(matcher predicate.PR[SegmentQuery]) { if section == nil { section = matcher } else { section = section.And(matcher) } } addToSection := func(matcherFields SegmentMatcherFields, f1 func(fields SegmentMatcherFields) []string, f2 func(q SegmentQuery) string) error { s1 := f1(matcherFields) if s1 == nil { // Nothing to match against. return nil } var sliceMatcher predicate.PR[SegmentQuery] for _, s := range s1 { negate := strings.HasPrefix(s, hglob.NegationPrefix) if negate { s = strings.TrimPrefix(s, hglob.NegationPrefix) } g, err := getGlob(s) if err != nil { return err } m := func(fields SegmentQuery) predicate.Match { s2 := f2(fields) if s2 == "" { return predicate.False } return predicate.BoolMatch(g.Match(s2) != negate) } if negate { sliceMatcher = sliceMatcher.And(m) } else { sliceMatcher = sliceMatcher.Or(m) } } if sliceMatcher != nil { addSectionMatcher(sliceMatcher) } return nil } for _, fields := range f { if len(fields.Kind) > 0 { if err := addToSection(fields, func(fields SegmentMatcherFields) []string { return fields.Kind }, func(fields SegmentQuery) string { return fields.Kind }, ); err != nil { return result, err } } if len(fields.Path) > 0 { if err := addToSection(fields, func(fields SegmentMatcherFields) []string { return fields.Path }, func(fields SegmentQuery) string { return fields.Path }, ); err != nil { return result, err } } if fields.Lang != "" { hugo.DeprecateWithLogger("config segments.[...]lang ", "Use sites.matrix instead, see https://gohugo.io/configuration/segments/#segment-definition", "v0.153.0", s.logger.Logger()) fields.Sites.Matrix.Languages = []string{fields.Lang} } if !fields.Sites.Matrix.IsZero() { intSetsCfg := sitesmatrix.IntSetsConfig{ Globs: fields.Sites.Matrix, } matrix := sitesmatrix.NewIntSetsBuilder(s.configuredDimensions).WithConfig(intSetsCfg).WithAllIfNotSet().Build() addSectionMatcher( func(fields SegmentQuery) predicate.Match { return predicate.BoolMatch(matrix.HasVector(fields.Site)) }, ) } if len(fields.Output) > 0 { if err := addToSection(fields, func(fields SegmentMatcherFields) []string { return fields.Output }, func(fields SegmentQuery) string { return fields.Output }, ); err != nil { return result, err } } if result == nil { result = section } else { result = result.Or(section) } section = nil } return result, nil } func (s *segmentsBuilder) build() (SegmentFilter, error) { var sf segmentFilter for _, segID := range s.segmentsToRender { segCfg, ok := s.segmentCfg[segID] if !ok { continue } include, err := s.buildOne(segCfg.Includes) if err != nil { return nil, err } exclude, err := s.buildOne(segCfg.Excludes) if err != nil { return nil, err } if sf.include == nil { sf.include = include } else { sf.include = sf.include.Or(include) } if sf.exclude == nil { sf.exclude = exclude } else { sf.exclude = sf.exclude.Or(exclude) } } if sf.exclude == nil { sf.exclude = matchNothing } if sf.include == nil { sf.include = matchAll } return sf, nil } func (b *Segments) InitConfig(logger loggers.Logger, _ sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions) error { if b.builder == nil || b.builder.isConfigInit { return nil } b.builder.isConfigInit = true b.builder.configuredDimensions = configuredDimensions return b.compile() } var ( matchAll = func(SegmentQuery) predicate.Match { return predicate.True } matchNothing = func(SegmentQuery) predicate.Match { return predicate.False } ) type SegmentConfig struct { Excludes []SegmentMatcherFields Includes []SegmentMatcherFields } type SegmentQuery struct { Kind string Path string Output string Site sitesmatrix.Vector } // SegmentMatcherFields holds string slices of ordered filters for segment matching. // The Glob patterns can be negated by prefixing with "! ". // The first match wins (either include or exclude). type SegmentMatcherFields struct { Kind []string Path []string Output []string Lang string // Deprecated: use Sites.Matrix instead. Sites sitesmatrix.Sites // Note that we only use Sites.Matrix for now. } func getGlob(s string) (glob.Glob, error) { if s == "" { return nil, nil } g, err := hglob.GetGlob(s) if err != nil { return nil, fmt.Errorf("failed to compile Glob %q: %w", s, err) } return g, nil } func DecodeSegments(in map[string]any, segmentsToRender []string, logger loggers.Logger) (*config.ConfigNamespace[map[string]SegmentConfig, *Segments], error) { buildConfig := func(in any) (*Segments, any, error) { m, err := maps.ToStringMapE(in) if err != nil { return nil, nil, err } if m == nil { m = map[string]any{} } m = maps.CleanConfigStringMap(m) var segmentCfg map[string]SegmentConfig if err := mapstructure.WeakDecode(m, &segmentCfg); err != nil { return nil, nil, err } sms := &Segments{ builder: &segmentsBuilder{ logger: logger, segmentCfg: segmentCfg, segmentsToRender: segmentsToRender, }, } return sms, nil, nil } ns, err := config.DecodeNamespace[map[string]SegmentConfig](in, buildConfig) if err != nil { return nil, fmt.Errorf("failed to decode segments: %w", err) } return ns, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/segments/segments_integration_test.go
hugolib/segments/segments_integration_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package segments_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestSegments(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.org/" renderSegments = ["docs"] [languages] [languages.en] weight = 1 [languages.no] weight = 2 [languages.nb] weight = 3 [segments] [segments.docs] [[segments.docs.includes]] kind = "{home,taxonomy,term}" [[segments.docs.includes]] path = "{/docs,/docs/**}" [[segments.docs.excludes]] path = "/blog/**" [[segments.docs.excludes]] lang = "n*" output = "rss" [[segments.docs.excludes]] output = "json" -- layouts/single.html -- Single: {{ .Title }}|{{ .RelPermalink }}| -- layouts/list.html -- List: {{ .Title }}|{{ .RelPermalink }}| -- content/docs/_index.md -- -- content/docs/section1/_index.md -- -- content/docs/section1/page1.md -- --- title: "Docs Page 1" tags: ["tag1", "tag2"] --- -- content/blog/_index.md -- -- content/blog/section1/page1.md -- --- title: "Blog Page 1" tags: ["tag1", "tag2"] --- ` b := hugolib.Test(t, files, hugolib.TestOptInfo()) b.AssertLogContains("deprecated") // lang => sites.matrix in v0.152.0 b.Assert(b.H.Configs.Base.RootConfig.RenderSegments, qt.DeepEquals, []string{"docs"}) b.AssertFileContent("public/docs/section1/page1/index.html", "Docs Page 1") b.AssertFileExists("public/blog/section1/page1/index.html", false) b.AssertFileExists("public/index.html", true) b.AssertFileExists("public/index.xml", true) b.AssertFileExists("public/no/index.html", true) b.AssertFileExists("public/no/index.xml", false) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/segments/segments_test.go
hugolib/segments/segments_test.go
package segments import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/predicate" "github.com/gohugoio/hugo/hugolib/sitesmatrix" ) var ( testDims = sitesmatrix.NewTestingDimensions([]string{"no", "en"}, []string{"v1.0.0", "v1.2.0", "v2.0.0"}, []string{"guest", "member"}) no = sitesmatrix.Vector{0, 0, 0} en = sitesmatrix.Vector{1, 0, 0} sitesNoStar = sitesmatrix.Sites{ Matrix: sitesmatrix.StringSlices{ Languages: []string{"n*"}, }, } sitesNo = sitesmatrix.Sites{ Matrix: sitesmatrix.StringSlices{ Languages: []string{"no"}, }, } sitesNotNo = sitesmatrix.Sites{ Matrix: sitesmatrix.StringSlices{ Languages: []string{"! no"}, }, } ) var compileSegments = func(c *qt.C, includes ...SegmentMatcherFields) predicate.P[SegmentQuery] { segments := Segments{ builder: &segmentsBuilder{ logger: loggers.NewDefault(), configuredDimensions: testDims, segmentsToRender: []string{"docs"}, segmentCfg: map[string]SegmentConfig{ "docs": { Includes: includes, }, }, }, } c.Assert(segments.compile(), qt.IsNil) return segments.SegmentFilter.ShouldExcludeFine } func TestCompileSegments(t *testing.T) { c := qt.New(t) c.Run("variants1", func(c *qt.C) { fields := []SegmentMatcherFields{ { Sites: sitesNoStar, Output: []string{"rss"}, }, } shouldExclude := compileSegments(c, fields...) check := func() { c.Assert(shouldExclude, qt.IsNotNil) c.Assert(shouldExclude(SegmentQuery{Site: no}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Site: no, Kind: "page"}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Site: no, Output: "rss"}), qt.Equals, false) c.Assert(shouldExclude(SegmentQuery{Site: no, Output: "html"}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Kind: "page"}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Site: no, Output: "rss", Kind: "page"}), qt.Equals, false) } check() fields = []SegmentMatcherFields{ { Path: []string{"/blog/**"}, }, { Sites: sitesNoStar, Output: []string{"rss"}, }, } shouldExclude = compileSegments(c, fields...) check() c.Assert(shouldExclude(SegmentQuery{Path: "/blog/foo"}), qt.Equals, false) }) c.Run("variants2", func(c *qt.C) { fields := []SegmentMatcherFields{ { Path: []string{"/docs/**"}, }, { Sites: sitesNo, Output: []string{"rss", "json"}, }, } shouldExclude := compileSegments(c, fields...) c.Assert(shouldExclude, qt.IsNotNil) c.Assert(shouldExclude(SegmentQuery{Site: no}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Kind: "page"}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Kind: "page", Path: "/blog/foo"}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Site: en}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Site: no, Output: "rss"}), qt.Equals, false) c.Assert(shouldExclude(SegmentQuery{Site: no, Output: "json"}), qt.Equals, false) c.Assert(shouldExclude(SegmentQuery{Site: no, Output: "html"}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Kind: "page", Path: "/docs/foo"}), qt.Equals, false) }) } func TestCompileSegmentsNegate(t *testing.T) { c := qt.New(t) fields := []SegmentMatcherFields{ { Sites: sitesNotNo, Output: []string{"! r**", "rem", "html"}, }, } shouldExclude := compileSegments(c, fields...) c.Assert(shouldExclude, qt.IsNotNil) c.Assert(shouldExclude(SegmentQuery{Site: no, Output: "html"}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Site: en, Output: "html"}), qt.Equals, false) c.Assert(shouldExclude(SegmentQuery{Site: en, Output: "rss"}), qt.Equals, true) c.Assert(shouldExclude(SegmentQuery{Site: en, Output: "rem"}), qt.Equals, true) } func BenchmarkSegmentsMatch(b *testing.B) { c := qt.New(b) fields := []SegmentMatcherFields{ { Path: []string{"/docs/**"}, }, { Sites: sitesNo, Output: []string{"rss"}, }, } match := compileSegments(c, fields...) for b.Loop() { match(SegmentQuery{Site: no, Output: "rss"}) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/doctree/nodeshifttree.go
hugolib/doctree/nodeshifttree.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package doctree import ( "context" "fmt" "path" "sync" radix "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/resources/resource" ) type ( Config[T any] struct { // Shifter handles tree transformations. Shifter Shifter[T] TransformerRaw Transformer[T] } // Shifter handles tree transformations. Shifter[T any] interface { // ForEeachInDimension will call the given function for each value in the given dimension d. // This is typicall used to e.g. walk all language translations of a given node. // If the function returns false, the walk will stop. ForEeachInDimension(n T, vec sitesmatrix.Vector, d int, f func(T) bool) // ForEeachInAllDimensions will call the given function for each value in all dimensions. // If the function returns false, the walk will stop. ForEeachInAllDimensions(n T, f func(T) bool) // Insert inserts new into the tree into the dimension it provides. // It may replace old. // It returns the updated and existing T // and a bool indicating if an existing record is updated. Insert(old, new T) (T, T, bool) // Delete deletes T from the given dimension and returns the deleted T and whether the dimension was deleted and if it's empty after the delete. Delete(v T, dimension sitesmatrix.Vector) (T, bool, bool) // DeleteFunc deletes nodes in v from the tree where the given function returns true. // It returns true if it's empty after the delete. DeleteFunc(v T, f func(n T) bool) bool // Shift shifts v into the given dimension, // if fallback is true, it will fall back a fallback match if found. // It returns the shifted T and a bool indicating if the shift was successful. Shift(v T, dimension sitesmatrix.Vector, fallback bool) (T, bool) } Transformer[T any] interface { // Append appends vs to t and returns the updated or replaced T and a bool indicating if T was replaced. // Note that t may be the zero value and should be ignored. Append(t T, ts ...T) (T, bool) } ) // NodeShiftTree is the root of a tree that can be shaped using the Shape method. // Note that multiplied shapes of the same tree is meant to be used concurrently, // so use the applicable locking when needed. type NodeShiftTree[T any] struct { tree *radix.Tree[T] // [language, version, role]. siteVector sitesmatrix.Vector shifter Shifter[T] transformerRaw Transformer[T] mu *sync.RWMutex } func New[T any](cfg Config[T]) *NodeShiftTree[T] { if cfg.Shifter == nil { panic("Shifter is required") } return &NodeShiftTree[T]{ mu: &sync.RWMutex{}, shifter: cfg.Shifter, transformerRaw: cfg.TransformerRaw, tree: radix.New[T](), } } // SiteVector returns the site vector of the current dimension. func (r *NodeShiftTree[T]) SiteVector() sitesmatrix.Vector { return r.siteVector } // Delete deletes the node at the given key in the current dimension. func (r *NodeShiftTree[T]) Delete(key string) (T, bool) { return r.delete(key) } // DeleteFuncRaw deletes nodes in the tree at the given key where the given function returns true. // It will delete nodes in all dimensions. func (r *NodeShiftTree[T]) DeleteFuncRaw(key string, f func(T) bool) (T, int) { var count int var lastDeleted T v, ok := r.tree.Get(key) if !ok { return lastDeleted, count } isEmpty := r.shifter.DeleteFunc(v, func(n T) bool { if f(n) { count++ lastDeleted = n return true } return false }) if isEmpty { r.tree.Delete(key) } return lastDeleted, count } // DeleteRaw deletes the node at the given key without any shifting or transformation. func (r *NodeShiftTree[T]) DeleteRaw(key string) { r.tree.Delete(key) } // DeletePrefix deletes all nodes with the given prefix in the current dimension. func (r *NodeShiftTree[T]) DeletePrefix(prefix string) int { count := 0 var keys []string var zero T var walkFn radix.WalkFn[T] = func(key string, value T) (radix.WalkFlag, T, error) { keys = append(keys, key) return radix.WalkContinue, zero, nil } r.tree.WalkPrefix(prefix, walkFn) for _, key := range keys { if _, ok := r.delete(key); ok { count++ } } return count } func (r *NodeShiftTree[T]) delete(key string) (T, bool) { var wasDeleted bool var deleted T if v, ok := r.tree.Get(key); ok { var isEmpty bool deleted, wasDeleted, isEmpty = r.shifter.Delete(v, r.siteVector) if isEmpty { r.tree.Delete(key) } } return deleted, wasDeleted } func (t *NodeShiftTree[T]) DeletePrefixRaw(prefix string) int { count := 0 var zero T var walkFn radix.WalkFn[T] = func(key string, value T) (radix.WalkFlag, T, error) { if v, ok := t.tree.Delete(key); ok { resource.MarkStale(v) count++ } return radix.WalkContinue, zero, nil } t.tree.WalkPrefix(prefix, walkFn) return count } // Insert inserts v into the tree at the given key and the // dimension defined by the value. // It returns the updated and existing T and a bool indicating if an existing record is updated. func (r *NodeShiftTree[T]) Insert(s string, v T) (T, T, bool) { s = mustValidateKey(cleanKey(s)) var ( updated bool existing T ) if vv, ok := r.tree.Get(s); ok { v, existing, updated = r.shifter.Insert(vv, v) } r.insert(s, v) return v, existing, updated } func (r *NodeShiftTree[T]) insert(s string, v T) (T, bool) { n, updated := r.tree.Insert(s, v) return n, updated } // InsertRaw inserts v into the tree at the given key without any shifting or transformation. func (r *NodeShiftTree[T]) InsertRaw(s string, v T) (T, bool) { return r.insert(s, v) } func (r *NodeShiftTree[T]) InsertRawWithLock(s string, v T) (T, bool) { r.mu.Lock() defer r.mu.Unlock() return r.insert(s, v) } // It returns the updated and existing T and a bool indicating if an existing record is updated. func (r *NodeShiftTree[T]) InsertWithLock(s string, v T) (T, T, bool) { r.mu.Lock() defer r.mu.Unlock() return r.Insert(s, v) } func (t *NodeShiftTree[T]) Len() int { return t.tree.Len() } func (t *NodeShiftTree[T]) CanLock() bool { ok := t.mu.TryLock() if ok { t.mu.Unlock() } return ok } // Lock locks the data store for read or read/write access. // Note that NodeShiftTree is not thread-safe outside of this transaction construct. func (t *NodeShiftTree[T]) Lock(writable bool) { if writable { t.mu.Lock() } else { t.mu.RLock() } } // Unlock unlocks the data store. func (t *NodeShiftTree[T]) Unlock(writable bool) { if writable { t.mu.Unlock() } else { t.mu.RUnlock() } } // LongestPrefix finds the longest prefix of s that exists in the tree that also matches the predicate (if set). // Set exact to true to only match exact in the current dimension (e.g. language). func (r *NodeShiftTree[T]) LongestPrefix(s string, fallback bool, predicate func(v T) bool) (string, T) { for { longestPrefix, v, found := r.tree.LongestPrefix(s) if found { if v, ok := r.shift(v, fallback); ok && (predicate == nil || predicate(v)) { return longestPrefix, v } } if s == "" || s == "/" { var t T return "", t } // Walk up to find a node in the correct dimension. s = path.Dir(s) } } // LongestPrefiValueRaw returns the longest prefix and value considering all dimensions func (r *NodeShiftTree[T]) LongestPrefiValueRaw(s string) (string, T) { s, v, found := r.tree.LongestPrefix(s) if !found { var t T return s, t } return s, v } // LongestPrefixRaw returns the longest prefix considering all dimensions. func (r *NodeShiftTree[T]) LongestPrefixRaw(s string) (string, bool) { s, _, found := r.tree.LongestPrefix(s) return s, found } // GetRaw returns the raw value at the given key without any shifting or transformation. func (r *NodeShiftTree[T]) GetRaw(s string) (T, bool) { v, ok := r.tree.Get(s) if !ok { var t T return t, false } return v, true } // AppendRaw appends ts to the node at the given key without any shifting or transformation. func (r *NodeShiftTree[T]) AppendRaw(s string, ts ...T) (T, bool) { if r.transformerRaw == nil { panic("transformerRaw is required") } n, found := r.GetRaw(s) n2, replaced := r.transformerRaw.Append(n, ts...) if replaced || !found { r.insert(s, n2) } return n2, replaced || !found } // WalkPrefixRaw walks all nodes with the given prefix in the tree without any shifting or transformation. func (r *NodeShiftTree[T]) WalkPrefixRaw(prefix string, fn radix.WalkFn[T]) error { return r.tree.WalkPrefix(prefix, fn) } // Shape returns a new NodeShiftTree shaped to the given dimension. func (t *NodeShiftTree[T]) Shape(v sitesmatrix.Vector) *NodeShiftTree[T] { x := t.clone() x.siteVector = v return x } func (t *NodeShiftTree[T]) String() string { return fmt.Sprintf("Root{%v}", t.siteVector) } func (r *NodeShiftTree[T]) Get(s string) T { t, _ := r.get(s) return t } func (r *NodeShiftTree[T]) ForEeachInDimension(s string, dims sitesmatrix.Vector, d int, f func(T) bool) { s = cleanKey(s) v, ok := r.tree.Get(s) if !ok { return } r.shifter.ForEeachInDimension(v, dims, d, f) } func (r *NodeShiftTree[T]) ForEeachInAllDimensions(s string, f func(T) bool) { s = cleanKey(s) v, ok := r.tree.Get(s) if !ok { return } r.shifter.ForEeachInAllDimensions(v, f) } type WalkFunc[T any] func(string, T) (bool, error) //go:generate stringer -type=NodeTransformState type NodeTransformState int const ( NodeTransformStateNone NodeTransformState = iota NodeTransformStateUpdated // Node is updated in place. NodeTransformStateReplaced // Node is replaced and needs to be re-inserted into the tree. NodeTransformStateDeleted // Node is deleted and should be removed from the tree. NodeTransformStateSkip // Skip this node, but continue the walk. NodeTransformStateTerminate // Terminate the walk. ) type NodeShiftTreeWalker[T any] struct { // The tree to walk. Tree *NodeShiftTree[T] // Transform will be called for each node in the main tree. // v2 will replace v1 in the tree if state returned is NodeTransformStateReplaced. Transform func(s string, v1 T) (v2 T, state NodeTransformState, err error) // Handle will be called for each node in the main tree. Handle func(s string, v T) (f radix.WalkFlag, err error) // Optional prefix filter. Prefix string // IncludeFilter is an optional filter that can be used to filter nodes. // If it returns false, the node will be skipped. // Note that v is the shifted value from the tree. IncludeFilter func(s string, v T) bool // IncludeRawFilter is an optional filter that can be used to filter nodes. // If it returns false, the node will be skipped. // Note that v is the raw value from the tree. IncludeRawFilter func(s string, v T) bool // Enable read or write locking if needed. LockType LockType // When set, no dimension shifting will be performed. NoShift bool // When set, will try to fall back to alternative match, // typically a shared resource common for all languages. Fallback bool // Used in development only. Debug bool // Optional context. // Note that this is copied to the nested walkers using Extend. // This means that walkers can pass data (down) and events (up) to // the related walkers. WalkContext *WalkContext[T] // Local state. // This is scoped to the current walker and not copied to the nested walkers. skipPrefixes []string } // Extend returns a new NodeShiftTreeWalker with the same configuration // and the same WalkContext as the original. // Any local state is reset. func (r *NodeShiftTreeWalker[T]) Extend() *NodeShiftTreeWalker[T] { return &NodeShiftTreeWalker[T]{ Tree: r.Tree, Transform: r.Transform, Handle: r.Handle, Prefix: r.Prefix, IncludeFilter: r.IncludeFilter, IncludeRawFilter: r.IncludeRawFilter, LockType: r.LockType, NoShift: r.NoShift, Fallback: r.Fallback, Debug: r.Debug, WalkContext: r.WalkContext, } } // WithPrefix returns a new NodeShiftTreeWalker with the given prefix. func (r *NodeShiftTreeWalker[T]) WithPrefix(prefix string) *NodeShiftTreeWalker[T] { r2 := r.Extend() r2.Prefix = prefix return r2 } // SkipPrefix adds a prefix to be skipped in the walk. func (r *NodeShiftTreeWalker[T]) SkipPrefix(prefix ...string) { r.skipPrefixes = append(r.skipPrefixes, prefix...) } func (r *NodeShiftTreeWalker[T]) ShouldSkipKey(s string) bool { return hstrings.HasAnyPrefix(s, r.skipPrefixes...) } // ShouldSkip returns whether the given value should be skipped in the walk. func (r *NodeShiftTreeWalker[T]) ShouldSkipValue(s string, v T) bool { if r.IncludeRawFilter != nil { if !r.IncludeRawFilter(s, v) { return true } } return false } type walkHandler[T any] struct { r *NodeShiftTreeWalker[T] handle func(s string, v T) (radix.WalkFlag, T, error) } func (h *walkHandler[T]) Check(s string) (radix.WalkFlag, error) { if h.r == nil { return radix.WalkContinue, nil } if h.r.ShouldSkipKey(s) { return radix.WalkSkip, nil } return radix.WalkContinue, nil } func (h *walkHandler[T]) Handle(s string, v T) (radix.WalkFlag, T, error) { if h.handle == nil { return radix.WalkContinue, v, nil } return h.handle(s, v) } func (r *NodeShiftTreeWalker[T]) lock() { switch r.LockType { case LockTypeRead: r.Tree.mu.RLock() case LockTypeWrite: r.Tree.mu.Lock() default: // No lock } } func (r *NodeShiftTreeWalker[T]) unlock() { switch r.LockType { case LockTypeRead: r.Tree.mu.RUnlock() case LockTypeWrite: r.Tree.mu.Unlock() default: // No lock } } func (r *NodeShiftTreeWalker[T]) Walk(ctx context.Context) error { var deletes []string return func() error { r.lock() defer r.unlock() r.resetLocalState() main := r.Tree var handleV radix.WalkFn[T] = func(s string, v T) (radix.WalkFlag, T, error) { var zero T // Context cancellation check. if ctx != nil && ctx.Err() != nil { return radix.WalkStop, zero, ctx.Err() } if r.ShouldSkipValue(s, v) { return radix.WalkContinue, zero, nil } var t T if r.NoShift { t = v } else { var ok bool t, ok = r.toT(r.Tree, v) if !ok { return radix.WalkContinue, zero, nil } } var ( ns NodeTransformState t2 T ) if r.IncludeFilter != nil && !r.IncludeFilter(s, t) { return radix.WalkContinue, zero, nil } if r.Transform != nil { if !r.NoShift { panic("Transform must be performed with NoShift=true") } var err error ns, err = func() (ns NodeTransformState, err error) { t2, ns, err = r.Transform(s, t) if ns >= NodeTransformStateSkip || err != nil { return } switch ns { case NodeTransformStateReplaced: case NodeTransformStateDeleted: // Delay delete until after the walk. deletes = append(deletes, s) ns = NodeTransformStateSkip } return }() if ns == NodeTransformStateTerminate || err != nil { return radix.WalkStop, zero, err } if ns == NodeTransformStateSkip { return radix.WalkContinue, zero, nil } } if r.Handle != nil { f, err := r.Handle(s, t) if f.ShouldSet() { panic("Handle cannot replace nodes in the tree, use Transform for that") } if f.ShouldStop() || err != nil { return f, zero, err } } if ns == NodeTransformStateTerminate { return radix.WalkStop, zero, nil } if ns == NodeTransformStateReplaced { return radix.WalkSet | radix.WalkContinue, t2, nil } return radix.WalkContinue, zero, nil } handle := &walkHandler[T]{ r: r, handle: handleV, } if r.Prefix != "" { if err := main.tree.WalkPrefix(r.Prefix, handle); err != nil { return err } } else { if err := main.tree.Walk(handle); err != nil { return err } } // This is currently only performed with no shift. for _, s := range deletes { main.tree.Delete(s) } return nil }() } func (r *NodeShiftTreeWalker[T]) resetLocalState() { r.skipPrefixes = nil } func (r *NodeShiftTreeWalker[T]) toT(tree *NodeShiftTree[T], v T) (T, bool) { return tree.shift(v, r.Fallback) } func (r *NodeShiftTree[T]) Has(s string) bool { _, ok := r.GetRaw(s) return ok } func (t NodeShiftTree[T]) clone() *NodeShiftTree[T] { return &t } func (r *NodeShiftTree[T]) shift(t T, fallback bool) (T, bool) { return r.shifter.Shift(t, r.siteVector, fallback) } func (r *NodeShiftTree[T]) get(s string) (T, bool) { s = cleanKey(s) v, ok := r.tree.Get(s) if !ok { var t T return t, false } if v, ok := r.shift(v, false); ok { return v, true } var t T return t, false }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/doctree/nodetransformstate_string.go
hugolib/doctree/nodetransformstate_string.go
// Code generated by "stringer -type=NodeTransformState"; DO NOT EDIT. package doctree import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[NodeTransformStateNone-0] _ = x[NodeTransformStateUpdated-1] _ = x[NodeTransformStateReplaced-2] _ = x[NodeTransformStateDeleted-3] _ = x[NodeTransformStateSkip-4] _ = x[NodeTransformStateTerminate-5] } const _NodeTransformState_name = "NodeTransformStateNoneNodeTransformStateUpdatedNodeTransformStateReplacedNodeTransformStateDeletedNodeTransformStateSkipNodeTransformStateTerminate" var _NodeTransformState_index = [...]uint8{0, 22, 47, 73, 98, 120, 147} func (i NodeTransformState) String() string { if i < 0 || i >= NodeTransformState(len(_NodeTransformState_index)-1) { return "NodeTransformState(" + strconv.FormatInt(int64(i), 10) + ")" } return _NodeTransformState_name[_NodeTransformState_index[i]:_NodeTransformState_index[i+1]] }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/doctree/nodeshiftree_test.go
hugolib/doctree/nodeshiftree_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package doctree_test import ( "context" "fmt" "math/rand" "path" "strings" "testing" qt "github.com/frankban/quicktest" radix "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/common/para" "github.com/gohugoio/hugo/hugolib/doctree" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/google/go-cmp/cmp" ) var eq = qt.CmpEquals( cmp.Comparer(func(n1, n2 *testValue) bool { if n1 == n2 { return true } return n1.ID == n2.ID && n1.Lang == n2.Lang }), ) func TestTree(t *testing.T) { c := qt.New(t) zeroZero := doctree.New( doctree.Config[*testValue]{ Shifter: &testShifter{}, }, ) a := &testValue{ID: "/a"} zeroZero.Insert("/a", a) ab := &testValue{ID: "/a/b"} zeroZero.Insert("/a/b", ab) c.Assert(zeroZero.Get("/a"), eq, &testValue{ID: "/a", Lang: 0}) s, v := zeroZero.LongestPrefix("/a/b/c", false, nil) c.Assert(v, eq, ab) c.Assert(s, eq, "/a/b") // Change language. oneZero := zeroZero.Shape(sitesmatrix.Vector{1, 0, 0}) c.Assert(zeroZero.Get("/a"), eq, &testValue{ID: "/a", Lang: 0}) c.Assert(oneZero.Get("/a"), eq, &testValue{ID: "/a", Lang: 1}) } func TestTreeData(t *testing.T) { c := qt.New(t) tree := doctree.New( doctree.Config[*testValue]{ Shifter: &testShifter{}, }, ) tree.Insert("", &testValue{ID: "HOME"}) tree.Insert("/a", &testValue{ID: "/a"}) tree.Insert("/a/b", &testValue{ID: "/a/b"}) tree.Insert("/b", &testValue{ID: "/b"}) tree.Insert("/b/c", &testValue{ID: "/b/c"}) tree.Insert("/b/c/d", &testValue{ID: "/b/c/d"}) var values []string ctx := &doctree.WalkContext[*testValue]{} w := &doctree.NodeShiftTreeWalker[*testValue]{ Tree: tree, WalkContext: ctx, Handle: func(s string, t *testValue) (radix.WalkFlag, error) { ctx.Data().Insert(s, map[string]any{ "id": t.ID, }) if s != "" { p, v := ctx.Data().LongestPrefix(path.Dir(s)) values = append(values, fmt.Sprintf("%s:%s:%v", s, p, v)) } return radix.WalkContinue, nil }, } w.Walk(context.Background()) c.Assert(strings.Join(values, "|"), qt.Equals, "/a::map[id:HOME]|/a/b:/a:map[id:/a]|/b::map[id:HOME]|/b/c:/b:map[id:/b]|/b/c/d:/b/c:map[id:/b/c]") } func TestTreeEvents(t *testing.T) { c := qt.New(t) tree := doctree.New( doctree.Config[*testValue]{ Shifter: &testShifter{echo: true}, }, ) tree.Insert("/a", &testValue{ID: "/a", Weight: 2, IsBranch: true}) tree.Insert("/a/p1", &testValue{ID: "/a/p1", Weight: 5}) tree.Insert("/a/p", &testValue{ID: "/a/p2", Weight: 6}) tree.Insert("/a/s1", &testValue{ID: "/a/s1", Weight: 5, IsBranch: true}) tree.Insert("/a/s1/p1", &testValue{ID: "/a/s1/p1", Weight: 8}) tree.Insert("/a/s1/p1", &testValue{ID: "/a/s1/p2", Weight: 9}) tree.Insert("/a/s1/s2", &testValue{ID: "/a/s1/s2", Weight: 6, IsBranch: true}) tree.Insert("/a/s1/s2/p1", &testValue{ID: "/a/s1/s2/p1", Weight: 8}) tree.Insert("/a/s1/s2/p2", &testValue{ID: "/a/s1/s2/p2", Weight: 7}) w := &doctree.NodeShiftTreeWalker[*testValue]{ Tree: tree, WalkContext: &doctree.WalkContext[*testValue]{}, } w.Handle = func(s string, t *testValue) (radix.WalkFlag, error) { if t.IsBranch { w.WalkContext.AddEventListener("weight", s, func(e *doctree.Event[*testValue]) { if e.Source.Weight > t.Weight { t.Weight = e.Source.Weight w.WalkContext.SendEvent(&doctree.Event[*testValue]{Source: t, Path: s, Name: "weight"}) } // Reduces the amount of events bubbling up the tree. If the weight for this branch has // increased, that will be announced in its own event. e.StopPropagation() }) } else { w.WalkContext.SendEvent(&doctree.Event[*testValue]{Source: t, Path: s, Name: "weight"}) } return radix.WalkContinue, nil } c.Assert(w.Walk(context.Background()), qt.IsNil) c.Assert(w.WalkContext.HandleEventsAndHooks(), qt.IsNil) c.Assert(tree.Get("/a").Weight, eq, 9) c.Assert(tree.Get("/a/s1").Weight, eq, 9) c.Assert(tree.Get("/a/p").Weight, eq, 6) c.Assert(tree.Get("/a/s1/s2").Weight, eq, 8) c.Assert(tree.Get("/a/s1/s2/p2").Weight, eq, 7) } func TestTreeInsert(t *testing.T) { c := qt.New(t) tree := doctree.New( doctree.Config[*testValue]{ Shifter: &testShifter{}, }, ) a := &testValue{ID: "/a"} tree.Insert("/a", a) ab := &testValue{ID: "/a/b"} tree.Insert("/a/b", ab) c.Assert(tree.Get("/a"), eq, &testValue{ID: "/a", Lang: 0}) c.Assert(tree.Get("/notfound"), qt.IsNil) ab2 := &testValue{ID: "/a/b", Lang: 0} v, _, ok := tree.Insert("/a/b", ab2) c.Assert(ok, qt.IsTrue) c.Assert(v, qt.DeepEquals, ab2) tree1 := tree.Shape(sitesmatrix.Vector{1, 0, 0}) c.Assert(tree1.Get("/a/b"), qt.DeepEquals, &testValue{ID: "/a/b", Lang: 1}) } func TestTreePara(t *testing.T) { c := qt.New(t) p := para.New(4) r, _ := p.Start(context.Background()) tree := doctree.New( doctree.Config[*testValue]{ Shifter: &testShifter{}, }, ) for i := range 8 { r.Run(func() error { a := &testValue{ID: "/a"} tree.Lock(true) defer tree.Unlock(true) tree.Insert("/a", a) ab := &testValue{ID: "/a/b"} tree.Insert("/a/b", ab) key := fmt.Sprintf("/a/b/c/%d", i) val := &testValue{ID: key} tree.Insert(key, val) c.Assert(tree.Get(key), eq, val) // s, _ := tree.LongestPrefix(key, nil) // c.Assert(s, eq, "/a/b") return nil }) } c.Assert(r.Wait(), qt.IsNil) } func TestValidateKey(t *testing.T) { c := qt.New(t) c.Assert(doctree.ValidateKey(""), qt.IsNil) c.Assert(doctree.ValidateKey("/a/b/c"), qt.IsNil) c.Assert(doctree.ValidateKey("/"), qt.IsNotNil) c.Assert(doctree.ValidateKey("a"), qt.IsNotNil) c.Assert(doctree.ValidateKey("abc"), qt.IsNotNil) c.Assert(doctree.ValidateKey("/abc/"), qt.IsNotNil) } type testShifter struct { echo bool } func (s *testShifter) ForEeachInDimension(n *testValue, v sitesmatrix.Vector, d int, f func(n *testValue) bool) { if d != sitesmatrix.Language { panic("not implemented") } f(n) } func (s *testShifter) ForEeachInAllDimensions(n *testValue, f func(*testValue) bool) { if n == nil { return } if !f(n) { return } for _, v := range s.All(n) { if v != n && !f(v) { return } } } func (s *testShifter) Insert(old, new *testValue) (*testValue, *testValue, bool) { return new, old, true } func (s *testShifter) Delete(n *testValue, dimension sitesmatrix.Vector) (*testValue, bool, bool) { return nil, true, true } func (s *testShifter) DeleteFunc(v *testValue, f func(*testValue) bool) bool { return f(v) } func (s *testShifter) Shift(n *testValue, dimension sitesmatrix.Vector, fallback bool) (v *testValue, ok bool) { ok = true v = n if s.echo { return } if n.NoCopy { if n.Lang == dimension[0] { return } v = nil ok = false return } c := *n c.Lang = dimension[0] v = &c return } func (s *testShifter) All(n *testValue) []*testValue { return []*testValue{n} } type testValue struct { ID string Lang int Weight int IsBranch bool NoCopy bool } func BenchmarkTreeInsert(b *testing.B) { runBench := func(b *testing.B, numElements int) { for b.Loop() { tree := doctree.New( doctree.Config[*testValue]{ Shifter: &testShifter{}, }, ) for i := range numElements { lang := rand.Intn(2) tree.Insert(fmt.Sprintf("/%d", i), &testValue{ID: fmt.Sprintf("/%d", i), Lang: lang, Weight: i, NoCopy: true}) } } } b.Run("1000", func(b *testing.B) { runBench(b, 1000) }) b.Run("10000", func(b *testing.B) { runBench(b, 10000) }) b.Run("100000", func(b *testing.B) { runBench(b, 100000) }) b.Run("300000", func(b *testing.B) { runBench(b, 300000) }) } func BenchmarkWalk(b *testing.B) { const numElements = 1000 createTree := func() *doctree.NodeShiftTree[*testValue] { tree := doctree.New( doctree.Config[*testValue]{ Shifter: &testShifter{}, }, ) for i := range numElements { lang := rand.Intn(2) tree.Insert(fmt.Sprintf("/%d", i), &testValue{ID: fmt.Sprintf("/%d", i), Lang: lang, Weight: i, NoCopy: true}) } return tree } handle := func(s string, t *testValue) (radix.WalkFlag, error) { return radix.WalkContinue, nil } for _, numElements := range []int{1000, 10000, 100000} { b.Run(fmt.Sprintf("Walk one dimension %d", numElements), func(b *testing.B) { tree := createTree() b.ResetTimer() for b.Loop() { w := &doctree.NodeShiftTreeWalker[*testValue]{ Tree: tree, Handle: handle, } if err := w.Walk(context.Background()); err != nil { b.Fatal(err) } } }) b.Run(fmt.Sprintf("Walk all dimensions %d", numElements), func(b *testing.B) { base := createTree() b.ResetTimer() for b.Loop() { for d1 := range 1 { for d2 := range 2 { tree := base.Shape(sitesmatrix.Vector{d1, d2, 0}) w := &doctree.NodeShiftTreeWalker[*testValue]{ Tree: tree, Handle: handle, } if err := w.Walk(context.Background()); err != nil { b.Fatal(err) } } } } }) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/doctree/treeshifttree.go
hugolib/doctree/treeshifttree.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package doctree import ( "iter" "github.com/gohugoio/hugo/hugolib/sitesmatrix" ) var _ TreeThreadSafe[string] = (*TreeShiftTreeSlice[string])(nil) type TreeShiftTreeSlice[T comparable] struct { // v points to a specific tree in the slice. v sitesmatrix.Vector // The zero value of T. zero T // trees is a 3D slice that holds all the trees. // Note that we have tested a version backed by a map, which is as fast to use, but is twice as epxensive/slow to create. trees [][][]*SimpleThreadSafeTree[T] } func NewTreeShiftTree[T comparable](v sitesmatrix.Vector) *TreeShiftTreeSlice[T] { trees := make([][][]*SimpleThreadSafeTree[T], v[0]) for i := 0; i < v[0]; i++ { trees[i] = make([][]*SimpleThreadSafeTree[T], v[1]) for j := 0; j < v[1]; j++ { trees[i][j] = make([]*SimpleThreadSafeTree[T], v[2]) for k := 0; k < v[2]; k++ { trees[i][j][k] = NewSimpleThreadSafeTree[T]() } } } return &TreeShiftTreeSlice[T]{trees: trees} } func (t TreeShiftTreeSlice[T]) Shape(v sitesmatrix.Vector) *TreeShiftTreeSlice[T] { t.v = v return &t } func (t *TreeShiftTreeSlice[T]) tree() *SimpleThreadSafeTree[T] { return t.trees[t.v[0]][t.v[1]][t.v[2]] } func (t *TreeShiftTreeSlice[T]) Get(s string) T { return t.tree().Get(s) } func (t *TreeShiftTreeSlice[T]) DeleteAllFunc(s string, f func(s string, v T) bool) { for tt := range t.Trees() { if v := tt.Get(s); v != t.zero { if f(s, v) { // Delete. tt.tree.Delete(s) } } } } func (t *TreeShiftTreeSlice[T]) Trees() iter.Seq[*SimpleThreadSafeTree[T]] { return func(yield func(v *SimpleThreadSafeTree[T]) bool) { for _, l1 := range t.trees { for _, l2 := range l1 { for _, l3 := range l2 { if !yield(l3) { return } } } } } } func (t *TreeShiftTreeSlice[T]) LongestPrefix(s string) (string, T) { return t.tree().LongestPrefix(s) } func (t *TreeShiftTreeSlice[T]) Insert(s string, v T) T { return t.tree().Insert(s, v) } func (t *TreeShiftTreeSlice[T]) Lock(lockType LockType) { t.tree().Lock(lockType) } func (t *TreeShiftTreeSlice[T]) Unlock(lockType LockType) { t.tree().Unlock(lockType) } func (t *TreeShiftTreeSlice[T]) WalkPrefix(lockType LockType, s string, f func(s string, v T) (bool, error)) error { return t.tree().WalkPrefix(lockType, s, f) } func (t *TreeShiftTreeSlice[T]) WalkPrefixRaw(lockType LockType, s string, f func(s string, v T) (bool, error)) error { for tt := range t.Trees() { if err := tt.WalkPrefix(lockType, s, f); err != nil { return err } } return nil } func (t *TreeShiftTreeSlice[T]) WalkPath(lockType LockType, s string, f func(s string, v T) (bool, error)) error { return t.tree().WalkPath(lockType, s, f) } func (t *TreeShiftTreeSlice[T]) All(lockType LockType) iter.Seq2[string, T] { return t.tree().All(lockType) } func (t *TreeShiftTreeSlice[T]) LenRaw() int { var count int for tt := range t.Trees() { count += tt.tree.Len() } return count } func (t *TreeShiftTreeSlice[T]) Delete(key string) { for tt := range t.Trees() { tt.tree.Delete(key) } } func (t *TreeShiftTreeSlice[T]) DeletePrefix(prefix string) int { var count int for tt := range t.Trees() { count += tt.tree.DeletePrefix(prefix) } return count }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/doctree/simpletree_test.go
hugolib/doctree/simpletree_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package doctree import ( "fmt" "testing" ) func BenchmarkSimpleThreadSafeTree(b *testing.B) { newTestTree := func() TreeThreadSafe[int] { t := NewSimpleThreadSafeTree[int]() for i := 0; i < 1000; i++ { t.Insert(fmt.Sprintf("key%d", i), i) } return t } b.Run("Get", func(b *testing.B) { t := newTestTree() b.ResetTimer() for b.Loop() { t.Get("key500") } }) b.Run("Insert", func(b *testing.B) { t := newTestTree() b.ResetTimer() for b.Loop() { t.Insert("key500", 501) } }) b.Run("LongestPrefix", func(b *testing.B) { t := newTestTree() b.ResetTimer() for b.Loop() { t.LongestPrefix("key500extra") } }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/doctree/simpletree.go
hugolib/doctree/simpletree.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package doctree import ( "iter" "sync" radix "github.com/gohugoio/go-radix" ) // Tree is a non thread safe radix tree that holds T. type Tree[T any] interface { TreeCommon[T] WalkPrefix(s string, f func(s string, v T) (bool, error)) error WalkPath(s string, f func(s string, v T) (bool, error)) error All() iter.Seq2[string, T] } // TreeThreadSafe is a thread safe radix tree that holds T. type TreeThreadSafe[T any] interface { TreeCommon[T] WalkPrefix(lockType LockType, s string, f func(s string, v T) (bool, error)) error WalkPath(lockType LockType, s string, f func(s string, v T) (bool, error)) error All(lockType LockType) iter.Seq2[string, T] } type TreeCommon[T any] interface { Get(s string) T LongestPrefix(s string) (string, T) Insert(s string, v T) T } func NewSimpleTree[T any]() *SimpleTree[T] { return &SimpleTree[T]{tree: radix.New[T]()} } // SimpleTree is a radix tree that holds T. // This tree is not thread safe. type SimpleTree[T any] struct { tree *radix.Tree[T] zero T } func (tree *SimpleTree[T]) Get(s string) T { v, _ := tree.tree.Get(s) return v } func (tree *SimpleTree[T]) LongestPrefix(s string) (string, T) { s, v, _ := tree.tree.LongestPrefix(s) return s, v } func (tree *SimpleTree[T]) Insert(s string, v T) T { tree.tree.Insert(s, v) return v } func (tree *SimpleTree[T]) Walk(f func(s string, v T) (bool, error)) error { var walkFn radix.WalkFn[T] = func(s string, v T) (radix.WalkFlag, T, error) { var b bool b, err := f(s, v) if b || err != nil { return radix.WalkStop, tree.zero, err } return radix.WalkContinue, tree.zero, nil } return tree.tree.Walk(walkFn) } func (tree *SimpleTree[T]) WalkPrefix(s string, f func(s string, v T) (bool, error)) error { var walkFn radix.WalkFn[T] = func(s string, v T) (radix.WalkFlag, T, error) { b, err := f(s, v) if b || err != nil { return radix.WalkStop, tree.zero, err } return radix.WalkContinue, tree.zero, nil } return tree.tree.WalkPrefix(s, walkFn) } func (tree *SimpleTree[T]) WalkPath(s string, f func(s string, v T) (bool, error)) error { var err error var walkFn radix.WalkFn[T] = func(s string, v T) (radix.WalkFlag, T, error) { var b bool b, err = f(s, v) if b || err != nil { return radix.WalkStop, tree.zero, err } return radix.WalkContinue, tree.zero, nil } tree.tree.WalkPath(s, walkFn) return err } func (tree *SimpleTree[T]) All() iter.Seq2[string, T] { return func(yield func(s string, v T) bool) { var walkFn radix.WalkFn[T] = func(s string, v T) (radix.WalkFlag, T, error) { if !yield(s, v) { return radix.WalkStop, tree.zero, nil } return radix.WalkContinue, tree.zero, nil } tree.tree.Walk(walkFn) } } func (tree *SimpleTree[T]) Len() int { return tree.tree.Len() } // NewSimpleThreadSafeTree creates a new SimpleTree. func NewSimpleThreadSafeTree[T any]() *SimpleThreadSafeTree[T] { return &SimpleThreadSafeTree[T]{tree: radix.New[T](), mu: new(sync.RWMutex)} } // SimpleThreadSafeTree is a thread safe radix tree that holds T. type SimpleThreadSafeTree[T any] struct { mu *sync.RWMutex tree *radix.Tree[T] zero T } func (tree *SimpleThreadSafeTree[T]) Get(s string) T { tree.mu.RLock() defer tree.mu.RUnlock() v, _ := tree.tree.Get(s) return v } func (tree *SimpleThreadSafeTree[T]) LongestPrefix(s string) (string, T) { tree.mu.RLock() defer tree.mu.RUnlock() s, v, _ := tree.tree.LongestPrefix(s) return s, v } func (tree *SimpleThreadSafeTree[T]) Insert(s string, v T) T { tree.mu.Lock() defer tree.mu.Unlock() tree.tree.Insert(s, v) return v } func (tree *SimpleThreadSafeTree[T]) Lock(lockType LockType) { switch lockType { case LockTypeRead: tree.mu.RLock() case LockTypeWrite: tree.mu.Lock() } } func (tree *SimpleThreadSafeTree[T]) Unlock(lockType LockType) { switch lockType { case LockTypeRead: tree.mu.RUnlock() case LockTypeWrite: tree.mu.Unlock() } } func (tree *SimpleThreadSafeTree[T]) WalkPrefix(lockType LockType, s string, f func(s string, v T) (bool, error)) error { tree.Lock(lockType) defer tree.Unlock(lockType) var walkFn radix.WalkFn[T] = func(s string, v T) (radix.WalkFlag, T, error) { var b bool b, err := f(s, v) if b || err != nil { return radix.WalkStop, tree.zero, err } return radix.WalkContinue, tree.zero, nil } return tree.tree.WalkPrefix(s, walkFn) } func (tree *SimpleThreadSafeTree[T]) WalkPath(lockType LockType, s string, f func(s string, v T) (bool, error)) error { tree.Lock(lockType) defer tree.Unlock(lockType) var err error var walkFn radix.WalkFn[T] = func(s string, v T) (radix.WalkFlag, T, error) { var b bool b, err = f(s, v) if b || err != nil { return radix.WalkStop, tree.zero, err } return radix.WalkContinue, tree.zero, nil } tree.tree.WalkPath(s, walkFn) return err } func (tree *SimpleThreadSafeTree[T]) All(lockType LockType) iter.Seq2[string, T] { return func(yield func(s string, v T) bool) { tree.Lock(lockType) defer tree.Unlock(lockType) var walkFn radix.WalkFn[T] = func(s string, v T) (radix.WalkFlag, T, error) { if !yield(s, v) { return radix.WalkStop, tree.zero, nil } return radix.WalkContinue, tree.zero, nil } tree.tree.Walk(walkFn) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/doctree/support.go
hugolib/doctree/support.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package doctree import ( "fmt" "iter" "strings" "sync" radix "github.com/gohugoio/go-radix" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/hugolib/sitesmatrix" ) var _ MutableTrees = MutableTrees{} const ( LockTypeNone LockType = iota LockTypeRead LockTypeWrite ) // AddEventListener adds an event listener to the tree. // Note that the handler func may not add listeners. func (ctx *WalkContext[T]) AddEventListener(event, path string, handler func(*Event[T])) { ctx.eventHandlersMu.Lock() defer ctx.eventHandlersMu.Unlock() if ctx.eventHandlers == nil { ctx.eventHandlers = make(eventHandlers[T]) } if ctx.eventHandlers[event] == nil { ctx.eventHandlers[event] = make([]func(*Event[T]), 0) } // We want to match all above the path, so we need to exclude any similar named siblings. if !strings.HasSuffix(path, "/") { path += "/" } ctx.eventHandlers[event] = append( ctx.eventHandlers[event], func(e *Event[T]) { // Propagate events up the tree only. if e.Path != path && strings.HasPrefix(e.Path, path) { handler(e) } }, ) } func (ctx *WalkContext[T]) Data() *SimpleThreadSafeTree[any] { ctx.dataInit.Do(func() { ctx.data = NewSimpleThreadSafeTree[any]() }) return ctx.data } func (ctx *WalkContext[T]) initDataRaw() { ctx.dataRawInit.Do(func() { ctx.dataRaw = maps.NewCache[sitesmatrix.Vector, *SimpleThreadSafeTree[any]]() }) } func (ctx *WalkContext[T]) DataRaw(vec sitesmatrix.Vector) *SimpleThreadSafeTree[any] { ctx.initDataRaw() v, _ := ctx.dataRaw.GetOrCreate(vec, func() (*SimpleThreadSafeTree[any], error) { return NewSimpleThreadSafeTree[any](), nil }) return v } func (ctx *WalkContext[T]) DataRawForEeach() iter.Seq2[sitesmatrix.Vector, *SimpleThreadSafeTree[any]] { ctx.initDataRaw() return func(yield func(vec sitesmatrix.Vector, data *SimpleThreadSafeTree[any]) bool) { ctx.dataRaw.ForEeach(func(vec sitesmatrix.Vector, data *SimpleThreadSafeTree[any]) bool { return yield(vec, data) }) } } // SendEvent sends an event up the tree. func (ctx *WalkContext[T]) SendEvent(event *Event[T]) { ctx.eventMu.Lock() defer ctx.eventMu.Unlock() ctx.events = append(ctx.events, event) } // StopPropagation stops the propagation of the event. func (e *Event[T]) StopPropagation() { e.stopPropagation = true } // ValidateKey returns an error if the key is not valid. func ValidateKey(key string) error { if key == "" { // Root node. return nil } if len(key) < 2 { return fmt.Errorf("too short key: %q", key) } if key[0] != '/' { return fmt.Errorf("key must start with '/': %q", key) } if key[len(key)-1] == '/' { return fmt.Errorf("key must not end with '/': %q", key) } return nil } // Event is used to communicate events in the tree. type Event[T any] struct { Name string Path string Source T stopPropagation bool } type LockType int // MutableTree is a tree that can be modified. type MutableTree interface { DeleteRaw(key string) DeletePrefix(prefix string) int DeletePrefixRaw(prefix string) int Lock(writable bool) Unlock(writable bool) CanLock() bool // Used for troubleshooting only. } // WalkableTree is a tree that can be walked. type WalkableTree[T any] interface { WalkPrefixRaw(prefix string, walker radix.WalkFn[T]) error } var _ WalkableTree[any] = (*WalkableTrees[any])(nil) type WalkableTrees[T any] []WalkableTree[T] func (t WalkableTrees[T]) WalkPrefixRaw(prefix string, walker radix.WalkFn[T]) error { for _, tree := range t { if err := tree.WalkPrefixRaw(prefix, walker); err != nil { return err } } return nil } var _ MutableTree = MutableTrees(nil) type MutableTrees []MutableTree func (t MutableTrees) DeleteRaw(key string) { for _, tree := range t { tree.DeleteRaw(key) } } func (t MutableTrees) DeletePrefix(prefix string) int { var count int for _, tree := range t { count += tree.DeletePrefix(prefix) } return count } func (t MutableTrees) DeletePrefixRaw(prefix string) int { var count int for _, tree := range t { count += tree.DeletePrefixRaw(prefix) } return count } func (t MutableTrees) Lock(writable bool) { for _, tree := range t { tree.Lock(writable) } } func (t MutableTrees) Unlock(writable bool) { for _, tree := range t { tree.Unlock(writable) } } func (t MutableTrees) CanLock() bool { for _, tree := range t { if !tree.CanLock() { return false } } return true } // WalkContext is passed to the Walk callback. type WalkContext[T any] struct { data *SimpleThreadSafeTree[any] dataInit sync.Once dataRaw *maps.Cache[sitesmatrix.Vector, *SimpleThreadSafeTree[any]] dataRawInit sync.Once eventHandlersMu sync.Mutex eventHandlers eventHandlers[T] eventMu sync.Mutex events []*Event[T] hooksPostInit sync.Once hooksPost *collections.StackThreadSafe[func() error] } type eventHandlers[T any] map[string][]func(*Event[T]) func cleanKey(key string) string { if key == "/" { // The path to the home page is logically "/", // but for technical reasons, it's stored as "". // This allows us to treat the home page as a section, // and a prefix search for "/" will return the home page's descendants. return "" } return key } func (ctx *WalkContext[T]) HandleEvents() error { ctx.eventHandlersMu.Lock() defer ctx.eventHandlersMu.Unlock() for len(ctx.events) > 0 { event := ctx.events[0] ctx.events = ctx.events[1:] // Loop the event handlers in reverse order so // that events created by the handlers themselves will // be picked up further up the tree. for i := len(ctx.eventHandlers[event.Name]) - 1; i >= 0; i-- { ctx.eventHandlers[event.Name][i](event) if event.stopPropagation { break } } } return nil } func (ctx *WalkContext[T]) HooksPost() *collections.StackThreadSafe[func() error] { ctx.hooksPostInit.Do(func() { ctx.hooksPost = collections.NewStackThreadSafe[func() error]() }) return ctx.hooksPost } func (ctx *WalkContext[T]) HandleEventsAndHooks() error { if err := ctx.HandleEvents(); err != nil { return err } for _, hook := range ctx.HooksPost().All() { if err := hook(); err != nil { return err } } return nil } func mustValidateKey(key string) string { if err := ValidateKey(key); err != nil { panic(err) } return key }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/doctree/treeshifttree_test.go
hugolib/doctree/treeshifttree_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package doctree_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib/doctree" "github.com/gohugoio/hugo/hugolib/sitesmatrix" ) func TestTreeShiftTree(t *testing.T) { c := qt.New(t) tree := doctree.NewTreeShiftTree[string](sitesmatrix.Vector{10, 1, 1}) c.Assert(tree, qt.IsNotNil) } func BenchmarkTreeShiftTreeSlice(b *testing.B) { v := sitesmatrix.Vector{10, 10, 10} t := doctree.NewTreeShiftTree[string](v) b.Run("New", func(b *testing.B) { for b.Loop() { for l1 := 0; l1 < v[0]; l1++ { for l2 := 0; l2 < v[1]; l2++ { for l3 := 0; l3 < v[2]; l3++ { _ = doctree.NewTreeShiftTree[string](sitesmatrix.Vector{l1, l2, l3}) } } } } }) b.Run("Shape", func(b *testing.B) { for b.Loop() { for l1 := 0; l1 < v[0]; l1++ { for l2 := 0; l2 < v[1]; l2++ { for l3 := 0; l3 < v[2]; l3++ { t.Shape(sitesmatrix.Vector{l1, l2, l3}) } } } } }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/roles/roles_integration_test.go
hugolib/roles/roles_integration_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package roles_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestRolesAndVersions(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org/" defaultContentVersion = "v4.0.0" defaultContentVersionInSubdir = true defaultContentRoleInSubdir = true defaultContentRole = "guest" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true disableKinds = ["taxonomy", "term", "rss", "sitemap"] [cascade.sites.matrix] versions = ["v2**"] [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [roles] [roles.guest] weight = 300 [roles.member] weight = 200 [versions] [versions."v2.0.0"] [versions."v1.2.3"] [versions."v2.1.0"] [versions."v3.0.0"] [versions."v4.0.0"] -- content/memberonlypost.md -- --- title: "Member Only" sites: matrix: languages: "**" roles: member versions: "v4.0.0" --- Member content. -- content/publicpost.md -- --- title: "Public" sites: matrix: versions: ["v1.2.3", "v2.**", "! v2.1.*"] complements: versions: "v3**" --- Users with guest role will see this. -- content/v3publicpost.md -- --- title: "Public v3" sites: matrix: versions: "v3**" --- Users with guest role will see this. -- layouts/all.html -- Role: {{ .Site.Role.Name }}|Version: {{ .Site.Version.Name }}|Lang: {{ .Site.Language.Lang }}| RegularPages: {{ range .RegularPages }}{{ .RelPermalink }} r: {{ .Site.Language.Name }} v: {{ .Site.Version.Name }} l: {{ .Site.Role.Name }}|{{ end }}$ ` for range 3 { b := hugolib.Test(t, files) b.AssertPublishDir( "guest/v1.2.3/en/publicpost", "guest/v2.0.0/en/publicpost", "! guest/v2.1.0/en/publicpost", "member/v4.0.0/en/memberonlypost", "member/v4.0.0/nn/memberonlypost", ) b.AssertFileContent("public/guest/v2.0.0/en/index.html", "Role: guest|Version: v2.0.0|", ) b.AssertFileContent("public/guest/v3.0.0/en/index.html", "egularPages: /guest/v2.0.0/en/publicpost/ r: en v: v2.0.0 l: guest|/guest/v3.0.0/en/v3publicpost/ r: en v: v3.0.0 l: guest|$") } } func TestDefaultContentRoleDoesNotExist(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true defaultContentRole = "doesnotexist" [roles] [roles.guest] weight = 300 [roles.member] weight = 200 ` b, err := hugolib.TestE(t, files) b.Assert(err, qt.ErrorMatches, `.*failed to decode "roles": the configured defaultContentRole "doesnotexist" does not exist`) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/roles/roles.go
hugolib/roles/roles.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package roles import ( "errors" "fmt" "iter" "sort" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/predicate" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/mitchellh/mapstructure" ) var _ sitesmatrix.DimensionInfo = (*roleWrapper)(nil) type RoleConfig struct { // The weight of the role. // Used to determine the order of the roles. // If zero, we use the role name. Weight int } type Role interface { Name() string } type Roles []Role var _ Role = (*roleWrapper)(nil) func NewRole(r RoleInternal) Role { return roleWrapper{r: r} } type roleWrapper struct { r RoleInternal } func (r roleWrapper) Name() string { return r.r.Name } func (r roleWrapper) IsDefault() bool { return r.r.Default } type RoleInternal struct { // Name is the name of the role, extracted from the key in the config. Name string // Whether this role is the default role. // This will be rendered in the root. // There is only be one default role. Default bool RoleConfig } type RolesInternal struct { roleConfigs map[string]RoleConfig Sorted []RoleInternal } func (r RolesInternal) Len() int { return len(r.Sorted) } func (r RolesInternal) IndexDefault() int { for i, role := range r.Sorted { if role.Default { return i } } panic("no default role found") } func (r RolesInternal) ResolveName(i int) string { if i < 0 || i >= len(r.Sorted) { panic(fmt.Sprintf("index %d out of range for roles", i)) } return r.Sorted[i].Name } func (r RolesInternal) ResolveIndex(name string) int { for i, role := range r.Sorted { if role.Name == name { return i } } panic(fmt.Sprintf("no role found for name %q", name)) } // IndexMatch returns an iterator for the roles that match the filter. func (r RolesInternal) IndexMatch(match predicate.P[string]) (iter.Seq[int], error) { return func(yield func(i int) bool) { for i, role := range r.Sorted { if match(role.Name) { if !yield(i) { return } } } }, nil } // ForEachIndex returns an iterator for the indices of the roles. func (r RolesInternal) ForEachIndex() iter.Seq[int] { return func(yield func(i int) bool) { for i := range r.Sorted { if !yield(i) { return } } } } const defaultContentRoleFallback = "guest" func (r *RolesInternal) init(defaultContentRole string) (string, error) { if r.roleConfigs == nil { r.roleConfigs = make(map[string]RoleConfig) } defaultContentRoleProvided := defaultContentRole != "" if len(r.roleConfigs) == 0 { // Add a default role. if defaultContentRole == "" { defaultContentRole = defaultContentRoleFallback } r.roleConfigs[defaultContentRole] = RoleConfig{} } var defaultSeen bool for k, v := range r.roleConfigs { if k == "" { return "", errors.New("role name cannot be empty") } if err := paths.ValidateIdentifier(k); err != nil { return "", fmt.Errorf("role name %q is invalid: %s", k, err) } var isDefault bool if k == defaultContentRole { isDefault = true defaultSeen = true } r.Sorted = append(r.Sorted, RoleInternal{Name: k, Default: isDefault, RoleConfig: v}) } // Sort by weight if set, then by name. sort.SliceStable(r.Sorted, func(i, j int) bool { ri, rj := r.Sorted[i], r.Sorted[j] if ri.Weight == rj.Weight { return ri.Name < rj.Name } if rj.Weight == 0 { return true } if ri.Weight == 0 { return false } return ri.Weight < rj.Weight }) if !defaultSeen { if defaultContentRoleProvided { return "", fmt.Errorf("the configured defaultContentRole %q does not exist", defaultContentRole) } // If no default role is set, we set the first one. first := r.Sorted[0] first.Default = true r.roleConfigs[first.Name] = first.RoleConfig r.Sorted[0] = first defaultContentRole = first.Name } return defaultContentRole, nil } func (r RolesInternal) Has(role string) bool { _, found := r.roleConfigs[role] return found } func DecodeConfig(defaultContentRole string, m map[string]any) (*config.ConfigNamespace[map[string]RoleConfig, RolesInternal], string, error) { v, err := config.DecodeNamespace[map[string]RoleConfig](m, func(in any) (RolesInternal, any, error) { var roles RolesInternal var conf map[string]RoleConfig if err := mapstructure.Decode(m, &conf); err != nil { return roles, nil, err } roles.roleConfigs = conf var err error if defaultContentRole, err = roles.init(defaultContentRole); err != nil { return roles, nil, err } return roles, roles.roleConfigs, nil }) return v, defaultContentRole, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/pagesfromdata/pagesfromgotmpl.go
hugolib/pagesfromdata/pagesfromgotmpl.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pagesfromdata import ( "context" "fmt" "io" "path/filepath" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/hstore" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/tpl/tplimpl" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" ) type PagesFromDataTemplateContext interface { // AddPage adds a new page to the site. // The first return value will always be an empty string. AddPage(any) (string, error) // AddResource adds a new resource to the site. // The first return value will always be an empty string. AddResource(any) (string, error) // The site to which the pages will be added. Site() page.Site // The same template may be executed multiple times for multiple languages. // The Store can be used to store state between these invocations. Store() *hstore.Scratch // By default, the template will be executed for the language // defined by the _content.gotmpl file (e.g. its mount definition). // This method can be used to activate the template for all languages. // The return value will always be an empty string. EnableAllLanguages() string } var _ PagesFromDataTemplateContext = (*pagesFromDataTemplateContext)(nil) type pagesFromDataTemplateContext struct { p *PagesFromTemplate } func (p *pagesFromDataTemplateContext) toPathSitesMap(v any) (string, map[string]any, map[string]any, error) { m, err := maps.ToStringMapE(v) if err != nil { return "", nil, nil, err } path, err := cast.ToStringE(m["path"]) if err != nil { return "", nil, nil, fmt.Errorf("invalid path %q", path) } sites := maps.ToStringMap(m["sites"]) return path, sites, m, nil } func (p *pagesFromDataTemplateContext) AddPage(v any) (string, error) { path, sites, m, err := p.toPathSitesMap(v) if err != nil { return "", err } hash, hasChanged := p.p.buildState.checkHasChangedAndSetSourceInfo(path, sites, m) if !hasChanged { return "", nil } pe := &pagemeta.PageConfigEarly{ IsFromContentAdapter: true, Frontmatter: m, SourceEntryHash: hash, } // The rest will be handled after the cascade is calculated and applied. if err := mapstructure.WeakDecode(pe.Frontmatter, pe); err != nil { err = fmt.Errorf("failed to decode page map: %w", err) return "", err } if err := pe.Init(true); err != nil { return "", err } p.p.buildState.NumPagesAdded++ return "", p.p.HandlePage(p.p, pe) } func (p *pagesFromDataTemplateContext) AddResource(v any) (string, error) { path, sites, m, err := p.toPathSitesMap(v) if err != nil { return "", err } hash, hasChanged := p.p.buildState.checkHasChangedAndSetSourceInfo(path, sites, m) if !hasChanged { return "", nil } var rd pagemeta.ResourceConfig if err := mapstructure.WeakDecode(m, &rd); err != nil { return "", err } rd.ContentAdapterSourceEntryHash = hash p.p.buildState.NumResourcesAdded++ if err := rd.Validate(); err != nil { return "", err } return "", p.p.HandleResource(p.p, &rd) } func (p *pagesFromDataTemplateContext) Site() page.Site { return p.p.Site } func (p *pagesFromDataTemplateContext) Store() *hstore.Scratch { return p.p.store } func (p *pagesFromDataTemplateContext) EnableAllLanguages() string { p.p.buildState.EnableAllLanguages = true return "" } func (p *pagesFromDataTemplateContext) EnableAllDimensions() string { p.p.buildState.EnableAllDimensions = true return "" } func NewPagesFromTemplate(opts PagesFromTemplateOptions) *PagesFromTemplate { return &PagesFromTemplate{ PagesFromTemplateOptions: opts, PagesFromTemplateDeps: opts.DepsFromSite(opts.Site), buildState: &BuildState{ sourceInfosCurrent: maps.NewCache[string, *sourceInfo](), }, store: hstore.NewScratch(), } } type PagesFromTemplateOptions struct { Site page.Site DepsFromSite func(page.Site) PagesFromTemplateDeps DependencyManager identity.Manager Watching bool HandlePage func(pt *PagesFromTemplate, p *pagemeta.PageConfigEarly) error HandleResource func(pt *PagesFromTemplate, p *pagemeta.ResourceConfig) error GoTmplFi hugofs.FileMetaInfo } type PagesFromTemplateDeps struct { TemplateStore *tplimpl.TemplateStore } var _ resource.Staler = (*PagesFromTemplate)(nil) type PagesFromTemplate struct { PagesFromTemplateOptions PagesFromTemplateDeps buildState *BuildState store *hstore.Scratch } func (b *PagesFromTemplate) AddChange(id identity.Identity) { b.buildState.ChangedIdentities = append(b.buildState.ChangedIdentities, id) } func (b *PagesFromTemplate) MarkStale() { b.buildState.StaleVersion++ } func (b *PagesFromTemplate) StaleVersion() uint32 { return b.buildState.StaleVersion } type BuildInfo struct { NumPagesAdded uint64 NumResourcesAdded uint64 EnableAllLanguages bool EnableAllDimensions bool ChangedIdentities []identity.Identity DeletedPaths []PathHashes Path *paths.Path } type BuildState struct { StaleVersion uint32 EnableAllLanguages bool EnableAllDimensions bool // PathHashes deleted in the current build. DeletedPaths []PathHashes // Changed identities in the current build. ChangedIdentities []identity.Identity NumPagesAdded uint64 NumResourcesAdded uint64 sourceInfosCurrent *maps.Cache[string, *sourceInfo] sourceInfosPrevious *maps.Cache[string, *sourceInfo] } func (b *BuildState) hash(v any) uint64 { return hashing.HashUint64(v) } type sourceInfo struct { siteHashes map[uint64]uint64 } func (b *BuildState) checkHasChangedAndSetSourceInfo(changedPath string, sites map[string]any, v any) (uint64, bool) { hv := b.hash(v) hsites := b.hash(sites) si, _ := b.sourceInfosCurrent.GetOrCreate(changedPath, func() (*sourceInfo, error) { return &sourceInfo{ siteHashes: make(map[uint64]uint64), }, nil }) if h, found := si.siteHashes[hsites]; found && h == hv { return hv, false } if psi, found := b.sourceInfosPrevious.Get(changedPath); found { if h, found := psi.siteHashes[hsites]; found && h == hv { // Not changed. si.siteHashes[hsites] = hv return hv, false } } // It has changed. si.siteHashes[hsites] = hv return hv, true } type PathHashes struct { Path string Hashes map[uint64]struct{} } func (b *BuildState) resolveDeletedPaths() { if b.sourceInfosPrevious == nil { b.DeletedPaths = nil return } var pathsHashes []PathHashes b.sourceInfosPrevious.ForEeach(func(k string, pv *sourceInfo) bool { if cv, found := b.sourceInfosCurrent.Get(k); !found { pathsHashes = append(pathsHashes, PathHashes{Path: k, Hashes: map[uint64]struct{}{}}) } else { deleted := map[uint64]struct{}{} for k, ph := range pv.siteHashes { ch, found := cv.siteHashes[k] if !found || ch != ph { deleted[ph] = struct{}{} } } if len(deleted) > 0 { pathsHashes = append(pathsHashes, PathHashes{Path: k, Hashes: deleted}) } } return true }) b.DeletedPaths = pathsHashes } func (b *BuildState) PrepareNextBuild() { b.sourceInfosPrevious = b.sourceInfosCurrent b.sourceInfosCurrent = maps.NewCache[string, *sourceInfo]() b.StaleVersion = 0 b.DeletedPaths = nil b.ChangedIdentities = nil b.NumPagesAdded = 0 b.NumResourcesAdded = 0 } func (p PagesFromTemplate) CloneForSite(s page.Site) *PagesFromTemplate { // We deliberately make them share the same DependencyManager and Store. p.PagesFromTemplateOptions.Site = s p.PagesFromTemplateDeps = p.PagesFromTemplateOptions.DepsFromSite(s) p.buildState = &BuildState{ sourceInfosCurrent: maps.NewCache[string, *sourceInfo](), } return &p } func (p PagesFromTemplate) CloneForGoTmpl(fi hugofs.FileMetaInfo) *PagesFromTemplate { p.PagesFromTemplateOptions.GoTmplFi = fi return &p } func (p *PagesFromTemplate) GetDependencyManagerForScope(scope int) identity.Manager { return p.DependencyManager } func (p *PagesFromTemplate) GetDependencyManagerForScopesAll() []identity.Manager { return []identity.Manager{p.DependencyManager} } func (p *PagesFromTemplate) Execute(ctx context.Context) (BuildInfo, error) { defer func() { p.buildState.PrepareNextBuild() }() f, err := p.GoTmplFi.Meta().Open() if err != nil { return BuildInfo{}, err } defer f.Close() tmpl, err := p.TemplateStore.TextParse(filepath.ToSlash(p.GoTmplFi.Meta().Filename), helpers.ReaderToString(f)) if err != nil { return BuildInfo{}, err } data := &pagesFromDataTemplateContext{ p: p, } ctx = tpl.Context.DependencyManagerScopedProvider.Set(ctx, p) if err := p.TemplateStore.ExecuteWithContext(ctx, tmpl, io.Discard, data); err != nil { return BuildInfo{}, err } if p.Watching { p.buildState.resolveDeletedPaths() } bi := BuildInfo{ NumPagesAdded: p.buildState.NumPagesAdded, NumResourcesAdded: p.buildState.NumResourcesAdded, EnableAllLanguages: p.buildState.EnableAllLanguages, EnableAllDimensions: p.buildState.EnableAllDimensions, ChangedIdentities: p.buildState.ChangedIdentities, DeletedPaths: p.buildState.DeletedPaths, Path: p.GoTmplFi.Meta().PathInfo, } return bi, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/pagesfromdata/pagesfromgotmpl_integration_test.go
hugolib/pagesfromdata/pagesfromgotmpl_integration_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pagesfromdata_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/markup/asciidocext" "github.com/gohugoio/hugo/markup/pandoc" "github.com/gohugoio/hugo/markup/rst" "github.com/gohugoio/hugo/related" ) const filesPagesFromDataTempleBasic = ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" disableLiveReload = true -- assets/a/pixel.png -- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg== -- assets/mydata.yaml -- p1: "p1" draft: false -- layouts/_partials/get-value.html -- {{ $val := "p1" }} {{ return $val }} -- layouts/baseof.html -- Baseof: {{ block "main" . }}{{ end }} -- layouts/single.html -- {{ define "main" }} Single: {{ .Title }}|{{ .Content }}|Params: {{ .Params.param1 }}|Path: {{ .Path }}| Dates: Date: {{ .Date.Format "2006-01-02" }}|Lastmod: {{ .Lastmod.Format "2006-01-02" }}|PublishDate: {{ .PublishDate.Format "2006-01-02" }}|ExpiryDate: {{ .ExpiryDate.Format "2006-01-02" }}| Len Resources: {{ .Resources | len }} Resources: {{ range .Resources }}RelPermalink: {{ .RelPermalink }}|Name: {{ .Name }}|Title: {{ .Title }}|Params: {{ .Params }}|{{ end }}$ {{ with .Resources.Get "featured.png" }} Featured Image: {{ .RelPermalink }}|{{ .Name }}| {{ with .Resize "10x10" }} Resized Featured Image: {{ .RelPermalink }}|{{ .Width }}| {{ end}} {{ end }} {{ end }} -- layouts/list.html -- List: {{ .Title }}|{{ .Content }}| RegularPagesRecursive: {{ range .RegularPagesRecursive }}{{ .Title }}:{{ .Path }}|{{ end }}$ Sections: {{ range .Sections }}{{ .Title }}:{{ .Path }}|{{ end }}$ -- content/docs/pfile.md -- --- title: "pfile" date: 2023-03-01 --- Pfile Content -- content/docs/_content.gotmpl -- {{ $pixel := resources.Get "a/pixel.png" }} {{ $dataResource := resources.Get "mydata.yaml" }} {{ $data := $dataResource | transform.Unmarshal }} {{ $pd := $data.p1 }} {{ $pp := partial "get-value.html" }} {{ $title := printf "%s:%s" $pd $pp }} {{ $date := "2023-03-01" | time.AsTime }} {{ $dates := dict "date" $date }} {{ $keywords := slice "foo" "Bar"}} {{ $contentMarkdown := dict "value" "**Hello World**" "mediaType" "text/markdown" }} {{ $contentMarkdownDefault := dict "value" "**Hello World Default**" }} {{ $contentHTML := dict "value" "<b>Hello World!</b> No **markdown** here." "mediaType" "text/html" }} {{ $.AddPage (dict "kind" "page" "path" "P1" "title" $title "dates" $dates "keywords" $keywords "content" $contentMarkdown "params" (dict "param1" "param1v" ) ) }} {{ $.AddPage (dict "kind" "page" "path" "p2" "title" "p2title" "dates" $dates "content" $contentHTML ) }} {{ $.AddPage (dict "kind" "page" "path" "p3" "title" "p3title" "dates" $dates "content" $contentMarkdownDefault "draft" false ) }} {{ $.AddPage (dict "kind" "page" "path" "p4" "title" "p4title" "dates" $dates "content" $contentMarkdownDefault "draft" $data.draft ) }} ADD_MORE_PLACEHOLDER {{ $resourceContent := dict "value" $dataResource }} {{ $.AddResource (dict "path" "p1/data1.yaml" "content" $resourceContent) }} {{ $.AddResource (dict "path" "p1/mytext.txt" "content" (dict "value" "some text") "name" "textresource" "title" "My Text Resource" "params" (dict "param1" "param1v") )}} {{ $.AddResource (dict "path" "p1/sub/mytex2.txt" "content" (dict "value" "some text") "title" "My Text Sub Resource" ) }} {{ $.AddResource (dict "path" "P1/Sub/MyMixCaseText2.txt" "content" (dict "value" "some text") "title" "My Text Sub Mixed Case Path Resource" ) }} {{ $.AddResource (dict "path" "p1/sub/data1.yaml" "content" $resourceContent "title" "Sub data") }} {{ $resourceParams := dict "data2ParaM1" "data2Param1v" }} {{ $.AddResource (dict "path" "p1/data2.yaml" "name" "data2.yaml" "title" "My data 2" "params" $resourceParams "content" $resourceContent) }} {{ $.AddResource (dict "path" "p1/featuredimage.png" "name" "featured.png" "title" "My Featured Image" "params" $resourceParams "content" (dict "value" $pixel ))}} ` func TestPagesFromGoTmplMisc(t *testing.T) { t.Parallel() b := hugolib.Test(t, filesPagesFromDataTempleBasic, hugolib.TestOptWarn()) b.AssertLogContains("! WARN") b.AssertPublishDir(` docs/p1/mytext.txt docs/p1/sub/mytex2.tx docs/p1/sub/mymixcasetext2.txt `) // Page from markdown file. b.AssertFileContent("public/docs/pfile/index.html", "Dates: Date: 2023-03-01|Lastmod: 2023-03-01|PublishDate: 2023-03-01|ExpiryDate: 0001-01-01|") // Pages from gotmpl. b.AssertFileContent("public/docs/p1/index.html", "Single: p1:p1|", "Path: /docs/p1|", "<strong>Hello World</strong>", "Params: param1v|", "Len Resources: 7", "RelPermalink: /mydata.yaml|Name: data1.yaml|Title: data1.yaml|Params: map[]|", "RelPermalink: /mydata.yaml|Name: data2.yaml|Title: My data 2|Params: map[data2param1:data2Param1v]|", "RelPermalink: /a/pixel.png|Name: featured.png|Title: My Featured Image|Params: map[data2param1:data2Param1v]|", "RelPermalink: /docs/p1/sub/mytex2.txt|Name: sub/mytex2.txt|", "RelPermalink: /docs/p1/sub/mymixcasetext2.txt|Name: sub/mymixcasetext2.txt|", "RelPermalink: /mydata.yaml|Name: sub/data1.yaml|Title: Sub data|Params: map[]|", "Featured Image: /a/pixel.png|featured.png|", "Resized Featured Image: /a/pixel_hu_a354833fd576551d.png|10|", // Resource from string "RelPermalink: /docs/p1/mytext.txt|Name: textresource|Title: My Text Resource|Params: map[param1:param1v]|", // Dates "Dates: Date: 2023-03-01|Lastmod: 2023-03-01|PublishDate: 2023-03-01|ExpiryDate: 0001-01-01|", ) b.AssertFileContent("public/docs/p2/index.html", "Single: p2title|", "<b>Hello World!</b> No **markdown** here.") b.AssertFileContent("public/docs/p3/index.html", "<strong>Hello World Default</strong>") } func TestPagesFromGoTmplAsciiDocAndSimilar(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" [security] [security.exec] allow = ['asciidoctor', 'pandoc','rst2html', 'python'] -- layouts/single.html -- |Content: {{ .Content }}|Title: {{ .Title }}|Path: {{ .Path }}| -- content/docs/_content.gotmpl -- {{ $.AddPage (dict "path" "asciidoc" "content" (dict "value" "Mark my words, #automation is essential#." "mediaType" "text/asciidoc" )) }} {{ $.AddPage (dict "path" "pandoc" "content" (dict "value" "This ~~is deleted text.~~" "mediaType" "text/pandoc" )) }} {{ $.AddPage (dict "path" "rst" "content" (dict "value" "This is *bold*." "mediaType" "text/rst" )) }} {{ $.AddPage (dict "path" "org" "content" (dict "value" "the ability to use +strikethrough+ is a plus" "mediaType" "text/org" )) }} {{ $.AddPage (dict "path" "nocontent" "title" "No Content" ) }} ` b := hugolib.Test(t, files) if ok, _ := asciidocext.Supports(); ok { b.AssertFileContent("public/docs/asciidoc/index.html", "Mark my words, <mark>automation is essential</mark>", "Path: /docs/asciidoc|", ) } if pandoc.Supports() { b.AssertFileContent("public/docs/pandoc/index.html", "This <del>is deleted text.</del>", "Path: /docs/pandoc|", ) } if rst.Supports() { b.AssertFileContent("public/docs/rst/index.html", "This is <em>bold</em>", "Path: /docs/rst|", ) } b.AssertFileContent("public/docs/org/index.html", "the ability to use <del>strikethrough</del> is a plus", "Path: /docs/org|", ) b.AssertFileContent("public/docs/nocontent/index.html", "|Content: |Title: No Content|Path: /docs/nocontent|") } func TestPagesFromGoTmplAddPageErrors(t *testing.T) { filesTemplate := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" -- content/docs/_content.gotmpl -- {{ $.AddPage DICT }} ` t.Run("AddPage, missing Path", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "DICT", `(dict "kind" "page" "title" "p1")`) b, err := hugolib.TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "_content.gotmpl:1:4") b.Assert(err.Error(), qt.Contains, "error calling AddPage: empty path is reserved for the home page") }) t.Run("Site methods not ready", func(t *testing.T) { filesTemplate := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" -- content/docs/_content.gotmpl -- {{ .Site.METHOD }} ` for _, method := range []string{"RegularPages", "Pages", "AllPages", "AllRegularPages", "Home", "Sections", "GetPage", "Menus", "MainSections", "Taxonomies"} { t.Run(method, func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "METHOD", method) b, err := hugolib.TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, fmt.Sprintf("error calling %s: this method cannot be called before the site is fully initialized", method)) }) } }) } func TestPagesFromGoTmplEditGoTmpl(t *testing.T) { t.Parallel() b := hugolib.TestRunning(t, filesPagesFromDataTempleBasic) b.EditFileReplaceAll("content/docs/_content.gotmpl", `"title" "p2title"`, `"title" "p2titleedited"`).Build() b.AssertFileContent("public/docs/p2/index.html", "Single: p2titleedited|") b.AssertFileContent("public/docs/index.html", "p2titleedited") } func TestPagesFromGoTmplEditDataResource(t *testing.T) { t.Parallel() b := hugolib.TestRunning(t, filesPagesFromDataTempleBasic) b.AssertRenderCountPage(7) b.EditFileReplaceAll("assets/mydata.yaml", "p1: \"p1\"", "p1: \"p1edited\"").Build() b.AssertFileContent("public/docs/p1/index.html", "Single: p1edited:p1|") b.AssertFileContent("public/docs/index.html", "p1edited") b.AssertRenderCountPage(3) } func TestPagesFromGoTmplEditPartial(t *testing.T) { t.Parallel() b := hugolib.TestRunning(t, filesPagesFromDataTempleBasic) b.EditFileReplaceAll("layouts/_partials/get-value.html", "p1", "p1edited").Build() b.AssertFileContent("public/docs/p1/index.html", "Single: p1:p1edited|") b.AssertFileContent("public/docs/index.html", "p1edited") } func TestPagesFromGoTmplRemovePage(t *testing.T) { t.Parallel() b := hugolib.TestRunning(t, filesPagesFromDataTempleBasic) b.EditFileReplaceAll("content/docs/_content.gotmpl", `{{ $.AddPage (dict "kind" "page" "path" "p2" "title" "p2title" "dates" $dates "content" $contentHTML ) }}`, "").Build() b.AssertFileContent("public/index.html", "RegularPagesRecursive: p1:p1:/docs/p1|p3title:/docs/p3|p4title:/docs/p4|pfile:/docs/pfile|$") } func TestPagesFromGoTmplAddPage(t *testing.T) { t.Parallel() b := hugolib.TestRunning(t, filesPagesFromDataTempleBasic) b.EditFileReplaceAll("content/docs/_content.gotmpl", "ADD_MORE_PLACEHOLDER", `{{ $.AddPage (dict "kind" "page" "path" "page_added" "title" "page_added_title" "dates" $dates "content" $contentHTML ) }}`).Build() b.AssertFileExists("public/docs/page_added/index.html", true) b.AssertFileContent("public/index.html", "RegularPagesRecursive: p1:p1:/docs/p1|p2title:/docs/p2|p3title:/docs/p3|p4title:/docs/p4|page_added_title:/docs/page_added|pfile:/docs/pfile|$") } func TestPagesFromGoTmplDraftPage(t *testing.T) { t.Parallel() b := hugolib.TestRunning(t, filesPagesFromDataTempleBasic) b.EditFileReplaceAll("content/docs/_content.gotmpl", `"draft" false`, `"draft" true`).Build() b.AssertFileContent("public/index.html", "RegularPagesRecursive: p1:p1:/docs/p1|p2title:/docs/p2|p4title:/docs/p4|pfile:/docs/pfile|$") } func TestPagesFromGoTmplDraftFlagFromResource(t *testing.T) { t.Parallel() b := hugolib.TestRunning(t, filesPagesFromDataTempleBasic) b.EditFileReplaceAll("assets/mydata.yaml", `draft: false`, `draft: true`).Build() b.AssertFileContent("public/index.html", "RegularPagesRecursive: p1:p1:/docs/p1|p2title:/docs/p2|p3title:/docs/p3|pfile:/docs/pfile|$") b.EditFileReplaceAll("assets/mydata.yaml", `draft: true`, `draft: false`).Build() b.AssertFileContent("public/index.html", "RegularPagesRecursive: p1:p1:/docs/p1|p2title:/docs/p2|p3title:/docs/p3|p4title:/docs/p4|pfile:/docs/pfile|$") } func TestPagesFromGoTmplMovePage(t *testing.T) { t.Parallel() b := hugolib.TestRunning(t, filesPagesFromDataTempleBasic) b.AssertFileContent("public/index.html", "RegularPagesRecursive: p1:p1:/docs/p1|p2title:/docs/p2|p3title:/docs/p3|p4title:/docs/p4|pfile:/docs/pfile|$") b.EditFileReplaceAll("content/docs/_content.gotmpl", `"path" "p2"`, `"path" "p2moved"`).Build() b.AssertFileContent("public/index.html", "RegularPagesRecursive: p1:p1:/docs/p1|p2title:/docs/p2moved|p3title:/docs/p3|p4title:/docs/p4|pfile:/docs/pfile|$") } func TestPagesFromGoTmplRemoveGoTmpl(t *testing.T) { t.Parallel() b := hugolib.TestRunning(t, filesPagesFromDataTempleBasic) b.AssertFileContent("public/index.html", "RegularPagesRecursive: p1:p1:/docs/p1|p2title:/docs/p2|p3title:/docs/p3|p4title:/docs/p4|pfile:/docs/pfile|$", "Sections: Docs:/docs|", ) b.AssertFileContent("public/docs/index.html", "RegularPagesRecursive: p1:p1:/docs/p1|p2title:/docs/p2|p3title:/docs/p3|p4title:/docs/p4|pfile:/docs/pfile|$") b.RemoveFiles("content/docs/_content.gotmpl").Build() // One regular page left. b.AssertFileContent("public/index.html", "RegularPagesRecursive: pfile:/docs/pfile|$", "Sections: Docs:/docs|", ) b.AssertFileContent("public/docs/index.html", "RegularPagesRecursive: pfile:/docs/pfile|$") } func TestPagesFromGoTmplEditOverlappingContentFile(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true disableKinds = ["taxonomy", "term", "rss", "sitemap"] -- layouts/all.html -- All: {{ .Content }}|{{ .Title }}| -- layouts/section.html -- Title: {{ .Title}}| RegularPages: {{ range .RegularPages }}{{ .Title }}:{{ .Path }}|{{ end }}| -- content/mysection/_index.md -- --- title: "My Section" --- -- content/mysection/p1.md -- --- title: "p1 content file" --- Content of p1 -- content/_content.gotmpl -- {{ $.AddPage (dict "kind" "page" "path" "mysection/p2" "title" "p2 content adapter") }} ` b := hugolib.TestRunning(t, files) b.AssertFileContent("public/mysection/index.html", "Title: My Section|", "RegularPages: p1 content file:/mysection/p1|p2 content adapter:/mysection/p2|") b.EditFileReplaceAll("content/mysection/p1.md", `"p1 content file"`, `"p1 content file edited"`).Build() b.AssertFileContent("public/mysection/index.html", "RegularPages: p1 content file edited:/mysection/p1|p2 content adapter:/mysection/p2|") b.EditFileReplaceAll("content/mysection/_index.md", "My Section", "My Section edited").Build() b.AssertFileContent("public/mysection/index.html", "Title: My Section edited|", "RegularPages: p1 content file edited:/mysection/p1|p2 content adapter:/mysection/p2|") b.RemoveFiles("content/mysection/p1.md").Build() b.AssertFileContent("public/mysection/index.html", "Title: My Section edited|\nRegularPages: p2 content adapter:/mysection/p2|") b.RemoveFiles("content/_content.gotmpl", "public/mysection/index.html").Build() b.AssertFileContent("public/mysection/index.html", "Title: My Section edited|\nRegularPages: |") } // Issue #13443. func TestPagesFromGoRelatedKeywords(t *testing.T) { t.Parallel() b := hugolib.Test(t, filesPagesFromDataTempleBasic) p1 := b.H.Sites[0].RegularPages()[0] icfg := related.IndexConfig{ Name: "keywords", } k, err := p1.RelatedKeywords(icfg) b.Assert(err, qt.IsNil) b.Assert(k, qt.DeepEquals, icfg.StringsToKeywords("foo", "Bar")) icfg.Name = "title" k, err = p1.RelatedKeywords(icfg) b.Assert(err, qt.IsNil) b.Assert(k, qt.DeepEquals, icfg.StringsToKeywords("p1:p1")) } func TestPagesFromGoTmplLanguagePerFile(t *testing.T) { filesTemplate := ` -- hugo.toml -- defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 title = "Title" [languages.fr] weight = 2 title = "Titre" disabled = DISABLE -- layouts/single.html -- Single: {{ .Title }}|{{ .Content }}| -- content/docs/_content.gotmpl -- {{ $.AddPage (dict "kind" "page" "path" "p1" "title" "Title" ) }} -- content/docs/_content.fr.gotmpl -- {{ $.AddPage (dict "kind" "page" "path" "p1" "title" "Titre" ) }} ` for _, disable := range []bool{false, true} { t.Run(fmt.Sprintf("disable=%t", disable), func(t *testing.T) { b := hugolib.Test(t, strings.ReplaceAll(filesTemplate, "DISABLE", fmt.Sprintf("%t", disable))) b.AssertFileContent("public/en/docs/p1/index.html", "Single: Title||") b.AssertFileExists("public/fr/docs/p1/index.html", !disable) if !disable { b.AssertFileContent("public/fr/docs/p1/index.html", "Single: Titre||") } }) } } func TestPagesFromGoTmplDefaultPageSort(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- defaultContentLanguage = "en" -- layouts/home.html -- {{ range site.RegularPages }}{{ .RelPermalink }}|{{ end}} -- content/_content.gotmpl -- {{ $.AddPage (dict "kind" "page" "path" "docs/_p22" "title" "A" ) }} {{ $.AddPage (dict "kind" "page" "path" "docs/p12" "title" "A" ) }} {{ $.AddPage (dict "kind" "page" "path" "docs/_p12" "title" "A" ) }} -- content/docs/_content.gotmpl -- {{ $.AddPage (dict "kind" "page" "path" "_p21" "title" "A" ) }} {{ $.AddPage (dict "kind" "page" "path" "p11" "title" "A" ) }} {{ $.AddPage (dict "kind" "page" "path" "_p11" "title" "A" ) }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "/docs/_p11/|/docs/_p12/|/docs/_p21/|/docs/_p22/|/docs/p11/|/docs/p12/|") } func TestPagesFromGoTmplEnableAllLanguages(t *testing.T) { t.Parallel() filesTemplate := ` -- hugo.toml -- defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] weight = 1 title = "Title" [languages.fr] title = "Titre" weight = 2 disabled = DISABLE -- i18n/en.yaml -- title: Title -- i18n/fr.yaml -- title: Titre -- content/docs/_content.gotmpl -- {{ .EnableAllLanguages }} {{ $titleFromStore := .Store.Get "title" }} {{ if not $titleFromStore }} {{ $titleFromStore = "notfound"}} {{ .Store.Set "title" site.Title }} {{ end }} {{ $title := printf "%s:%s:%s" site.Title (i18n "title") $titleFromStore }} {{ $.AddPage (dict "kind" "page" "path" "p1" "title" $title ) }} -- layouts/_default/single.html -- Single: {{ .Title }}|{{ .Content }}| ` for _, disable := range []bool{false, true} { t.Run(fmt.Sprintf("disable=%t", disable), func(t *testing.T) { b := hugolib.Test(t, strings.ReplaceAll(filesTemplate, "DISABLE", fmt.Sprintf("%t", disable))) b.AssertFileExists("public/fr/docs/p1/index.html", !disable) if !disable { b.AssertFileContent("public/en/docs/p1/index.html", "Single: Title:Title:notfound||") b.AssertFileContent("public/fr/docs/p1/index.html", "Single: Titre:Titre:Title||") } }) } } func TestPagesFromGoTmplMarkdownify(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" -- layouts/single.html -- |Content: {{ .Content }}|Title: {{ .Title }}|Path: {{ .Path }}| -- content/docs/_content.gotmpl -- {{ $content := "**Hello World**" | markdownify }} {{ $.AddPage (dict "path" "p1" "content" (dict "value" $content "mediaType" "text/html" )) }} ` b, err := hugolib.TestE(t, files) // This currently fails. We should fix this, but that is not a trivial task, so do it later. b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "error calling markdownify: this method cannot be called before the site is fully initialized") } func TestPagesFromGoTmplResourceWithoutExtensionWithMediaTypeProvided(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" -- layouts/single.html -- |Content: {{ .Content }}|Title: {{ .Title }}|Path: {{ .Path }}| {{ range .Resources }} |RelPermalink: {{ .RelPermalink }}|Name: {{ .Name }}|Title: {{ .Title }}|Params: {{ .Params }}|MediaType: {{ .MediaType }}| {{ end }} -- content/docs/_content.gotmpl -- {{ $.AddPage (dict "path" "p1" "content" (dict "value" "**Hello World**" "mediaType" "text/markdown" )) }} {{ $.AddResource (dict "path" "p1/myresource" "content" (dict "value" "abcde" "mediaType" "text/plain" )) }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/docs/p1/index.html", "RelPermalink: /docs/p1/myresource|Name: myresource|Title: myresource|Params: map[]|MediaType: text/plain|") } func TestPagesFromGoTmplCascade(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" -- layouts/single.html -- |Content: {{ .Content }}|Title: {{ .Title }}|Path: {{ .Path }}|Params: {{ .Params }}| -- content/_content.gotmpl -- {{ $cascade := dict "params" (dict "cascadeparam1" "cascadeparam1value" ) }} {{ $.AddPage (dict "path" "docs" "kind" "section" "cascade" $cascade ) }} {{ $.AddPage (dict "path" "docs/p1" "content" (dict "value" "**Hello World**" "mediaType" "text/markdown" )) }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/docs/p1/index.html", "|Path: /docs/p1|Params: map[cascadeparam1:cascadeparam1value") } func TestPagesFromGoBuildOptions(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" -- layouts/single.html -- |Content: {{ .Content }}|Title: {{ .Title }}|Path: {{ .Path }}|Params: {{ .Params }}| -- content/_content.gotmpl -- {{ $.AddPage (dict "path" "docs/p1" "content" (dict "value" "**Hello World**" "mediaType" "text/markdown" )) }} {{ $never := dict "list" "never" "publishResources" false "render" "never" }} {{ $.AddPage (dict "path" "docs/p2" "content" (dict "value" "**Hello World**" "mediaType" "text/markdown" ) "build" $never ) }} ` b := hugolib.Test(t, files) b.AssertFileExists("public/docs/p1/index.html", true) b.AssertFileExists("public/docs/p2/index.html", false) } func TestPagesFromGoPathsWithDotsIssue12493(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','section','rss','sitemap','taxonomy','term'] -- content/_content.gotmpl -- {{ .AddPage (dict "path" "s-1.2.3/p-4.5.6" "title" "p-4.5.6") }} -- layouts/single.html -- {{ .Title }} ` b := hugolib.Test(t, files) b.AssertFileExists("public/s-1.2.3/p-4.5.6/index.html", true) } func TestPagesFromGoParamsIssue12497(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','section','rss','sitemap','taxonomy','term'] -- content/_content.gotmpl -- {{ .AddPage (dict "path" "p1" "title" "p1" "params" (dict "paraM1" "param1v" )) }} {{ .AddResource (dict "path" "p1/data1.yaml" "content" (dict "value" "data1" ) "params" (dict "paraM1" "param1v" )) }} -- layouts/single.html -- {{ .Title }}|{{ .Params.paraM1 }} {{ range .Resources }} {{ .Name }}|{{ .Params.paraM1 }} {{ end }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "p1|param1v", "data1.yaml|param1v", ) } func TestPagesFromGoTmplShortcodeNoPreceddingCharacterIssue12544(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] -- content/_content.gotmpl -- {{ $content := dict "mediaType" "text/html" "value" "x{{< sc >}}" }} {{ .AddPage (dict "content" $content "path" "a") }} {{ $content := dict "mediaType" "text/html" "value" "{{< sc >}}" }} {{ .AddPage (dict "content" $content "path" "b") }} -- layouts/single.html -- |{{ .Content }}| -- layouts/_shortcodes/sc.html -- foo {{- /**/ -}} ` b := hugolib.Test(t, files) b.AssertFileContent("public/a/index.html", "|xfoo|") b.AssertFileContent("public/b/index.html", "|foo|") // fails } func TestPagesFromGoTmplMenus(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','section','sitemap','taxonomy','term'] [menus] [[menus.main]] name = "Main" [[menus.footer]] name = "Footer" -- content/_content.gotmpl -- {{ .AddPage (dict "path" "p1" "title" "p1" "menus" "main" ) }} {{ .AddPage (dict "path" "p2" "title" "p2" "menus" (slice "main" "footer")) }} -- layouts/home.html -- Main: {{ range index site.Menus.main }}{{ .Name }}|{{ end }}| Footer: {{ range index site.Menus.footer }}{{ .Name }}|{{ end }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "Main: Main|p1|p2||", "Footer: Footer|p2||", ) } // Issue 13384. func TestPagesFromGoTmplMenusMap(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['rss','section','sitemap','taxonomy','term'] -- content/_content.gotmpl -- {{ $menu1 := dict "parent" "main-page" "identifier" "id1" }} {{ $menu2 := dict "parent" "main-page" "identifier" "id2" }} {{ $menus := dict "m1" $menu1 "m2" $menu2 }} {{ .AddPage (dict "path" "p1" "title" "p1" "menus" $menus ) }} -- layouts/home.html -- Menus: {{ range $k, $v := site.Menus }}{{ $k }}|{{ end }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "Menus: m1|m2|") } func TestPagesFromGoTmplMore(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] [markup.goldmark.renderer] unsafe = true -- content/s1/_content.gotmpl -- {{ $page := dict "content" (dict "mediaType" "text/markdown" "value" "aaa <!--more--> bbb") "title" "p1" "path" "p1" }} {{ .AddPage $page }} -- layouts/single.html -- summary: {{ .Summary }}|content: {{ .Content}} ` b := hugolib.Test(t, files) b.AssertFileContent("public/s1/p1/index.html", "<p>aaa</p>|content: <p>aaa</p>\n<p>bbb</p>", ) } // Issue 13063. func TestPagesFromGoTmplTermIsEmpty(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ['section', 'home', 'rss','sitemap'] printPathWarnings = true [taxonomies] tag = "tags" -- content/mypost.md -- --- title: "My Post" tags: ["mytag"] --- -- content/tags/_content.gotmpl -- {{ .AddPage (dict "path" "mothertag" "title" "My title" "kind" "term") }} -- -- layouts/taxonomy.html -- Terms: {{ range .Data.Terms.ByCount }}{{ .Name }}: {{ .Count }}|{{ end }}§s -- layouts/single.html -- Single. ` b := hugolib.Test(t, files, hugolib.TestOptWarn()) b.AssertFileContent("public/tags/index.html", "Terms: mytag: 1|§s") } func TestContentAdapterOutputsIssue13689(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] [outputs] page = ['html','json'] -- layouts/page.html -- html: {{ .Title }} -- layouts/page.json -- json: {{ .Title }} -- content/p1.md -- --- title: p1 --- -- content/p2.md -- --- title: p2 outputs: - html --- -- content/_content.gotmpl -- {{ $page := dict "path" "p3" "title" "p3" }} {{ $.AddPage $page }} {{ $page := dict "path" "p4" "title" "p4" "outputs" (slice "html") }} {{ $.AddPage $page }} ` b := hugolib.Test(t, files) b.AssertFileExists("public/p1/index.html", true) b.AssertFileExists("public/p1/index.json", true) b.AssertFileExists("public/p2/index.html", true) b.AssertFileExists("public/p2/index.json", false) b.AssertFileExists("public/p3/index.html", true) b.AssertFileExists("public/p3/index.json", true) b.AssertFileExists("public/p4/index.html", true) b.AssertFileExists("public/p4/index.json", false) // currently returns true } func TestContentAdapterOutputsIssue13692(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','home','sitemap','taxonomy','term'] [[cascade]] outputs = ['html','json'] [cascade.target] path = '{/s2,/s4}' -- layouts/section.html -- html: {{ .Title }} -- layouts/section.json -- json: {{ .Title }} -- content/s1/_index.md -- --- title: s1 --- -- content/s2/_index.md -- --- title: s2 --- -- content/_content.gotmpl -- {{ $page := dict "path" "s3" "title" "s3" "kind" "section" }} {{ $.AddPage $page }} {{ $page := dict "path" "s4" "title" "s4" "kind" "section" }} {{ $.AddPage $page }} {{ $page := dict "path" "s5" "title" "s5" "kind" "section" "outputs" (slice "html") }} {{ $.AddPage $page }} ` b := hugolib.Test(t, files) b.AssertFileExists("public/s1/index.html", true) b.AssertFileExists("public/s1/index.json", false) b.AssertFileExists("public/s1/index.xml", true) b.AssertFileExists("public/s2/index.html", true) b.AssertFileExists("public/s2/index.json", true) b.AssertFileExists("public/s2/index.xml", false) b.AssertFileExists("public/s3/index.html", true) b.AssertFileExists("public/s3/index.json", false) b.AssertFileExists("public/s3/index.xml", true) b.AssertFileExists("public/s4/index.html", true) b.AssertFileExists("public/s4/index.json", true) b.AssertFileExists("public/s4/index.xml", false) b.AssertFileExists("public/s5/index.html", true) b.AssertFileExists("public/s5/index.json", false) b.AssertFileExists("public/s5/index.xml", false) } func TestContentAdapterCascadeBasic(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLiveReload = true -- content/_index.md -- --- cascade: - title: foo target: path: "**" --- -- layouts/all.html -- Title: {{ .Title }}|Content: {{ .Content }}| -- content/_content.gotmpl -- {{ $content := dict "mediaType" "text/markdown" "value" "The _Hunchback of Notre Dame_ was written by Victor Hugo." }} {{ $page := dict "path" "s1" "kind" "page" }} {{ $.AddPage $page }} {{ $page := dict "path" "s2" "kind" "page" "title" "bar" "content" $content }} {{ $.AddPage $page }} ` b := hugolib.TestRunning(t, files) b.AssertFileContent("public/s1/index.html", "Title: foo|") b.AssertFileContent("public/s2/index.html", "Title: bar|", "Content: <p>The <em>Hunchback of Notre Dame</em> was written by Victor Hugo.</p>") b.EditFileReplaceAll("content/_index.md", "foo", "baz").Build() b.AssertFileContent("public/s1/index.html", "Title: baz|") } func TestPagesFromGoTmplHome(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" -- layouts/all.html -- {{ .Kind }}: {{ .Title }}| -- content/_content.gotmpl -- {{ $.AddPage (dict "title" "My Home!" "kind" "home" ) }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "home: My Home!|") } func TestPagesFromGoTmplIssue14299(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap"] baseURL = "https://example.com" -- layouts/all.html -- {{ .Kind }}: {{ .Title }}| -- content/_content.gotmpl -- {{ $a := "foo" }} -- content/_index.md -- -- content/bar/_content.gotmpl -- {{ $a := "bar" }} -- content/bar/index.md -- ` // _content.gotmpl which was siblings of index.md (leaf bundles) was mistakingly classified as a content resource. hugolib.Test(t, files) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/pagesfromdata/pagesfromgotmpl_test.go
hugolib/pagesfromdata/pagesfromgotmpl_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pagesfromdata import "testing" func BenchmarkHash(b *testing.B) { m := map[string]any{ "foo": "bar", "bar": "foo", "stringSlice": []any{"a", "b", "c"}, "intSlice": []any{1, 2, 3}, "largeText": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit.", } bs := BuildState{} for b.Loop() { bs.hash(m) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/paths/paths.go
hugolib/paths/paths.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package paths import ( "path/filepath" "strings" hpaths "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/hugofs" ) var FilePathSeparator = string(filepath.Separator) type Paths struct { Fs *hugofs.Fs Cfg config.AllProvider // Directories to store Resource related artifacts. AbsResourcesDir string AbsPublishDir string // When in multihost mode, this returns a list of base paths below PublishDir // for each language. MultihostTargetBasePaths []string } func New(fs *hugofs.Fs, cfg config.AllProvider) (*Paths, error) { bcfg := cfg.BaseConfig() publishDir := bcfg.PublishDir if publishDir == "" { panic("publishDir not set") } absPublishDir := hpaths.AbsPathify(bcfg.WorkingDir, publishDir) if !strings.HasSuffix(absPublishDir, FilePathSeparator) { absPublishDir += FilePathSeparator } // If root, remove the second '/' if absPublishDir == "//" { absPublishDir = FilePathSeparator } absResourcesDir := hpaths.AbsPathify(bcfg.WorkingDir, cfg.Dirs().ResourceDir) if !strings.HasSuffix(absResourcesDir, FilePathSeparator) { absResourcesDir += FilePathSeparator } if absResourcesDir == "//" { absResourcesDir = FilePathSeparator } var multihostTargetBasePaths []string if cfg.IsMultihost() && len(cfg.Languages().(langs.Languages)) > 1 { for _, l := range cfg.Languages().(langs.Languages) { multihostTargetBasePaths = append(multihostTargetBasePaths, hpaths.ToSlashPreserveLeading(l.Lang)) } } p := &Paths{ Fs: fs, Cfg: cfg, AbsResourcesDir: absResourcesDir, AbsPublishDir: absPublishDir, MultihostTargetBasePaths: multihostTargetBasePaths, } return p, nil } func (p *Paths) AllModules() modules.Modules { return p.Cfg.GetConfigSection("allModules").(modules.Modules) } // GetBasePath returns any path element in baseURL if needed. // The path returned will have a leading, but no trailing slash. func (p *Paths) GetBasePath(isRelativeURL bool) string { if isRelativeURL && p.Cfg.CanonifyURLs() { // The baseURL will be prepended later. return "" } return p.Cfg.BaseURL().BasePathNoTrailingSlash } func (p *Paths) Lang() string { if p == nil || p.Cfg.Language() == nil { return "" } return p.Cfg.Language().(*langs.Language).Lang } func (p *Paths) GetTargetLanguageBasePath() string { if p.Cfg.IsMultihost() { // In a multihost configuration all assets will be published below the language code. return p.Lang() } return p.GetLanguagePrefix() } func (p *Paths) GetLanguagePrefix() string { return p.Cfg.LanguagePrefix() } // AbsPathify creates an absolute path if given a relative path. If already // absolute, the path is just cleaned. func (p *Paths) AbsPathify(inPath string) string { return hpaths.AbsPathify(p.Cfg.BaseConfig().WorkingDir, inPath) } // RelPathify trims any WorkingDir prefix from the given filename. If // the filename is not considered to be absolute, the path is just cleaned. func (p *Paths) RelPathify(filename string) string { filename = filepath.Clean(filename) if !filepath.IsAbs(filename) { return filename } return strings.TrimPrefix(strings.TrimPrefix(filename, p.Cfg.BaseConfig().WorkingDir), FilePathSeparator) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/sitesmatrix/dimensions.go
hugolib/sitesmatrix/dimensions.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sitesmatrix import ( "fmt" ) const ( // Dimensions in the Hugo build matrix. // These can be used as indices into the Vector type. Language int = iota Version Role ) // Vector represents a site vector in the Hugo sites matrix from the three dimensions: // Language, Version and Role. // This is a fixed-size array for performance reasons (for one, it can be used as map key). type Vector [3]int // Compare returns -1 if v1 is less than v2, 0 if they are equal, and 1 if v1 is greater than v2. // This adds a implicit weighting to the dimensions, where the first dimension is the most important, // but this is just used for sorting to get stable output. func (v1 Vector) Compare(v2 Vector) int { // note that a and b will never be equal. minusOneOrOne := func(a, b int) int { if a < b { return -1 } return 1 } if v1[0] != v2[0] { return minusOneOrOne(v1[0], v2[0]) } if v1[1] != v2[1] { return minusOneOrOne(v1[1], v2[1]) } if v1[2] != v2[2] { return minusOneOrOne(v1[2], v2[2]) } // They are equal. return 0 } // Distance returns the distance between v1 and v2 // using the first dimension that is different. func (v1 Vector) Distance(v2 Vector) int { if v1[0] != v2[0] { return v1[0] - v2[0] } if v1[1] != v2[1] { return v1[1] - v2[1] } if v1[2] != v2[2] { return v1[2] - v2[2] } return 0 } // EuclideanDistanceSquared returns the Euclidean distance between two vectors as the sum of the squared differences. func (v1 Vector) HasVector(v2 Vector) bool { return v1 == v2 } func (v1 Vector) HasAnyVector(vp VectorProvider) bool { n := vp.LenVectors() if n == 0 { return false } if n == 1 { return v1 == vp.VectorSample() } return !vp.ForEachVector(func(v2 Vector) bool { if v1 == v2 { return false // stop iteration } return true // continue iteration }) } func (v1 Vector) LenVectors() int { return 1 } func (v1 Vector) VectorSample() Vector { return v1 } func (v1 Vector) EqualsVector(other VectorProvider) bool { if other.LenVectors() != 1 { return false } return other.VectorSample() == v1 } func (v1 Vector) ForEachVector(yield func(v Vector) bool) bool { return yield(v1) } // Language returns the language dimension. func (v1 Vector) Language() int { return v1[Language] } // Version returns the version dimension. func (v1 Vector) Version() int { return v1[Version] } // IsFirst returns true if this is the first vector in the matrix, i.e. all dimensions are 0. func (v1 Vector) IsFirst() bool { return v1[Language] == 0 && v1[Version] == 0 && v1[Role] == 0 } // Role returns the role dimension. func (v1 Vector) Role() int { return v1[Role] } func (v1 Vector) Weight() int { return 0 } var _ ToVectorStoreProvider = Vectors{} type Vectors map[Vector]struct{} func (vs Vectors) ForEachVector(yield func(v Vector) bool) bool { for v := range vs { if !yield(v) { return false } } return true } func (vs Vectors) LenVectors() int { return len(vs) } func (vs Vectors) ToVectorStore() VectorStore { return newVectorStoreMapFromVectors(vs) } // VectorSample returns one of the vectors in the set. func (vs Vectors) VectorSample() Vector { for v := range vs { return v } panic("no vectors") } type ( VectorIterator interface { // ForEachVector iterates over all vectors in the provider. // It returns false if the iteration was stopped early. ForEachVector(func(v Vector) bool) bool // LenVectors returns the number of vectors in the provider. LenVectors() int // VectorSample returns one of the vectors in the provider, usually the first or the only one. // This will panic if the provider is empty. VectorSample() Vector } ) // Bools holds boolean values for each dimension in the Hugo build matrix. type Bools [3]bool func (d Bools) Language() bool { return d[Language] } func (d Bools) Version() bool { return d[Version] } func (d Bools) Role() bool { return d[Role] } func (d Bools) IsZero() bool { return !d[0] && !d[1] && !d[2] } type VectorProvider interface { VectorIterator // HasVector returns true if the given vector is contained in the provider. // Used for membership testing of files, resources and pages. HasVector(HasAnyVectorv Vector) bool // HasAnyVector returns true if any of the vectors in the provider matches any of the vectors in v. HasAnyVector(v VectorProvider) bool // Equals returns true if this provider is equal to the other provider. EqualsVector(other VectorProvider) bool } type VectorStore interface { VectorProvider Complement(...VectorProvider) VectorStore WithLanguageIndices(i int) VectorStore HasLanguage(lang int) bool HasVersion(version int) bool HasRole(role int) bool MustHash() uint64 // Used in tests. KeysSorted() ([]int, []int, []int) Vectors() []Vector } type ToVectorStoreProvider interface { ToVectorStore() VectorStore } func VectorIteratorToStore(vi VectorIterator) VectorStore { switch v := vi.(type) { case VectorStore: return v case ToVectorStoreProvider: return v.ToVectorStore() } vectors := make(Vectors) vi.ForEachVector(func(v Vector) bool { vectors[v] = struct{}{} return true }) return vectors.ToVectorStore() } type weightedVectorStore struct { VectorStore weight int } func (w weightedVectorStore) Weight() int { return w.weight } func NewWeightedVectorStore(vs VectorStore, weight int) VectorStore { if vs == nil { return nil } return weightedVectorStore{VectorStore: vs, weight: weight} } // Dimension is a dimension in the Hugo build matrix. type Dimension int8 func ParseDimension(s string) (int, error) { switch s { case "language": return Language, nil case "version": return Version, nil case "role": return Role, nil default: return 0, fmt.Errorf("unknown dimension %q", s) } } func DimensionName(d int) string { switch d { case Language: return "language" case Version: return "version" case Role: return "role" default: panic("unknown dimension") } } // Common information provided by all of language, version and role. type DimensionInfo interface { // The name. This corresponds to the key in the config, e.g. "en", "v1.2.3", "guest". Name() string // Whether this is the default value for this dimension. IsDefault() bool }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/sitesmatrix/vectorstores_test.go
hugolib/sitesmatrix/vectorstores_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sitesmatrix_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/hugolib/sitesmatrix" ) func newTestDims() *sitesmatrix.ConfiguredDimensions { return sitesmatrix.NewTestingDimensions([]string{"en", "no"}, []string{"v1", "v2", "v3"}, []string{"admin", "editor", "viewer", "guest"}) } func TestIntSets(t *testing.T) { c := qt.New(t) testDims := newTestDims() sets := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3), ).Build() sets2 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 4), ).Build() sets3 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(2, 1), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(2, 1, 4), ).Build() sets4 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(3, 4, 5), maps.NewOrderedIntSet(3, 4, 5), maps.NewOrderedIntSet(3, 4, 5), ).Build() c.Assert(hashing.HashStringHex(sets), qt.Equals, "790f6004619934ff") c.Assert(hashing.HashStringHex(sets2), qt.Equals, "99abddc51cd22f24") c.Assert(hashing.HashStringHex(sets3), qt.Equals, "99abddc51cd22f24") c.Assert(sets.HasVector(sitesmatrix.Vector{1, 2, 3}), qt.Equals, true) c.Assert(sets.HasVector(sitesmatrix.Vector{3, 2, 3}), qt.Equals, false) c.Assert(sets.HasAnyVector(sets2), qt.Equals, true) c.Assert(sets.HasAnyVector(sets3), qt.Equals, true) c.Assert(sets.HasAnyVector(sets4), qt.Equals, false) c.Assert(sets.VectorSample(), qt.Equals, sitesmatrix.Vector{1, 1, 1}) c.Assert(sets.EqualsVector(sets), qt.Equals, true) c.Assert(sets.EqualsVector( sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3), ).Build(), ), qt.Equals, true) c.Assert(sets.EqualsVector( sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3, 4), maps.NewOrderedIntSet(1, 2, 3, 4), ).Build(), ), qt.Equals, false) c.Assert(sets.EqualsVector( sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(2, 3, 4), ).Build(), ), qt.Equals, false) allCount := 0 seen := make(map[sitesmatrix.Vector]bool) ok := sets.ForEachVector(func(v sitesmatrix.Vector) bool { c.Assert(seen[v], qt.IsFalse) seen[v] = true allCount++ return true }) c.Assert(ok, qt.IsTrue) // 2 languages * 3 versions * 3 roles = 18 combinations. c.Assert(allCount, qt.Equals, 18) } func TestIntSetsComplement(t *testing.T) { c := qt.New(t) type values struct { v0 []int v1 []int v2 []int } type test struct { name string left values input []values expected []sitesmatrix.Vector } runOne := func(c *qt.C, test test) { c.Helper() testDims := newTestDims() self := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(test.left.v0...), maps.NewOrderedIntSet(test.left.v1...), maps.NewOrderedIntSet(test.left.v2...), ).Build() var input []sitesmatrix.VectorProvider for _, v := range test.input { input = append(input, sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(v.v0...), maps.NewOrderedIntSet(v.v1...), maps.NewOrderedIntSet(v.v2...), ).Build()) } result := self.Complement(input...) vectors := result.Vectors() c.Assert(vectors, qt.DeepEquals, test.expected) c.Assert(hashing.HashStringHex(result), qt.Not(qt.Equals), hashing.HashStringHex(self)) } for _, test := range []test{ { name: "Test 3", left: values{ v0: []int{1, 3, 5}, v1: []int{1}, v2: []int{1}, }, input: []values{ {v0: []int{2}, v1: []int{1}, v2: []int{1}}, {v0: []int{2, 3}, v1: []int{1}, v2: []int{1}}, }, expected: []sitesmatrix.Vector{ {1, 1, 1}, {5, 1, 1}, }, }, { name: "Test 1", left: values{ v0: []int{1}, v1: []int{1}, v2: []int{1}, }, input: []values{ {v0: []int{2}, v1: []int{1}, v2: []int{1}}, }, expected: []sitesmatrix.Vector{ {1, 1, 1}, }, }, { name: "Same values", left: values{ v0: []int{1}, v1: []int{1}, v2: []int{1}, }, input: []values{ {v0: []int{1}, v1: []int{1}, v2: []int{1}}, }, expected: nil, }, { name: "Test 2", left: values{ v0: []int{1, 3, 5}, v1: []int{1}, v2: []int{1}, }, input: []values{ {v0: []int{2}, v1: []int{1}, v2: []int{1}}, }, expected: []sitesmatrix.Vector{ {1, 1, 1}, {3, 1, 1}, {5, 1, 1}, }, }, { name: "Many", left: values{ v0: []int{1, 3, 5, 6, 7}, v1: []int{1, 3, 5, 6, 7}, v2: []int{1, 3, 5, 6, 7}, }, input: []values{ { v0: []int{1, 3, 5, 6, 7}, v1: []int{1, 3, 5, 6}, v2: []int{1, 3, 5, 6, 7}, }, }, expected: []sitesmatrix.Vector{ {1, 7, 1}, {1, 7, 3}, {1, 7, 5}, {1, 7, 6}, {1, 7, 7}, {3, 7, 1}, {3, 7, 3}, {3, 7, 5}, {3, 7, 6}, {3, 7, 7}, {5, 7, 1}, {5, 7, 3}, {5, 7, 5}, {5, 7, 6}, {5, 7, 7}, {6, 7, 1}, {6, 7, 3}, {6, 7, 5}, {6, 7, 6}, {6, 7, 7}, {7, 7, 1}, {7, 7, 3}, {7, 7, 5}, {7, 7, 6}, {7, 7, 7}, }, }, } { c.Run(test.name, func(c *qt.C) { runOne(c, test) }) } } func TestIntSetsComplementOfComplement(t *testing.T) { c := qt.New(t) testDims := newTestDims() sets1 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1), maps.NewOrderedIntSet(1), maps.NewOrderedIntSet(1), ).Build() sets2 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2), maps.NewOrderedIntSet(1), maps.NewOrderedIntSet(1, 3), ).Build() c1 := sets2.Complement(sets1) vectors := c1.Vectors() // c.Assert(len(vectors), qt.Equals, 3) c.Assert(vectors, qt.DeepEquals, []sitesmatrix.Vector{ {1, 1, 3}, {2, 1, 1}, {2, 1, 3}, }) c.Assert(hashing.HashStringHex(c1), qt.Not(qt.Equals), hashing.HashStringHex(sets1)) c.Assert(hashing.HashStringHex(c1), qt.Not(qt.Equals), hashing.HashStringHex(sets2)) c2 := sets1.Complement(c1) c.Assert(c2.Vectors(), qt.DeepEquals, []sitesmatrix.Vector{ {1, 1, 1}, }) } func BenchmarkIntSetsComplement(b *testing.B) { testDims := newTestDims() sets1 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3), ).Build() sets1Copy := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3), ).Build() sets2 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2, 3, 4), maps.NewOrderedIntSet(1, 2, 3, 4), maps.NewOrderedIntSet(1, 2, 3, 4, 6), ).Build() setsLanguage1 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1), maps.NewOrderedIntSet(1), maps.NewOrderedIntSet(1), ).Build() b.ResetTimer() b.Run("sub set", func(b *testing.B) { for b.Loop() { _ = sets2.Complement(sets1) } }) b.Run("super set", func(b *testing.B) { for b.Loop() { _ = sets1.Complement(sets2) } }) b.Run("self", func(b *testing.B) { for b.Loop() { _ = sets1.Complement(sets1) } }) b.Run("self multiple", func(b *testing.B) { for b.Loop() { _ = sets1.Complement(sets1, sets1, sets1, sets1, sets1, sets1, sets1) } }) b.Run("same", func(b *testing.B) { for b.Loop() { _ = sets1.Complement(sets1Copy) } }) b.Run("one overlapping language", func(b *testing.B) { for b.Loop() { _ = setsLanguage1.Complement(sets1) } }) } func BenchmarkSets(b *testing.B) { testDims := newTestDims() sets1 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3), ).Build() sets1Copy := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3), ).Build() sets2 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3, 4), maps.NewOrderedIntSet(1, 2, 3, 4), ).Build() v1 := sitesmatrix.Vector{1, 2, 3} v2 := sitesmatrix.Vector{3, 2, 3} b.ResetTimer() b.Run("Build", func(b *testing.B) { for b.Loop() { _ = sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2), maps.NewOrderedIntSet(1, 2, 3), maps.NewOrderedIntSet(1, 2, 3), ).Build() } }) b.Run("HasVector", func(b *testing.B) { for b.Loop() { _ = sets1.HasVector(v1) _ = sets1.HasVector(v2) } }) b.Run("HasAnyVector(Sets)", func(b *testing.B) { for b.Loop() { _ = sets1.HasAnyVector(sets2) } }) b.Run("HasAnyVector(Vector)", func(b *testing.B) { for b.Loop() { _ = sets1.HasAnyVector(v1) } }) b.Run("HasAnyVector(&Vector)", func(b *testing.B) { for b.Loop() { _ = sets1.HasAnyVector(&v1) } }) b.Run("FirstVector", func(b *testing.B) { for b.Loop() { _ = sets1.VectorSample() } }) b.Run("LenVectors", func(b *testing.B) { for b.Loop() { _ = sets1.LenVectors() } }) b.Run("ForEachVector", func(b *testing.B) { for b.Loop() { allCount := 0 ok := sets1.ForEachVector(func(v sitesmatrix.Vector) bool { allCount++ _ = v return true }) if !ok { b.Fatal("Expected ForEachVector to return true") } if allCount != 18 { b.Fatalf("Expected 18 combinations, got %d", allCount) } } }) b.Run("EqualsVector pointer equal", func(b *testing.B) { for b.Loop() { if !sets1.EqualsVector(sets1) { b.Fatal("Expected sets1 to equal itself") } } }) b.Run("EqualsVector equal copy", func(b *testing.B) { for b.Loop() { if !sets1.EqualsVector(sets1Copy) { b.Fatal("Expected sets1 to equal its copy") } } }) b.Run("EqualsVector different sets", func(b *testing.B) { for b.Loop() { if sets1.EqualsVector(sets2) { b.Fatal("Expected sets1 to not equal sets2") } } }) b.Run("Distance", func(b *testing.B) { for b.Loop() { _ = sets1.VectorSample().Distance(v1) _ = sets1.VectorSample().Distance(v2) } }) } func TestVectorStoreMap(t *testing.T) { c := qt.New(t) testDims := newTestDims() c.Run("Complement", func(c *qt.C) { v1 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 3), maps.NewOrderedIntSet(1), maps.NewOrderedIntSet(1, 3), ).Build() m := v1.ToVectorStoreMap() v2 := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(1, 2), maps.NewOrderedIntSet(1), maps.NewOrderedIntSet(1, 3), ).Build() complement := m.Complement(v2) c.Assert(complement.Vectors(), qt.DeepEquals, []sitesmatrix.Vector{ {3, 1, 1}, {3, 1, 3}, }) }) } func BenchmarkHasAnyVectorSingle(b *testing.B) { testDims := newTestDims() set := sitesmatrix.NewIntSetsBuilder(testDims).WithSets( maps.NewOrderedIntSet(0), maps.NewOrderedIntSet(0), maps.NewOrderedIntSet(0), ).Build() v := sitesmatrix.Vector{0, 0, 0} for b.Loop() { _ = set.HasAnyVector(v) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/sitesmatrix/sitematrix_integration_test.go
hugolib/sitesmatrix/sitematrix_integration_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sitesmatrix_test import ( "encoding/json" "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestPageRotate(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.org/" defaultContentVersion = "v4.0.0" defaultContentVersionInSubdir = true defaultContentRoleInSubdir = true defaultContentRole = "guest" defaultContentLanguage = "en" defaultContentLanguageInSubdir = true disableKinds = ["taxonomy", "term", "rss", "sitemap"] [cascade] versions = ["v2**"] [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [roles] [roles.guest] weight = 300 [roles.member] weight = 200 [versions] [versions."v2.0.0"] [versions."v1.2.3"] [versions."v2.1.0"] [versions."v3.0.0"] [versions."v4.0.0"] -- content/_index.en.md -- --- title: "Home" sites: matrix: roles: ["**"] versions: ["**"] --- -- content/_index.nn.md -- --- title: "Heim" sites: matrix: roles: ["**"] versions: ["**"] --- -- content/memberonlypost.md -- --- title: "Member Only" sites: matrix: roles: ["member"] languages: ["**"] --- Member content. -- content/publicpost.md -- --- title: "Public" sites: matrix: versions: ["! v2.1.*", "v1.2.3", "v2.**"] complements: versions: ["v3**"] --- Users with guest role will see this. -- content/v3publicpost.md -- --- title: "Public v3" sites: matrix: versions: ["v3**"] languages: ["**"] --- Users with guest role will see this. -- layouts/all.html -- Rotate(language): {{ with .Rotate "language" }}{{ range . }}{{ template "printp" . }}|{{ end }}{{ end }}$ Rotate(version): {{ with .Rotate "version" }}{{ range . }}{{ template "printp" . }}|{{ end }}{{ end }}$ Rotate(role): {{ with .Rotate "role" }}{{ range . }}{{ template "printp" . }}|{{ end }}{{ end }}$ .Site.Dimension.language {{ (.Site.Dimension "language").Name }}| .Site.Dimension.version: {{ (.Site.Dimension "version").Name }}| .Site.Dimension.role: {{ (.Site.Dimension "role").Name }}| {{ define "printp" }}{{ .RelPermalink }}:{{ with .Site }}{{ template "prints" . }}{{ end }}{{ end }} {{ define "prints" }}/l:{{ .Language.Name }}/v:{{ .Version.Name }}/r:{{ .Role.Name }}{{ end }} ` for range 3 { b := hugolib.Test(t, files) b.AssertFileContent("public/guest/v2.0.0/en/publicpost/index.html", "Rotate(language): /guest/v2.0.0/en/publicpost/:/l:en/v:v2.0.0/r:guest|$", "Rotate(version): /guest/v4.0.0/en/publicpost/:/l:en/v:v4.0.0/r:guest|/guest/v3.0.0/en/publicpost/:/l:en/v:v3.0.0/r:guest|/guest/v2.0.0/en/publicpost/:/l:en/v:v2.0.0/r:guest|/guest/v1.2.3/en/publicpost/:/l:en/v:v1.2.3/r:guest|$", "Rotate(role): /guest/v2.0.0/en/publicpost/:/l:en/v:v2.0.0/r:guest|$", ) b.AssertFileContent("public/guest/v3.0.0/en/index.html", "Rotate(language): /guest/v3.0.0/en/:/l:en/v:v3.0.0/r:guest|/guest/v3.0.0/nn/:/l:nn/v:v3.0.0/r:guest|$", "Rotate(version): /guest/v4.0.0/en/:/l:en/v:v4.0.0/r:guest|/guest/v3.0.0/en/:/l:en/v:v3.0.0/r:guest|/guest/v2.1.0/en/:/l:en/v:v2.1.0/r:guest|/guest/v2.0.0/en/:/l:en/v:v2.0.0/r:guest|/guest/v1.2.3/en/:/l:en/v:v1.2.3/r:guest", "Rotate(role): /member/v3.0.0/en/:/l:en/v:v3.0.0/r:member|/guest/v3.0.0/en/:/l:en/v:v3.0.0/r:guest|$", ".Site.Dimension.language en|", ".Site.Dimension.version: v3.0.0|", ".Site.Dimension.role: guest|", ) } } func TestFileMountSitesMatrix(t *testing.T) { filesTemplate := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss", "sitemap", "section"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true defaultCOntentVersionInSubDir = true [versions] [versions."v1.2.3"] [versions."v2.0.0"] [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [module] [[module.mounts]] source = 'content/en' target = 'content' DIMSEN [[module.mounts]] source = 'content/nn' target = 'content' DIMSNN [[module.mounts]] source = 'content/all' target = 'content' [module.mounts.sites.matrix] languages = ["**"] versions = ["**"] -- content/en/p1/index.md -- --- title: "Title English" --- -- content/en/p1/mytext.txt -- Text English -- content/nn/p1/index.md -- --- title: "Tittel Nynorsk" --- -- content/all/p2/index.md -- --- title: "p2 all" --- -- content/nn/p1/mytext.txt -- Tekst Nynorsk -- layouts/all.html -- {{ $mytext := .Resources.Get "mytext.txt" }} {{ .Title }}|{{ with $mytext }}{{ .Content | safeHTML }}{{ end }}| site.GetPage p2: {{ with .Site.GetPage "p2" }}{{ .Title }}|{{ end }}$ site.GetPage p1: {{ with .Site.GetPage "p1" }}{{ .Title }}|{{ end }}$ ` testOne := func(t *testing.T, name, files string) { t.Run(name, func(t *testing.T) { t.Parallel() b := hugolib.Test(t, files) nn20 := b.SiteHelper("nn", "v2.0.0", "") b.Assert(nn20.PageHelper("/p2").MatrixFromFile()["matrix"], qt.DeepEquals, map[string][]string{"languages": {"en", "nn"}, "roles": {"guest"}, "versions": {"v2.0.0", "v1.2.3"}}) b.AssertFileContent("public/v2.0.0/nn/p1/index.html", "Tittel Nynorsk", "Tekst Nynorsk", "site.GetPage p1: Tittel Nynorsk|") b.AssertFileContent("public/v2.0.0/nn/p2/index.html", "p2 all||", "site.GetPage p2: p2 all", "site.GetPage p1: Tittel Nynorsk|") b.AssertFileContent("public/v2.0.0/nn/p2/index.html", "p2 all||", "site.GetPage p1: Tittel Nynorsk|$") b.AssertFileContent("public/v1.2.3/en/p2/index.html", "p2 all||", "site.GetPage p2: p2 all") }) } // Format from v0.148.0: dims := `[module.mounts.sites.matrix] languages = ["en"] versions = ["v1**"] ` files := strings.Replace(filesTemplate, "DIMSEN", dims, 1) dims = strings.Replace(dims, `["en"]`, `["nn"]`, 1) dims = strings.Replace(dims, `["v1**"]`, `["v2**"]`, 1) files = strings.Replace(files, "DIMSNN", dims, 1) testOne(t, "new", files) // Old format: files = strings.Replace(filesTemplate, "DIMSEN", `lang = "en"`, 1) files = strings.Replace(files, "DIMSNN", `lang = "nn"`, 1) testOne(t, "old", files) } func TestSpecificMountShouldAlwaysWin(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true defaultCOntentVersionInSubDir = true defaultContentVersion = "v2.0.0" [taxonomies] tag = "tags" [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [versions] [versions."v1.2.3"] [versions."v2.0.0"] [module] [[module.mounts]] source = 'content/nn' target = 'content' [module.mounts.sites.matrix] languages = ["nn"] versions = ["v1.**"] [[module.mounts]] source = 'content/en' target = 'content' [module.mounts.sites.matrix] languages = ["**"] versions = ["**"] -- content/en/_index.md -- --- title: "English Home" tags: ["tag1"] --- -- content/en/p1.md -- --- title: "English p1" --- -- content/nn/_index.md -- --- title: "Nynorsk Heim" tags: ["tag2"] --- -- layouts/all.html -- title: {{ .Title }}| tags: {{ range $term, $taxonomy := .Site.Taxonomies.tags }}{{ $term }}: {{ range $taxonomy.Pages }}{{ .Title }}: {{ .RelPermalink}}|{{ end }}{{ end }}$ ` for range 2 { b := hugolib.Test(t, files) // b.AssertPublishDir("asdf") b.AssertFileContent("public/v1.2.3/nn/index.html", "title: Nynorsk Heim|", "tags: tag2: Nynorsk Heim: /v1.2.3/nn/|$") b.AssertFileContent("public/v2.0.0/en/index.html", "title: English Home|", "tags: tag1: English Home: /v2.0.0/en/|$") b.AssertFileContent("public/v2.0.0/nn/index.html", "title: English Home|", "tags: tag1: English Home: /v2.0.0/nn/|$") // v2.0.0 is only in English. b.AssertFileContent("public/v1.2.3/en/index.html", "title: English Home|") } } const filesVariationsSitesMatrixBase = ` -- hugo.toml -- baseURL = "https://example.org/" disableKinds = ["rss", "sitemap", "section"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true defaultCOntentVersionInSubDir = true defaultContentVersion = "v2.0.0" defaultContentRole = "guest" defaultContentRoleInSubDir = true [taxonomies] tag = "tags" [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [versions] [versions."v1.2.3"] [versions."v1.4.0"] [versions."v2.0.0"] [roles] [roles.guest] weight = 300 [roles.member] weight = 200 [module] [[module.mounts]] source = 'content/nn' target = 'content' [module.mounts.sites.matrix] languages = ["nn"] versions = ["v1.2.*"] [[module.mounts]] source = 'content/en' target = 'content' [module.mounts.sites.matrix] languages = ["**"] versions = ["**"] [[module.mounts]] source = 'content/other' target = 'content' -- content/en/_index.md -- --- title: "English Home" tags: ["tag1"] --- Ref home: {{< ref "/" >}}| -- content/en/p1.md -- --- title: "English p1" --- -- content/nn/_index.md -- --- title: "Nynorsk Heim" tags: ["tag2"] --- Ref home: {{< ref "/" >}}| ` const filesVariationsSitesMatrix = filesVariationsSitesMatrixBase + ` -- layouts/all.html -- title: {{ .Title }}| tags: {{ range $term, $taxonomy := .Site.Taxonomies.tags }}{{ $term }}: {{ range $taxonomy.Pages }}{{ .Title }}: {{ .RelPermalink}}|{{ end }}{{ end }}$ .Language.IsDefault: {{ with .Rotate "language" }}{{ range . }}{{ .RelPermalink }}: {{ with .Site.Language }}{{ .Name}}: {{ .IsDefault }}|{{ end }}{{ end }}{{ end }}$ .Version.IsDefault: {{ with .Rotate "version" }}{{ range . }}{{ .RelPermalink }}: {{ with .Site.Version }}{{ .Name}}: {{ .IsDefault }}|{{ end }}{{ end }}{{ end }}$ .Role.IsDefault: {{ with .Rotate "role" }}{{ range . }}{{ .RelPermalink }}: {{ with .Site.Role }}{{ .Name}}: {{ .IsDefault }}|{{ end }}{{ end }}{{ end }}$ ` func TestFrontMatterSitesMatrix(t *testing.T) { t.Parallel() files := filesVariationsSitesMatrix files += ` -- content/other/p2.md -- --- title: "NN p2" sites: matrix: languages: - nn versions: - v1.2.3 --- ` b := hugolib.Test(t, files) b.AssertFileContent("public/guest/v1.2.3/nn/p2/index.html", "title: NN p2|") } func TestFrontMatterSitesMatrixShouldWin(t *testing.T) { t.Parallel() files := filesVariationsSitesMatrix // nn mount config is nn, v1.2.*. files += ` -- content/nn/p2.md -- --- title: "EN p2" sites: matrix: languages: - en versions: - v1.4.* --- ` b := hugolib.Test(t, files) b.AssertFileContent("public/guest/v1.4.0/en/p2/index.html", "title: EN p2|") } func TestGetPageAndRef(t *testing.T) { t.Parallel() files := filesVariationsSitesMatrixBase + ` -- layouts/all.html -- Title: {{ .Title }}| Home: {{ with .Site.GetPage "/" }}{{ with .Site }}Language: {{ .Language.Name }}|Version: {{ .Version.Name }}|Role: {{ .Role.Name }}{{ end }}|{{ end }}$ Content: {{ .Content }}$ ` b := hugolib.Test(t, files) b.AssertFileContent( "public/guest/v2.0.0/en/index.html", "Home: Language: en|Version: v2.0.0|Role: guest|$", "Ref home: https://example.org/guest/v2.0.0/en/|", ) b.AssertFileContent( "public/member/v1.4.0/nn/index.html", "Home: Language: nn|Version: v1.4.0|Role: member|$", ) b.AssertFileContent( "public/guest/v1.2.3/nn/index.html", "Home: Language: nn|Version: v1.2.3|Role: guest|$", "Ref home: https://example.org/guest/v1.2.3/nn/|", ) } func TestFrontMatterSitesMatrixShouldBeMergedWithMount(t *testing.T) { t.Parallel() files := filesVariationsSitesMatrix // nn mount config is nn, v1.2.*. // This changes only the language, not the version. files += ` -- content/nn/p2.md -- --- title: "EN p2" sites: matrix: languages: - en --- ` b := hugolib.Test(t, files) b.AssertFileContent("public/guest/v1.2.3/en/p2/index.html", "title: EN p2|") } func TestCascadeMatrixInFrontMatter(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [languages.sv] weight = 3 -- content/_index.md -- +++ title = "English home" [cascade] [cascade.params] p1 = "p1cascade" [cascade.target.sites.matrix] languages = ["en"] +++ -- content/_index.nn.md -- +++ title = "Scandinavian home" [sites.matrix] languages = "{nn,sv}" [cascade] [cascade.params] p1 = "p1cascadescandinavian" [cascade.sites.matrix] languages = "{nn,sv}" [cascade.target] path = "**scandinavian**" +++ -- content/mysection/_index.md -- +++ title = "My section" [cascade.target.sites.matrix] languages = "**" +++ -- content/mysection/p1.md -- +++ title = "English p1" +++ -- content/mysection/scandinavianpages/p1.md -- +++ title = "Scandinavian p1" +++ -- layouts/all.html -- {{ .Title }}|{{ .Site.Language.Name }}|{{ .Site.Version.Name }}|p1: {{ .Params.p1 }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/en/mysection/p1/index.html", "English p1|en|v1.0.0|p1: p1cascade|") b.AssertFileContent("public/sv/mysection/scandinavianpages/p1/index.html", "Scandinavian p1|sv|v1.0.0|p1: p1cascadescandinavian|") } func TestCascadeMatrixConfigPerLanguage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [cascade.params] p1 = "p1cascadeall" p2 = "p2cascadeall" [languages] [languages.en] weight = 1 [languages.en.cascade.params] p1 = "p1cascadeen" [languages.nn] weight = 2 [languages.nn.cascade.params] p1 = "p1cascadenn" -- content/_index.md -- --- title: "English home" --- -- content/mysection/p1.md -- --- title: "English p1" --- -- content/mysection/p1.nn.md -- --- title: "Nynorsk p1" --- -- layouts/all.html -- {{ .Title }}|{{ .Site.Language.Name }}|{{ .Site.Version.Name }}|p1: {{ .Params.p1 }}|p2: {{ .Params.p2 }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/en/mysection/p1/index.html", "English p1|en|v1.0.0|p1: p1cascadeen|p2: p2cascadeall|") b.AssertFileContent("public/nn/mysection/p1/index.html", "Nynorsk p1|nn|v1.0.0|p1: p1cascadenn|p2: p2cascadeall|") } func TestCascadeMatrixNoHomeContent(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [cascade.params] p1 = "p1cascadeall" p2 = "p2cascadeall" -- content/mysection/p1.md -- -- layouts/all.html -- {{ .Title }}|{{ .Kind }}|{{ .Site.Language.Name }}|{{ .Site.Version.Name }}|p1: {{ .Params.p1 }}|p2: {{ .Params.p2 }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/en/index.html", "|home|en|v1.0.0|p1: p1cascadeall|p2: p2cascadeall|") b.AssertFileContent("public/en/mysection/index.html", "Mysections|section|en|v1.0.0|p1: p1cascadeall|p2: p2cascadeall|") b.AssertFileContent("public/en/mysection/p1/index.html", "|page|en|v1.0.0|p1: p1cascadeall|p2: p2cascadeall|") } func TestMountCascadeFrontMatterSitesMatrixAndComplementsShouldBeMerged(t *testing.T) { t.Parallel() // Pick language from mount, role from cascade and version from front matter. files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true defaultCOntentVersionInSubDir = true defaultContentVersion = "v1.2.3" defaultContentRole = "guest" defaultContentRoleInSubDir = true [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [versions] [versions."v1.2.3"] [versions."v1.4.0"] [versions."v2.0.0"] [roles] [roles.guest] weight = 300 [roles.member] weight = 200 [[module.mounts]] source = 'content/other' target = 'content' [module.mounts.sites.matrix] languages = ["nn"] # used. versions = ["v1.2.*"] # not used. roles = ["guest"] # not used. [module.mounts.sites.complements] languages = ["en"] # used. versions = ["v1.4.*"] # not used. roles = ["member"] # not used. [cascade.sites.matrix] roles = ["member"] # used versions = ["v1.2.*"] # not used. [cascade.sites.complements] roles = ["guest"] # used versions = ["v2**"] # not used. -- content/other/p2.md -- +++ title = "NN p2" [sites.matrix] versions = ["v1.2.*","v1.4.*"] [sites.complements] versions = ["v2.*.*"] +++ -- content/other/p3.md -- +++ title = "NN p3" [sites.matrix] versions = "v1.4.*" +++ -- layouts/all.html -- All. {{ site.Language.Name }}|{{ site.Version.Name }}|{{ site.Role.Name }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/member/v1.4.0/nn/p2/index.html", "All.") s := b.SiteHelper("nn", "v1.4.0", "member") p2 := s.PageHelper("/p2") s.Assert(p2.MatrixFromPageConfig(), qt.DeepEquals, map[string]map[string][]string{ "complements": { "languages": {"en"}, "roles": {"guest"}, "versions": {"v2.0.0"}, }, "matrix": { "languages": {"nn"}, "roles": {"member"}, "versions": {"v1.4.0", "v1.2.3"}, }, }, ) p3 := s.PageHelper("/p3") s.Assert(p3.MatrixFromPageConfig(), qt.DeepEquals, map[string]map[string][]string{ "complements": { "languages": {"en"}, "roles": {"guest"}, "versions": {"v2.0.0"}, }, "matrix": { "languages": {"nn"}, "roles": {"member"}, "versions": {"v1.4.0"}, }, }) } func TestLanguageVersionRoleIsDefault(t *testing.T) { files := filesVariationsSitesMatrix b := hugolib.Test(t, files) b.AssertFileContent("public/guest/v2.0.0/en/index.html", ".Language.IsDefault: /guest/v2.0.0/en/: en: true|/guest/v2.0.0/nn/: nn: false|$", ".Version.IsDefault: /guest/v2.0.0/en/: v2.0.0: true|/guest/v1.4.0/en/: v1.4.0: false|/guest/v1.2.3/en/: v1.2.3: false|$", ".Role.IsDefault: /member/v2.0.0/en/: member: false|/guest/v2.0.0/en/: guest: true|$", ) } func TestModuleMountsLanguageOverlap(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] theme = "mytheme" defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [[module.mounts]] source = 'content' target = 'content' [module.mounts.sites.matrix] languages = "en" -- content/p1.md -- --- title: "Project p1" --- -- themes/mytheme/hugo.toml -- [[module.mounts]] source = 'content' target = 'content' [module.mounts.sites.matrix] languages = "**" -- themes/mytheme/content/p1.md -- --- title: "Theme p1" --- -- themes/mytheme/content/p2.md -- --- title: "Theme p1" --- -- layouts/all.html -- {{ .Title }}| ` b := hugolib.Test(t, files) sEn := b.SiteHelper("en", "", "") sNN := b.SiteHelper("nn", "", "guest") b.Assert(sEn.PageHelper("/p1").MatrixFromPageConfig()["matrix"], qt.DeepEquals, map[string][]string{"languages": {"en"}, "roles": {"guest"}, "versions": {"v1.0.0"}}) b.Assert(sEn.PageHelper("/p2").MatrixFromPageConfig()["matrix"], qt.DeepEquals, map[string][]string{ "languages": {"en", "nn"}, "roles": {"guest"}, "versions": {"v1.0.0"}, }) p1NN := sNN.PageHelper("/p1") p2NN := sNN.PageHelper("/p2") b.Assert(p2NN.MatrixFromPageConfig()["matrix"], qt.DeepEquals, map[string][]string{ "languages": {"en", "nn"}, "roles": {"guest"}, "versions": {"v1.0.0"}, }) b.Assert(p1NN.MatrixFromFile()["matrix"], qt.DeepEquals, map[string][]string{ "languages": {"nn"}, // It's defined as ** in the mount. "roles": {"guest"}, "versions": {"v1.0.0"}, }) } func TestMountLanguageComplements(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] weight = 1 [languages.sv] weight = 2 [languages.da] weight = 3 [[module.mounts]] source = 'content/en' target = 'content' [module.mounts.sites.matrix] languages = "en" [module.mounts.sites.complements] languages = "{sv,da}" [[module.mounts]] source = 'content/sv' target = 'content' [module.mounts.sites.matrix] languages = "sv" -- content/en/p1.md -- --- title: "English p1" --- -- content/en/p2.md -- --- title: "English p2" --- -- content/sv/p1.md -- --- title: "Swedish p1" --- -- layouts/home.html -- RegularPagesRecursive: {{ range .RegularPagesRecursive }}{{ .Title }}|{{ .RelPermalink }}{{ end }}$ -- layouts/all.html -- {{ .Title }}|{{ .Site.Language.Name }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/en/index.html", "RegularPagesRecursive: English p1|/en/p1/English p2|/en/p2/$") b.AssertFileContent("public/sv/index.html", "RegularPagesRecursive: English p2|/en/p2/Swedish p1|/sv/p1/$") b.AssertFileContent("public/da/index.html", "RegularPagesRecursive: English p1|/en/p1/English p2|/en/p2/$") } func TestContentAdapterSitesMatrixResources(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [languages.sv] weight = 3 [languages.da] weight = 4 -- content/_content.gotmpl -- {{ $scandinavia := dict "languages" "{nn,sv}" }} {{ $en := dict "languages" "en" }} {{ $da := dict "languages" "da" }} {{ $contentMarkdown := dict "value" "**Hello World**" "mediaType" "text/markdown" }} {{ $contentTextEnglish := dict "value" "Hello World" "mediaType" "text/plain" }} {{ $contentTextNorsk := dict "value" "Hallo verd" "mediaType" "text/plain" }} {{ .AddPage (dict "path" "p1" "title" "P1 en" "content" $contentMarkdown "sites" (dict "matrix" $en )) }} {{ .AddPage (dict "path" "p1" "title" "P1 scandinavia" "content" $contentMarkdown "sites" (dict "matrix" $scandinavia )) }} {{ .AddPage (dict "path" "p1" "title" "P1 da" "content" $contentMarkdown "sites" (dict "matrix" $da )) }} {{ .AddResource (dict "path" "p1/hello.txt" "title" "Hello en" "content" $contentTextEnglish "sites" (dict "matrix" $en )) }} {{ .AddResource (dict "path" "p1/hello.txt" "title" "Hello scandinavia" "content" $contentTextNorsk "sites" (dict "matrix" $scandinavia "complements" $da )) }} -- layouts/all.html -- len .Resources: {{ len .Resources}}| {{ $hello := .Resources.Get "hello.txt" }} All. {{ .Title }}|Hello: {{ with $hello }}{{ .RelPermalink }}|{{ .Content | safeHTML }}{{ end }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/en/p1/index.html", "Hello: /en/p1/hello.txt|Hello World|") b.AssertFileContent("public/nn/p1/index.html", "P1 scandinavia|", "/nn/p1/hello.txt|Hallo verd|") b.AssertFileContent("public/sv/p1/index.html", "P1 scandinavia|", "/sv/p1/hello.txt|Hallo verd|") b.AssertFileContent("public/da/p1/index.html", "P1 da|", "/sv/p1/hello.txt|Hallo verd|") // Because it's closest of the Scandinavian complements. } func TestContentAdapterSitesMatrixContentPageSwitchLanguage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true disableLiveReload = true [languages] [languages.en] weight = 1 [languages.sv] weight = 2 [languages.da] weight = 3 [languages.no] weight = 4 -- content/_content.gotmpl -- {{ $contentMarkdown := dict "value" "**Hello World**" "mediaType" "text/markdown" }} {{ $en := dict "languages" "en" }} {{ $sv := dict "languages" "sv" }} {{ $da := dict "languages" "da" }} {{ $no := dict "languages" "no" }} {{ .AddPage (dict "path" "p1" "title" "P1-1" "content" $contentMarkdown "sites" (dict "matrix" $en )) }} {{ .AddPage (dict "path" "p1" "title" "P1-2" "content" $contentMarkdown "sites" (dict "matrix" $sv )) }} {{ .AddPage (dict "path" "p1" "title" "P1-3" "content" $contentMarkdown "sites" (dict "matrix" $da )) }} -- layouts/all.html -- All. {{ .Title }}|{{ .Site.Language.Name }}| ` b := hugolib.TestRunning(t, files) b.AssertFileExists("public/no/p1/index.html", false) b.AssertFileExists("public/sv/p1/index.html", true) b.RemovePublishDir() b.AssertFileExists("public/sv/p1/index.html", false) b.EditFileReplaceAll("content/_content.gotmpl", `"sv"`, `"no"`).Build() b.AssertFileExists("public/no/p1/index.html", true) b.AssertFileExists("public/sv/p1/index.html", false) } func TestContentAdapterSitesMatrixContentResourceSwitchLanguage(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] disableLiveReload = true defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] weight = 1 [languages.sv] weight = 2 [languages.da] weight = 3 [languages.no] weight = 4 -- content/_content.gotmpl -- {{ $contentTextEnglish := dict "value" "Hello World" "mediaType" "text/plain" }} {{ $contentTextSwedish := dict "value" "Hei världen" "mediaType" "text/plain" }} {{ $contentTextDanish := dict "value" "Hej verden" "mediaType" "text/plain" }} {{ $en := dict "languages" "en" }} {{ $sv := dict "languages" "sv" }} {{ $da := dict "languages" "da" }} {{ .AddResource (dict "path" "hello.txt" "title" "Hello" "content" $contentTextEnglish "sites" (dict "matrix" $en )) }} {{ .AddResource (dict "path" "hello.txt" "title" "Hello" "content" $contentTextSwedish "sites" (dict "matrix" $sv )) }} {{ .AddResource (dict "path" "hello.txt" "title" "Hello" "content" $contentTextDanish "sites" (dict "matrix" $da )) }} -- layouts/all.html -- {{ $hello := .Resources.Get "hello.txt" }} All. {{ .Title }}|{{ .Site.Language.Name }}|hello: {{ with $hello }}{{ .RelPermalink }}: {{ .Content }}|{{ end }}| ` b := hugolib.TestRunning(t, files) b.AssertFileContent("public/en/index.html", "en|hello: /en/hello.txt: Hello World|") b.AssertFileContent("public/sv/index.html", "sv|hello: /sv/hello.txt: Hei världen|") b.AssertFileContent("public/no/index.html", "no|hello: |") b.EditFileReplaceAll("content/_content.gotmpl", `"sv"`, `"no"`).Build() b.AssertFileContent("public/no/index.html", "no|hello: /no/hello.txt: Hei världen|") b.AssertFileContent("public/en/index.html", "en|hello: /en/hello.txt: Hello World|") b.AssertFileContent("public/sv/index.html", "|sv|hello: |") } const filesContentAdapterSitesMatrixFromConfig = ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true defaultContentRole = "enrole" defaultContentRoleInSubDir = true [languages] [languages.en] weight = 1 [languages.en.cascade.sites.matrix] roles = ["enrole"] [languages.nn] weight = 2 [languages.nn.cascade.sites.matrix] roles = ["nnrole"] [roles] [roles.enrole] weight = 200 [roles.nnrole] weight = 100 -- layouts/all.html -- All. {{ .Title }}|{{ .Site.Language.Name }}|{{ .Site.Role.Name }}| Resources: {{ range .Resources }}{{ .Title }}|{{ end }}$ ` func TestContentAdapterSitesMatrixSitesMatrixFromConfig(t *testing.T) { t.Parallel() files := filesContentAdapterSitesMatrixFromConfig + ` -- content/_content.gotmpl -- {{ $title := printf "P1 %s:%s" .Site.Language.Name .Site.Role.Name }} {{ .AddPage (dict "path" "p1" "title" $title ) }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/enrole/en/p1/index.html", "P1 en:enrole|en|enrole|") b.AssertPublishDir("! nn/p1") } func TestContentAdapterSitesMatrixSitesMatrixFromConfigEnableAllLanguages(t *testing.T) { t.Parallel() files := filesContentAdapterSitesMatrixFromConfig + ` -- content/_content.gotmpl -- {{ .EnableAllLanguages }} {{ $title := printf "P1 %s:%s" .Site.Language.Name .Site.Role.Name }} {{ .AddPage (dict "path" "p1" "title" $title ) }} {{ $.AddResource (dict "path" "p1/mytext.txt" "title" $title "content" (dict "value" $title) )}} ` b := hugolib.Test(t, files) b.AssertFileContent("public/enrole/en/p1/index.html", "P1 en:enrole|en|enrole|", "Resources: P1 en:enrole|$") b.AssertFileContent("public/nnrole/nn/p1/index.html", "P1 nn:nnrole|nn|nnrole|", "Resources: P1 nn:nnrole|$") } func TestSitesMatrixCustomContentFilenameIdentifier(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [languages.sv] weight = 3 [languages.da] weight = 4 [languages.de] weight = 5 -- content/p1.en.md -- --- title: "P1 en" --- -- content/p1._scandinavian_.md -- --- title: "P1 scandinavian" sites: matrix: languages: "{nn,sv,da}" --- -- content/p1.de.md -- --- title: "P1 de" --- -- layouts/all.html -- All.{{ .Title }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/en/p1/index.html", "All.P1 en|") b.AssertFileContent("public/nn/p1/index.html", "All.P1 scandinavian|") b.AssertFileContent("public/sv/p1/index.html", "All.P1 scandinavian|") b.AssertFileContent("public/da/p1/index.html", "All.P1 scandinavian|") b.AssertFileContent("public/de/p1/index.html", "All.P1 de|") } func TestSitesMatrixDefaultValues(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] -- layouts/all.html -- All. {{ .Title }}|Lang: {{ .Site.Language.Name }}|Ver: {{ .Site.Version.Name }}|Role: {{ .Site.Role.Name }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "All. |Lang: en|Ver: v1.0.0|Role: guest|") } func newSitesMatrixContentBenchmarkBuilder(t testing.TB, numPages int, skipRender, multipleDimensions bool) *hugolib.IntegrationTestBuilder { files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true defaultCOntentVersionInSubDir = true defaultContentVersion = "v1.0.0" defaultContentRole = "guest" defaultContentRoleInSubDir = true title = "Benchmark" [languages] [languages.en] weight = 1 ` if multipleDimensions { files += ` [languages.nn] weight = 2 [languages.sv] weight = 3 [versions] [versions."v1.0.0"] [versions."v2.0.0"] [roles] [roles.guest] weight = 300 [roles.member] weight = 200 ` } files += ` [[module.mounts]] source = 'content' target = 'content' [module.mounts.sites.matrix] languages = ["**"] versions = ["**"] roles = ["**"] -- layouts/all.html -- All. {{ .Title }}| ` if multipleDimensions { files += ` Rotate(language): {{ with .Rotate "language" }}{{ range . }}{{ template "printp" . }}|{{ end }}{{ end }}$ Rotate(version): {{ with .Rotate "version" }}{{ range . }}{{ template "printp" . }}|{{ end }}{{ end }}$ Rotate(role): {{ with .Rotate "role" }}{{ range . }}{{ template "printp" . }}|{{ end }}{{ end }}$ {{ define "printp" }}{{ .RelPermalink }}:{{ with .Site }}{{ template "prints" . }}{{ end }}{{ end }} {{ define "prints" }}/l:{{ .Language.Name }}/v:{{ .Version.Name }}/r:{{ .Role.Name }}{{ end }} ` } for i := range numPages { files += fmt.Sprintf(` -- content/p%d/index.md -- --- title: "P%d" --- `, i+1, i+1) } b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, BuildCfg: hugolib.BuildCfg{ SkipRender: skipRender, }, }) return b } // See #14132. We recently reworked the config structs for languages, versions, and roles, // which made them incomplete when generating the docshelper YAML file. // Add a test here to ensure we don't regress. func TestUnmarshalSitesMatrixConfig(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- defaultContentLanguage = "en" defaultContentLanguageInSubDir = true defaultCOntentVersionInSubDir = true defaultContentVersion = "v1.0.0" defaultContentRole = "guest" defaultContentRoleInSubDir = true [moule.mounts] source = 'content' target = 'content' [languages] [languages.en] [versions] [versions."v1.0.0"] [roles] [roles.guest] ` b := hugolib.Test(t, files) toJSONAndMap := func(v any) map[string]any { bb, err := json.Marshal(v) b.Assert(err, qt.IsNil) var m map[string]any err = json.Unmarshal(bb, &m) b.Assert(err, qt.IsNil) return m } conf := b.H.Configs.Base b.Assert(toJSONAndMap(conf.Languages), qt.DeepEquals, map[string]any{ "en": map[string]any{ "Disabled": bool(false), "LanguageCode": "", "LanguageDirection": "", "LanguageName": "", "Title": "", "Weight": float64(0), }, }) b.Assert(toJSONAndMap(conf.Versions), qt.DeepEquals, map[string]any{ "v1.0.0": map[string]any{ "Weight": float64(0), }, }) b.Assert(toJSONAndMap(conf.Roles), qt.DeepEquals, map[string]any{ "guest": map[string]any{ "Weight": float64(0), }, }) firstMount := conf.Module.Mounts[0] b.Assert(toJSONAndMap(firstMount.Sites.Matrix), qt.DeepEquals, map[string]any{
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/sitesmatrix/vectorstores.go
hugolib/sitesmatrix/vectorstores.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sitesmatrix import ( "cmp" "fmt" "iter" xmaps "maps" "slices" "sort" "sync" "github.com/gohugoio/hashstructure" "github.com/gohugoio/hugo/common/hashing" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/predicate" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/hugofs/hglob" ) var ( _ VectorStore = &IntSets{} _ VectorStore = &vectorStoreMap{} _ hashstructure.Hashable = &IntSets{} _ hashstructure.Hashable = &vectorStoreMap{} ) func newVectorStoreMap(cap int) *vectorStoreMap { return &vectorStoreMap{ sets: make(Vectors, cap), h: &hashOnce{}, } } func newVectorStoreMapFromVectors(v Vectors) *vectorStoreMap { return &vectorStoreMap{ sets: v, h: &hashOnce{}, } } // A vector store backed by a map. type vectorStoreMap struct { sets Vectors h *hashOnce } func (s *vectorStoreMap) initHash() { s.h.once.Do(func() { var err error s.h.hash, err = hashing.Hash(s.sets) if err != nil { panic(fmt.Errorf("failed to calculate hash for MapVectorStore: %w", err)) } }) } func (s *vectorStoreMap) setVector(vec Vector) { s.sets[vec] = struct{}{} } func (s *vectorStoreMap) KeysSorted() ([]int, []int, []int) { var k0, k1, k2 []int for v := range s.sets { k0 = append(k0, v.Language()) k1 = append(k1, v.Version()) k2 = append(k2, v.Role()) } sort.Ints(k0) sort.Ints(k1) sort.Ints(k2) k0 = slices.Compact(k0) k1 = slices.Compact(k1) k2 = slices.Compact(k2) return k0, k1, k2 } func (s *vectorStoreMap) Hash() (uint64, error) { s.initHash() return s.h.hash, nil } func (s *vectorStoreMap) MustHash() uint64 { i, _ := s.Hash() return i } func (s *vectorStoreMap) HasVector(v Vector) bool { if _, ok := s.sets[v]; ok { return true } return false } func (s *vectorStoreMap) HasAnyVector(v VectorProvider) bool { if v == nil || s.LenVectors() == 0 || v.LenVectors() == 0 { return false } return !v.ForEachVector(func(vec Vector) bool { if s.HasVector(vec) { return false // stop iteration } return true // continue iteration }) } func (s *vectorStoreMap) LenVectors() int { return len(s.sets) } // Complement returns a new VectorStore that contains all vectors in s that are not in any of ss. func (s *vectorStoreMap) Complement(ss ...VectorProvider) VectorStore { if len(ss) == 0 || (len(ss) == 1 && ss[0] == s) { return nil } for _, v := range ss { if v == s { var s *vectorStoreMap return s } } result := newVectorStoreMap(36) s.ForEachVector(func(vec Vector) bool { var found bool for _, v := range ss { if v.HasVector(vec) { found = true break } } if !found { result.setVector(vec) } return true }) return result } func (s *vectorStoreMap) EqualsVector(other VectorProvider) bool { if other == nil { return false } if s == other { return true } if s.LenVectors() != other.LenVectors() { return false } return other.ForEachVector(func(v Vector) bool { _, ok := s.sets[v] return ok }) } func (s *vectorStoreMap) VectorSample() Vector { if len(s.sets) == 0 { panic("no vectors available") } for v := range s.sets { return v } panic("unreachable") } func (s *vectorStoreMap) ForEachVector(yield func(v Vector) bool) bool { if len(s.sets) == 0 { return true } for v := range s.sets { if !yield(v) { return false } } return true } func (s *vectorStoreMap) Vectors() []Vector { if s == nil || len(s.sets) == 0 { return nil } var vectors []Vector for v := range s.sets { vectors = append(vectors, v) } sort.Slice(vectors, func(i, j int) bool { v1, v2 := vectors[i], vectors[j] return v1.Compare(v2) < 0 }) return vectors } func (s *vectorStoreMap) WithLanguageIndices(i int) VectorStore { c := s.clone() for v := range c.sets { v[Language] = i c.sets[v] = struct{}{} } return c } func (s *vectorStoreMap) HasLanguage(i int) bool { for v := range s.sets { if v.Language() == i { return true } } return false } func (s *vectorStoreMap) HasVersion(i int) bool { for v := range s.sets { if v.Version() == i { return true } } return false } func (s *vectorStoreMap) HasRole(i int) bool { for v := range s.sets { if v.Role() == i { return true } } return false } func (s *vectorStoreMap) clone() *vectorStoreMap { c := *s c.h = &hashOnce{} c.sets = xmaps.Clone(s.sets) return &c } func NewIntSetsBuilder(cfg *ConfiguredDimensions) *IntSetsBuilder { if cfg == nil { panic("cfg is required") } return &IntSetsBuilder{cfg: cfg, s: &IntSets{h: &hashOnce{}}} } type ConfiguredDimension interface { predicate.IndexMatcher IndexDefault() int ResolveIndex(string) int ResolveName(int) string ForEachIndex() iter.Seq[int] Len() int } // ConfiguredDimensions holds the configured dimensions for the site matrix. type ConfiguredDimensions struct { ConfiguredLanguages ConfiguredDimension ConfiguredVersions ConfiguredDimension ConfiguredRoles ConfiguredDimension CommonSitesMatrix CommonSitestMatrix singleVectorStoreCache *maps.Cache[Vector, *IntSets] } func (c *ConfiguredDimensions) IsSingleVector() bool { return c.ConfiguredLanguages.Len() == 1 && c.ConfiguredRoles.Len() == 1 && c.ConfiguredVersions.Len() == 1 } // GetOrCreateSingleVectorStore returns a VectorStore for the given vector. func (c *ConfiguredDimensions) GetOrCreateSingleVectorStore(vec Vector) *IntSets { store, _ := c.singleVectorStoreCache.GetOrCreate(vec, func() (*IntSets, error) { is := &IntSets{} is.setValuesInNilSets(vec, true, true, true) return is, nil }) return store } func (c *ConfiguredDimensions) Init() error { c.singleVectorStoreCache = maps.NewCache[Vector, *IntSets]() b := NewIntSetsBuilder(c).WithDefaultsIfNotSet().Build() defaultVec := b.VectorSample() c.singleVectorStoreCache.Set(defaultVec, b) c.CommonSitesMatrix.DefaultSite = b return nil } type CommonSitestMatrix struct { DefaultSite VectorStore } func (c *ConfiguredDimensions) ResolveNames(v Vector) types.Strings3 { return types.Strings3{ c.ConfiguredLanguages.ResolveName(v.Language()), c.ConfiguredVersions.ResolveName(v.Version()), c.ConfiguredRoles.ResolveName(v.Role()), } } func (c *ConfiguredDimensions) ResolveVector(names types.Strings3) Vector { var vec Vector if s := names[0]; s != "" { vec[0] = c.ConfiguredLanguages.ResolveIndex(s) } else { vec[0] = c.ConfiguredLanguages.IndexDefault() } if s := names[1]; s != "" { vec[1] = c.ConfiguredVersions.ResolveIndex(s) } else { vec[1] = c.ConfiguredVersions.IndexDefault() } if s := names[2]; s != "" { vec[2] = c.ConfiguredRoles.ResolveIndex(s) } else { vec[2] = c.ConfiguredRoles.IndexDefault() } return vec } // IntSets holds the ordered sets of integers for the dimensions, // which is used for fast membership testing of files, resources and pages. type IntSets struct { languages *maps.OrderedIntSet `mapstructure:"-" json:"-"` versions *maps.OrderedIntSet `mapstructure:"-" json:"-"` roles *maps.OrderedIntSet `mapstructure:"-" json:"-"` h *hashOnce } var NilStore *IntSets = nil type hashOnce struct { once sync.Once hash uint64 } func (s *IntSets) ToVectorStoreMap() *vectorStoreMap { if s == nil { return nil } result := newVectorStoreMap(36) s.ForEachVector(func(vec Vector) bool { result.setVector(vec) return true }) return result } func (s *IntSets) IsSuperSet(other *IntSets) bool { return s.languages.IsSuperSet(other.languages) && s.versions.IsSuperSet(other.versions) && s.roles.IsSuperSet(other.roles) } func (s *IntSets) DifferenceCardinality(other *IntSets) Vector { return Vector{ int(s.languages.Values().DifferenceCardinality(other.languages.Values())), int(s.versions.Values().DifferenceCardinality(other.versions.Values())), int(s.roles.Values().DifferenceCardinality(other.roles.Values())), } } func (s *IntSets) Intersects(other *IntSets) bool { if s == nil || other == nil { return false } return s.languages.Values().IntersectionCardinality(other.languages.Values()) > 0 && s.versions.Values().IntersectionCardinality(other.versions.Values()) > 0 && s.roles.Values().IntersectionCardinality(other.roles.Values()) > 0 } // Complement returns a new VectorStore that contains all vectors in s that are not in any of ss. func (s *IntSets) Complement(ss ...VectorProvider) VectorStore { if len(ss) == 0 || (len(ss) == 1 && ss[0] == s) { return NilStore } for _, v := range ss { vv, ok := v.(*IntSets) if !ok { continue } if vv.IsSuperSet(s) { return NilStore } } result := newVectorStoreMap(36) s.ForEachVector(func(vec Vector) bool { var found bool for _, v := range ss { if v.HasVector(vec) { found = true break } } if !found { result.setVector(vec) } return true }) return result } func (s *IntSets) EqualsVector(other VectorProvider) bool { if s == nil && other == nil { return true } if s == nil || other == nil { return false } if s == other { return true } if s.LenVectors() != other.LenVectors() { return false } return other.ForEachVector(func(v Vector) bool { return s.HasVector(v) }) } func (s *IntSets) VectorSample() Vector { if s.LenVectors() == 0 { panic("no vectors available") } return Vector{ s.languages.Next(0), s.versions.Next(0), s.roles.Next(0), } } // The reason we don't use iter.Seq is https://github.com/golang/go/issues/69015 // This is 60% faster and allocation free. // The yield function should return false to stop iteration. func (s *IntSets) ForEachVector(yield func(v Vector) bool) bool { if s.LenVectors() == 0 { return true } b := s.languages.ForEachKey(func(lang int) bool { return s.versions.ForEachKey(func(ver int) bool { return s.roles.ForEachKey(func(role int) bool { return yield(Vector{lang, ver, role}) }) }) }) return b } func (s *IntSets) Vectors() []Vector { if s.LenVectors() == 0 { return nil } var vectors []Vector s.ForEachVector(func(v Vector) bool { vectors = append(vectors, v) return true }) sort.Slice(vectors, func(i, j int) bool { v1, v2 := vectors[i], vectors[j] return v1.Compare(v2) < 0 }) return vectors } func (s *IntSets) KeysSorted() ([]int, []int, []int) { if s == nil { return nil, nil, nil } languages := s.languages.KeysSorted() versions := s.versions.KeysSorted() roles := s.roles.KeysSorted() return languages, versions, roles } func (s *IntSets) HasLanguage(lang int) bool { if s == nil { return false } return s.languages.Has(lang) } // LenVectors returns the total number of vectors represented by the IntSets. // This is the Cartesian product of the lengths of the individual sets. // This will be 0 if s is nil or any of the sets is empty. func (s *IntSets) LenVectors() int { if s == nil { return 0 } return s.languages.Len() * s.versions.Len() * s.roles.Len() } func (s *IntSets) HasRole(role int) bool { if s == nil { return false } return s.roles.Has(role) } func (s *IntSets) String() string { return fmt.Sprintf("Languages: %v, Versions: %v, Roles: %v", s.languages, s.versions, s.roles) } // HasVector checks if the given vector is contained in the sets. func (s *IntSets) HasVector(v Vector) bool { if s == nil { return false } if !s.languages.Has(v.Language()) { return false } if !s.versions.Has(v.Version()) { return false } if !s.roles.Has(v.Role()) { return false } return true } func (s *IntSets) HasAnyVector(v VectorProvider) bool { if s == nil || v == nil { return false } if s.LenVectors() == 0 || v.LenVectors() == 0 { return false } if v.LenVectors() == 1 { // Fast path. return s.HasVector(v.VectorSample()) } if vs, ok := v.(*IntSets); ok { // Fast path. return s.Intersects(vs) } return !v.ForEachVector(func(vec Vector) bool { if s.HasVector(vec) { return false // stop iteration } return true // continue iteration }) } func (s *IntSets) HasVersion(ver int) bool { if s == nil { return false } return s.versions.Has(ver) } func (s IntSets) shallowClone() *IntSets { s.h = &hashOnce{} return &s } // WithLanguageIndices replaces the current language set with a single language index. func (s *IntSets) WithLanguageIndices(i int) VectorStore { c := s.shallowClone() c.languages = maps.NewOrderedIntSet(i) return c.init() } func (s *IntSets) Hash() (uint64, error) { s.initHash() return s.h.hash, nil } func (s *IntSets) MustHash() uint64 { if s == nil { return 0 } hash, err := s.Hash() if err != nil { panic(fmt.Errorf("failed to calculate hash for IntSets: %w", err)) } return hash } // setDefaultsIfNotSet applies default values to the IntSets if they are not already set. func (s *IntSets) setDefaultsIfNotSet(cfg *ConfiguredDimensions) { if s.languages == nil { s.languages = maps.NewOrderedIntSet() s.languages.Set(cfg.ConfiguredLanguages.IndexDefault()) } if s.versions == nil { s.versions = maps.NewOrderedIntSet() s.versions.Set(cfg.ConfiguredVersions.IndexDefault()) } if s.roles == nil { s.roles = maps.NewOrderedIntSet() s.roles.Set(cfg.ConfiguredRoles.IndexDefault()) } } func (s *IntSets) setDefaultsAndAllLAnguagesIfNotSet(cfg *ConfiguredDimensions) { if s.languages == nil { s.languages = maps.NewOrderedIntSet() for i := range cfg.ConfiguredLanguages.ForEachIndex() { s.languages.Set(i) } } s.setDefaultsIfNotSet(cfg) } func (s *IntSets) setAllIfNotSet(cfg *ConfiguredDimensions) { if s.languages == nil { s.languages = maps.NewOrderedIntSet() for i := range cfg.ConfiguredLanguages.ForEachIndex() { s.languages.Set(i) } } if s.versions == nil { s.versions = maps.NewOrderedIntSet() for i := range cfg.ConfiguredVersions.ForEachIndex() { s.versions.Set(i) } } if s.roles == nil { s.roles = maps.NewOrderedIntSet() for i := range cfg.ConfiguredRoles.ForEachIndex() { s.roles.Set(i) } } } func (s *IntSets) initHash() { s.h.once.Do(func() { var err error s.h.hash, err = hashing.Hash(s.languages.Words(), s.versions.Words(), s.roles.Words()) if err != nil { panic(fmt.Errorf("failed to calculate hash for IntSets: %w", err)) } }) } func (s *IntSets) init() *IntSets { return s } func (s *IntSets) setDimensionsFromOtherIfNotSet(other VectorIterator) { if other == nil { return } setLang := s.languages == nil setVer := s.versions == nil setRole := s.roles == nil if !(setLang || setVer || setRole) { return } other.ForEachVector(func(v Vector) bool { if !s.HasVector(v) { s.setValuesInNilSets(v, setLang, setVer, setRole) } return true }) } func (s *IntSets) setValuesInNilSets(vec Vector, setLang, setVer, setRole bool) { if setLang { if s.languages == nil { s.languages = maps.NewOrderedIntSet() } s.languages.Set(vec.Language()) } if setVer { if s.versions == nil { s.versions = maps.NewOrderedIntSet() } s.versions.Set(vec.Version()) } if setRole { if s.roles == nil { s.roles = maps.NewOrderedIntSet() } s.roles.Set(vec.Role()) } } type IntSetsBuilder struct { cfg *ConfiguredDimensions s *IntSets // Set when a Glob (e.g. "en") filter is provided but no matches are found. GlobFilterMisses Bools } func (b *IntSetsBuilder) Build() *IntSets { b.s.init() if b.s.LenVectors() == 1 { // Cache it or use the existing cached version, which will allow b.s to be GCed. bb, _ := b.cfg.singleVectorStoreCache.GetOrCreate(b.s.VectorSample(), func() (*IntSets, error) { return b.s, nil }) return bb } return b.s } func (b *IntSetsBuilder) WithConfig(cfg IntSetsConfig) *IntSetsBuilder { applyFilter := func(what string, values []string, matcher ConfiguredDimension) (*maps.OrderedIntSet, error) { var result *maps.OrderedIntSet if len(values) == 0 { if cfg.ApplyDefaults > 0 { result = maps.NewOrderedIntSet() } switch cfg.ApplyDefaults { case IntSetsConfigApplyDefaultsIfNotSet: result.Set(matcher.IndexDefault()) case IntSetsConfigApplyDefaultsAndAllLanguagesIfNotSet: if what == "languages" { for i := range matcher.ForEachIndex() { result.Set(i) } } else { result.Set(matcher.IndexDefault()) } } return result, nil } // Dot separated globs. filter, err := predicate.NewStringPredicateFromGlobs(values, hglob.GetGlobDot) if err != nil { return nil, fmt.Errorf("failed to create filter for %s: %w", what, err) } for _, pattern := range values { iter, err := matcher.IndexMatch(filter) if err != nil { return nil, fmt.Errorf("failed to match %s %q: %w", what, pattern, err) } for i := range iter { if result == nil { result = maps.NewOrderedIntSet() } result.Set(i) } } return result, nil } l, err1 := applyFilter("languages", cfg.Globs.Languages, b.cfg.ConfiguredLanguages) v, err2 := applyFilter("versions", cfg.Globs.Versions, b.cfg.ConfiguredVersions) r, err3 := applyFilter("roles", cfg.Globs.Roles, b.cfg.ConfiguredRoles) if err := cmp.Or(err1, err2, err3); err != nil { panic(fmt.Errorf("failed to apply filters: %w", err)) } b.GlobFilterMisses = Bools{ len(cfg.Globs.Languages) > 0 && l == nil, len(cfg.Globs.Versions) > 0 && v == nil, len(cfg.Globs.Roles) > 0 && r == nil, } b.s.languages = l b.s.versions = v b.s.roles = r return b } func (s *IntSetsBuilder) WithLanguageIndices(idxs ...int) *IntSetsBuilder { if len(idxs) == 0 { return s } if s.s.languages == nil { s.s.languages = maps.NewOrderedIntSet() } for _, i := range idxs { s.s.languages.Set(i) } return s } func (s *IntSetsBuilder) WithDefaultsAndAllLanguagesIfNotSet() *IntSetsBuilder { s.s.setDefaultsAndAllLAnguagesIfNotSet(s.cfg) return s } func (s *IntSetsBuilder) WithAllIfNotSet() *IntSetsBuilder { s.s.setAllIfNotSet(s.cfg) return s } func (s *IntSetsBuilder) WithDefaultsIfNotSet() *IntSetsBuilder { s.s.setDefaultsIfNotSet(s.cfg) return s } func (s *IntSetsBuilder) WithDimensionsFromOtherIfNotSet(other VectorIterator) *IntSetsBuilder { s.s.setDimensionsFromOtherIfNotSet(other) return s } func (b *IntSetsBuilder) WithSets(languages, versions, roles *maps.OrderedIntSet) *IntSetsBuilder { b.s.languages = languages b.s.versions = versions b.s.roles = roles return b } type IntSetsConfigApplyDefaults int const ( IntSetsConfigApplyDefaultsNone IntSetsConfigApplyDefaults = iota IntSetsConfigApplyDefaultsIfNotSet IntSetsConfigApplyDefaultsAndAllLanguagesIfNotSet ) type IntSetsConfig struct { ApplyDefaults IntSetsConfigApplyDefaults Globs StringSlices } // Sites holds configuration about which sites a file/content/page/resource belongs to. type Sites struct { // Matrix defines what sites to build this content for. Matrix StringSlices `mapstructure:"matrix" json:"matrix"` // Complements defines what sites to complement with this content. Complements StringSlices `mapstructure:"complements" json:"complements"` } func (s *Sites) Equal(other Sites) bool { return s.Matrix.Equal(other.Matrix) && s.Complements.Equal(other.Complements) } func (s *Sites) SetFromParamsIfNotSet(params maps.Params) { const ( matrixKey = "matrix" complementsKey = "complements" ) if m, ok := params[matrixKey]; ok { s.Matrix.SetFromParamsIfNotSet(m.(maps.Params)) } if f, ok := params[complementsKey]; ok { s.Complements.SetFromParamsIfNotSet(f.(maps.Params)) } } // IsZero returns true if all slices are empty. func (s Sites) IsZero() bool { return s.Matrix.IsZero() && s.Complements.IsZero() } // StringSlices holds slices of Glob patterns for languages, versions, and roles. type StringSlices struct { Languages []string `mapstructure:"languages" json:"languages"` Versions []string `mapstructure:"versions" json:"versions"` Roles []string `mapstructure:"roles" json:"roles"` } func (d StringSlices) Equal(other StringSlices) bool { return slices.Equal(d.Languages, other.Languages) && slices.Equal(d.Versions, other.Versions) && slices.Equal(d.Roles, other.Roles) } func (d *StringSlices) SetFromParamsIfNotSet(params maps.Params) { const ( languagesKey = "languages" versionsKey = "versions" rolesKey = "roles" ) if len(d.Languages) == 0 { if v, ok := params[languagesKey]; ok { d.Languages = types.ToStringSlicePreserveString(v) } } if len(d.Versions) == 0 { if v, ok := params[versionsKey]; ok { d.Versions = types.ToStringSlicePreserveString(v) } } if len(d.Roles) == 0 { if v, ok := params[rolesKey]; ok { d.Roles = types.ToStringSlicePreserveString(v) } } } func (d StringSlices) IsZero() bool { return len(d.Languages) == 0 && len(d.Versions) == 0 && len(d.Roles) == 0 } // Used in tests. type testDimension struct { names []string } func (m testDimension) Len() int { return len(m.names) } func (m testDimension) IndexDefault() int { return 0 } func (m *testDimension) ResolveIndex(name string) int { for i, n := range m.names { if n == name { return i } } return -1 } func (m *testDimension) ResolveName(i int) string { if i < 0 || i >= len(m.names) { return "" } return m.names[i] } func (m *testDimension) ForEachIndex() iter.Seq[int] { return func(yield func(i int) bool) { for i := range m.names { if !yield(i) { return } } } } func (m *testDimension) IndexMatch(match predicate.P[string]) (iter.Seq[int], error) { return func(yield func(i int) bool) { for i, n := range m.names { if match(n) { if !yield(i) { return } } } }, nil } // NewTestingDimensions creates a new ConfiguredDimensions for testing. func NewTestingDimensions(languages, versions, roles []string) *ConfiguredDimensions { c := &ConfiguredDimensions{ ConfiguredLanguages: &testDimension{names: languages}, ConfiguredVersions: &testDimension{names: versions}, ConfiguredRoles: &testDimension{names: roles}, } if err := c.Init(); err != nil { panic(err) } return c }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/sitesmatrix/dimensions_test.go
hugolib/sitesmatrix/dimensions_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sitesmatrix import ( "testing" qt "github.com/frankban/quicktest" ) func TestDimensionsCompare(t *testing.T) { c := qt.New(t) c.Assert(Vector{1, 2, 3}.Compare(Vector{1, 2, 8}), qt.Equals, -1) c.Assert(Vector{1, 2, 3}.Compare(Vector{1, 2, 3}), qt.Equals, 0) c.Assert(Vector{1, 2, 3}.Compare(Vector{1, 2, 0}), qt.Equals, 1) c.Assert(Vector{1, 2, 3}.Compare(Vector{1, 0, 3}), qt.Equals, 1) c.Assert(Vector{1, 2, 3}.Compare(Vector{0, 3, 2}), qt.Equals, 1) c.Assert(Vector{1, 2, 3}.Compare(Vector{0, 0, 0}), qt.Equals, 1) c.Assert(Vector{0, 0, 0}.Compare(Vector{1, 2, 3}), qt.Equals, -1) c.Assert(Vector{0, 0, 0}.Compare(Vector{0, 0, 0}), qt.Equals, 0) c.Assert(Vector{0, 0, 0}.Compare(Vector{1, 0, 0}), qt.Equals, -1) c.Assert(Vector{0, 0, 0}.Compare(Vector{0, 1, 0}), qt.Equals, -1) c.Assert(Vector{0, 0, 0}.Compare(Vector{0, 0, 1}), qt.Equals, -1) } func TestDimensionsDistance(t *testing.T) { c := qt.New(t) c.Assert(Vector{1, 2, 3}.Distance(Vector{1, 2, 8}), qt.Equals, -5) c.Assert(Vector{1, 2, 3}.Distance(Vector{1, 2, 3}), qt.Equals, 0) c.Assert(Vector{1, 2, 3}.Distance(Vector{1, 2, 0}), qt.Equals, 3) c.Assert(Vector{1, 2, 3}.Distance(Vector{1, 0, 3}), qt.Equals, 2) c.Assert(Vector{1, 2, 3}.Distance(Vector{0, 3, 2}), qt.Equals, 1) } func BenchmarkCompare(b *testing.B) { b.Run("Equal", func(b *testing.B) { v1 := Vector{1, 2, 3} v2 := Vector{1, 2, 3} for b.Loop() { v1.Compare(v2) } }) b.Run("First different", func(b *testing.B) { v1 := Vector{1, 2, 3} v2 := Vector{2, 2, 3} for b.Loop() { v1.Compare(v2) } }) b.Run("Last different", func(b *testing.B) { v1 := Vector{1, 2, 3} v2 := Vector{1, 2, 4} for b.Loop() { v1.Compare(v2) } }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/versions/versions.go
hugolib/versions/versions.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package versions import ( "errors" "fmt" "iter" "sort" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/predicate" "github.com/gohugoio/hugo/common/version" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/mitchellh/mapstructure" ) var _ sitesmatrix.DimensionInfo = (*versionWrapper)(nil) type VersionConfig struct { // The weight of the version. // Used to determine the order of the versions. // If zero, we use the version name to sort. Weight int } type Version interface { Name() string } type Versions []Version type versionWrapper struct { v VersionInternal } func (v versionWrapper) Name() string { return v.v.Name } func (v versionWrapper) IsDefault() bool { return v.v.Default } func NewVersion(v VersionInternal) Version { return versionWrapper{v: v} } var _ Version = (*versionWrapper)(nil) type VersionInternal struct { // Name of the version. // This is the key from the config. Name string // Whether this version is the default version. // This will be by default rendered in the root. // There can only be one default version. Default bool VersionConfig } type VersionsInternal struct { versionConfigs map[string]VersionConfig Sorted []VersionInternal } func (r VersionsInternal) Len() int { return len(r.Sorted) } func (r VersionsInternal) IndexDefault() int { for i, version := range r.Sorted { if version.Default { return i } } panic("no default version found") } func (r VersionsInternal) ResolveName(i int) string { if i < 0 || i >= len(r.Sorted) { panic(fmt.Sprintf("index %d out of range for versions", i)) } return r.Sorted[i].Name } func (r VersionsInternal) ResolveIndex(name string) int { for i, version := range r.Sorted { if version.Name == name { return i } } panic(fmt.Sprintf("no version found for name %q", name)) } // IndexMatch returns an iterator for the versions that match the filter. func (r VersionsInternal) IndexMatch(match predicate.P[string]) (iter.Seq[int], error) { return func(yield func(i int) bool) { for i, version := range r.Sorted { if match(version.Name) { if !yield(i) { return } } } }, nil } // ForEachIndex returns an iterator for the indices of the versions. func (r VersionsInternal) ForEachIndex() iter.Seq[int] { return func(yield func(i int) bool) { for i := range r.Sorted { if !yield(i) { return } } } } const defaultContentVersionFallback = "v1.0.0" func (r *VersionsInternal) init(defaultContentVersion string) error { if r.versionConfigs == nil { r.versionConfigs = make(map[string]VersionConfig) } defaultContentVersionProvided := defaultContentVersion != "" if len(r.versionConfigs) == 0 { if defaultContentVersion == "" { defaultContentVersion = defaultContentVersionFallback } // Add a default version. r.versionConfigs[defaultContentVersion] = VersionConfig{} } var defaultSeen bool for k, v := range r.versionConfigs { if k == "" { return errors.New("version name cannot be empty") } if err := paths.ValidateIdentifier(k); err != nil { return fmt.Errorf("version name %q is invalid: %s", k, err) } var isDefault bool if k == defaultContentVersion { isDefault = true defaultSeen = true } r.Sorted = append(r.Sorted, VersionInternal{Name: k, Default: isDefault, VersionConfig: v}) } // Sort by weight if set, then semver descending. sort.SliceStable(r.Sorted, func(i, j int) bool { ri, rj := r.Sorted[i], r.Sorted[j] if ri.Weight == rj.Weight { v1, v2 := version.MustParseVersion(ri.Name), version.MustParseVersion(rj.Name) return v1.Compare(v2) < 0 } if rj.Weight == 0 { return true } if ri.Weight == 0 { return false } return ri.Weight < rj.Weight }) if !defaultSeen { if defaultContentVersionProvided { return fmt.Errorf("the configured defaultContentVersion %q does not exist", defaultContentVersion) } // If no default version is set, we set the first one. first := r.Sorted[0] first.Default = true r.versionConfigs[first.Name] = first.VersionConfig r.Sorted[0] = first } return nil } func (r VersionsInternal) Has(version string) bool { _, found := r.versionConfigs[version] return found } func DecodeConfig(defaultContentVersion string, m map[string]any) (*config.ConfigNamespace[map[string]VersionConfig, VersionsInternal], error) { return config.DecodeNamespace[map[string]VersionConfig](m, func(in any) (VersionsInternal, any, error) { var versions VersionsInternal var conf map[string]VersionConfig if err := mapstructure.Decode(m, &conf); err != nil { return versions, nil, err } versions.versionConfigs = conf if err := versions.init(defaultContentVersion); err != nil { return versions, nil, err } return versions, versions.versionConfigs, nil }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/versions/versions_integration_test.go
hugolib/versions/versions_integration_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package versions_test import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestDefaultContentVersionDoesNotExist(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"] defaultContentLanguage = "en" defaultContentLanguageInSubDir = true defaultContentVersion = "doesnotexist" [versions] [versions."v1.0.0"] ` b, err := hugolib.TestE(t, files) b.Assert(err, qt.ErrorMatches, `.*failed to decode "versions": the configured defaultContentVersion "doesnotexist" does not exist`) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/filesystems/basefs_test.go
hugolib/filesystems/basefs_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package filesystems_test import ( "context" "errors" "fmt" "os" "path/filepath" "runtime" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/hugolib" "github.com/spf13/afero" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/hugolib/paths" ) func TestNewBaseFs(t *testing.T) { c := qt.New(t) v := config.New() themes := []string{"btheme", "atheme"} workingDir := filepath.FromSlash("/my/work") v.Set("workingDir", workingDir) v.Set("contentDir", "content") v.Set("themesDir", "themes") v.Set("defaultContentLanguage", "en") v.Set("theme", themes[:1]) v.Set("publishDir", "public") afs := afero.NewMemMapFs() // Write some data to the themes for _, theme := range themes { for _, dir := range []string{"i18n", "data", "archetypes", "layouts"} { base := filepath.Join(workingDir, "themes", theme, dir) filenameTheme := filepath.Join(base, fmt.Sprintf("theme-file-%s.txt", theme)) filenameOverlap := filepath.Join(base, "f3.txt") afs.Mkdir(base, 0o755) content := fmt.Appendf(nil, "content:%s:%s", theme, dir) afero.WriteFile(afs, filenameTheme, content, 0o755) afero.WriteFile(afs, filenameOverlap, content, 0o755) } // Write some files to the root of the theme base := filepath.Join(workingDir, "themes", theme) afero.WriteFile(afs, filepath.Join(base, fmt.Sprintf("theme-root-%s.txt", theme)), fmt.Appendf(nil, "content:%s", theme), 0o755) afero.WriteFile(afs, filepath.Join(base, "file-theme-root.txt"), fmt.Appendf(nil, "content:%s", theme), 0o755) } afero.WriteFile(afs, filepath.Join(workingDir, "file-root.txt"), []byte("content-project"), 0o755) afero.WriteFile(afs, filepath.Join(workingDir, "themes", "btheme", "config.toml"), []byte(` theme = ["atheme"] `), 0o755) setConfigAndWriteSomeFilesTo(afs, v, "contentDir", "mycontent", 3) setConfigAndWriteSomeFilesTo(afs, v, "i18nDir", "myi18n", 4) setConfigAndWriteSomeFilesTo(afs, v, "layoutDir", "mylayouts", 5) setConfigAndWriteSomeFilesTo(afs, v, "staticDir", "mystatic", 6) setConfigAndWriteSomeFilesTo(afs, v, "dataDir", "mydata", 7) setConfigAndWriteSomeFilesTo(afs, v, "archetypeDir", "myarchetypes", 8) setConfigAndWriteSomeFilesTo(afs, v, "assetDir", "myassets", 9) setConfigAndWriteSomeFilesTo(afs, v, "resourceDir", "myrsesource", 10) conf := testconfig.GetTestConfig(afs, v) fs := hugofs.NewFrom(afs, conf.BaseConfig()) p, err := paths.New(fs, conf) c.Assert(err, qt.IsNil) bfs, err := filesystems.NewBase(p, nil) c.Assert(err, qt.IsNil) c.Assert(bfs, qt.Not(qt.IsNil)) root, err := bfs.I18n.Fs.Open("") c.Assert(err, qt.IsNil) dirnames, err := root.Readdirnames(-1) c.Assert(err, qt.IsNil) c.Assert(dirnames, qt.DeepEquals, []string{"f1.txt", "f2.txt", "f3.txt", "f4.txt", "f3.txt", "theme-file-btheme.txt", "f3.txt", "theme-file-atheme.txt"}) root, err = bfs.Data.Fs.Open("") c.Assert(err, qt.IsNil) dirnames, err = root.Readdirnames(-1) c.Assert(err, qt.IsNil) c.Assert(dirnames, qt.DeepEquals, []string{"f1.txt", "f2.txt", "f3.txt", "f4.txt", "f5.txt", "f6.txt", "f7.txt", "f3.txt", "theme-file-btheme.txt", "f3.txt", "theme-file-atheme.txt"}) checkFileCount(bfs.Layouts.Fs, "", c, 7) checkFileCount(bfs.Content.Fs, "", c, 3) checkFileCount(bfs.I18n.Fs, "", c, 8) // 4 + 4 themes checkFileCount(bfs.Static[""].Fs, "", c, 6) checkFileCount(bfs.Data.Fs, "", c, 11) // 7 + 4 themes checkFileCount(bfs.Archetypes.Fs, "", c, 10) // 8 + 2 themes checkFileCount(bfs.Assets.Fs, "", c, 9) checkFileCount(bfs.Work, "", c, 90) c.Assert(bfs.IsStatic(filepath.Join(workingDir, "mystatic", "file1.txt")), qt.Equals, true) contentFilename := filepath.Join(workingDir, "mycontent", "file1.txt") c.Assert(bfs.IsContent(contentFilename), qt.Equals, true) // Check Work fs vs theme checkFileContent(bfs.Work, "file-root.txt", c, "content-project") checkFileContent(bfs.Work, "theme-root-atheme.txt", c, "content:atheme") // https://github.com/gohugoio/hugo/issues/5318 // Check both project and theme. for _, fs := range []afero.Fs{bfs.Archetypes.Fs, bfs.Layouts.Fs} { for _, filename := range []string{"/f1.txt", "/theme-file-atheme.txt"} { filename = filepath.FromSlash(filename) f, err := fs.Open(filename) c.Assert(err, qt.IsNil) f.Close() } } } func TestNewBaseFsEmpty(t *testing.T) { c := qt.New(t) afs := afero.NewMemMapFs() conf := testconfig.GetTestConfig(afs, nil) fs := hugofs.NewFrom(afs, conf.BaseConfig()) p, err := paths.New(fs, conf) c.Assert(err, qt.IsNil) bfs, err := filesystems.NewBase(p, nil) c.Assert(err, qt.IsNil) c.Assert(bfs, qt.Not(qt.IsNil)) c.Assert(bfs.Archetypes.Fs, qt.Not(qt.IsNil)) c.Assert(bfs.Layouts.Fs, qt.Not(qt.IsNil)) c.Assert(bfs.Data.Fs, qt.Not(qt.IsNil)) c.Assert(bfs.I18n.Fs, qt.Not(qt.IsNil)) c.Assert(bfs.Work, qt.Not(qt.IsNil)) c.Assert(bfs.Content.Fs, qt.Not(qt.IsNil)) c.Assert(bfs.Static, qt.Not(qt.IsNil)) } func TestRealDirs(t *testing.T) { c := qt.New(t) v := config.New() root, themesDir := t.TempDir(), t.TempDir() v.Set("workingDir", root) v.Set("themesDir", themesDir) v.Set("assetDir", "myassets") v.Set("theme", "mytheme") afs := &hugofs.OpenFilesFs{Fs: hugofs.Os} c.Assert(afs.MkdirAll(filepath.Join(root, "myassets", "scss", "sf1"), 0o755), qt.IsNil) c.Assert(afs.MkdirAll(filepath.Join(root, "myassets", "scss", "sf2"), 0o755), qt.IsNil) c.Assert(afs.MkdirAll(filepath.Join(themesDir, "mytheme", "assets", "scss", "sf2"), 0o755), qt.IsNil) c.Assert(afs.MkdirAll(filepath.Join(themesDir, "mytheme", "assets", "scss", "sf3"), 0o755), qt.IsNil) c.Assert(afs.MkdirAll(filepath.Join(root, "resources"), 0o755), qt.IsNil) c.Assert(afs.MkdirAll(filepath.Join(themesDir, "mytheme", "resources"), 0o755), qt.IsNil) c.Assert(afs.MkdirAll(filepath.Join(root, "myassets", "js", "f2"), 0o755), qt.IsNil) afero.WriteFile(afs, filepath.Join(filepath.Join(root, "myassets", "scss", "sf1", "a1.scss")), []byte("content"), 0o755) afero.WriteFile(afs, filepath.Join(filepath.Join(root, "myassets", "scss", "sf2", "a3.scss")), []byte("content"), 0o755) afero.WriteFile(afs, filepath.Join(filepath.Join(root, "myassets", "scss", "a2.scss")), []byte("content"), 0o755) afero.WriteFile(afs, filepath.Join(filepath.Join(themesDir, "mytheme", "assets", "scss", "sf2", "a3.scss")), []byte("content"), 0o755) afero.WriteFile(afs, filepath.Join(filepath.Join(themesDir, "mytheme", "assets", "scss", "sf3", "a4.scss")), []byte("content"), 0o755) afero.WriteFile(afs, filepath.Join(filepath.Join(themesDir, "mytheme", "resources", "t1.txt")), []byte("content"), 0o755) afero.WriteFile(afs, filepath.Join(filepath.Join(root, "resources", "p1.txt")), []byte("content"), 0o755) afero.WriteFile(afs, filepath.Join(filepath.Join(root, "resources", "p2.txt")), []byte("content"), 0o755) afero.WriteFile(afs, filepath.Join(filepath.Join(root, "myassets", "js", "f2", "a1.js")), []byte("content"), 0o755) afero.WriteFile(afs, filepath.Join(filepath.Join(root, "myassets", "js", "a2.js")), []byte("content"), 0o755) conf := testconfig.GetTestConfig(afs, v) fs := hugofs.NewFrom(afs, conf.BaseConfig()) p, err := paths.New(fs, conf) c.Assert(err, qt.IsNil) bfs, err := filesystems.NewBase(p, nil) c.Assert(err, qt.IsNil) c.Assert(bfs, qt.Not(qt.IsNil)) checkFileCount(bfs.Assets.Fs, "", c, 6) realDirs := bfs.Assets.RealDirs("scss") c.Assert(len(realDirs), qt.Equals, 2) c.Assert(realDirs[0], qt.Equals, filepath.Join(root, "myassets/scss")) c.Assert(realDirs[len(realDirs)-1], qt.Equals, filepath.Join(themesDir, "mytheme/assets/scss")) realDirs = bfs.Assets.RealDirs("foo") c.Assert(len(realDirs), qt.Equals, 0) c.Assert(afs.OpenFiles(), qt.HasLen, 0) } func TestWatchFilenames(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- theme = "t1" [[module.mounts]] source = 'content' target = 'content' [[module.mounts]] source = 'content2' target = 'content/c2' [[module.mounts]] source = 'content3' target = 'content/watchdisabled' disableWatch = true [[module.mounts]] source = 'content4' target = 'content/excludedsome' excludeFiles = 'p1.md' [[module.mounts]] source = 'content5' target = 'content/excludedall' excludeFiles = '/**' [[module.mounts]] source = "hugo_stats.json" target = "assets/watching/hugo_stats.json" -- hugo_stats.json -- Some stats. -- content/foo.md -- foo -- content2/bar.md -- -- themes/t1/layouts/_default/single.html -- {{ .Content }} -- themes/t1/static/f1.txt -- -- content3/p1.md -- -- content4/p1.md -- -- content4/p2.md -- -- content5/p3.md -- -- content5/p4.md -- ` b := hugolib.Test(t, files) bfs := b.H.BaseFs watchFilenames := toSlashes(bfs.WatchFilenames()) // content3 has disableWatch = true // content5 has excludeFiles = '/**' b.Assert(watchFilenames, qt.DeepEquals, []string{"/hugo_stats.json", "/content", "/content2", "/content4", "/themes/t1/layouts", "/themes/t1/layouts/_default", "/themes/t1/static"}) } func toSlashes(in []string) []string { out := make([]string, len(in)) for i, s := range in { out[i] = filepath.ToSlash(s) } return out } func TestNoSymlinks(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("skip on Windows") } files := ` -- hugo.toml -- theme = "t1" -- content/a/foo.md -- foo -- static/a/f1.txt -- F1 text -- themes/t1/layouts/_default/single.html -- {{ .Content }} -- themes/t1/static/a/f1.txt -- ` tmpDir := t.TempDir() wd, _ := os.Getwd() for _, component := range []string{"content", "static"} { aDir := filepath.Join(tmpDir, component, "a") bDir := filepath.Join(tmpDir, component, "b") os.MkdirAll(aDir, 0o755) os.MkdirAll(bDir, 0o755) os.Chdir(bDir) os.Symlink("../a", "c") } os.Chdir(wd) b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, WorkingDir: tmpDir, }, ).Build() bfs := b.H.BaseFs watchFilenames := bfs.WatchFilenames() b.Assert(watchFilenames, qt.HasLen, 10) } func TestStaticFs(t *testing.T) { c := qt.New(t) v := config.New() workDir := "mywork" v.Set("workingDir", workDir) v.Set("themesDir", "themes") v.Set("staticDir", "mystatic") v.Set("theme", []string{"t1", "t2"}) afs := afero.NewMemMapFs() themeStaticDir := filepath.Join(workDir, "themes", "t1", "static") themeStaticDir2 := filepath.Join(workDir, "themes", "t2", "static") afero.WriteFile(afs, filepath.Join(workDir, "mystatic", "f1.txt"), []byte("Hugo Rocks!"), 0o755) afero.WriteFile(afs, filepath.Join(themeStaticDir, "f1.txt"), []byte("Hugo Themes Rocks!"), 0o755) afero.WriteFile(afs, filepath.Join(themeStaticDir, "f2.txt"), []byte("Hugo Themes Still Rocks!"), 0o755) afero.WriteFile(afs, filepath.Join(themeStaticDir2, "f2.txt"), []byte("Hugo Themes Rocks in t2!"), 0o755) conf := testconfig.GetTestConfig(afs, v) fs := hugofs.NewFrom(afs, conf.BaseConfig()) p, err := paths.New(fs, conf) c.Assert(err, qt.IsNil) bfs, err := filesystems.NewBase(p, nil) c.Assert(err, qt.IsNil) sfs := bfs.StaticFs("en") checkFileContent(sfs, "f1.txt", c, "Hugo Rocks!") checkFileContent(sfs, "f2.txt", c, "Hugo Themes Still Rocks!") } func TestStaticFsMultihost(t *testing.T) { c := qt.New(t) v := config.New() workDir := "mywork" v.Set("workingDir", workDir) v.Set("themesDir", "themes") v.Set("staticDir", "mystatic") v.Set("theme", "t1") v.Set("defaultContentLanguage", "en") langConfig := map[string]any{ "no": map[string]any{ "staticDir": "static_no", "baseURL": "https://example.org/no/", }, "en": map[string]any{ "baseURL": "https://example.org/en/", }, } v.Set("languages", langConfig) afs := afero.NewMemMapFs() themeStaticDir := filepath.Join(workDir, "themes", "t1", "static") afero.WriteFile(afs, filepath.Join(workDir, "mystatic", "f1.txt"), []byte("Hugo Rocks!"), 0o755) afero.WriteFile(afs, filepath.Join(workDir, "static_no", "f1.txt"), []byte("Hugo Rocks in Norway!"), 0o755) afero.WriteFile(afs, filepath.Join(themeStaticDir, "f1.txt"), []byte("Hugo Themes Rocks!"), 0o755) afero.WriteFile(afs, filepath.Join(themeStaticDir, "f2.txt"), []byte("Hugo Themes Still Rocks!"), 0o755) conf := testconfig.GetTestConfig(afs, v) fs := hugofs.NewFrom(afs, conf.BaseConfig()) p, err := paths.New(fs, conf) c.Assert(err, qt.IsNil) bfs, err := filesystems.NewBase(p, nil) c.Assert(err, qt.IsNil) enFs := bfs.StaticFs("en") checkFileContent(enFs, "f1.txt", c, "Hugo Rocks!") checkFileContent(enFs, "f2.txt", c, "Hugo Themes Still Rocks!") noFs := bfs.StaticFs("no") checkFileContent(noFs, "f1.txt", c, "Hugo Rocks in Norway!") checkFileContent(noFs, "f2.txt", c, "Hugo Themes Still Rocks!") } func TestMakePathRelative(t *testing.T) { files := ` -- hugo.toml -- [[module.mounts]] source = "bar.txt" target = "assets/foo/baz.txt" [[module.imports]] path = "t1" [[module.imports.mounts]] source = "src" target = "assets/foo/bar" -- bar.txt -- Bar. -- themes/t1/src/main.js -- Main. ` b := hugolib.Test(t, files) rel, found := b.H.BaseFs.Assets.MakePathRelative(filepath.FromSlash("/themes/t1/src/main.js"), true) b.Assert(found, qt.Equals, true) b.Assert(rel, qt.Equals, filepath.FromSlash("foo/bar/main.js")) rel, found = b.H.BaseFs.Assets.MakePathRelative(filepath.FromSlash("/bar.txt"), true) b.Assert(found, qt.Equals, true) b.Assert(rel, qt.Equals, filepath.FromSlash("foo/baz.txt")) } func TestAbsProjectContentDir(t *testing.T) { tempDir := t.TempDir() files := ` -- hugo.toml -- [[module.mounts]] source = "content" target = "content" -- content/foo.md -- --- title: "Foo" --- ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, WorkingDir: tempDir, TxtarString: files, }, ).Build() abs1 := filepath.Join(tempDir, "content", "foo.md") rel, abs2, err := b.H.BaseFs.AbsProjectContentDir("foo.md") b.Assert(err, qt.IsNil) b.Assert(abs2, qt.Equals, abs1) b.Assert(rel, qt.Equals, filepath.FromSlash("foo.md")) rel2, abs3, err := b.H.BaseFs.AbsProjectContentDir(abs1) b.Assert(err, qt.IsNil) b.Assert(abs3, qt.Equals, abs1) b.Assert(rel2, qt.Equals, rel) } func TestContentReverseLookup(t *testing.T) { files := ` -- README.md -- --- title: README --- -- blog/b1.md -- --- title: b1 --- -- docs/d1.md -- --- title: d1 --- -- hugo.toml -- baseURL = "https://example.com/" [module] [[module.mounts]] source = "layouts" target = "layouts" [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "blog" target = "content/posts" [[module.mounts]] source = "docs" target = "content/mydocs" -- layouts/home.html -- Home. ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "Home.") stat := func(path string) hugofs.FileMetaInfo { ps, err := b.H.BaseFs.Content.ReverseLookup(filepath.FromSlash(path), true) b.Assert(err, qt.IsNil) b.Assert(ps, qt.HasLen, 1) first := ps[0] fi, err := b.H.BaseFs.Content.Fs.Stat(filepath.FromSlash(first.Path)) b.Assert(err, qt.IsNil) b.Assert(fi, qt.Not(qt.IsNil)) return fi.(hugofs.FileMetaInfo) } sfs := b.H.Fs.Source _, err := sfs.Stat("blog/b1.md") b.Assert(err, qt.Not(qt.IsNil)) _ = stat("blog/b1.md") } func TestReverseLookupShouldOnlyConsiderFilesInCurrentComponent(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com/" [module] [[module.mounts]] source = "files/layouts" target = "layouts" [[module.mounts]] source = "files/layouts/assets" target = "assets" -- files/layouts/l1.txt -- l1 -- files/layouts/assets/l2.txt -- l2 ` b := hugolib.Test(t, files) assetsFs := b.H.Assets for _, checkExists := range []bool{false, true} { cps, err := assetsFs.ReverseLookup(filepath.FromSlash("files/layouts/assets/l2.txt"), checkExists) b.Assert(err, qt.IsNil) b.Assert(cps, qt.HasLen, 1) cps, err = assetsFs.ReverseLookup(filepath.FromSlash("files/layouts/l2.txt"), checkExists) b.Assert(err, qt.IsNil) b.Assert(cps, qt.HasLen, 0) } } func TestAssetsIssue12175(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com/" [module] [[module.mounts]] source = "node_modules/@foo/core/assets" target = "assets" [[module.mounts]] source = "assets" target = "assets" -- node_modules/@foo/core/assets/js/app.js -- JS. -- node_modules/@foo/core/assets/scss/app.scss -- body { color: red; } -- assets/scss/app.scss -- body { color: blue; } -- layouts/home.html -- Home. SCSS: {{ with resources.Get "scss/app.scss" }}{{ .RelPermalink }}|{{ .Content }}{{ end }}| # Note that the pattern below will match 2 resources, which doesn't make much sense, # but is how the current (and also < v0.123.0) merge logic works, and for most practical purposes, it doesn't matter. SCSS Match: {{ with resources.Match "**.scss" }}{{ . | len }}|{{ range .}}{{ .RelPermalink }}|{{ end }}{{ end }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` SCSS: /scss/app.scss|body { color: blue; }| SCSS Match: 2| `) } func TestStaticComposite(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] [module] [[module.mounts]] source = "myfiles/f1.txt" target = "static/files/f1.txt" [[module.mounts]] source = "f3.txt" target = "static/f3.txt" [[module.mounts]] source = "static" target = "static" -- static/files/f2.txt -- f2 -- myfiles/f1.txt -- f1 -- f3.txt -- f3 -- layouts/home.html -- Home. ` b := hugolib.Test(t, files) b.AssertFs(b.H.BaseFs.StaticFs(""), ` . true f3.txt false files true files/f1.txt false files/f2.txt false `) } func TestMountIssue12141(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] [module] [[module.mounts]] source = "myfiles" target = "static" [[module.mounts]] source = "myfiles/f1.txt" target = "static/f2.txt" -- myfiles/f1.txt -- f1 ` b := hugolib.Test(t, files) fs := b.H.BaseFs.StaticFs("") b.AssertFs(fs, ` . true f1.txt false f2.txt false `) } func checkFileCount(fs afero.Fs, dirname string, c *qt.C, expected int) { c.Helper() count, names, err := countFilesAndGetFilenames(fs, dirname) namesComment := qt.Commentf("filenames: %v", names) c.Assert(err, qt.IsNil, namesComment) c.Assert(count, qt.Equals, expected, namesComment) } func checkFileContent(fs afero.Fs, filename string, c *qt.C, expected ...string) { b, err := afero.ReadFile(fs, filename) c.Assert(err, qt.IsNil) content := string(b) for _, e := range expected { c.Assert(content, qt.Contains, e) } } func countFilesAndGetFilenames(fs afero.Fs, dirname string) (int, []string, error) { if fs == nil { return 0, nil, errors.New("no fs") } counter := 0 var filenames []string wf := func(ctx context.Context, path string, info hugofs.FileMetaInfo) error { if !info.IsDir() { counter++ } if info.Name() != "." { name := info.Name() name = strings.Replace(name, filepath.FromSlash("/my/work"), "WORK_DIR", 1) filenames = append(filenames, name) } return nil } w := hugofs.NewWalkway(hugofs.WalkwayConfig{Fs: fs, Root: dirname, WalkFn: wf}) if err := w.Walk(); err != nil { return -1, nil, err } return counter, filenames, nil } func setConfigAndWriteSomeFilesTo(fs afero.Fs, v config.Provider, key, val string, num int) { workingDir := v.GetString("workingDir") v.Set(key, val) fs.Mkdir(val, 0o755) for i := range num { filename := filepath.Join(workingDir, val, fmt.Sprintf("f%d.txt", i+1)) afero.WriteFile(fs, filename, fmt.Appendf(nil, "content:%s:%d", key, i+1), 0o755) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugolib/filesystems/basefs.go
hugolib/filesystems/basefs.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package filesystems provides the fine grained file systems used by Hugo. These // are typically virtual filesystems that are composites of project and theme content. package filesystems import ( "context" "fmt" "io" "os" "path/filepath" "strings" "sync" "github.com/bep/overlayfs" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/rogpeppe/go-internal/lockedfile" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/modules" hpaths "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugolib/paths" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/spf13/afero" ) const ( // Used to control concurrency between multiple Hugo instances, e.g. // a running server and building new content with 'hugo new'. // It's placed in the project root. lockFileBuild = ".hugo_build.lock" ) var filePathSeparator = string(filepath.Separator) // BaseFs contains the core base filesystems used by Hugo. The name "base" is used // to underline that even if they can be composites, they all have a base path set to a specific // resource folder, e.g "/my-project/content". So, no absolute filenames needed. type BaseFs struct { // SourceFilesystems contains the different source file systems. *SourceFilesystems // The source filesystem (needs absolute filenames). SourceFs afero.Fs // The project source. ProjectSourceFs afero.Fs // The filesystem used to publish the rendered site. // This usually maps to /my-project/public. PublishFs afero.Fs // The filesystem used for static files. PublishFsStatic afero.Fs // A read-only filesystem starting from the project workDir. WorkDir afero.Fs theBigFs *filesystemsCollector workingDir string // Locks. buildMu Lockable // <project>/.hugo_build.lock } type Lockable interface { Lock() (unlock func(), err error) } type fakeLockfileMutex struct { mu sync.Mutex } func (f *fakeLockfileMutex) Lock() (func(), error) { f.mu.Lock() return func() { f.mu.Unlock() }, nil } // Tries to acquire a build lock. func (b *BaseFs) LockBuild() (unlock func(), err error) { return b.buildMu.Lock() } func (b *BaseFs) WatchFilenames() []string { var filenames []string sourceFs := b.SourceFs for _, rfs := range b.RootFss { for _, component := range files.ComponentFolders { fis, err := rfs.Mounts(component) if err != nil { continue } for _, fim := range fis { meta := fim.Meta() if !meta.Watch { continue } if !fim.IsDir() { filenames = append(filenames, meta.Filename) continue } w := hugofs.NewWalkway(hugofs.WalkwayConfig{ Fs: sourceFs, Root: meta.Filename, WalkFn: func(ctx context.Context, path string, fi hugofs.FileMetaInfo) error { if !fi.IsDir() { return nil } if fi.Name() == ".git" || fi.Name() == "node_modules" || fi.Name() == "bower_components" { return filepath.SkipDir } filenames = append(filenames, fi.Meta().Filename) return nil }, }) w.Walk() } } } return filenames } func (b *BaseFs) mountsForComponent(component string) []hugofs.FileMetaInfo { var result []hugofs.FileMetaInfo for _, rfs := range b.RootFss { dirs, err := rfs.Mounts(component) if err == nil { result = append(result, dirs...) } } return result } // AbsProjectContentDir tries to construct a filename below the most // relevant content directory. func (b *BaseFs) AbsProjectContentDir(filename string) (string, string, error) { isAbs := filepath.IsAbs(filename) for _, fi := range b.mountsForComponent(files.ComponentFolderContent) { if !fi.IsDir() { continue } meta := fi.Meta() if !meta.IsProject { continue } if isAbs { if strings.HasPrefix(filename, meta.Filename) { return strings.TrimPrefix(filename, meta.Filename+filePathSeparator), filename, nil } } else { contentDir := strings.TrimPrefix(strings.TrimPrefix(meta.Filename, meta.BaseDir), filePathSeparator) + filePathSeparator if after, ok := strings.CutPrefix(filename, contentDir); ok { relFilename := after absFilename := filepath.Join(meta.Filename, relFilename) return relFilename, absFilename, nil } } } if !isAbs { // A filename on the form "posts/mypage.md", put it inside // the first content folder, usually <workDir>/content. // Pick the first project dir (which is probably the most important one). for _, dir := range b.SourceFilesystems.Content.mounts() { if !dir.IsDir() { continue } meta := dir.Meta() if meta.IsProject { return filename, filepath.Join(meta.Filename, filename), nil } } } return "", "", fmt.Errorf("could not determine content directory for %q", filename) } // ResolveJSConfigFile resolves the JS-related config file to a absolute // filename. One example of such would be postcss.config.js. func (b *BaseFs) ResolveJSConfigFile(name string) string { // First look in assets/_jsconfig fi, err := b.Assets.Fs.Stat(filepath.Join(files.FolderJSConfig, name)) if err == nil { return fi.(hugofs.FileMetaInfo).Meta().Filename } // Fall back to the work dir. fi, err = b.Work.Stat(name) if err == nil { return fi.(hugofs.FileMetaInfo).Meta().Filename } return "" } // SourceFilesystems contains the different source file systems. These can be // composite file systems (theme and project etc.), and they have all root // set to the source type the provides: data, i18n, static, layouts. type SourceFilesystems struct { Content *SourceFilesystem Data *SourceFilesystem I18n *SourceFilesystem Layouts *SourceFilesystem Archetypes *SourceFilesystem Assets *SourceFilesystem AssetsWithDuplicatesPreserved *SourceFilesystem RootFss []*hugofs.RootMappingFs // Writable filesystem on top the project's resources directory, // with any sub module's resource fs layered below. ResourcesCache afero.Fs // The work folder (may be a composite of project and theme components). Work afero.Fs // When in multihost we have one static filesystem per language. The sync // static files is currently done outside of the Hugo build (where there is // a concept of a site per language). // When in non-multihost mode there will be one entry in this map with a blank key. Static map[string]*SourceFilesystem conf config.AllProvider } // A SourceFilesystem holds the filesystem for a given source type in Hugo (data, // i18n, layouts, static) and additional metadata to be able to use that filesystem // in server mode. type SourceFilesystem struct { // Name matches one in files.ComponentFolders Name string // This is a virtual composite filesystem. It expects path relative to a context. Fs afero.Fs // The source filesystem (usually the OS filesystem). SourceFs afero.Fs // When syncing a source folder to the target (e.g. /public), this may // be set to publish into a subfolder. This is used for static syncing // in multihost mode. PublishFolder string } // StaticFs returns the static filesystem for the given language. // This can be a composite filesystem. func (s SourceFilesystems) StaticFs(lang string) afero.Fs { var staticFs afero.Fs = hugofs.NoOpFs if fs, ok := s.Static[lang]; ok { staticFs = fs.Fs } else if fs, ok := s.Static[""]; ok { staticFs = fs.Fs } return staticFs } // StatResource looks for a resource in these filesystems in order: static, assets and finally content. // If found in any of them, it returns FileInfo and the relevant filesystem. // Any non herrors.IsNotExist error will be returned. // An herrors.IsNotExist error will be returned only if all filesystems return such an error. // Note that if we only wanted to find the file, we could create a composite Afero fs, // but we also need to know which filesystem root it lives in. func (s SourceFilesystems) StatResource(lang, filename string) (fi os.FileInfo, fs afero.Fs, err error) { for _, fsToCheck := range []afero.Fs{s.StaticFs(lang), s.Assets.Fs, s.Content.Fs} { fs = fsToCheck fi, err = fs.Stat(filename) if err == nil || !herrors.IsNotExist(err) { return } } // Not found. return } // IsStatic returns true if the given filename is a member of one of the static // filesystems. func (s SourceFilesystems) IsStatic(filename string) bool { for _, staticFs := range s.Static { if staticFs.Contains(filename) { return true } } return false } // IsContent returns true if the given filename is a member of the content filesystem. func (s SourceFilesystems) IsContent(filename string) bool { return s.Content.Contains(filename) } // ResolvePaths resolves the given filename to a list of paths in the filesystems. func (s *SourceFilesystems) ResolvePaths(filename string) []hugofs.ComponentPath { var cpss []hugofs.ComponentPath for _, rfs := range s.RootFss { cps, err := rfs.ReverseLookup(filename) if err != nil { panic(err) } cpss = append(cpss, cps...) } return cpss } // MakeStaticPathRelative makes an absolute static filename into a relative one. // It will return an empty string if the filename is not a member of a static filesystem. func (s SourceFilesystems) MakeStaticPathRelative(filename string) string { for _, staticFs := range s.Static { rel, _ := staticFs.MakePathRelative(filename, true) if rel != "" { return rel } } return "" } // MakePathRelative creates a relative path from the given filename. func (d *SourceFilesystem) MakePathRelative(filename string, checkExists bool) (string, bool) { cps, err := d.ReverseLookup(filename, checkExists) if err != nil { panic(err) } if len(cps) == 0 { return "", false } return filepath.FromSlash(cps[0].Path), true } // ReverseLookup returns the component paths for the given filename. func (d *SourceFilesystem) ReverseLookup(filename string, checkExists bool) ([]hugofs.ComponentPath, error) { var cps []hugofs.ComponentPath hugofs.WalkFilesystems(d.Fs, func(fs afero.Fs) bool { if rfs, ok := fs.(hugofs.ReverseLookupProvder); ok { if c, err := rfs.ReverseLookupComponent(d.Name, filename); err == nil { if checkExists { n := 0 for _, cp := range c { if _, err := d.Fs.Stat(filepath.FromSlash(cp.Path)); err == nil { c[n] = cp n++ } } c = c[:n] } cps = append(cps, c...) } } return false }) return cps, nil } func (d *SourceFilesystem) mounts() []hugofs.FileMetaInfo { var m []hugofs.FileMetaInfo hugofs.WalkFilesystems(d.Fs, func(fs afero.Fs) bool { if rfs, ok := fs.(*hugofs.RootMappingFs); ok { mounts, err := rfs.Mounts(d.Name) if err == nil { m = append(m, mounts...) } } return false }) // Filter out any mounts not belonging to this filesystem. // TODO(bep) I think this is superfluous. n := 0 for _, mm := range m { if mm.Meta().Component == d.Name { m[n] = mm n++ } } m = m[:n] return m } func (d *SourceFilesystem) RealFilename(rel string) string { fi, err := d.Fs.Stat(rel) if err != nil { return rel } if realfi, ok := fi.(hugofs.FileMetaInfo); ok { return realfi.Meta().Filename } return rel } // Contains returns whether the given filename is a member of the current filesystem. func (d *SourceFilesystem) Contains(filename string) bool { for _, dir := range d.mounts() { if !dir.IsDir() { continue } if strings.HasPrefix(filename, dir.Meta().Filename) { return true } } return false } // RealDirs gets a list of absolute paths to directories starting from the given // path. func (d *SourceFilesystem) RealDirs(from string) []string { var dirnames []string for _, m := range d.mounts() { if !m.IsDir() { continue } dirname := filepath.Join(m.Meta().Filename, from) if _, err := d.SourceFs.Stat(dirname); err == nil { dirnames = append(dirnames, dirname) } } return dirnames } // WithBaseFs allows reuse of some potentially expensive to create parts that remain // the same across sites/languages. func WithBaseFs(b *BaseFs) func(*BaseFs) error { return func(bb *BaseFs) error { bb.theBigFs = b.theBigFs bb.SourceFilesystems = b.SourceFilesystems return nil } } // NewBase builds the filesystems used by Hugo given the paths and options provided.NewBase func NewBase(p *paths.Paths, logger loggers.Logger, options ...func(*BaseFs) error) (*BaseFs, error) { fs := p.Fs if logger == nil { logger = loggers.NewDefault() } publishFs := hugofs.NewBaseFileDecorator(fs.PublishDir) projectSourceFs := hugofs.NewBaseFileDecorator(hugofs.NewBasePathFs(fs.Source, p.Cfg.BaseConfig().WorkingDir)) sourceFs := hugofs.NewBaseFileDecorator(fs.Source) publishFsStatic := fs.PublishDirStatic var buildMu Lockable if p.Cfg.NoBuildLock() || htesting.IsTest { buildMu = &fakeLockfileMutex{} } else { buildMu = lockedfile.MutexAt(filepath.Join(p.Cfg.BaseConfig().WorkingDir, lockFileBuild)) } b := &BaseFs{ SourceFs: sourceFs, ProjectSourceFs: projectSourceFs, WorkDir: fs.WorkingDirReadOnly, PublishFs: publishFs, PublishFsStatic: publishFsStatic, workingDir: p.Cfg.BaseConfig().WorkingDir, buildMu: buildMu, } for _, opt := range options { if err := opt(b); err != nil { return nil, err } } if b.theBigFs != nil && b.SourceFilesystems != nil { return b, nil } builder := newSourceFilesystemsBuilder(p, logger, b) sourceFilesystems, err := builder.Build() if err != nil { return nil, fmt.Errorf("build filesystems: %w", err) } b.SourceFilesystems = sourceFilesystems b.theBigFs = builder.theBigFs return b, nil } type sourceFilesystemsBuilder struct { logger loggers.Logger p *paths.Paths sourceFs afero.Fs result *SourceFilesystems theBigFs *filesystemsCollector } func newSourceFilesystemsBuilder(p *paths.Paths, logger loggers.Logger, b *BaseFs) *sourceFilesystemsBuilder { sourceFs := hugofs.NewBaseFileDecorator(p.Fs.Source) return &sourceFilesystemsBuilder{ p: p, logger: logger, sourceFs: sourceFs, theBigFs: b.theBigFs, result: &SourceFilesystems{ conf: p.Cfg, }, } } func (b *sourceFilesystemsBuilder) newSourceFilesystem(name string, fs afero.Fs) *SourceFilesystem { return &SourceFilesystem{ Name: name, Fs: fs, SourceFs: b.sourceFs, } } func (b *sourceFilesystemsBuilder) Build() (*SourceFilesystems, error) { if b.theBigFs == nil { theBigFs, err := b.createMainOverlayFs(b.p) if err != nil { return nil, fmt.Errorf("create main fs: %w", err) } b.theBigFs = theBigFs } createView := func(componentID string, overlayFs *overlayfs.OverlayFs) *SourceFilesystem { if b.theBigFs == nil || b.theBigFs.overlayMounts == nil { return b.newSourceFilesystem(componentID, hugofs.NoOpFs) } fs := hugofs.NewComponentFs( hugofs.ComponentFsOptions{ Fs: overlayFs, Component: componentID, Cfg: b.p.Cfg, }, ) return b.newSourceFilesystem(componentID, fs) } b.result.Archetypes = createView(files.ComponentFolderArchetypes, b.theBigFs.overlayMounts) b.result.Layouts = createView(files.ComponentFolderLayouts, b.theBigFs.overlayMounts) b.result.Assets = createView(files.ComponentFolderAssets, b.theBigFs.overlayMounts) b.result.ResourcesCache = b.theBigFs.overlayResources b.result.RootFss = b.theBigFs.rootFss // data and i18n needs a different merge strategy. overlayMountsPreserveDupes := b.theBigFs.overlayMounts.WithDirsMerger(hugofs.AppendDirsMerger) b.result.Data = createView(files.ComponentFolderData, overlayMountsPreserveDupes) b.result.I18n = createView(files.ComponentFolderI18n, overlayMountsPreserveDupes) b.result.AssetsWithDuplicatesPreserved = createView(files.ComponentFolderAssets, overlayMountsPreserveDupes) contentFs := hugofs.NewComponentFs( hugofs.ComponentFsOptions{ Fs: b.theBigFs.overlayMountsContent, Component: files.ComponentFolderContent, Cfg: b.p.Cfg, }, ) b.result.Content = b.newSourceFilesystem(files.ComponentFolderContent, contentFs) b.result.Work = hugofs.NewReadOnlyFs(b.theBigFs.overlayFull) // Create static filesystem(s) ms := make(map[string]*SourceFilesystem) b.result.Static = ms if b.theBigFs.staticPerLanguage != nil { // Multihost mode for k, v := range b.theBigFs.staticPerLanguage { sfs := b.newSourceFilesystem(files.ComponentFolderStatic, v) sfs.PublishFolder = k ms[k] = sfs } } else { bfs := hugofs.NewBasePathFs(b.theBigFs.overlayMountsStatic, files.ComponentFolderStatic) ms[""] = b.newSourceFilesystem(files.ComponentFolderStatic, bfs) } return b.result, nil } func (b *sourceFilesystemsBuilder) createMainOverlayFs(p *paths.Paths) (*filesystemsCollector, error) { var staticFsMap map[string]*overlayfs.OverlayFs if b.p.Cfg.IsMultihost() { languages := b.p.Cfg.Languages().(langs.Languages) staticFsMap = make(map[string]*overlayfs.OverlayFs) for _, l := range languages { staticFsMap[l.Lang] = overlayfs.New(overlayfs.Options{}) } } collector := &filesystemsCollector{ sourceProject: b.sourceFs, sourceModules: b.sourceFs, staticPerLanguage: staticFsMap, overlayMounts: overlayfs.New(overlayfs.Options{}), overlayMountsContent: overlayfs.New(overlayfs.Options{DirsMerger: hugofs.AppendDirsMerger}), overlayMountsStatic: overlayfs.New(overlayfs.Options{}), overlayFull: overlayfs.New(overlayfs.Options{}), overlayResources: overlayfs.New(overlayfs.Options{FirstWritable: true}), } mods := p.AllModules() mounts := make([]mountsDescriptor, len(mods)) for i := range mods { mod := mods[i] dir := mod.Dir() isMainProject := mod.Owner() == nil mounts[i] = mountsDescriptor{ Module: mod, dir: dir, isMainProject: isMainProject, ordinal: i, } } err := b.createOverlayFs(collector, mounts) return collector, err } func (b *sourceFilesystemsBuilder) isContentMount(mnt modules.Mount) bool { return strings.HasPrefix(mnt.Target, files.ComponentFolderContent) } func (b *sourceFilesystemsBuilder) isStaticMount(mnt modules.Mount) bool { return strings.HasPrefix(mnt.Target, files.ComponentFolderStatic) } func (b *sourceFilesystemsBuilder) isLayoutsMount(mnt modules.Mount) bool { return strings.HasPrefix(mnt.Target, files.ComponentFolderLayouts) } func (b *sourceFilesystemsBuilder) createOverlayFs( collector *filesystemsCollector, mounts []mountsDescriptor, ) error { if len(mounts) == 0 { appendNopIfEmpty := func(ofs *overlayfs.OverlayFs) *overlayfs.OverlayFs { if ofs.NumFilesystems() > 0 { return ofs } return ofs.Append(hugofs.NoOpFs) } collector.overlayMounts = appendNopIfEmpty(collector.overlayMounts) collector.overlayMountsContent = appendNopIfEmpty(collector.overlayMountsContent) collector.overlayMountsStatic = appendNopIfEmpty(collector.overlayMountsStatic) collector.overlayMountsFull = appendNopIfEmpty(collector.overlayMountsFull) collector.overlayFull = appendNopIfEmpty(collector.overlayFull) collector.overlayResources = appendNopIfEmpty(collector.overlayResources) return nil } for _, md := range mounts { var ( fromTo []*hugofs.RootMapping fromToContent []*hugofs.RootMapping fromToStatic []*hugofs.RootMapping ) absPathify := func(path string) (string, string) { if filepath.IsAbs(path) { return "", path } return md.dir, hpaths.AbsPathify(md.dir, path) } for i, mount := range md.Mounts() { // Add more weight to early mounts. // When two mounts contain the same filename, // the first entry wins. mountWeight := (10 + md.ordinal) * (len(md.Mounts()) - i) patterns, hasLegacyIncludes, hasLegacyExcludes := mount.FilesToFilter() if hasLegacyIncludes { hugo.Deprecate("module.mounts.includeFiles", "Replaced by the simpler 'files' setting, see https://gohugo.io/configuration/module/#files", "v0.153.0") } if hasLegacyExcludes { hugo.Deprecate("module.mounts.excludeFiles", "Replaced by the simpler 'files' setting, see https://gohugo.io/configuration/module/#files", "v0.153.0") } inclusionFilter, err := hglob.NewFilenameFilterV2(patterns) if err != nil { return err } base, filename := absPathify(mount.Source) var matrix *sitesmatrix.IntSets v := mount.Sites needsDefaultsIfNotset := b.isContentMount(mount) needsDefaultsAndAllLanguagesIfNotSet := b.isStaticMount(mount) needsAllIfNotSet := b.isLayoutsMount(mount) intSetsCfg := sitesmatrix.IntSetsConfig{ ApplyDefaults: 0, Globs: v.Matrix, } matrixBuilder := sitesmatrix.NewIntSetsBuilder(b.p.Cfg.ConfiguredDimensions()) if !v.Matrix.IsZero() { matrixBuilder.WithConfig(intSetsCfg) if !matrixBuilder.GlobFilterMisses.IsZero() { continue } if needsDefaultsIfNotset { matrixBuilder.WithDefaultsIfNotSet() } if needsAllIfNotSet { matrixBuilder.WithAllIfNotSet() } matrix = matrixBuilder.Build() } else if needsAllIfNotSet { matrixBuilder.WithAllIfNotSet() matrix = matrixBuilder.Build() } else if needsDefaultsAndAllLanguagesIfNotSet { matrixBuilder.WithDefaultsAndAllLanguagesIfNotSet() matrix = matrixBuilder.Build() } else if needsDefaultsIfNotset { matrix = b.p.Cfg.DefaultContentsitesMatrix() } else { if needsDefaultsIfNotset { matrixBuilder.WithDefaultsIfNotSet() } matrix = matrixBuilder.Build() } var complements *sitesmatrix.IntSets if !v.Complements.IsZero() { intSetsCfg.Globs = v.Complements intSetsCfg.ApplyDefaults = 0 matrixBuilder = sitesmatrix.NewIntSetsBuilder(b.p.Cfg.ConfiguredDimensions()).WithConfig(intSetsCfg).WithAllIfNotSet() complements = matrixBuilder.Build() } rm := &hugofs.RootMapping{ From: mount.Target, To: filename, ToBase: base, Module: md.Module.Path(), ModuleOrdinal: md.ordinal, IsProject: md.isMainProject, Meta: &hugofs.FileMeta{ Watch: !mount.DisableWatch && md.Watch(), Weight: mountWeight, InclusionFilter: inclusionFilter, SitesMatrix: matrix, SitesComplements: complements, }, } isContentMount := b.isContentMount(mount) if isContentMount { fromToContent = append(fromToContent, rm) } else if b.isStaticMount(mount) { fromToStatic = append(fromToStatic, rm) } else { fromTo = append(fromTo, rm) } } modBase := collector.sourceProject if !md.isMainProject { modBase = collector.sourceModules } sourceStatic := modBase rmfs, err := hugofs.NewRootMappingFs(modBase, fromTo...) if err != nil { return err } rmfsContent, err := hugofs.NewRootMappingFs(modBase, fromToContent...) if err != nil { return err } rmfsStatic, err := hugofs.NewRootMappingFs(sourceStatic, fromToStatic...) if err != nil { return err } // We need to keep the list of directories for watching. collector.addRootFs(rmfs) collector.addRootFs(rmfsContent) collector.addRootFs(rmfsStatic) if collector.staticPerLanguage != nil { for i, l := range b.p.Cfg.Languages().(langs.Languages) { lang := l.Lang lfs := rmfsStatic.Filter(func(rm *hugofs.RootMapping) bool { return rm.Meta.SitesMatrix.HasLanguage(i) }) bfs := hugofs.NewBasePathFs(lfs, files.ComponentFolderStatic) collector.staticPerLanguage[lang] = collector.staticPerLanguage[lang].Append(bfs) } } getResourcesDir := func() string { if md.isMainProject { return b.p.AbsResourcesDir } _, filename := absPathify(files.FolderResources) return filename } collector.overlayMounts = collector.overlayMounts.Append(rmfs) collector.overlayMountsContent = collector.overlayMountsContent.Append(rmfsContent) collector.overlayMountsStatic = collector.overlayMountsStatic.Append(rmfsStatic) collector.overlayFull = collector.overlayFull.Append(hugofs.NewBasePathFs(modBase, md.dir)) collector.overlayResources = collector.overlayResources.Append(hugofs.NewBasePathFs(modBase, getResourcesDir())) } return nil } //lint:ignore U1000 useful for debugging func printFs(fs afero.Fs, path string, w io.Writer) { if fs == nil { return } afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } var filename string if fim, ok := info.(hugofs.FileMetaInfo); ok { filename = fim.Meta().Filename } fmt.Fprintf(w, " %q %q\n", path, filename) return nil }) } type filesystemsCollector struct { sourceProject afero.Fs // Source for project folders sourceModules afero.Fs // Source for modules/themes overlayMounts *overlayfs.OverlayFs overlayMountsContent *overlayfs.OverlayFs overlayMountsStatic *overlayfs.OverlayFs overlayMountsFull *overlayfs.OverlayFs overlayFull *overlayfs.OverlayFs overlayResources *overlayfs.OverlayFs rootFss []*hugofs.RootMappingFs // Set if in multihost mode staticPerLanguage map[string]*overlayfs.OverlayFs } func (c *filesystemsCollector) addRootFs(rfs *hugofs.RootMappingFs) { c.rootFss = append(c.rootFss, rfs) } type mountsDescriptor struct { modules.Module dir string isMainProject bool ordinal int // zero based starting from the project. }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/media/config.go
media/config.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package media import ( "fmt" "path/filepath" "reflect" "slices" "sort" "strings" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/config" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" ) // DefaultTypes is the default media types supported by Hugo. var DefaultTypes Types func init() { // Apply delimiter to all. for _, m := range defaultMediaTypesConfig { m.(map[string]any)["delimiter"] = "." } ns, err := DecodeTypes(nil) if err != nil { panic(err) } DefaultTypes = ns.Config // Initialize the Builtin types with values from DefaultTypes. v := reflect.ValueOf(&Builtin).Elem() for i := range v.NumField() { f := v.Field(i) fieldName := v.Type().Field(i).Name builtinType := f.Interface().(Type) if builtinType.Type == "" { panic(fmt.Errorf("builtin type %q is empty", fieldName)) } defaultType, found := DefaultTypes.GetByType(builtinType.Type) if !found { panic(fmt.Errorf("missing default type for field builtin type: %q", fieldName)) } f.Set(reflect.ValueOf(defaultType)) } } func init() { DefaultContentTypes = ContentTypes{ HTML: Builtin.HTMLType, Markdown: Builtin.MarkdownType, AsciiDoc: Builtin.AsciiDocType, Pandoc: Builtin.PandocType, ReStructuredText: Builtin.ReStructuredTextType, EmacsOrgMode: Builtin.EmacsOrgModeType, } DefaultContentTypes.init(nil) } var DefaultContentTypes ContentTypes type ContentTypeConfig struct { // Empty for now. } // ContentTypes holds the media types that are considered content in Hugo. type ContentTypes struct { HTML Type Markdown Type AsciiDoc Type Pandoc Type ReStructuredText Type EmacsOrgMode Type types Types // Created in init(). extensionSet map[string]bool } func (t *ContentTypes) init(types Types) { sort.Slice(t.types, func(i, j int) bool { return t.types[i].Type < t.types[j].Type }) if tt, ok := types.GetByType(t.HTML.Type); ok { t.HTML = tt } if tt, ok := types.GetByType(t.Markdown.Type); ok { t.Markdown = tt } if tt, ok := types.GetByType(t.AsciiDoc.Type); ok { t.AsciiDoc = tt } if tt, ok := types.GetByType(t.Pandoc.Type); ok { t.Pandoc = tt } if tt, ok := types.GetByType(t.ReStructuredText.Type); ok { t.ReStructuredText = tt } if tt, ok := types.GetByType(t.EmacsOrgMode.Type); ok { t.EmacsOrgMode = tt } t.extensionSet = make(map[string]bool) for _, mt := range t.types { for _, suffix := range mt.Suffixes() { t.extensionSet[suffix] = true } } } func (t ContentTypes) IsContentSuffix(suffix string) bool { return t.extensionSet[suffix] } // IsContentFile returns whether the given filename is a content file. func (t ContentTypes) IsContentFile(filename string) bool { return t.IsContentSuffix(strings.TrimPrefix(filepath.Ext(filename), ".")) } // IsIndexContentFile returns whether the given filename is an index content file. func (t ContentTypes) IsIndexContentFile(filename string) bool { if !t.IsContentFile(filename) { return false } base := filepath.Base(filename) return strings.HasPrefix(base, "index.") || strings.HasPrefix(base, "_index.") } // IsHTMLSuffix returns whether the given suffix is a HTML media type. func (t ContentTypes) IsHTMLSuffix(suffix string) bool { return slices.Contains(t.HTML.Suffixes(), suffix) } // Types is a slice of media types. func (t ContentTypes) Types() Types { return t.types } // Hold the configuration for a given media type. type MediaTypeConfig struct { // The file suffixes used for this media type. Suffixes []string // Delimiter used before suffix. Delimiter string } var defaultContentTypesConfig = map[string]ContentTypeConfig{ Builtin.HTMLType.Type: {}, Builtin.MarkdownType.Type: {}, Builtin.AsciiDocType.Type: {}, Builtin.PandocType.Type: {}, Builtin.ReStructuredTextType.Type: {}, Builtin.EmacsOrgModeType.Type: {}, } // DecodeContentTypes decodes the given map of content types. func DecodeContentTypes(in map[string]any, types Types) (*config.ConfigNamespace[map[string]ContentTypeConfig, ContentTypes], error) { buildConfig := func(v any) (ContentTypes, any, error) { var s map[string]ContentTypeConfig c := DefaultContentTypes m, err := maps.ToStringMapE(v) if err != nil { return c, nil, err } if len(m) == 0 { s = defaultContentTypesConfig } else { s = make(map[string]ContentTypeConfig) m = maps.CleanConfigStringMap(m) for k, v := range m { var ctc ContentTypeConfig if err := mapstructure.WeakDecode(v, &ctc); err != nil { return c, nil, err } s[k] = ctc } } for k := range s { mediaType, found := types.GetByType(k) if !found { return c, nil, fmt.Errorf("unknown media type %q", k) } c.types = append(c.types, mediaType) } c.init(types) return c, s, nil } ns, err := config.DecodeNamespace[map[string]ContentTypeConfig](in, buildConfig) if err != nil { return nil, fmt.Errorf("failed to decode media types: %w", err) } return ns, nil } // DecodeTypes decodes the given map of media types. func DecodeTypes(in map[string]any) (*config.ConfigNamespace[map[string]MediaTypeConfig, Types], error) { buildConfig := func(v any) (Types, any, error) { m, err := maps.ToStringMapE(v) if err != nil { return nil, nil, err } if m == nil { m = map[string]any{} } m = maps.CleanConfigStringMap(m) // Merge with defaults. maps.MergeShallow(m, defaultMediaTypesConfig) var types Types for k, v := range m { mediaType, err := FromString(k) if err != nil { return nil, nil, err } if err := mapstructure.WeakDecode(v, &mediaType); err != nil { return nil, nil, err } mm := maps.ToStringMap(v) suffixes, _, found := maps.LookupEqualFold(mm, "suffixes") if found { mediaType.SuffixesCSV = strings.TrimSpace(strings.ToLower(strings.Join(cast.ToStringSlice(suffixes), ","))) } if mediaType.SuffixesCSV != "" && mediaType.Delimiter == "" { mediaType.Delimiter = DefaultDelimiter } InitMediaType(&mediaType) types = append(types, mediaType) } sort.Sort(types) return types, m, nil } ns, err := config.DecodeNamespace[map[string]MediaTypeConfig](in, buildConfig) if err != nil { return nil, fmt.Errorf("failed to decode media types: %w", err) } return ns, nil } // TODO(bep) get rid of this. var DefaultPathParser = &paths.PathParser{ IsContentExt: func(ext string) bool { panic("not supported") }, IsOutputFormat: func(name, ext string) bool { panic("DefaultPathParser: not supported") }, }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/media/builtin.go
media/builtin.go
package media type BuiltinTypes struct { CalendarType Type CSSType Type SCSSType Type SASSType Type GotmplType Type CSVType Type HTMLType Type JavascriptType Type TypeScriptType Type TSXType Type JSXType Type JSONType Type WebAppManifestType Type RSSType Type XMLType Type SVGType Type TextType Type TOMLType Type YAMLType Type // Common image types PNGType Type JPEGType Type GIFType Type TIFFType Type BMPType Type WEBPType Type // Common font types TrueTypeFontType Type OpenTypeFontType Type // Common document types PDFType Type MarkdownType Type EmacsOrgModeType Type AsciiDocType Type PandocType Type ReStructuredTextType Type // Common video types AVIType Type MPEGType Type MP4Type Type OGGType Type WEBMType Type GPPType Type // wasm WasmType Type OctetType Type } var Builtin = BuiltinTypes{ CalendarType: Type{Type: "text/calendar"}, CSSType: Type{Type: "text/css"}, SCSSType: Type{Type: "text/x-scss"}, SASSType: Type{Type: "text/x-sass"}, GotmplType: Type{Type: "text/x-gotmpl"}, CSVType: Type{Type: "text/csv"}, HTMLType: Type{Type: "text/html"}, JavascriptType: Type{Type: "text/javascript"}, TypeScriptType: Type{Type: "text/typescript"}, TSXType: Type{Type: "text/tsx"}, JSXType: Type{Type: "text/jsx"}, JSONType: Type{Type: "application/json"}, WebAppManifestType: Type{Type: "application/manifest+json"}, RSSType: Type{Type: "application/rss+xml"}, XMLType: Type{Type: "application/xml"}, SVGType: Type{Type: "image/svg+xml"}, TextType: Type{Type: "text/plain"}, TOMLType: Type{Type: "application/toml"}, YAMLType: Type{Type: "application/yaml"}, // Common image types PNGType: Type{Type: "image/png"}, JPEGType: Type{Type: "image/jpeg"}, GIFType: Type{Type: "image/gif"}, TIFFType: Type{Type: "image/tiff"}, BMPType: Type{Type: "image/bmp"}, WEBPType: Type{Type: "image/webp"}, // Common font types TrueTypeFontType: Type{Type: "font/ttf"}, OpenTypeFontType: Type{Type: "font/otf"}, // Common document types PDFType: Type{Type: "application/pdf"}, MarkdownType: Type{Type: "text/markdown"}, AsciiDocType: Type{Type: "text/asciidoc"}, // https://github.com/asciidoctor/asciidoctor/issues/2502 PandocType: Type{Type: "text/pandoc"}, ReStructuredTextType: Type{Type: "text/rst"}, // https://docutils.sourceforge.io/FAQ.html#what-s-the-official-mime-type-for-restructuredtext-data EmacsOrgModeType: Type{Type: "text/org"}, // Common video types AVIType: Type{Type: "video/x-msvideo"}, MPEGType: Type{Type: "video/mpeg"}, MP4Type: Type{Type: "video/mp4"}, OGGType: Type{Type: "video/ogg"}, WEBMType: Type{Type: "video/webm"}, GPPType: Type{Type: "video/3gpp"}, // Web assembly. WasmType: Type{Type: "application/wasm"}, OctetType: Type{Type: "application/octet-stream"}, } var defaultMediaTypesConfig = map[string]any{ "text/calendar": map[string]any{"suffixes": []string{"ics"}}, "text/css": map[string]any{"suffixes": []string{"css"}}, "text/x-scss": map[string]any{"suffixes": []string{"scss"}}, "text/x-sass": map[string]any{"suffixes": []string{"sass"}}, "text/csv": map[string]any{"suffixes": []string{"csv"}}, "text/html": map[string]any{"suffixes": []string{"html", "htm"}}, "text/javascript": map[string]any{"suffixes": []string{"js", "jsm", "mjs"}}, "text/typescript": map[string]any{"suffixes": []string{"ts"}}, "text/tsx": map[string]any{"suffixes": []string{"tsx"}}, "text/jsx": map[string]any{"suffixes": []string{"jsx"}}, "text/x-gotmpl": map[string]any{"suffixes": []string{"gotmpl"}}, "application/json": map[string]any{"suffixes": []string{"json"}}, "application/manifest+json": map[string]any{"suffixes": []string{"webmanifest"}}, "application/rss+xml": map[string]any{"suffixes": []string{"xml", "rss"}}, "application/xml": map[string]any{"suffixes": []string{"xml"}}, "image/svg+xml": map[string]any{"suffixes": []string{"svg"}}, "text/plain": map[string]any{"suffixes": []string{"txt"}}, "application/toml": map[string]any{"suffixes": []string{"toml"}}, "application/yaml": map[string]any{"suffixes": []string{"yaml", "yml"}}, // Common image types "image/png": map[string]any{"suffixes": []string{"png"}}, "image/jpeg": map[string]any{"suffixes": []string{"jpg", "jpeg", "jpe", "jif", "jfif"}}, "image/gif": map[string]any{"suffixes": []string{"gif"}}, "image/tiff": map[string]any{"suffixes": []string{"tif", "tiff"}}, "image/bmp": map[string]any{"suffixes": []string{"bmp"}}, "image/webp": map[string]any{"suffixes": []string{"webp"}}, // Common font types "font/ttf": map[string]any{"suffixes": []string{"ttf"}}, "font/otf": map[string]any{"suffixes": []string{"otf"}}, // Common document types "application/pdf": map[string]any{"suffixes": []string{"pdf"}}, "text/markdown": map[string]any{"suffixes": []string{"md", "mdown", "markdown"}}, "text/asciidoc": map[string]any{"suffixes": []string{"adoc", "asciidoc", "ad"}}, "text/pandoc": map[string]any{"suffixes": []string{"pandoc", "pdc"}}, "text/rst": map[string]any{"suffixes": []string{"rst"}}, "text/org": map[string]any{"suffixes": []string{"org"}}, // Common video types "video/x-msvideo": map[string]any{"suffixes": []string{"avi"}}, "video/mpeg": map[string]any{"suffixes": []string{"mpg", "mpeg"}}, "video/mp4": map[string]any{"suffixes": []string{"mp4"}}, "video/ogg": map[string]any{"suffixes": []string{"ogv"}}, "video/webm": map[string]any{"suffixes": []string{"webm"}}, "video/3gpp": map[string]any{"suffixes": []string{"3gpp", "3gp"}}, // wasm "application/wasm": map[string]any{"suffixes": []string{"wasm"}}, "application/octet-stream": map[string]any{}, }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/media/config_test.go
media/config_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package media import ( "fmt" "testing" qt "github.com/frankban/quicktest" ) func TestDecodeTypes(t *testing.T) { c := qt.New(t) tests := []struct { name string m map[string]any shouldError bool assert func(t *testing.T, name string, tt Types) }{ { "Redefine JSON", map[string]any{ "application/json": map[string]any{ "suffixes": []string{"jasn"}, }, }, false, func(t *testing.T, name string, tt Types) { for _, ttt := range tt { if _, ok := DefaultTypes.GetByType(ttt.Type); !ok { fmt.Println(ttt.Type, "not found in default types") } } c.Assert(len(tt), qt.Equals, len(DefaultTypes)) json, si, found := tt.GetBySuffix("jasn") c.Assert(found, qt.Equals, true) c.Assert(json.String(), qt.Equals, "application/json") c.Assert(si.FullSuffix, qt.Equals, ".jasn") }, }, { "MIME suffix in key, multiple file suffixes, custom delimiter", map[string]any{ "application/hugo+hg": map[string]any{ "suffixes": []string{"hg1", "hG2"}, "Delimiter": "_", }, }, false, func(t *testing.T, name string, tt Types) { c.Assert(len(tt), qt.Equals, len(DefaultTypes)+1) hg, si, found := tt.GetBySuffix("hg2") c.Assert(found, qt.Equals, true) c.Assert(hg.FirstSuffix.Suffix, qt.Equals, "hg1") c.Assert(hg.FirstSuffix.FullSuffix, qt.Equals, "_hg1") c.Assert(si.Suffix, qt.Equals, "hg2") c.Assert(si.FullSuffix, qt.Equals, "_hg2") c.Assert(hg.String(), qt.Equals, "application/hugo+hg") _, found = tt.GetByType("application/hugo+hg") c.Assert(found, qt.Equals, true) }, }, { "Add custom media type", map[string]any{ "text/hugo+hgo": map[string]any{ "Suffixes": []string{"hgo2"}, }, }, false, func(t *testing.T, name string, tp Types) { c.Assert(len(tp), qt.Equals, len(DefaultTypes)+1) // Make sure we have not broken the default config. _, _, found := tp.GetBySuffix("json") c.Assert(found, qt.Equals, true) hugo, _, found := tp.GetBySuffix("hgo2") c.Assert(found, qt.Equals, true) c.Assert(hugo.String(), qt.Equals, "text/hugo+hgo") }, }, } for _, test := range tests { result, err := DecodeTypes(test.m) if test.shouldError { c.Assert(err, qt.Not(qt.IsNil)) } else { c.Assert(err, qt.IsNil) test.assert(t, test.name, result.Config) } } } func TestDefaultTypes(t *testing.T) { c := qt.New(t) for _, test := range []struct { tp Type expectedMainType string expectedSubType string expectedSuffixes string expectedType string expectedString string }{ {Builtin.CalendarType, "text", "calendar", "ics", "text/calendar", "text/calendar"}, {Builtin.CSSType, "text", "css", "css", "text/css", "text/css"}, {Builtin.SCSSType, "text", "x-scss", "scss", "text/x-scss", "text/x-scss"}, {Builtin.CSVType, "text", "csv", "csv", "text/csv", "text/csv"}, {Builtin.HTMLType, "text", "html", "html,htm", "text/html", "text/html"}, {Builtin.MarkdownType, "text", "markdown", "md,mdown,markdown", "text/markdown", "text/markdown"}, {Builtin.EmacsOrgModeType, "text", "org", "org", "text/org", "text/org"}, {Builtin.PandocType, "text", "pandoc", "pandoc,pdc", "text/pandoc", "text/pandoc"}, {Builtin.ReStructuredTextType, "text", "rst", "rst", "text/rst", "text/rst"}, {Builtin.AsciiDocType, "text", "asciidoc", "adoc,asciidoc,ad", "text/asciidoc", "text/asciidoc"}, {Builtin.JavascriptType, "text", "javascript", "js,jsm,mjs", "text/javascript", "text/javascript"}, {Builtin.TypeScriptType, "text", "typescript", "ts", "text/typescript", "text/typescript"}, {Builtin.TSXType, "text", "tsx", "tsx", "text/tsx", "text/tsx"}, {Builtin.JSXType, "text", "jsx", "jsx", "text/jsx", "text/jsx"}, {Builtin.JSONType, "application", "json", "json", "application/json", "application/json"}, {Builtin.RSSType, "application", "rss", "xml,rss", "application/rss+xml", "application/rss+xml"}, {Builtin.SVGType, "image", "svg", "svg", "image/svg+xml", "image/svg+xml"}, {Builtin.TextType, "text", "plain", "txt", "text/plain", "text/plain"}, {Builtin.XMLType, "application", "xml", "xml", "application/xml", "application/xml"}, {Builtin.TOMLType, "application", "toml", "toml", "application/toml", "application/toml"}, {Builtin.YAMLType, "application", "yaml", "yaml,yml", "application/yaml", "application/yaml"}, {Builtin.PDFType, "application", "pdf", "pdf", "application/pdf", "application/pdf"}, {Builtin.TrueTypeFontType, "font", "ttf", "ttf", "font/ttf", "font/ttf"}, {Builtin.OpenTypeFontType, "font", "otf", "otf", "font/otf", "font/otf"}, } { c.Assert(test.tp.MainType, qt.Equals, test.expectedMainType) c.Assert(test.tp.SubType, qt.Equals, test.expectedSubType) c.Assert(test.tp.SuffixesCSV, qt.Equals, test.expectedSuffixes) c.Assert(test.tp.Type, qt.Equals, test.expectedType) c.Assert(test.tp.String(), qt.Equals, test.expectedString) } c.Assert(len(DefaultTypes), qt.Equals, 41) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/media/mediaType.go
media/mediaType.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package media contains Media Type (MIME type) related types and functions. package media import ( "encoding/json" "fmt" "net/http" "strings" ) var zero Type const ( DefaultDelimiter = "." ) // MediaType (also known as MIME type and content type) is a two-part identifier for // file formats and format contents transmitted on the Internet. // For Hugo's use case, we use the top-level type name / subtype name + suffix. // One example would be application/svg+xml // If suffix is not provided, the sub type will be used. // <docsmeta>{ "name": "MediaType" }</docsmeta> type Type struct { // The full MIME type string, e.g. "application/rss+xml". Type string `json:"-"` // The top-level type name, e.g. "application". MainType string `json:"mainType"` // The subtype name, e.g. "rss". SubType string `json:"subType"` // The delimiter before the suffix, e.g. ".". Delimiter string `json:"delimiter"` // FirstSuffix holds the first suffix defined for this MediaType. FirstSuffix SuffixInfo `json:"-"` // This is the optional suffix after the "+" in the MIME type, // e.g. "xml" in "application/rss+xml". mimeSuffix string // E.g. "jpg,jpeg" // Stored as a string to make Type comparable. // For internal use only. SuffixesCSV string `json:"-"` } // SuffixInfo holds information about a Media Type's suffix. type SuffixInfo struct { // Suffix is the suffix without the delimiter, e.g. "xml". Suffix string `json:"suffix"` // FullSuffix is the suffix with the delimiter, e.g. ".xml". FullSuffix string `json:"fullSuffix"` } // FromContent resolve the Type primarily using http.DetectContentType. // If http.DetectContentType resolves to application/octet-stream, a zero Type is returned. // If http.DetectContentType resolves to text/plain or application/xml, we try to get more specific using types and ext. func FromContent(types Types, extensionHints []string, content []byte) Type { t := strings.Split(http.DetectContentType(content), ";")[0] if t == "application/octet-stream" { return zero } var found bool m, found := types.GetByType(t) if !found { if t == "text/xml" { // This is how it's configured in Hugo by default. m, found = types.GetByType("application/xml") } } if !found { return zero } var mm Type for _, extension := range extensionHints { extension = strings.TrimPrefix(extension, ".") mm, _, found = types.GetFirstBySuffix(extension) if found { break } } if found { if m == mm { return m } if m.IsText() && mm.IsText() { // http.DetectContentType isn't brilliant when it comes to common text formats, so we need to do better. // For now we say that if it's detected to be a text format and the extension/content type in header reports // it to be a text format, then we use that. return mm } // E.g. an image with a *.js extension. return zero } return m } // FromStringAndExt creates a Type from a MIME string and a given extensions func FromStringAndExt(t string, ext ...string) (Type, error) { tp, err := FromString(t) if err != nil { return tp, err } for i, e := range ext { ext[i] = strings.TrimPrefix(e, ".") } tp.SuffixesCSV = strings.Join(ext, ",") tp.Delimiter = DefaultDelimiter tp.init() return tp, nil } // FromString creates a new Type given a type string on the form MainType/SubType and // an optional suffix, e.g. "text/html" or "text/html+html". func FromString(t string) (Type, error) { t = strings.ToLower(t) parts := strings.Split(t, "/") if len(parts) != 2 { return Type{}, fmt.Errorf("cannot parse %q as a media type", t) } mainType := parts[0] subParts := strings.Split(parts[1], "+") subType := strings.Split(subParts[0], ";")[0] var suffix string if len(subParts) > 1 { suffix = subParts[1] } var typ string if suffix != "" { typ = mainType + "/" + subType + "+" + suffix } else { typ = mainType + "/" + subType } return Type{Type: typ, MainType: mainType, SubType: subType, mimeSuffix: suffix}, nil } // For internal use. func (m Type) String() string { return m.Type } // Suffixes returns all valid file suffixes for this type. func (m Type) Suffixes() []string { if m.SuffixesCSV == "" { return nil } return strings.Split(m.SuffixesCSV, ",") } // IsText returns whether this Type is a text format. // Note that this may currently return false negatives. // TODO(bep) improve // For internal use. func (m Type) IsText() bool { if m.MainType == "text" { return true } switch m.SubType { case "javascript", "json", "rss", "xml", "svg", "toml", "yml", "yaml": return true } return false } // For internal use. func (m Type) IsHTML() bool { return m.SubType == Builtin.HTMLType.SubType } // For internal use. func (m Type) IsMarkdown() bool { return m.SubType == Builtin.MarkdownType.SubType } func InitMediaType(m *Type) { m.init() } func (m *Type) init() { m.FirstSuffix.FullSuffix = "" m.FirstSuffix.Suffix = "" if suffixes := m.Suffixes(); suffixes != nil { m.FirstSuffix.Suffix = suffixes[0] m.FirstSuffix.FullSuffix = m.Delimiter + m.FirstSuffix.Suffix } } func newMediaType(main, sub string, suffixes []string) Type { t := Type{MainType: main, SubType: sub, SuffixesCSV: strings.Join(suffixes, ","), Delimiter: DefaultDelimiter} t.init() return t } func newMediaTypeWithMimeSuffix(main, sub, mimeSuffix string, suffixes []string) Type { mt := newMediaType(main, sub, suffixes) mt.mimeSuffix = mimeSuffix mt.init() return mt } // Types is a slice of media types. // <docsmeta>{ "name": "MediaTypes" }</docsmeta> type Types []Type func (t Types) Len() int { return len(t) } func (t Types) Swap(i, j int) { t[i], t[j] = t[j], t[i] } func (t Types) Less(i, j int) bool { return t[i].Type < t[j].Type } // GetBestMatch returns the best match for the given media type string. func (t Types) GetBestMatch(s string) (Type, bool) { // First try an exact match. if mt, found := t.GetByType(s); found { return mt, true } // Try main type. if mt, found := t.GetBySubType(s); found { return mt, true } // Try extension. if mt, _, found := t.GetFirstBySuffix(s); found { return mt, true } return Type{}, false } // GetByType returns a media type for tp. func (t Types) GetByType(tp string) (Type, bool) { for _, tt := range t { if strings.EqualFold(tt.Type, tp) { return tt, true } } if !strings.Contains(tp, "+") { // Try with the main and sub type parts := strings.Split(tp, "/") if len(parts) == 2 { return t.GetByMainSubType(parts[0], parts[1]) } } return Type{}, false } func (t Types) normalizeSuffix(s string) string { return strings.ToLower(strings.TrimPrefix(s, ".")) } // BySuffix will return all media types matching a suffix. func (t Types) BySuffix(suffix string) []Type { suffix = t.normalizeSuffix(suffix) var types []Type for _, tt := range t { if tt.HasSuffix(suffix) { types = append(types, tt) } } return types } // GetFirstBySuffix will return the first type matching the given suffix. func (t Types) GetFirstBySuffix(suffix string) (Type, SuffixInfo, bool) { suffix = t.normalizeSuffix(suffix) for _, tt := range t { if tt.HasSuffix(suffix) { return tt, SuffixInfo{ FullSuffix: tt.Delimiter + suffix, Suffix: suffix, }, true } } return Type{}, SuffixInfo{}, false } // GetBySuffix gets a media type given as suffix, e.g. "html". // It will return false if no format could be found, or if the suffix given // is ambiguous. // The lookup is case insensitive. func (t Types) GetBySuffix(suffix string) (tp Type, si SuffixInfo, found bool) { suffix = t.normalizeSuffix(suffix) for _, tt := range t { if tt.HasSuffix(suffix) { if found { // ambiguous found = false return } tp = tt si = SuffixInfo{ FullSuffix: tt.Delimiter + suffix, Suffix: suffix, } found = true } } return } func (t Types) IsTextSuffix(suffix string) bool { suffix = t.normalizeSuffix(suffix) for _, tt := range t { if tt.HasSuffix(suffix) { return tt.IsText() } } return false } func (m Type) HasSuffix(suffix string) bool { return strings.Contains(","+m.SuffixesCSV+",", ","+suffix+",") } // GetByMainSubType gets a media type given a main and a sub type e.g. "text" and "plain". // It will return false if no format could be found, or if the combination given // is ambiguous. // The lookup is case insensitive. func (t Types) GetByMainSubType(mainType, subType string) (tp Type, found bool) { for _, tt := range t { if strings.EqualFold(mainType, tt.MainType) && strings.EqualFold(subType, tt.SubType) { if found { // ambiguous found = false return } tp = tt found = true } } return } // GetBySubType gets a media type given a sub type e.g. "plain". func (t Types) GetBySubType(subType string) (tp Type, found bool) { for _, tt := range t { if strings.EqualFold(subType, tt.SubType) { if found { // ambiguous found = false return } tp = tt found = true } } return } // IsZero reports whether this Type represents a zero value. // For internal use. func (m Type) IsZero() bool { return m.SubType == "" } // MarshalJSON returns the JSON encoding of m. // For internal use. func (m Type) MarshalJSON() ([]byte, error) { type Alias Type return json.Marshal(&struct { Alias Type string `json:"type"` String string `json:"string"` Suffixes []string `json:"suffixes"` }{ Alias: (Alias)(m), Type: m.Type, String: m.String(), Suffixes: strings.Split(m.SuffixesCSV, ","), }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/media/mediaType_test.go
media/mediaType_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package media import ( "encoding/json" "os" "path/filepath" "sort" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/paths" ) func TestGetByType(t *testing.T) { c := qt.New(t) types := DefaultTypes mt, found := types.GetByType("text/HTML") c.Assert(found, qt.Equals, true) c.Assert(mt.SubType, qt.Equals, "html") _, found = types.GetByType("text/nono") c.Assert(found, qt.Equals, false) mt, found = types.GetByType("application/rss+xml") c.Assert(found, qt.Equals, true) c.Assert(mt.SubType, qt.Equals, "rss") mt, found = types.GetByType("application/rss") c.Assert(found, qt.Equals, true) c.Assert(mt.SubType, qt.Equals, "rss") } func TestGetByMainSubType(t *testing.T) { c := qt.New(t) f, found := DefaultTypes.GetByMainSubType("text", "plain") c.Assert(found, qt.Equals, true) c.Assert(f.SubType, qt.Equals, "plain") _, found = DefaultTypes.GetByMainSubType("foo", "plain") c.Assert(found, qt.Equals, false) } func TestBySuffix(t *testing.T) { c := qt.New(t) formats := DefaultTypes.BySuffix("xml") c.Assert(len(formats), qt.Equals, 2) c.Assert(formats[0].SubType, qt.Equals, "rss") c.Assert(formats[1].SubType, qt.Equals, "xml") } func TestGetFirstBySuffix(t *testing.T) { c := qt.New(t) types := make(Types, len(DefaultTypes)) copy(types, DefaultTypes) // Issue #8406 geoJSON := newMediaTypeWithMimeSuffix("application", "geo", "json", []string{"geojson", "gjson"}) types = append(types, geoJSON) sort.Sort(types) check := func(suffix string, expectedType Type) { t, f, found := types.GetFirstBySuffix(suffix) c.Assert(found, qt.Equals, true) c.Assert(f, qt.Equals, SuffixInfo{ Suffix: suffix, FullSuffix: "." + suffix, }) c.Assert(t, qt.Equals, expectedType) } check("js", Builtin.JavascriptType) check("json", Builtin.JSONType) check("geojson", geoJSON) check("gjson", geoJSON) } func TestFromTypeString(t *testing.T) { c := qt.New(t) f, err := FromString("text/html") c.Assert(err, qt.IsNil) c.Assert(f.Type, qt.Equals, Builtin.HTMLType.Type) f, err = FromString("application/custom") c.Assert(err, qt.IsNil) c.Assert(f, qt.Equals, Type{Type: "application/custom", MainType: "application", SubType: "custom", mimeSuffix: ""}) f, err = FromString("application/custom+sfx") c.Assert(err, qt.IsNil) c.Assert(f, qt.Equals, Type{Type: "application/custom+sfx", MainType: "application", SubType: "custom", mimeSuffix: "sfx"}) _, err = FromString("noslash") c.Assert(err, qt.Not(qt.IsNil)) f, err = FromString("text/xml; charset=utf-8") c.Assert(err, qt.IsNil) c.Assert(f, qt.Equals, Type{Type: "text/xml", MainType: "text", SubType: "xml", mimeSuffix: ""}) } func TestFromStringAndExt(t *testing.T) { c := qt.New(t) f, err := FromStringAndExt("text/html", "html", "htm") c.Assert(err, qt.IsNil) c.Assert(f, qt.Equals, Builtin.HTMLType) f, err = FromStringAndExt("text/html", ".html", ".htm") c.Assert(err, qt.IsNil) c.Assert(f, qt.Equals, Builtin.HTMLType) } // Add a test for the SVG case // https://github.com/gohugoio/hugo/issues/4920 func TestFromExtensionMultipleSuffixes(t *testing.T) { c := qt.New(t) tp, si, found := DefaultTypes.GetBySuffix("svg") c.Assert(found, qt.Equals, true) c.Assert(tp.String(), qt.Equals, "image/svg+xml") c.Assert(si.Suffix, qt.Equals, "svg") c.Assert(si.FullSuffix, qt.Equals, ".svg") c.Assert(tp.FirstSuffix.Suffix, qt.Equals, si.Suffix) c.Assert(tp.FirstSuffix.FullSuffix, qt.Equals, si.FullSuffix) ftp, found := DefaultTypes.GetByType("image/svg+xml") c.Assert(found, qt.Equals, true) c.Assert(ftp.String(), qt.Equals, "image/svg+xml") c.Assert(found, qt.Equals, true) } func TestFromContent(t *testing.T) { c := qt.New(t) files, err := filepath.Glob("./testdata/resource.*") c.Assert(err, qt.IsNil) for _, filename := range files { name := filepath.Base(filename) c.Run(name, func(c *qt.C) { content, err := os.ReadFile(filename) c.Assert(err, qt.IsNil) ext := strings.TrimPrefix(paths.Ext(filename), ".") var exts []string if ext == "jpg" { exts = append(exts, "foo", "bar", "jpg") } else { exts = []string{ext} } expected, _, found := DefaultTypes.GetFirstBySuffix(ext) c.Assert(found, qt.IsTrue) got := FromContent(DefaultTypes, exts, content) c.Assert(got, qt.Equals, expected) }) } } func TestFromContentFakes(t *testing.T) { c := qt.New(t) files, err := filepath.Glob("./testdata/fake.*") c.Assert(err, qt.IsNil) for _, filename := range files { name := filepath.Base(filename) c.Run(name, func(c *qt.C) { content, err := os.ReadFile(filename) c.Assert(err, qt.IsNil) ext := strings.TrimPrefix(paths.Ext(filename), ".") got := FromContent(DefaultTypes, []string{ext}, content) c.Assert(got, qt.Equals, zero) }) } } func TestToJSON(t *testing.T) { c := qt.New(t) b, err := json.Marshal(Builtin.MPEGType) c.Assert(err, qt.IsNil) c.Assert(string(b), qt.Equals, `{"mainType":"video","subType":"mpeg","delimiter":".","type":"video/mpeg","string":"video/mpeg","suffixes":["mpg","mpeg"]}`) } func BenchmarkTypeOps(b *testing.B) { mt := Builtin.MPEGType mts := DefaultTypes for b.Loop() { ff := mt.FirstSuffix _ = ff.FullSuffix _ = mt.IsZero() c, err := mt.MarshalJSON() if c == nil || err != nil { b.Fatal("failed") } _ = mt.String() _ = ff.Suffix _ = mt.Suffixes _ = mt.Type _ = mts.BySuffix("xml") _, _ = mts.GetByMainSubType("application", "xml") _, _, _ = mts.GetBySuffix("xml") _, _ = mts.GetByType("application") _, _, _ = mts.GetFirstBySuffix("xml") } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/defaultConfigProvider_test.go
config/defaultConfigProvider_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "context" "errors" "fmt" "slices" "strconv" "strings" "testing" "github.com/gohugoio/hugo/common/para" "github.com/gohugoio/hugo/common/maps" qt "github.com/frankban/quicktest" ) func TestDefaultConfigProvider(t *testing.T) { c := qt.New(t) c.Run("Set and get", func(c *qt.C) { cfg := New() var k string var v any k, v = "foo", "bar" cfg.Set(k, v) c.Assert(cfg.Get(k), qt.Equals, v) c.Assert(cfg.Get(strings.ToUpper(k)), qt.Equals, v) c.Assert(cfg.GetString(k), qt.Equals, v) k, v = "foo", 42 cfg.Set(k, v) c.Assert(cfg.Get(k), qt.Equals, v) c.Assert(cfg.GetInt(k), qt.Equals, v) c.Assert(cfg.Get(""), qt.DeepEquals, maps.Params{ "foo": 42, }) }) c.Run("Set and get map", func(c *qt.C) { cfg := New() cfg.Set("foo", map[string]any{ "bar": "baz", }) c.Assert(cfg.Get("foo"), qt.DeepEquals, maps.Params{ "bar": "baz", }) c.Assert(cfg.GetStringMap("foo"), qt.DeepEquals, map[string]any{"bar": string("baz")}) c.Assert(cfg.GetStringMapString("foo"), qt.DeepEquals, map[string]string{"bar": string("baz")}) }) c.Run("Set and get nested", func(c *qt.C) { cfg := New() cfg.Set("a", map[string]any{ "B": "bv", }) cfg.Set("a.c", "cv") c.Assert(cfg.Get("a"), qt.DeepEquals, maps.Params{ "b": "bv", "c": "cv", }) c.Assert(cfg.Get("a.c"), qt.Equals, "cv") cfg.Set("b.a", "av") c.Assert(cfg.Get("b"), qt.DeepEquals, maps.Params{ "a": "av", }) cfg.Set("b", map[string]any{ "b": "bv", }) c.Assert(cfg.Get("b"), qt.DeepEquals, maps.Params{ "a": "av", "b": "bv", }) cfg = New() cfg.Set("a", "av") cfg.Set("", map[string]any{ "a": "av2", "b": "bv2", }) c.Assert(cfg.Get(""), qt.DeepEquals, maps.Params{ "a": "av2", "b": "bv2", }) cfg = New() cfg.Set("a", "av") cfg.Set("", map[string]any{ "b": "bv2", }) c.Assert(cfg.Get(""), qt.DeepEquals, maps.Params{ "a": "av", "b": "bv2", }) cfg = New() cfg.Set("", map[string]any{ "foo": map[string]any{ "a": "av", }, }) cfg.Set("", map[string]any{ "foo": map[string]any{ "b": "bv2", }, }) c.Assert(cfg.Get("foo"), qt.DeepEquals, maps.Params{ "a": "av", "b": "bv2", }) }) c.Run("Merge default strategy", func(c *qt.C) { cfg := New() cfg.Set("a", map[string]any{ "B": "bv", }) cfg.Merge("a", map[string]any{ "B": "bv2", "c": "cv2", }) c.Assert(cfg.Get("a"), qt.DeepEquals, maps.Params{ "b": "bv", "c": "cv2", }) cfg = New() cfg.Set("a", "av") cfg.Merge("", map[string]any{ "a": "av2", "b": "bv2", }) c.Assert(cfg.Get(""), qt.DeepEquals, maps.Params{ "a": "av", }) }) c.Run("Merge shallow", func(c *qt.C) { cfg := New() cfg.Set("a", map[string]any{ "_merge": "shallow", "B": "bv", "c": map[string]any{ "b": "bv", }, }) cfg.Merge("a", map[string]any{ "c": map[string]any{ "d": "dv2", }, "e": "ev2", }) c.Assert(cfg.Get("a"), qt.DeepEquals, maps.Params{ "e": "ev2", "_merge": maps.ParamsMergeStrategyShallow, "b": "bv", "c": maps.Params{ "b": "bv", }, }) }) // Issue #8679 c.Run("Merge typed maps", func(c *qt.C) { for _, left := range []any{ map[string]string{ "c": "cv1", }, map[string]any{ "c": "cv1", }, map[any]any{ "c": "cv1", }, } { cfg := New() cfg.Set("", map[string]any{ "b": left, }) cfg.Merge("", maps.Params{ "b": maps.Params{ "c": "cv2", "d": "dv2", }, }) c.Assert(cfg.Get(""), qt.DeepEquals, maps.Params{ "b": maps.Params{ "c": "cv1", "d": "dv2", }, }) } for _, left := range []any{ map[string]string{ "b": "bv1", }, map[string]any{ "b": "bv1", }, map[any]any{ "b": "bv1", }, } { for _, right := range []any{ map[string]string{ "b": "bv2", "c": "cv2", }, map[string]any{ "b": "bv2", "c": "cv2", }, map[any]any{ "b": "bv2", "c": "cv2", }, } { cfg := New() cfg.Set("a", left) cfg.Merge("a", right) c.Assert(cfg.Get(""), qt.DeepEquals, maps.Params{ "a": maps.Params{ "b": "bv1", "c": "cv2", }, }) } } }) // Issue #8701 c.Run("Prevent _merge only maps", func(c *qt.C) { cfg := New() cfg.Set("", map[string]any{ "B": "bv", }) cfg.Merge("", map[string]any{ "c": map[string]any{ "_merge": "shallow", "d": "dv2", }, }) c.Assert(cfg.Get(""), qt.DeepEquals, maps.Params{ "b": "bv", }) }) c.Run("IsSet", func(c *qt.C) { cfg := New() cfg.Set("a", map[string]any{ "B": "bv", }) c.Assert(cfg.IsSet("A"), qt.IsTrue) c.Assert(cfg.IsSet("a.b"), qt.IsTrue) c.Assert(cfg.IsSet("z"), qt.IsFalse) }) c.Run("Para", func(c *qt.C) { cfg := New() p := para.New(4) r, _ := p.Start(context.Background()) setAndGet := func(k string, v int) error { vs := strconv.Itoa(v) cfg.Set(k, v) err := errors.New("get failed") if cfg.Get(k) != v { return err } if cfg.GetInt(k) != v { return err } if cfg.GetString(k) != vs { return err } if !cfg.IsSet(k) { return err } return nil } for i := range 20 { r.Run(func() error { const v = 42 k := fmt.Sprintf("k%d", i) if err := setAndGet(k, v); err != nil { return err } m := maps.Params{ "new": 42, } cfg.Merge("", m) return nil }) } c.Assert(r.Wait(), qt.IsNil) }) c.Run("GetBool", func(c *qt.C) { cfg := New() var k string var v bool k, v = "foo", true cfg.Set(k, v) c.Assert(cfg.Get(k), qt.Equals, v) c.Assert(cfg.GetBool(k), qt.Equals, v) }) c.Run("GetParams", func(c *qt.C) { cfg := New() k := "foo" cfg.Set(k, maps.Params{k: true}) c.Assert(cfg.GetParams(k), qt.DeepEquals, maps.Params{ k: true, }) c.Assert(cfg.GetParams("bar"), qt.IsNil) }) c.Run("Keys", func(c *qt.C) { cfg := New() k := "foo" k2 := "bar" cfg.Set(k, maps.Params{k: struct{}{}}) cfg.Set(k2, maps.Params{k2: struct{}{}}) c.Assert(len(cfg.Keys()), qt.Equals, 2) got := cfg.Keys() slices.Sort(got) want := []string{k, k2} slices.Sort(want) c.Assert(got, qt.DeepEquals, want) }) c.Run("WalkParams", func(c *qt.C) { cfg := New() cfg.Set("x", maps.Params{}) cfg.Set("y", maps.Params{}) var got []string cfg.WalkParams(func(params ...maps.KeyParams) bool { got = append(got, params[len(params)-1].Key) return false }) want := []string{"", "x", "y"} slices.Sort(got) slices.Sort(want) c.Assert(got, qt.DeepEquals, want) cfg = New() cfg.WalkParams(func(params ...maps.KeyParams) bool { return true }) got = []string{""} want = []string{""} c.Assert(got, qt.DeepEquals, want) }) c.Run("SetDefaults", func(c *qt.C) { cfg := New() cfg.SetDefaults(maps.Params{ "foo": "bar", "bar": "baz", }) c.Assert(cfg.Get("foo"), qt.Equals, "bar") c.Assert(cfg.Get("bar"), qt.Equals, "baz") }) } func BenchmarkDefaultConfigProvider(b *testing.B) { type cfger interface { Get(key string) any Set(key string, value any) IsSet(key string) bool } newMap := func() map[string]any { return map[string]any{ "a": map[string]any{ "b": map[string]any{ "c": 32, "d": 43, }, }, "b": 62, } } runMethods := func(b *testing.B, cfg cfger) { m := newMap() cfg.Set("mymap", m) cfg.Set("num", 32) if !(cfg.IsSet("mymap") && cfg.IsSet("mymap.a") && cfg.IsSet("mymap.a.b") && cfg.IsSet("mymap.a.b.c")) { b.Fatal("IsSet failed") } if cfg.Get("num") != 32 { b.Fatal("Get failed") } if cfg.Get("mymap.a.b.c") != 32 { b.Fatal("Get failed") } } b.Run("Custom", func(b *testing.B) { cfg := New() for b.Loop() { runMethods(b, cfg) } }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/commonConfig_test.go
config/commonConfig_test.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "errors" "testing" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/types" qt "github.com/frankban/quicktest" ) func TestBuild(t *testing.T) { c := qt.New(t) v := New() v.Set("build", map[string]any{ "useResourceCacheWhen": "always", }) b := DecodeBuildConfig(v) c.Assert(b.UseResourceCacheWhen, qt.Equals, "always") v.Set("build", map[string]any{ "useResourceCacheWhen": "foo", }) b = DecodeBuildConfig(v) c.Assert(b.UseResourceCacheWhen, qt.Equals, "fallback") c.Assert(b.UseResourceCache(herrors.ErrFeatureNotAvailable), qt.Equals, true) c.Assert(b.UseResourceCache(errors.New("err")), qt.Equals, false) b.UseResourceCacheWhen = "always" c.Assert(b.UseResourceCache(herrors.ErrFeatureNotAvailable), qt.Equals, true) c.Assert(b.UseResourceCache(errors.New("err")), qt.Equals, true) c.Assert(b.UseResourceCache(nil), qt.Equals, true) b.UseResourceCacheWhen = "never" c.Assert(b.UseResourceCache(herrors.ErrFeatureNotAvailable), qt.Equals, false) c.Assert(b.UseResourceCache(errors.New("err")), qt.Equals, false) c.Assert(b.UseResourceCache(nil), qt.Equals, false) } func TestServer(t *testing.T) { c := qt.New(t) cfg, err := FromConfigString(`[[server.headers]] for = "/*.jpg" [server.headers.values] X-Frame-Options = "DENY" X-XSS-Protection = "1; mode=block" X-Content-Type-Options = "nosniff" [[server.redirects]] from = "/foo/**" to = "/baz/index.html" status = 200 [[server.redirects]] from = "/loop/**" to = "/loop/foo/" status = 200 [[server.redirects]] from = "/b/**" fromRe = "/b/(.*)/" to = "/baz/$1/" status = 200 [[server.redirects]] fromRe = "/c/(.*)/" to = "/boo/$1/" status = 200 [[server.redirects]] fromRe = "/d/(.*)/" to = "/boo/$1/" status = 200 [[server.redirects]] from = "/google/**" to = "https://google.com/" status = 301 `, "toml") c.Assert(err, qt.IsNil) s, err := DecodeServer(cfg) c.Assert(err, qt.IsNil) c.Assert(s.CompileConfig(loggers.NewDefault()), qt.IsNil) c.Assert(s.MatchHeaders("/foo.jpg"), qt.DeepEquals, []types.KeyValueStr{ {Key: "X-Content-Type-Options", Value: "nosniff"}, {Key: "X-Frame-Options", Value: "DENY"}, {Key: "X-XSS-Protection", Value: "1; mode=block"}, }) c.Assert(s.MatchRedirect("/foo/bar/baz", nil), qt.DeepEquals, Redirect{ From: "/foo/**", To: "/baz/", Status: 200, }) c.Assert(s.MatchRedirect("/foo/bar/", nil), qt.DeepEquals, Redirect{ From: "/foo/**", To: "/baz/", Status: 200, }) c.Assert(s.MatchRedirect("/b/c/", nil), qt.DeepEquals, Redirect{ From: "/b/**", FromRe: "/b/(.*)/", To: "/baz/c/", Status: 200, }) c.Assert(s.MatchRedirect("/c/d/", nil).To, qt.Equals, "/boo/d/") c.Assert(s.MatchRedirect("/c/d/e/", nil).To, qt.Equals, "/boo/d/e/") c.Assert(s.MatchRedirect("/someother", nil), qt.DeepEquals, Redirect{}) c.Assert(s.MatchRedirect("/google/foo", nil), qt.DeepEquals, Redirect{ From: "/google/**", To: "https://google.com/", Status: 301, }) } func TestBuildConfigCacheBusters(t *testing.T) { c := qt.New(t) cfg := New() conf := DecodeBuildConfig(cfg) l := loggers.NewDefault() c.Assert(conf.CompileConfig(l), qt.IsNil) m, _ := conf.MatchCacheBuster(l, "tailwind.config.js") c.Assert(m, qt.IsNotNil) c.Assert(m("css"), qt.IsTrue) c.Assert(m("js"), qt.IsFalse) m, _ = conf.MatchCacheBuster(l, "foo.bar") c.Assert(m, qt.IsNil) } func TestBuildConfigCacheBusterstTailwindSetup(t *testing.T) { c := qt.New(t) cfg := New() cfg.Set("build", map[string]any{ "cacheBusters": []map[string]string{ { "source": "assets/watching/hugo_stats\\.json", "target": "css", }, { "source": "(postcss|tailwind)\\.config\\.js", "target": "css", }, { "source": "assets/.*\\.(js|ts|jsx|tsx)", "target": "js", }, { "source": "assets/.*\\.(.*)$", "target": "$1", }, }, }) conf := DecodeBuildConfig(cfg) l := loggers.NewDefault() c.Assert(conf.CompileConfig(l), qt.IsNil) m, err := conf.MatchCacheBuster(l, "assets/watching/hugo_stats.json") c.Assert(err, qt.IsNil) c.Assert(m("css"), qt.IsTrue) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/namespace.go
config/namespace.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "encoding/json" "github.com/gohugoio/hugo/common/hashing" ) func DecodeNamespace[S, C any](configSource any, buildConfig func(any) (C, any, error)) (*ConfigNamespace[S, C], error) { // Calculate the hash of the input (not including any defaults applied later). // This allows us to introduce new config options without breaking the hash. h := hashing.HashStringHex(configSource) // Build the config c, ext, err := buildConfig(configSource) if err != nil { return nil, err } if ext == nil { ext = configSource } if ext == nil { panic("ext is nil") } ns := &ConfigNamespace[S, C]{ SourceStructure: ext, SourceHash: h, Config: c, } return ns, nil } // ConfigNamespace holds a Hugo configuration namespace. // The construct looks a little odd, but it's built to make the configuration elements // both self-documenting and contained in a common structure. type ConfigNamespace[S, C any] struct { // SourceStructure represents the source configuration with any defaults applied. // This is used for documentation and printing of the configuration setup to the user. SourceStructure any // SourceHash is a hash of the source configuration before any defaults gets applied. SourceHash string // Config is the final configuration as used by Hugo. Config C } // MarshalJSON marshals the source structure. func (ns *ConfigNamespace[S, C]) MarshalJSON() ([]byte, error) { return json.Marshal(ns.SourceStructure) } // Signature returns the signature of the source structure. // Note that this is for documentation purposes only and SourceStructure may not always be cast to S (it's usually just a map). func (ns *ConfigNamespace[S, C]) Signature() S { var s S return s }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/configLoader_test.go
config/configLoader_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "regexp" "strings" "testing" qt "github.com/frankban/quicktest" ) func TestIsValidConfigFileName(t *testing.T) { c := qt.New(t) for _, ext := range ValidConfigFileExtensions { filename := "config." + ext c.Assert(IsValidConfigFilename(filename), qt.Equals, true) c.Assert(IsValidConfigFilename(strings.ToUpper(filename)), qt.Equals, true) } c.Assert(IsValidConfigFilename(""), qt.Equals, false) c.Assert(IsValidConfigFilename("config.toml.swp"), qt.Equals, false) } func TestFromTOMLConfigString(t *testing.T) { c := qt.New(t) c.Assert( func() { FromTOMLConfigString("cfg") }, qt.PanicMatches, regexp.MustCompile("_stream.toml:.*"), ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/configLoader.go
config/configLoader.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "fmt" "os" "path/filepath" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/afero" ) var ( // See issue #8979 for context. // Hugo has always used config.toml etc. as the default config file name. // But hugo.toml is a more descriptive name, but we need to check for both. DefaultConfigNames = []string{"hugo", "config"} DefaultConfigNamesSet = make(map[string]bool) ValidConfigFileExtensions = []string{"toml", "yaml", "yml", "json"} validConfigFileExtensionsMap map[string]bool = make(map[string]bool) ) func init() { for _, name := range DefaultConfigNames { DefaultConfigNamesSet[name] = true } for _, ext := range ValidConfigFileExtensions { validConfigFileExtensionsMap[ext] = true } } // IsValidConfigFilename returns whether filename is one of the supported // config formats in Hugo. func IsValidConfigFilename(filename string) bool { ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(filename), ".")) return validConfigFileExtensionsMap[ext] } // FromTOMLConfigString creates a config from the given TOML config. This is useful in tests. func FromTOMLConfigString(config string) Provider { cfg, err := FromConfigString(config, "toml") if err != nil { panic(err) } return cfg } // FromMapToTOMLString converts the given map to a TOML string. This is useful in tests. func FromMapToTOMLString(v map[string]any) string { var sb strings.Builder err := parser.InterfaceToConfig(v, metadecoders.TOML, &sb) if err != nil { panic(err) } return sb.String() } // FromConfigString creates a config from the given YAML, JSON or TOML config. This is useful in tests. func FromConfigString(config, configType string) (Provider, error) { m, err := readConfig(metadecoders.FormatFromString(configType), []byte(config)) if err != nil { return nil, err } return NewFrom(m), nil } // FromFile loads the configuration from the given filename. func FromFile(fs afero.Fs, filename string) (Provider, error) { m, err := loadConfigFromFile(fs, filename) if err != nil { fe := herrors.UnwrapFileError(err) if fe != nil { pos := fe.Position() pos.Filename = filename fe.UpdatePosition(pos) return nil, err } return nil, herrors.NewFileErrorFromFile(err, filename, fs, nil) } return NewFrom(m), nil } // FromFileToMap is the same as FromFile, but it returns the config values // as a simple map. func FromFileToMap(fs afero.Fs, filename string) (map[string]any, error) { return loadConfigFromFile(fs, filename) } func readConfig(format metadecoders.Format, data []byte) (map[string]any, error) { m, err := metadecoders.Default.UnmarshalToMap(data, format) if err != nil { return nil, err } RenameKeys(m) return m, nil } func loadConfigFromFile(fs afero.Fs, filename string) (map[string]any, error) { m, err := metadecoders.Default.UnmarshalFileToMap(fs, filename) if err != nil { return nil, err } RenameKeys(m) return m, nil } func LoadConfigFromDir(sourceFs afero.Fs, configDir, environment string) (Provider, []string, error) { defaultConfigDir := filepath.Join(configDir, "_default") environmentConfigDir := filepath.Join(configDir, environment) cfg := New() var configDirs []string // Merge from least to most specific. for _, dir := range []string{defaultConfigDir, environmentConfigDir} { if _, err := sourceFs.Stat(dir); err == nil { configDirs = append(configDirs, dir) } } if len(configDirs) == 0 { return nil, nil, nil } // Keep track of these so we can watch them for changes. var dirnames []string for _, configDir := range configDirs { err := afero.Walk(sourceFs, configDir, func(path string, fi os.FileInfo, err error) error { if fi == nil || err != nil { return nil } if fi.IsDir() { dirnames = append(dirnames, path) return nil } if !IsValidConfigFilename(path) { return nil } name := paths.Filename(filepath.Base(path)) item, err := metadecoders.Default.UnmarshalFileToMap(sourceFs, path) if err != nil { // This will be used in error reporting, use the most specific value. dirnames = []string{path} return fmt.Errorf("failed to unmarshal config for path %q: %w", path, err) } var keyPath []string if !DefaultConfigNamesSet[name] { // Can be params.jp, menus.en etc. name, lang := paths.FileAndExtNoDelimiter(name) keyPath = []string{name} if lang != "" { keyPath = []string{"languages", lang} switch name { case "menu", "menus": keyPath = append(keyPath, "menus") case "params": keyPath = append(keyPath, "params") } } } root := item if len(keyPath) > 0 { root = make(map[string]any) m := root for i, key := range keyPath { if i >= len(keyPath)-1 { m[key] = item } else { nm := make(map[string]any) m[key] = nm m = nm } } } // Migrate menu => menus etc. RenameKeys(root) // Set will overwrite keys with the same name, recursively. cfg.Set("", root) return nil }) if err != nil { return nil, dirnames, err } } return cfg, dirnames, nil } var keyAliases maps.KeyRenamer func init() { var err error keyAliases, err = maps.NewKeyRenamer( // Before 0.53 we used singular for "menu". "{menu,languages/*/menu}", "menus", ) if err != nil { panic(err) } } // RenameKeys renames config keys in m recursively according to a global Hugo // alias definition. func RenameKeys(m map[string]any) { keyAliases.Rename(m) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/env_test.go
config/env_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "testing" qt "github.com/frankban/quicktest" ) func TestSetEnvVars(t *testing.T) { t.Parallel() c := qt.New(t) vars := []string{"FOO=bar", "HUGO=cool", "BAR=foo"} SetEnvVars(&vars, "HUGO", "rocking!", "NEW", "bar") c.Assert(vars, qt.DeepEquals, []string{"FOO=bar", "HUGO=rocking!", "BAR=foo", "NEW=bar"}) key, val := SplitEnvVar("HUGO=rocks") c.Assert(key, qt.Equals, "HUGO") c.Assert(val, qt.Equals, "rocks") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/namespace_test.go
config/namespace_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/maps" "github.com/mitchellh/mapstructure" ) func TestNamespace(t *testing.T) { c := qt.New(t) c.Assert(true, qt.Equals, true) // ns, err := config.DecodeNamespace[map[string]DocsMediaTypeConfig](in, defaultMediaTypesConfig, buildConfig) ns, err := DecodeNamespace[[]*tstNsExt]( map[string]any{"foo": "bar"}, func(v any) (*tstNsExt, any, error) { t := &tstNsExt{} m, err := maps.ToStringMapE(v) if err != nil { return nil, nil, err } return t, nil, mapstructure.WeakDecode(m, t) }, ) c.Assert(err, qt.IsNil) c.Assert(ns, qt.Not(qt.IsNil)) c.Assert(ns.SourceStructure, qt.DeepEquals, map[string]any{"foo": "bar"}) c.Assert(ns.SourceHash, qt.Equals, "1420f6c7782f7459") c.Assert(ns.Config, qt.DeepEquals, &tstNsExt{Foo: "bar"}) c.Assert(ns.Signature(), qt.DeepEquals, []*tstNsExt(nil)) } type ( tstNsExt struct { Foo string } ) func (t *tstNsExt) Init() error { t.Foo = strings.ToUpper(t.Foo) return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/configProvider_test.go
config/configProvider_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "testing" qt "github.com/frankban/quicktest" ) func TestGetStringSlicePreserveString(t *testing.T) { c := qt.New(t) cfg := New() s := "This is a string" sSlice := []string{"This", "is", "a", "slice"} cfg.Set("s1", s) cfg.Set("s2", sSlice) c.Assert(GetStringSlicePreserveString(cfg, "s1"), qt.DeepEquals, []string{s}) c.Assert(GetStringSlicePreserveString(cfg, "s2"), qt.DeepEquals, sSlice) c.Assert(GetStringSlicePreserveString(cfg, "s3"), qt.IsNil) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/commonConfig.go
config/commonConfig.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "fmt" "net/http" "regexp" "slices" "sort" "strings" "github.com/bep/logg" "github.com/gobwas/glob" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/common/herrors" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" ) type BaseConfig struct { WorkingDir string CacheDir string ThemesDir string PublishDir string } type CommonDirs struct { // The directory where Hugo will look for themes. ThemesDir string // Where to put the generated files. PublishDir string // The directory to put the generated resources files. This directory should in most situations be considered temporary // and not be committed to version control. But there may be cached content in here that you want to keep, // e.g. resources/_gen/images for performance reasons or CSS built from SASS when your CI server doesn't have the full setup. ResourceDir string // The project root directory. WorkingDir string // The root directory for all cache files. CacheDir string // The content source directory. // Deprecated: Use module mounts. ContentDir string // Deprecated: Use module mounts. // The data source directory. DataDir string // Deprecated: Use module mounts. // The layout source directory. LayoutDir string // Deprecated: Use module mounts. // The i18n source directory. I18nDir string // Deprecated: Use module mounts. // The archetypes source directory. ArcheTypeDir string // Deprecated: Use module mounts. // The assets source directory. AssetDir string } type LoadConfigResult struct { Cfg Provider ConfigFiles []string BaseConfig BaseConfig } var defaultBuild = BuildConfig{ UseResourceCacheWhen: "fallback", BuildStats: BuildStats{}, CacheBusters: []CacheBuster{ { Source: `(postcss|tailwind)\.config\.js`, Target: cssTargetCachebusterRe, }, }, } // BuildConfig holds some build related configuration. type BuildConfig struct { // When to use the resource file cache. // One of never, fallback, always. Default is fallback UseResourceCacheWhen string // When enabled, will collect and write a hugo_stats.json with some build // related aggregated data (e.g. CSS class names). // Note that this was a bool <= v0.115.0. BuildStats BuildStats // Can be used to toggle off writing of the IntelliSense /assets/jsconfig.js // file. NoJSConfigInAssets bool // Can used to control how the resource cache gets evicted on rebuilds. CacheBusters []CacheBuster } // BuildStats configures if and what to write to the hugo_stats.json file. type BuildStats struct { Enable bool DisableTags bool DisableClasses bool DisableIDs bool } func (w BuildStats) Enabled() bool { if !w.Enable { return false } return !w.DisableTags || !w.DisableClasses || !w.DisableIDs } func (b BuildConfig) clone() BuildConfig { b.CacheBusters = slices.Clone(b.CacheBusters) return b } func (b BuildConfig) UseResourceCache(err error) bool { if b.UseResourceCacheWhen == "never" { return false } if b.UseResourceCacheWhen == "fallback" { return herrors.IsFeatureNotAvailableError(err) } return true } // MatchCacheBuster returns the cache buster for the given path p, nil if none. func (s BuildConfig) MatchCacheBuster(logger loggers.Logger, p string) (func(string) bool, error) { var matchers []func(string) bool for _, cb := range s.CacheBusters { if matcher := cb.compiledSource(p); matcher != nil { matchers = append(matchers, matcher) } } if len(matchers) > 0 { return (func(cacheKey string) bool { for _, m := range matchers { if m(cacheKey) { return true } } return false }), nil } return nil, nil } func (b *BuildConfig) CompileConfig(logger loggers.Logger) error { for i, cb := range b.CacheBusters { if err := cb.CompileConfig(logger); err != nil { return fmt.Errorf("failed to compile cache buster %q: %w", cb.Source, err) } b.CacheBusters[i] = cb } return nil } func DecodeBuildConfig(cfg Provider) BuildConfig { m := cfg.GetStringMap("build") b := defaultBuild.clone() if m == nil { return b } // writeStats was a bool <= v0.115.0. if writeStats, ok := m["writestats"]; ok { if bb, ok := writeStats.(bool); ok { m["buildstats"] = BuildStats{Enable: bb} } } err := mapstructure.WeakDecode(m, &b) if err != nil { return b } b.UseResourceCacheWhen = strings.ToLower(b.UseResourceCacheWhen) when := b.UseResourceCacheWhen if when != "never" && when != "always" && when != "fallback" { b.UseResourceCacheWhen = "fallback" } return b } // SitemapConfig configures the sitemap to be generated. type SitemapConfig struct { // The page change frequency. ChangeFreq string // The priority of the page. Priority float64 // The sitemap filename. Filename string // Whether to disable page inclusion. Disable bool } func DecodeSitemap(prototype SitemapConfig, input map[string]any) (SitemapConfig, error) { err := mapstructure.WeakDecode(input, &prototype) return prototype, err } // Config for the dev server. type Server struct { Headers []Headers Redirects []Redirect compiledHeaders []glob.Glob compiledRedirects []redirect } type redirect struct { from glob.Glob fromRe *regexp.Regexp headers map[string]glob.Glob } func (r redirect) matchHeader(header http.Header) bool { for k, v := range r.headers { if !v.Match(header.Get(k)) { return false } } return true } func (s *Server) CompileConfig(logger loggers.Logger) error { if s.compiledHeaders != nil { return nil } for _, h := range s.Headers { g, err := glob.Compile(h.For) if err != nil { return fmt.Errorf("failed to compile Headers glob %q: %w", h.For, err) } s.compiledHeaders = append(s.compiledHeaders, g) } for _, r := range s.Redirects { if r.From == "" && r.FromRe == "" { return fmt.Errorf("redirects must have either From or FromRe set") } rd := redirect{ headers: make(map[string]glob.Glob), } if r.From != "" { g, err := glob.Compile(r.From) if err != nil { return fmt.Errorf("failed to compile Redirect glob %q: %w", r.From, err) } rd.from = g } if r.FromRe != "" { re, err := regexp.Compile(r.FromRe) if err != nil { return fmt.Errorf("failed to compile Redirect regexp %q: %w", r.FromRe, err) } rd.fromRe = re } for k, v := range r.FromHeaders { g, err := glob.Compile(v) if err != nil { return fmt.Errorf("failed to compile Redirect header glob %q: %w", v, err) } rd.headers[k] = g } s.compiledRedirects = append(s.compiledRedirects, rd) } return nil } func (s *Server) MatchHeaders(pattern string) []types.KeyValueStr { if s.compiledHeaders == nil { return nil } var matches []types.KeyValueStr for i, g := range s.compiledHeaders { if g.Match(pattern) { h := s.Headers[i] for k, v := range h.Values { matches = append(matches, types.KeyValueStr{Key: k, Value: cast.ToString(v)}) } } } sort.Slice(matches, func(i, j int) bool { return matches[i].Key < matches[j].Key }) return matches } func (s *Server) MatchRedirect(pattern string, header http.Header) Redirect { if s.compiledRedirects == nil { return Redirect{} } pattern = strings.TrimSuffix(pattern, "index.html") for i, r := range s.compiledRedirects { redir := s.Redirects[i] var found bool if r.from != nil { if r.from.Match(pattern) { found = header == nil || r.matchHeader(header) // We need to do regexp group replacements if needed. } } if r.fromRe != nil { m := r.fromRe.FindStringSubmatch(pattern) if m != nil { if !found { found = header == nil || r.matchHeader(header) } if found { // Replace $1, $2 etc. in To. for i, g := range m[1:] { redir.To = strings.ReplaceAll(redir.To, fmt.Sprintf("$%d", i+1), g) } } } } if found { return redir } } return Redirect{} } type Headers struct { For string Values map[string]any } type Redirect struct { // From is the Glob pattern to match. // One of From or FromRe must be set. From string // FromRe is the regexp to match. // This regexp can contain group matches (e.g. $1) that can be used in the To field. // One of From or FromRe must be set. FromRe string // To is the target URL. To string // Headers to match for the redirect. // This maps the HTTP header name to a Glob pattern with values to match. // If the map is empty, the redirect will always be triggered. FromHeaders map[string]string // HTTP status code to use for the redirect. // A status code of 200 will trigger a URL rewrite. Status int // Forcode redirect, even if original request path exists. Force bool } // CacheBuster configures cache busting for assets. type CacheBuster struct { // Trigger for files matching this regexp. Source string // Cache bust targets matching this regexp. // This regexp can contain group matches (e.g. $1) from the source regexp. Target string compiledSource func(string) func(string) bool } func (c *CacheBuster) CompileConfig(logger loggers.Logger) error { if c.compiledSource != nil { return nil } source := c.Source sourceRe, err := regexp.Compile(source) if err != nil { return fmt.Errorf("failed to compile cache buster source %q: %w", c.Source, err) } target := c.Target var compileErr error debugl := logger.Logger().WithLevel(logg.LevelDebug).WithField(loggers.FieldNameCmd, "cachebuster") c.compiledSource = func(s string) func(string) bool { m := sourceRe.FindStringSubmatch(s) matchString := "no match" match := m != nil if match { matchString = "match!" } debugl.Logf("Matching %q with source %q: %s", s, source, matchString) if !match { return nil } groups := m[1:] currentTarget := target // Replace $1, $2 etc. in target. for i, g := range groups { currentTarget = strings.ReplaceAll(target, fmt.Sprintf("$%d", i+1), g) } targetRe, err := regexp.Compile(currentTarget) if err != nil { compileErr = fmt.Errorf("failed to compile cache buster target %q: %w", currentTarget, err) return nil } return func(ss string) bool { match = targetRe.MatchString(ss) matchString := "no match" if match { matchString = "match!" } logger.Debugf("Matching %q with target %q: %s", ss, currentTarget, matchString) return match } } return compileErr } func (r Redirect) IsZero() bool { return r.From == "" && r.FromRe == "" } const ( // Keep this a little coarse grained, some false positives are OK. cssTargetCachebusterRe = `(css|styles|scss|sass)` ) func DecodeServer(cfg Provider) (Server, error) { s := &Server{} _ = mapstructure.WeakDecode(cfg.GetStringMap("server"), s) for i, redir := range s.Redirects { redir.To = strings.TrimSuffix(redir.To, "index.html") s.Redirects[i] = redir } if len(s.Redirects) == 0 { // Set up a default redirect for 404s. s.Redirects = []Redirect{ { From: "/**", To: "/404.html", Status: 404, }, } } return *s, nil } // Pagination configures the pagination behavior. type Pagination struct { // Default number of elements per pager in pagination. PagerSize int // The path element used during pagination. Path string // Whether to disable generation of alias for the first pagination page. DisableAliases bool } // PageConfig configures the behavior of pages. type PageConfig struct { // Sort order for Page.Next and Page.Prev. Default "desc" (the default page sort order in Hugo). NextPrevSortOrder string // Sort order for Page.NextInSection and Page.PrevInSection. Default "desc". NextPrevInSectionSortOrder string } func (c *PageConfig) CompileConfig(loggers.Logger) error { c.NextPrevInSectionSortOrder = strings.ToLower(c.NextPrevInSectionSortOrder) c.NextPrevSortOrder = strings.ToLower(c.NextPrevSortOrder) return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/env.go
config/env.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "os" "runtime" "strconv" "strings" "github.com/pbnjay/memory" ) const ( gigabyte = 1 << 30 ) // GetNumWorkerMultiplier returns the base value used to calculate the number // of workers to use for Hugo's parallel execution. // It returns the value in HUGO_NUMWORKERMULTIPLIER OS env variable if set to a // positive integer, else the number of logical CPUs. func GetNumWorkerMultiplier() int { if gmp := os.Getenv("HUGO_NUMWORKERMULTIPLIER"); gmp != "" { if p, err := strconv.Atoi(gmp); err == nil && p > 0 { return p } } return runtime.NumCPU() } // GetMemoryLimit returns the upper memory limit in bytes for Hugo's in-memory caches. // Note that this does not represent "all of the memory" that Hugo will use, // so it needs to be set to a lower number than the available system memory. // It will read from the HUGO_MEMORYLIMIT (in Gigabytes) environment variable. // If that is not set, it will set aside a quarter of the total system memory. func GetMemoryLimit() uint64 { if mem := os.Getenv("HUGO_MEMORYLIMIT"); mem != "" { if v := stringToGibabyte(mem); v > 0 { return v } } // There is a FreeMemory function, but as the kernel in most situations // will take whatever memory that is left and use for caching etc., // that value is not something that we can use. m := memory.TotalMemory() if m != 0 { return uint64(m / 4) } return 2 * gigabyte } func stringToGibabyte(f string) uint64 { if v, err := strconv.ParseFloat(f, 32); err == nil && v > 0 { return uint64(v * gigabyte) } return 0 } // SetEnvVars sets vars on the form key=value in the oldVars slice. func SetEnvVars(oldVars *[]string, keyValues ...string) { for i := 0; i < len(keyValues); i += 2 { setEnvVar(oldVars, keyValues[i], keyValues[i+1]) } } func SplitEnvVar(v string) (string, string) { name, value, _ := strings.Cut(v, "=") return name, value } func setEnvVar(vars *[]string, key, value string) { for i := range *vars { if strings.HasPrefix((*vars)[i], key+"=") { (*vars)[i] = key + "=" + value return } } // New var. *vars = append(*vars, key+"="+value) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/configProvider.go
config/configProvider.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "time" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/common/urls" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/gohugoio/hugo/identity" ) // AllProvider is a sub set of all config settings. type AllProvider interface { Language() any LanguageIndex() int Languages() any LanguagePrefix() string BaseURL() urls.BaseURL BaseURLLiveReload() urls.BaseURL PathParser() *paths.PathParser Environment() string IsMultihost() bool IsMultilingual() bool NoBuildLock() bool BaseConfig() BaseConfig Dirs() CommonDirs Quiet() bool DirsBase() CommonDirs ContentTypes() ContentTypesProvider GetConfigSection(string) any GetConfig() any CanonifyURLs() bool DisablePathToLower() bool RemovePathAccents() bool IsUglyURLs(section string) bool DefaultContentLanguage() string DefaultContentLanguageInSubdir() bool DefaultContentRoleInSubdir() bool DefaultContentVersionInSubdir() bool DefaultContentsitesMatrix() *sitesmatrix.IntSets AllSitesMatrix() *sitesmatrix.IntSets IsKindEnabled(string) bool IsLangDisabled(string) bool SummaryLength() int Pagination() Pagination BuildExpired() bool BuildFuture() bool BuildDrafts() bool Running() bool Watching() bool NewIdentityManager(opts ...identity.ManagerOption) identity.Manager FastRenderMode() bool PrintUnusedTemplates() bool EnableMissingTranslationPlaceholders() bool TemplateMetrics() bool TemplateMetricsHints() bool PrintI18nWarnings() bool CreateTitle(s string) string IgnoreFile(s string) bool NewContentEditor() string Timeout() time.Duration StaticDirs() []string IgnoredLogs() map[string]bool WorkingDir() string EnableEmoji() bool ConfiguredDimensions() *sitesmatrix.ConfiguredDimensions CacheDirMisc() string } // We cannot import the media package as that would create a circular dependency. // This interface defines a subset of what media.ContentTypes provides. type ContentTypesProvider interface { IsContentSuffix(suffix string) bool IsContentFile(filename string) bool IsIndexContentFile(filename string) bool IsHTMLSuffix(suffix string) bool } // Provider provides the configuration settings for Hugo. type Provider interface { GetString(key string) string GetInt(key string) int GetBool(key string) bool GetParams(key string) maps.Params GetStringMap(key string) map[string]any GetStringMapString(key string) map[string]string GetStringSlice(key string) []string Get(key string) any Set(key string, value any) Keys() []string Merge(key string, value any) SetDefaults(params maps.Params) SetDefaultMergeStrategy() WalkParams(walkFn func(params ...maps.KeyParams) bool) IsSet(key string) bool } // GetStringSlicePreserveString returns a string slice from the given config and key. // It differs from the GetStringSlice method in that if the config value is a string, // we do not attempt to split it into fields. func GetStringSlicePreserveString(cfg Provider, key string) []string { sd := cfg.Get(key) return types.ToStringSlicePreserveString(sd) } /*func (cd ConfiguredDimensions) Language(v sitesmatrix.Vector) ConfiguredDimension { }*/
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/defaultConfigProvider.go
config/defaultConfigProvider.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "errors" "fmt" "sort" "strings" "sync" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/maps" ) // New creates a Provider backed by an empty maps.Params. func New() Provider { return &defaultConfigProvider{ root: make(maps.Params), } } // NewFrom creates a Provider backed by params. func NewFrom(params maps.Params) Provider { maps.PrepareParams(params) return &defaultConfigProvider{ root: params, } } // defaultConfigProvider is a Provider backed by a map where all keys are lower case. // All methods are thread safe. type defaultConfigProvider struct { mu sync.RWMutex root maps.Params keyCache sync.Map } func (c *defaultConfigProvider) Get(k string) any { if k == "" { return c.root } c.mu.RLock() key, m := c.getNestedKeyAndMap(strings.ToLower(k), false) if m == nil { c.mu.RUnlock() return nil } v := m[key] c.mu.RUnlock() return v } func (c *defaultConfigProvider) GetBool(k string) bool { v := c.Get(k) return cast.ToBool(v) } func (c *defaultConfigProvider) GetInt(k string) int { v := c.Get(k) return cast.ToInt(v) } func (c *defaultConfigProvider) IsSet(k string) bool { var found bool c.mu.RLock() key, m := c.getNestedKeyAndMap(strings.ToLower(k), false) if m != nil { _, found = m[key] } c.mu.RUnlock() return found } func (c *defaultConfigProvider) GetString(k string) string { v := c.Get(k) return cast.ToString(v) } func (c *defaultConfigProvider) GetParams(k string) maps.Params { v := c.Get(k) if v == nil { return nil } return v.(maps.Params) } func (c *defaultConfigProvider) GetStringMap(k string) map[string]any { v := c.Get(k) return maps.ToStringMap(v) } func (c *defaultConfigProvider) GetStringMapString(k string) map[string]string { v := c.Get(k) return maps.ToStringMapString(v) } func (c *defaultConfigProvider) GetStringSlice(k string) []string { v := c.Get(k) return cast.ToStringSlice(v) } func (c *defaultConfigProvider) Set(k string, v any) { c.mu.Lock() defer c.mu.Unlock() k = strings.ToLower(k) if k == "" { if p, err := maps.ToParamsAndPrepare(v); err == nil { // Set the values directly in root. maps.SetParams(c.root, p) } else { c.root[k] = v } return } switch vv := v.(type) { case map[string]any, map[any]any, map[string]string: p := maps.MustToParamsAndPrepare(vv) v = p } key, m := c.getNestedKeyAndMap(k, true) if m == nil { return } if existing, found := m[key]; found { if p1, ok := existing.(maps.Params); ok { if p2, ok := v.(maps.Params); ok { maps.SetParams(p1, p2) return } } } m[key] = v } // SetDefaults will set values from params if not already set. func (c *defaultConfigProvider) SetDefaults(params maps.Params) { maps.PrepareParams(params) for k, v := range params { if _, found := c.root[k]; !found { c.root[k] = v } } } func (c *defaultConfigProvider) Merge(k string, v any) { c.mu.Lock() defer c.mu.Unlock() k = strings.ToLower(k) if k == "" { rs, f := c.root.GetMergeStrategy() if f && rs == maps.ParamsMergeStrategyNone { // The user has set a "no merge" strategy on this, // nothing more to do. return } if p, err := maps.ToParamsAndPrepare(v); err == nil { // As there may be keys in p not in root, we need to handle // those as a special case. var keysToDelete []string for kk, vv := range p { if pp, ok := vv.(maps.Params); ok { if pppi, ok := c.root[kk]; ok { ppp := pppi.(maps.Params) maps.MergeParamsWithStrategy("", ppp, pp) } else { // We need to use the default merge strategy for // this key. np := make(maps.Params) strategy := c.determineMergeStrategy(maps.KeyParams{Key: "", Params: c.root}, maps.KeyParams{Key: kk, Params: np}) np.SetMergeStrategy(strategy) maps.MergeParamsWithStrategy("", np, pp) c.root[kk] = np if np.IsZero() { // Just keep it until merge is done. keysToDelete = append(keysToDelete, kk) } } } } // Merge the rest. maps.MergeParams(c.root, p) for _, k := range keysToDelete { delete(c.root, k) } } else { panic(fmt.Sprintf("unsupported type %T received in Merge", v)) } return } switch vv := v.(type) { case map[string]any, map[any]any, map[string]string: p := maps.MustToParamsAndPrepare(vv) v = p } key, m := c.getNestedKeyAndMap(k, true) if m == nil { return } if existing, found := m[key]; found { if p1, ok := existing.(maps.Params); ok { if p2, ok := v.(maps.Params); ok { maps.MergeParamsWithStrategy("", p1, p2) } } } else { m[key] = v } } func (c *defaultConfigProvider) Keys() []string { c.mu.RLock() defer c.mu.RUnlock() var keys []string for k := range c.root { keys = append(keys, k) } sort.Strings(keys) return keys } func (c *defaultConfigProvider) WalkParams(walkFn func(params ...maps.KeyParams) bool) { maxDepth := 1000 var walk func(depth int, params ...maps.KeyParams) walk = func(depth int, params ...maps.KeyParams) { if depth > maxDepth { panic(errors.New("max depth exceeded")) } if walkFn(params...) { return } p1 := params[len(params)-1] i := len(params) for k, v := range p1.Params { if p2, ok := v.(maps.Params); ok { paramsplus1 := make([]maps.KeyParams, i+1) copy(paramsplus1, params) paramsplus1[i] = maps.KeyParams{Key: k, Params: p2} walk(depth+1, paramsplus1...) } } } walk(0, maps.KeyParams{Key: "", Params: c.root}) } func (c *defaultConfigProvider) determineMergeStrategy(params ...maps.KeyParams) maps.ParamsMergeStrategy { if len(params) == 0 { return maps.ParamsMergeStrategyNone } var ( strategy maps.ParamsMergeStrategy prevIsRoot bool curr = params[len(params)-1] ) if len(params) > 1 { prev := params[len(params)-2] prevIsRoot = prev.Key == "" // Inherit from parent (but not from the root unless it's set by user). s, found := prev.Params.GetMergeStrategy() if !prevIsRoot && !found { panic("invalid state, merge strategy not set on parent") } if found || !prevIsRoot { strategy = s } } switch curr.Key { case "": // Don't set a merge strategy on the root unless set by user. // This will be handled as a special case. case "params": strategy = maps.ParamsMergeStrategyDeep case "outputformats", "mediatypes": if prevIsRoot { strategy = maps.ParamsMergeStrategyShallow } case "menus": isMenuKey := prevIsRoot if !isMenuKey { // Can also be set below languages. // root > languages > en > menus if len(params) == 4 && params[1].Key == "languages" { isMenuKey = true } } if isMenuKey { strategy = maps.ParamsMergeStrategyShallow } default: if strategy == "" { strategy = maps.ParamsMergeStrategyNone } } return strategy } func (c *defaultConfigProvider) SetDefaultMergeStrategy() { c.WalkParams(func(params ...maps.KeyParams) bool { if len(params) == 0 { return false } p := params[len(params)-1].Params var found bool if _, found = p.GetMergeStrategy(); found { // Set by user. return false } strategy := c.determineMergeStrategy(params...) if strategy != "" { p.SetMergeStrategy(strategy) } return false }) } func (c *defaultConfigProvider) getNestedKeyAndMap(key string, create bool) (string, maps.Params) { var parts []string v, ok := c.keyCache.Load(key) if ok { parts = v.([]string) } else { parts = strings.Split(key, ".") c.keyCache.Store(key, parts) } current := c.root for i := range len(parts) - 1 { next, found := current[parts[i]] if !found { if create { next = make(maps.Params) current[parts[i]] = next } else { return "", nil } } var ok bool current, ok = next.(maps.Params) if !ok { // E.g. a string, not a map that we can store values in. return "", nil } } return parts[len(parts)-1], current }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/services/servicesConfig_test.go
config/services/servicesConfig_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package services import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" ) func TestDecodeConfigFromTOML(t *testing.T) { c := qt.New(t) tomlConfig := ` someOtherValue = "foo" [services] [services.disqus] shortname = "DS" [services.googleAnalytics] id = "ga_id" [services.instagram] disableInlineCSS = true [services.twitter] disableInlineCSS = true [services.x] disableInlineCSS = true ` cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) config, err := DecodeConfig(cfg) c.Assert(err, qt.IsNil) c.Assert(config, qt.Not(qt.IsNil)) c.Assert(config.Disqus.Shortname, qt.Equals, "DS") c.Assert(config.GoogleAnalytics.ID, qt.Equals, "ga_id") c.Assert(config.Instagram.DisableInlineCSS, qt.Equals, true) } // Support old root-level GA settings etc. func TestUseSettingsFromRootIfSet(t *testing.T) { c := qt.New(t) cfg := config.New() cfg.Set("disqusShortname", "root_short") cfg.Set("googleAnalytics", "ga_root") config, err := DecodeConfig(cfg) c.Assert(err, qt.IsNil) c.Assert(config, qt.Not(qt.IsNil)) c.Assert(config.Disqus.Shortname, qt.Equals, "root_short") c.Assert(config.GoogleAnalytics.ID, qt.Equals, "ga_root") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/services/servicesConfig.go
config/services/servicesConfig.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package services import ( "github.com/gohugoio/hugo/config" "github.com/mitchellh/mapstructure" ) const ( servicesConfigKey = "services" disqusShortnameKey = "disqusshortname" googleAnalyticsKey = "googleanalytics" rssLimitKey = "rssLimit" ) // Config is a services configuration for all the relevant services in Hugo. type Config struct { Disqus Disqus GoogleAnalytics GoogleAnalytics Instagram Instagram `json:"-"` // the embedded instagram shortcode no longer uses this Twitter Twitter `json:"-"` // deprecated in favor of X in v0.141.0 X X RSS RSS } // Disqus holds the functional configuration settings related to the Disqus template. type Disqus struct { // A Shortname is the unique identifier assigned to a Disqus site. Shortname string } // GoogleAnalytics holds the functional configuration settings related to the Google Analytics template. type GoogleAnalytics struct { // The GA tracking ID. ID string } // Instagram holds the functional configuration settings related to the Instagram shortcodes. type Instagram struct { // The Simple variant of the Instagram is decorated with Bootstrap 4 card classes. // This means that if you use Bootstrap 4 or want to provide your own CSS, you want // to disable the inline CSS provided by Hugo. DisableInlineCSS bool // this is no longer used by the embedded instagram shortcode // App or Client Access Token. // If you are using a Client Access Token, remember that you must combine it with your App ID // using a pipe symbol (<APPID>|<CLIENTTOKEN>) otherwise the request will fail. AccessToken string // this is no longer used by the embedded instagram shortcode } // Twitter holds the functional configuration settings related to the Twitter shortcodes. // Deprecated in favor of X in v0.141.0. type Twitter struct { // The Simple variant of Twitter is decorated with a basic set of inline styles. // This means that if you want to provide your own CSS, you want // to disable the inline CSS provided by Hugo. DisableInlineCSS bool } // X holds the functional configuration settings related to the X shortcodes. type X struct { // The Simple variant of X is decorated with a basic set of inline styles. // This means that if you want to provide your own CSS, you want // to disable the inline CSS provided by Hugo. DisableInlineCSS bool } // RSS holds the functional configuration settings related to the RSS feeds. type RSS struct { // Limit the number of pages. Limit int } // DecodeConfig creates a services Config from a given Hugo configuration. func DecodeConfig(cfg config.Provider) (c Config, err error) { m := cfg.GetStringMap(servicesConfigKey) err = mapstructure.WeakDecode(m, &c) // Keep backwards compatibility. if c.GoogleAnalytics.ID == "" { // Try the global config c.GoogleAnalytics.ID = cfg.GetString(googleAnalyticsKey) } if c.Disqus.Shortname == "" { c.Disqus.Shortname = cfg.GetString(disqusShortnameKey) } if c.RSS.Limit == 0 { c.RSS.Limit = cfg.GetInt(rssLimitKey) if c.RSS.Limit == 0 { c.RSS.Limit = -1 } } return }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/testconfig/testconfig.go
config/testconfig/testconfig.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This package should only be used for testing. package testconfig import ( _ "unsafe" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/allconfig" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/internal/warpc" toml "github.com/pelletier/go-toml/v2" "github.com/spf13/afero" ) func GetTestConfigs(fs afero.Fs, cfg config.Provider) *allconfig.Configs { if fs == nil { fs = afero.NewMemMapFs() } if cfg == nil { cfg = config.New() } // Make sure that the workingDir exists. workingDir := cfg.GetString("workingDir") if workingDir != "" { if err := fs.MkdirAll(workingDir, 0o777); err != nil { panic(err) } } configs, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Fs: fs, Flags: cfg, Environ: []string{"EMPTY_TEST_ENVIRONMENT"}}) if err != nil { panic(err) } return configs } func GetTestConfig(fs afero.Fs, cfg config.Provider) config.AllProvider { return GetTestConfigs(fs, cfg).GetFirstLanguageConfig() } func GetTestDeps(fs afero.Fs, cfg config.Provider, beforeInit ...func(*deps.Deps)) *deps.Deps { if fs == nil { fs = afero.NewMemMapFs() } conf := GetTestConfig(fs, cfg) d := &deps.Deps{ Conf: conf, Fs: hugofs.NewFrom(fs, conf.BaseConfig()), WasmDispatchers: warpc.AllDispatchers( warpc.Options{ PoolSize: 1, }, warpc.Options{ PoolSize: 1, }, ), } for _, f := range beforeInit { f(d) } if err := d.Init(); err != nil { panic(err) } return d } func GetTestConfigSectionFromStruct(section string, v any) config.AllProvider { data, err := toml.Marshal(v) if err != nil { panic(err) } p := maps.Params{ section: config.FromTOMLConfigString(string(data)).Get(""), } cfg := config.NewFrom(p) return GetTestConfig(nil, cfg) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/privacy/privacyConfig.go
config/privacy/privacyConfig.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package privacy import ( "github.com/gohugoio/hugo/config" "github.com/mitchellh/mapstructure" ) const privacyConfigKey = "privacy" // Service is the common values for a service in a policy definition. type Service struct { Disable bool } // Config is a privacy configuration for all the relevant services in Hugo. type Config struct { Disqus Disqus GoogleAnalytics GoogleAnalytics Instagram Instagram Twitter Twitter `json:"-"` // deprecated in favor of X in v0.141.0 Vimeo Vimeo YouTube YouTube X X } // Disqus holds the privacy configuration settings related to the Disqus template. type Disqus struct { Service `mapstructure:",squash"` } // GoogleAnalytics holds the privacy configuration settings related to the Google Analytics template. type GoogleAnalytics struct { Service `mapstructure:",squash"` // Enabling this will make the GA templates respect the // "Do Not Track" HTTP header. See https://www.paulfurley.com/google-analytics-dnt/. RespectDoNotTrack bool } // Instagram holds the privacy configuration settings related to the Instagram shortcode. type Instagram struct { Service `mapstructure:",squash"` // If simple mode is enabled, a static and no-JS version of the Instagram // image card will be built. Simple bool } // Twitter holds the privacy configuration settings related to the Twitter shortcode. // Deprecated in favor of X in v0.141.0. type Twitter struct { Service `mapstructure:",squash"` // When set to true, the Tweet and its embedded page on your site are not used // for purposes that include personalized suggestions and personalized ads. EnableDNT bool // If simple mode is enabled, a static and no-JS version of the Tweet will be built. Simple bool } // Vimeo holds the privacy configuration settings related to the Vimeo shortcode. type Vimeo struct { Service `mapstructure:",squash"` // When set to true, the Vimeo player will be blocked from tracking any session data, // including all cookies and stats. EnableDNT bool // If simple mode is enabled, only a thumbnail is fetched from i.vimeocdn.com and // shown with a play button overlaid. If a user clicks the button, he/she will // be taken to the video page on vimeo.com in a new browser tab. Simple bool } // YouTube holds the privacy configuration settings related to the YouTube shortcode. type YouTube struct { Service `mapstructure:",squash"` // When you turn on privacy-enhanced mode, // YouTube won’t store information about visitors on your website // unless the user plays the embedded video. PrivacyEnhanced bool } // X holds the privacy configuration settings related to the X shortcode. type X struct { Service `mapstructure:",squash"` // When set to true, the X post and its embedded page on your site are not // used for purposes that include personalized suggestions and personalized // ads. EnableDNT bool // If simple mode is enabled, a static and no-JS version of the X post will // be built. Simple bool } // DecodeConfig creates a privacy Config from a given Hugo configuration. func DecodeConfig(cfg config.Provider) (pc Config, err error) { pc.GoogleAnalytics.RespectDoNotTrack = true m := cfg.GetStringMap(privacyConfigKey) err = mapstructure.WeakDecode(m, &pc) return }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/privacy/privacyConfig_test.go
config/privacy/privacyConfig_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package privacy import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" ) func TestDecodeConfigFromTOML(t *testing.T) { c := qt.New(t) tomlConfig := ` someOtherValue = "foo" [privacy] [privacy.disqus] disable = true [privacy.googleAnalytics] disable = true respectDoNotTrack = true [privacy.instagram] disable = true simple = true [privacy.x] disable = true enableDNT = true simple = true [privacy.vimeo] disable = true enableDNT = true simple = true [privacy.youtube] disable = true privacyEnhanced = true simple = true ` cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) pc, err := DecodeConfig(cfg) c.Assert(err, qt.IsNil) c.Assert(pc, qt.Not(qt.IsNil)) got := []bool{ pc.Disqus.Disable, pc.GoogleAnalytics.Disable, pc.GoogleAnalytics.RespectDoNotTrack, pc.Instagram.Disable, pc.Instagram.Simple, pc.Vimeo.Disable, pc.Vimeo.EnableDNT, pc.Vimeo.Simple, pc.YouTube.PrivacyEnhanced, pc.YouTube.Disable, pc.X.Disable, pc.X.EnableDNT, pc.X.Simple, } c.Assert(got, qt.All(qt.Equals), true) } func TestDecodeConfigFromTOMLCaseInsensitive(t *testing.T) { c := qt.New(t) tomlConfig := ` someOtherValue = "foo" [Privacy] [Privacy.YouTube] PrivacyENhanced = true ` cfg, err := config.FromConfigString(tomlConfig, "toml") c.Assert(err, qt.IsNil) pc, err := DecodeConfig(cfg) c.Assert(err, qt.IsNil) c.Assert(pc, qt.Not(qt.IsNil)) c.Assert(pc.YouTube.PrivacyEnhanced, qt.Equals, true) } func TestDecodeConfigDefault(t *testing.T) { c := qt.New(t) pc, err := DecodeConfig(config.New()) c.Assert(err, qt.IsNil) c.Assert(pc, qt.Not(qt.IsNil)) c.Assert(pc.YouTube.PrivacyEnhanced, qt.Equals, false) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/allconfig/allconfig_integration_test.go
config/allconfig/allconfig_integration_test.go
package allconfig_test import ( "path/filepath" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/config/allconfig" "github.com/gohugoio/hugo/hugolib" gc "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/media" ) func TestDirsMount(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" disableKinds = ["taxonomy", "term"] [languages] [languages.en] weight = 1 [languages.sv] weight = 2 [[module.mounts]] source = 'content/en' target = 'content' lang = 'en' [[module.mounts]] source = 'content/sv' target = 'content' lang = 'sv' -- content/en/p1.md -- --- title: "p1" --- -- content/sv/p1.md -- --- title: "p1" --- -- layouts/single.html -- Title: {{ .Title }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t, TxtarString: files}, ).Build() // b.AssertFileContent("public/p1/index.html", "Title: p1") sites := b.H.Sites b.Assert(len(sites), qt.Equals, 2) configs := b.H.Configs mods := configs.Modules b.Assert(len(mods), qt.Equals, 1) mod := mods[0] b.Assert(mod.Mounts(), qt.HasLen, 8) enConcp := sites[0].Conf enConf := enConcp.GetConfig().(*allconfig.Config) b.Assert(enConcp.BaseURL().String(), qt.Equals, "https://example.com/") modConf := enConf.Module b.Assert(modConf.Mounts, qt.HasLen, 8) b.Assert(modConf.Mounts[0].Source, qt.Equals, filepath.FromSlash("content/en")) b.Assert(modConf.Mounts[0].Target, qt.Equals, "content") b.Assert(modConf.Mounts[0].Lang, qt.Equals, "") b.Assert(modConf.Mounts[0].Sites.Matrix.Languages, qt.DeepEquals, []string{"en"}) b.Assert(modConf.Mounts[1].Source, qt.Equals, filepath.FromSlash("content/sv")) b.Assert(modConf.Mounts[1].Target, qt.Equals, "content") b.Assert(modConf.Mounts[1].Lang, qt.Equals, "") b.Assert(modConf.Mounts[1].Sites.Matrix.Languages, qt.DeepEquals, []string{"sv"}) } func TestConfigAliases(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" logI18nWarnings = true logPathWarnings = true ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{T: t, TxtarString: files}, ).Build() conf := b.H.Configs.Base b.Assert(conf.PrintI18nWarnings, qt.Equals, true) b.Assert(conf.PrintPathWarnings, qt.Equals, true) } func TestRedefineContentTypes(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" [mediaTypes] [mediaTypes."text/html"] suffixes = ["html", "xhtml"] ` b := hugolib.Test(t, files) conf := b.H.Configs.Base contentTypes := conf.ContentTypes.Config b.Assert(contentTypes.HTML.Suffixes(), qt.DeepEquals, []string{"html", "xhtml"}) b.Assert(contentTypes.Markdown.Suffixes(), qt.DeepEquals, []string{"md", "mdown", "markdown"}) } func TestPaginationConfig(t *testing.T) { files := ` -- hugo.toml -- [languages.en] weight = 1 [languages.en.pagination] pagerSize = 20 [languages.de] weight = 2 [languages.de.pagination] path = "page-de" ` b := hugolib.Test(t, files) confEn := b.H.Sites[0].Conf.Pagination() confDe := b.H.Sites[1].Conf.Pagination() b.Assert(confEn.Path, qt.Equals, "page") b.Assert(confEn.PagerSize, qt.Equals, 20) b.Assert(confDe.Path, qt.Equals, "page-de") b.Assert(confDe.PagerSize, qt.Equals, 10) } func TestPaginationConfigDisableAliases(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] [pagination] disableAliases = true pagerSize = 2 -- layouts/list.html -- {{ $paginator := .Paginate site.RegularPages }} {{ template "_internal/pagination.html" . }} {{ range $paginator.Pages }} {{ .Title }} {{ end }} -- content/p1.md -- --- title: "p1" --- -- content/p2.md -- --- title: "p2" --- -- content/p3.md -- --- title: "p3" --- ` b := hugolib.Test(t, files) b.AssertFileExists("public/page/1/index.html", false) b.AssertFileContent("public/page/2/index.html", "pagination-default") } func TestMapUglyURLs(t *testing.T) { files := ` -- hugo.toml -- [uglyurls] posts = true ` b := hugolib.Test(t, files) c := b.H.Configs.Base b.Assert(c.C.IsUglyURLSection("posts"), qt.IsTrue) b.Assert(c.C.IsUglyURLSection("blog"), qt.IsFalse) } // Issue 13199 func TestInvalidOutputFormat(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] [outputs] home = ['html','foo'] -- layouts/home.html -- x ` b, err := hugolib.TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `failed to create config: unknown output format "foo" for kind "home"`) } func TestContentTypesDefault(t *testing.T) { files := ` -- hugo.toml -- baseURL = "https://example.com" ` b := hugolib.Test(t, files) ct := b.H.Configs.Base.ContentTypes c := ct.Config s := ct.SourceStructure.(map[string]media.ContentTypeConfig) b.Assert(c.IsContentFile("foo.md"), qt.Equals, true) b.Assert(len(s), qt.Equals, 6) } func TestMergeDeep(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" theme = ["theme1", "theme2"] _merge = "deep" -- themes/theme1/hugo.toml -- [sitemap] filename = 'mysitemap.xml' [services] [services.googleAnalytics] id = 'foo bar' [taxonomies] foo = 'bars' -- themes/theme2/config/_default/hugo.toml -- [taxonomies] bar = 'baz' -- layouts/home.html -- GA ID: {{ site.Config.Services.GoogleAnalytics.ID }}. ` b := hugolib.Test(t, files) conf := b.H.Configs base := conf.Base b.Assert(base.Environment, qt.Equals, hugo.EnvironmentProduction) b.Assert(base.BaseURL, qt.Equals, "https://example.com") b.Assert(base.Sitemap.Filename, qt.Equals, "mysitemap.xml") b.Assert(base.Taxonomies, qt.DeepEquals, map[string]string{"bar": "baz", "foo": "bars"}) b.AssertFileContent("public/index.html", "GA ID: foo bar.") } func TestMergeDeepBuildStats(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" title = "Theme 1" _merge = "deep" [module] [module.hugoVersion] [[module.imports]] path = "theme1" -- themes/theme1/hugo.toml -- [build] [build.buildStats] disableIDs = true enable = true -- layouts/home.html -- Home. ` b := hugolib.Test(t, files, hugolib.TestOptOsFs()) conf := b.H.Configs base := conf.Base b.Assert(base.Title, qt.Equals, "Theme 1") b.Assert(len(base.Module.Imports), qt.Equals, 1) b.Assert(base.Build.BuildStats.Enable, qt.Equals, true) b.AssertFileExists("/hugo_stats.json", true) } func TestMergeDeepBuildStatsTheme(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" _merge = "deep" theme = ["theme1"] -- themes/theme1/hugo.toml -- title = "Theme 1" [build] [build.buildStats] disableIDs = true enable = true -- layouts/home.html -- Home. ` b := hugolib.Test(t, files, hugolib.TestOptOsFs()) conf := b.H.Configs base := conf.Base b.Assert(base.Title, qt.Equals, "Theme 1") b.Assert(len(base.Module.Imports), qt.Equals, 1) b.Assert(base.Build.BuildStats.Enable, qt.Equals, true) b.AssertFileExists("/hugo_stats.json", true) } func TestDefaultConfigLanguageBlankWhenNoEnglishExists(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- baseURL = "https://example.com" [languages] [languages.nn] weight = 20 [languages.sv] weight = 10 [languages.sv.taxonomies] tag = "taggar" -- layouts/all.html -- All. ` b := hugolib.Test(t, files) b.Assert(b.H.Conf.DefaultContentLanguage(), qt.Equals, "sv") } func TestDefaultConfigEnvDisableLanguagesIssue13707(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableLanguages = [] [languages] [languages.en] weight = 1 [languages.nn] weight = 2 [languages.sv] weight = 3 ` b := hugolib.Test(t, files, hugolib.TestOptWithConfig(func(conf *hugolib.IntegrationTestConfig) { conf.Environ = []string{`HUGO_DISABLELANGUAGES=sv nn`} })) b.Assert(len(b.H.Sites), qt.Equals, 1) } // Issue 13535 // We changed enablement of the embedded link and image render hooks from // booleans to enums in v0.148.0. func TestLegacyEmbeddedRenderHookEnablement(t *testing.T) { files := ` -- hugo.toml -- [markup.goldmark.renderHooks.image] #KEY_VALUE [markup.goldmark.renderHooks.link] #KEY_VALUE ` f := strings.ReplaceAll(files, "#KEY_VALUE", "enableDefault = false") b := hugolib.Test(t, f) c := b.H.Configs.Base.Markup.Goldmark.RenderHooks b.Assert(c.Link.UseEmbedded, qt.Equals, gc.RenderHookUseEmbeddedNever) b.Assert(c.Image.UseEmbedded, qt.Equals, gc.RenderHookUseEmbeddedNever) f = strings.ReplaceAll(files, "#KEY_VALUE", "enableDefault = true") b = hugolib.Test(t, f) c = b.H.Configs.Base.Markup.Goldmark.RenderHooks b.Assert(c.Link.UseEmbedded, qt.Equals, gc.RenderHookUseEmbeddedFallback) b.Assert(c.Image.UseEmbedded, qt.Equals, gc.RenderHookUseEmbeddedFallback) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/allconfig/load.go
config/allconfig/load.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package allconfig contains the full configuration for Hugo. package allconfig import ( "errors" "fmt" "os" "path/filepath" "runtime/debug" "strings" "github.com/gobwas/glob" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/helpers" hglob "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/afero" ) //lint:ignore ST1005 end user message. var ErrNoConfigFile = errors.New("Unable to locate config file or config directory. Perhaps you need to create a new site.\n Run `hugo help new` for details.\n") func LoadConfig(d ConfigSourceDescriptor) (configs *Configs, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("failed to load config: %v", r) debug.PrintStack() } }() if len(d.Environ) == 0 && !hugo.IsRunningAsTest() { d.Environ = os.Environ() } if d.Logger == nil { d.Logger = loggers.NewDefault() } l := &configLoader{ConfigSourceDescriptor: d, cfg: config.New()} // Make sure we always do this, even in error situations, // as we have commands (e.g. "hugo mod init") that will // use a partial configuration to do its job. defer l.deleteMergeStrategies() res, _, err := l.loadConfigMain(d) if err != nil { return nil, fmt.Errorf("failed to load config: %w", err) } configs, err = fromLoadConfigResult(d.Fs, d.Logger, res) if err != nil { return nil, fmt.Errorf("failed to create config from result: %w", err) } moduleConfig, modulesClient, err := l.loadModules(configs, d.IgnoreModuleDoesNotExist) if err != nil { return nil, fmt.Errorf("failed to load modules: %w", err) } if len(l.ModulesConfigFiles) > 0 { // Config merged in from modules. // Re-read the config. configs, err = fromLoadConfigResult(d.Fs, d.Logger, res) if err != nil { return nil, fmt.Errorf("failed to create config from modules config: %w", err) } if err := configs.transientErr(); err != nil { return nil, fmt.Errorf("failed to create config from modules config: %w", err) } configs.LoadingInfo.ConfigFiles = append(configs.LoadingInfo.ConfigFiles, l.ModulesConfigFiles...) } else if err := configs.transientErr(); err != nil { return nil, fmt.Errorf("failed to create config: %w", err) } configs.Modules = moduleConfig.AllModules configs.ModulesClient = modulesClient if err := configs.Init(d.Logger); err != nil { return nil, fmt.Errorf("failed to init config: %w", err) } loggers.SetGlobalLogger(d.Logger) return } // ConfigSourceDescriptor describes where to find the config (e.g. config.toml etc.). type ConfigSourceDescriptor struct { Fs afero.Fs Logger loggers.Logger // Config received from the command line. // These will override any config file settings. Flags config.Provider // Path to the config file to use, e.g. /my/project/config.toml Filename string // The (optional) directory for additional configuration files. ConfigDir string // production, development Environment string // Defaults to os.Environ if not set. Environ []string // If set, this will be used to ignore the module does not exist error. IgnoreModuleDoesNotExist bool } func (d ConfigSourceDescriptor) configFilenames() []string { if d.Filename == "" { return nil } return strings.Split(d.Filename, ",") } type configLoader struct { cfg config.Provider BaseConfig config.BaseConfig ConfigSourceDescriptor // collected ModulesConfig modules.ModulesConfig ModulesConfigFiles []string } // Handle some legacy values. func (l configLoader) applyConfigAliases() error { aliases := []types.KeyValueStr{ {Key: "indexes", Value: "taxonomies"}, {Key: "logI18nWarnings", Value: "printI18nWarnings"}, {Key: "logPathWarnings", Value: "printPathWarnings"}, {Key: "ignoreErrors", Value: "ignoreLogs"}, } for _, alias := range aliases { if l.cfg.IsSet(alias.Key) { vv := l.cfg.Get(alias.Key) l.cfg.Set(alias.Value, vv) } } return nil } func (l configLoader) applyDefaultConfig() error { defaultSettings := maps.Params{ // These dirs are used early/before we build the config struct. "themesDir": "themes", "configDir": "config", } l.cfg.SetDefaults(defaultSettings) return nil } func (l configLoader) normalizeCfg(cfg config.Provider) error { if b, ok := cfg.Get("minifyOutput").(bool); ok { hugo.Deprecate("site config minifyOutput", "Use minify.minifyOutput instead.", "v0.150.0") if b { cfg.Set("minify.minifyOutput", true) } } else if b, ok := cfg.Get("minify").(bool); ok { hugo.Deprecate("site config minify", "Use minify.minifyOutput instead.", "v0.150.0") if b { cfg.Set("minify", maps.Params{"minifyOutput": true}) } } return nil } func (l configLoader) cleanExternalConfig(cfg config.Provider) error { if cfg.IsSet("internal") { cfg.Set("internal", nil) } return nil } func (l configLoader) applyFlagsOverrides(cfg config.Provider) error { for _, k := range cfg.Keys() { l.cfg.Set(k, cfg.Get(k)) } return nil } func (l configLoader) applyOsEnvOverrides(environ []string) error { if len(environ) == 0 { return nil } const delim = "__env__delim" // Extract all that start with the HUGO prefix. // The delimiter is the following rune, usually "_". const hugoEnvPrefix = "HUGO" var hugoEnv []types.KeyValueStr for _, v := range environ { key, val := config.SplitEnvVar(v) if after, ok := strings.CutPrefix(key, hugoEnvPrefix); ok { delimiterAndKey := after if len(delimiterAndKey) < 2 { continue } // Allow delimiters to be case sensitive. // It turns out there isn't that many allowed special // chars in environment variables when used in Bash and similar, // so variables on the form HUGOxPARAMSxFOO=bar is one option. key := strings.ReplaceAll(delimiterAndKey[1:], delimiterAndKey[:1], delim) key = strings.ToLower(key) hugoEnv = append(hugoEnv, types.KeyValueStr{ Key: key, Value: val, }) } } for _, env := range hugoEnv { existing, nestedKey, owner, err := maps.GetNestedParamFn(env.Key, delim, l.cfg.Get) if err != nil { return err } if existing != nil { val, err := metadecoders.Default.UnmarshalStringTo(env.Value, existing) if err == nil { val = l.envValToVal(env.Key, val) if owner != nil { owner[nestedKey] = val } else { l.cfg.Set(env.Key, val) } continue } } if owner != nil && nestedKey != "" { owner[nestedKey] = env.Value } else { var val any key := strings.ReplaceAll(env.Key, delim, ".") _, ok := allDecoderSetups[key] if ok { // A map. if v, err := metadecoders.Default.UnmarshalStringTo(env.Value, map[string]any{}); err == nil { val = v } } if val == nil { // A string. val = l.envStringToVal(key, env.Value) } l.cfg.Set(key, val) } } return nil } func (l *configLoader) envValToVal(k string, v any) any { switch v := v.(type) { case string: return l.envStringToVal(k, v) default: return v } } func (l *configLoader) envStringToVal(k, v string) any { switch k { case "disablekinds", "disablelanguages", "ignorefiles", "ignorelogs": v = strings.TrimSpace(v) if strings.HasPrefix(v, "[") && strings.HasSuffix(v, "]") { if parsed, err := metadecoders.Default.UnmarshalStringTo(v, []any{}); err == nil { return parsed } } if strings.Contains(v, ",") { return strings.Split(v, ",") } else { return strings.Fields(v) } default: return v } } func (l *configLoader) loadConfigMain(d ConfigSourceDescriptor) (config.LoadConfigResult, modules.ModulesConfig, error) { var res config.LoadConfigResult if d.Flags != nil { if err := l.normalizeCfg(d.Flags); err != nil { return res, l.ModulesConfig, err } } if d.Fs == nil { return res, l.ModulesConfig, errors.New("no filesystem provided") } if d.Flags != nil { if err := l.applyFlagsOverrides(d.Flags); err != nil { return res, l.ModulesConfig, err } workingDir := filepath.Clean(l.cfg.GetString("workingDir")) l.BaseConfig = config.BaseConfig{ WorkingDir: workingDir, ThemesDir: paths.AbsPathify(workingDir, l.cfg.GetString("themesDir")), } } names := d.configFilenames() if names != nil { for _, name := range names { var filename string filename, err := l.loadConfig(name) if err == nil { res.ConfigFiles = append(res.ConfigFiles, filename) } else if err != ErrNoConfigFile { return res, l.ModulesConfig, l.wrapFileError(err, filename) } } } else { for _, name := range config.DefaultConfigNames { var filename string filename, err := l.loadConfig(name) if err == nil { res.ConfigFiles = append(res.ConfigFiles, filename) break } else if err != ErrNoConfigFile { return res, l.ModulesConfig, l.wrapFileError(err, filename) } } } if d.ConfigDir != "" { absConfigDir := paths.AbsPathify(l.BaseConfig.WorkingDir, d.ConfigDir) dcfg, dirnames, err := config.LoadConfigFromDir(l.Fs, absConfigDir, l.Environment) if err == nil { if len(dirnames) > 0 { if err := l.normalizeCfg(dcfg); err != nil { return res, l.ModulesConfig, err } if err := l.cleanExternalConfig(dcfg); err != nil { return res, l.ModulesConfig, err } l.cfg.Set("", dcfg.Get("")) res.ConfigFiles = append(res.ConfigFiles, dirnames...) } } else if err != ErrNoConfigFile { if len(dirnames) > 0 { return res, l.ModulesConfig, l.wrapFileError(err, dirnames[0]) } return res, l.ModulesConfig, err } } res.Cfg = l.cfg if err := l.applyDefaultConfig(); err != nil { return res, l.ModulesConfig, err } // Some settings are used before we're done collecting all settings, // so apply OS environment both before and after. if err := l.applyOsEnvOverrides(d.Environ); err != nil { return res, l.ModulesConfig, err } workingDir := filepath.Clean(l.cfg.GetString("workingDir")) l.BaseConfig = config.BaseConfig{ WorkingDir: workingDir, CacheDir: l.cfg.GetString("cacheDir"), ThemesDir: paths.AbsPathify(workingDir, l.cfg.GetString("themesDir")), } var err error l.BaseConfig.CacheDir, err = helpers.GetCacheDir(l.Fs, l.BaseConfig.CacheDir) if err != nil { return res, l.ModulesConfig, err } res.BaseConfig = l.BaseConfig l.cfg.SetDefaultMergeStrategy() res.ConfigFiles = append(res.ConfigFiles, l.ModulesConfigFiles...) if d.Flags != nil { if err := l.applyFlagsOverrides(d.Flags); err != nil { return res, l.ModulesConfig, err } } if err := l.applyOsEnvOverrides(d.Environ); err != nil { return res, l.ModulesConfig, err } if err = l.applyConfigAliases(); err != nil { return res, l.ModulesConfig, err } return res, l.ModulesConfig, err } func (l *configLoader) loadModules(configs *Configs, ignoreModuleDoesNotExist bool) (modules.ModulesConfig, *modules.Client, error) { bcfg := configs.LoadingInfo.BaseConfig conf := configs.Base workingDir := bcfg.WorkingDir themesDir := bcfg.ThemesDir publishDir := bcfg.PublishDir cfg := configs.LoadingInfo.Cfg var ignoreVendor glob.Glob if s := conf.IgnoreVendorPaths; s != "" { ignoreVendor, _ = hglob.GetGlob(hglob.NormalizePath(s)) } ex := hexec.New(conf.Security, workingDir, l.Logger) hook := func(m *modules.ModulesConfig) error { for _, tc := range m.AllModules { if len(tc.ConfigFilenames()) > 0 { if tc.Watch() { l.ModulesConfigFiles = append(l.ModulesConfigFiles, tc.ConfigFilenames()...) } // Merge in the theme config using the configured // merge strategy. cfg.Merge("", tc.Cfg().Get("")) } } return nil } modulesClient := modules.NewClient(modules.ClientConfig{ Fs: l.Fs, Logger: l.Logger, Exec: ex, HookBeforeFinalize: hook, WorkingDir: workingDir, ThemesDir: themesDir, PublishDir: publishDir, Environment: l.Environment, CacheDir: conf.Caches.CacheDirModules(), ModuleConfig: conf.Module, IgnoreVendor: ignoreVendor, IgnoreModuleDoesNotExist: ignoreModuleDoesNotExist, }) moduleConfig, err := modulesClient.Collect() // We want to watch these for changes and trigger rebuild on version // changes etc. if moduleConfig.GoModulesFilename != "" { l.ModulesConfigFiles = append(l.ModulesConfigFiles, moduleConfig.GoModulesFilename) } if moduleConfig.GoWorkspaceFilename != "" { l.ModulesConfigFiles = append(l.ModulesConfigFiles, moduleConfig.GoWorkspaceFilename) } return moduleConfig, modulesClient, err } func (l configLoader) loadConfig(configName string) (string, error) { baseDir := l.BaseConfig.WorkingDir var baseFilename string if filepath.IsAbs(configName) { baseFilename = configName } else { baseFilename = filepath.Join(baseDir, configName) } var filename string if paths.ExtNoDelimiter(configName) != "" { exists, _ := helpers.Exists(baseFilename, l.Fs) if exists { filename = baseFilename } } else { for _, ext := range config.ValidConfigFileExtensions { filenameToCheck := baseFilename + "." + ext exists, _ := helpers.Exists(filenameToCheck, l.Fs) if exists { filename = filenameToCheck break } } } if filename == "" { return "", ErrNoConfigFile } m, err := config.FromFileToMap(l.Fs, filename) if err != nil { return filename, err } // Set overwrites keys of the same name, recursively. l.cfg.Set("", m) if err := l.normalizeCfg(l.cfg); err != nil { return filename, err } if err := l.cleanExternalConfig(l.cfg); err != nil { return filename, err } return filename, nil } func (l configLoader) deleteMergeStrategies() (err error) { l.cfg.WalkParams(func(params ...maps.KeyParams) bool { params[len(params)-1].Params.DeleteMergeStrategy() return false }) return } func (l configLoader) wrapFileError(err error, filename string) error { fe := herrors.UnwrapFileError(err) if fe != nil { pos := fe.Position() pos.Filename = filename fe.UpdatePosition(pos) return err } return herrors.NewFileErrorFromFile(err, filename, l.Fs, nil) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/config/allconfig/alldecoders.go
config/allconfig/alldecoders.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package allconfig import ( "fmt" "sort" "strings" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/cache/httpcache" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/privacy" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/config/services" "github.com/gohugoio/hugo/deploy/deployconfig" "github.com/gohugoio/hugo/hugolib/roles" "github.com/gohugoio/hugo/hugolib/segments" "github.com/gohugoio/hugo/hugolib/versions" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/minifiers" "github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/navigation" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/related" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/mitchellh/mapstructure" "github.com/spf13/afero" "github.com/spf13/cast" ) type decodeConfig struct { p config.Provider c *Config fs afero.Fs bcfg config.BaseConfig logger loggers.Logger } type decodeWeight struct { key string decode func(decodeWeight, decodeConfig) error getCompiler func(c *Config) configCompiler getInitializer func(c *Config) configInitializer weight int internalOrDeprecated bool // Hide it from the docs. } var allDecoderSetups = map[string]decodeWeight{ "": { key: "", weight: -100, // Always first. decode: func(d decodeWeight, p decodeConfig) error { if err := mapstructure.WeakDecode(p.p.Get(""), &p.c.RootConfig); err != nil { return err } // This need to match with the map keys, always lower case. p.c.RootConfig.DefaultContentLanguage = strings.ToLower(p.c.RootConfig.DefaultContentLanguage) p.c.RootConfig.DefaultContentRole = strings.ToLower(p.c.RootConfig.DefaultContentRole) p.c.RootConfig.DefaultContentVersion = strings.ToLower(p.c.RootConfig.DefaultContentVersion) return nil }, }, "imaging": { key: "imaging", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Imaging, err = images.DecodeConfig(p.p.GetStringMap(d.key)) return err }, }, "caches": { key: "caches", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Caches, err = filecache.DecodeConfig(p.fs, p.bcfg, p.p.GetStringMap(d.key)) if p.c.IgnoreCache { // Set MaxAge in all caches to 0. for k, cache := range p.c.Caches { cache.MaxAge = 0 p.c.Caches[k] = cache } } return err }, }, "httpcache": { key: "httpcache", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.HTTPCache, err = httpcache.DecodeConfig(p.bcfg, p.p.GetStringMap(d.key)) if p.c.IgnoreCache { p.c.HTTPCache.Cache.For.Excludes = []string{"**"} p.c.HTTPCache.Cache.For.Includes = []string{} } return err }, }, "build": { key: "build", decode: func(d decodeWeight, p decodeConfig) error { p.c.Build = config.DecodeBuildConfig(p.p) return nil }, getCompiler: func(c *Config) configCompiler { return &c.Build }, }, "frontmatter": { key: "frontmatter", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Frontmatter, err = pagemeta.DecodeFrontMatterConfig(p.p) return err }, }, "markup": { key: "markup", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Markup, err = markup_config.Decode(p.p) return err }, }, "segments": { key: "segments", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Segments, err = segments.DecodeSegments(p.p.GetStringMap(d.key), p.c.RenderSegments, p.logger) return err }, getInitializer: func(c *Config) configInitializer { return c.Segments.Config }, }, "server": { key: "server", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Server, err = config.DecodeServer(p.p) return err }, getCompiler: func(c *Config) configCompiler { return &c.Server }, }, "minify": { key: "minify", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Minify, err = minifiers.DecodeConfig(p.p.Get(d.key)) return err }, }, "contenttypes": { key: "contenttypes", weight: 100, // This needs to be decoded after media types. decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.ContentTypes, err = media.DecodeContentTypes(p.p.GetStringMap(d.key), p.c.MediaTypes.Config) return err }, }, "mediatypes": { key: "mediatypes", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.MediaTypes, err = media.DecodeTypes(p.p.GetStringMap(d.key)) return err }, }, "outputs": { key: "outputs", decode: func(d decodeWeight, p decodeConfig) error { defaults := createDefaultOutputFormats(p.c.OutputFormats.Config) m := maps.CleanConfigStringMap(p.p.GetStringMap("outputs")) p.c.Outputs = make(map[string][]string) for k, v := range m { s := types.ToStringSlicePreserveString(v) for i, v := range s { s[i] = strings.ToLower(v) } p.c.Outputs[k] = s } // Apply defaults. for k, v := range defaults { if _, found := p.c.Outputs[k]; !found { p.c.Outputs[k] = v } } return nil }, }, "outputformats": { key: "outputformats", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.OutputFormats, err = output.DecodeConfig(p.c.MediaTypes.Config, p.p.Get(d.key)) return err }, }, "languages": { key: "languages", decode: func(d decodeWeight, p decodeConfig) error { m := maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) if len(m) == 1 { // In v0.112.4 we moved this to the language config, but it's very commmon for mono language sites to have this at the top level. var first maps.Params var ok bool for _, v := range m { first, ok = v.(maps.Params) if ok { break } } if first != nil { if _, found := first["languagecode"]; !found { first["languagecode"] = p.p.GetString("languagecode") } } } var ( err error defaultContentLanguage string ) p.c.Languages, defaultContentLanguage, err = langs.DecodeConfig(p.c.RootConfig.DefaultContentLanguage, p.c.RootConfig.DisableLanguages, m) if err != nil { return fmt.Errorf("failed to decode languages config: %w", err) } for k, v := range p.c.Languages.Config.LanguageConfigs { if v.Disabled { p.c.RootConfig.DisableLanguages = append(p.c.RootConfig.DisableLanguages, k) } } p.c.RootConfig.DisableLanguages = hstrings.UniqueStringsReuse(p.c.RootConfig.DisableLanguages) sort.Strings(p.c.RootConfig.DisableLanguages) p.c.RootConfig.DefaultContentLanguage = defaultContentLanguage return nil }, }, "versions": { key: "versions", decode: func(d decodeWeight, p decodeConfig) error { var err error m := maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) p.c.Versions, err = versions.DecodeConfig(p.c.RootConfig.DefaultContentVersion, m) return err }, }, "roles": { key: "roles", decode: func(d decodeWeight, p decodeConfig) error { var ( err error defaultContentRole string ) m := maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) p.c.Roles, defaultContentRole, err = roles.DecodeConfig(p.c.RootConfig.DefaultContentRole, m) p.c.RootConfig.DefaultContentRole = defaultContentRole return err }, }, "params": { key: "params", decode: func(d decodeWeight, p decodeConfig) error { p.c.Params = maps.CleanConfigStringMap(p.p.GetStringMap("params")) if p.c.Params == nil { p.c.Params = make(map[string]any) } // Before Hugo 0.112.0 this was configured via site Params. if mainSections, found := p.c.Params["mainsections"]; found { p.c.MainSections = types.ToStringSlicePreserveString(mainSections) if p.c.MainSections == nil { p.c.MainSections = []string{} } } return nil }, }, "module": { key: "module", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Module, err = modules.DecodeConfig(p.logger.Logger(), p.p) return err }, }, "permalinks": { key: "permalinks", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Permalinks, err = page.DecodePermalinksConfig(p.p.GetStringMap(d.key)) return err }, }, "sitemap": { key: "sitemap", decode: func(d decodeWeight, p decodeConfig) error { var err error if p.p.IsSet(d.key) { p.c.Sitemap, err = config.DecodeSitemap(p.c.Sitemap, p.p.GetStringMap(d.key)) } return err }, }, "taxonomies": { key: "taxonomies", decode: func(d decodeWeight, p decodeConfig) error { if p.p.IsSet(d.key) { p.c.Taxonomies = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) } return nil }, }, "related": { key: "related", weight: 100, // This needs to be decoded after taxonomies. decode: func(d decodeWeight, p decodeConfig) error { if p.p.IsSet(d.key) { var err error p.c.Related, err = related.DecodeConfig(p.p.GetParams(d.key)) if err != nil { return fmt.Errorf("failed to decode related config: %w", err) } } else { p.c.Related = related.DefaultConfig if _, found := p.c.Taxonomies["tag"]; found { p.c.Related.Add(related.IndexConfig{Name: "tags", Weight: 80, Type: related.TypeBasic}) } } return nil }, }, "cascade": { key: "cascade", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Cascade, err = page.DecodeCascadeConfig(p.p.Get(d.key)) return err }, getInitializer: func(c *Config) configInitializer { return c.Cascade }, }, "menus": { key: "menus", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Menus, err = navigation.DecodeConfig(p.p.Get(d.key)) return err }, }, "page": { key: "page", decode: func(d decodeWeight, p decodeConfig) error { p.c.Page = config.PageConfig{ NextPrevSortOrder: "desc", NextPrevInSectionSortOrder: "desc", } if p.p.IsSet(d.key) { if err := mapstructure.WeakDecode(p.p.Get(d.key), &p.c.Page); err != nil { return err } } return nil }, getCompiler: func(c *Config) configCompiler { return &c.Page }, }, "pagination": { key: "pagination", decode: func(d decodeWeight, p decodeConfig) error { p.c.Pagination = config.Pagination{ PagerSize: 10, Path: "page", } if p.p.IsSet(d.key) { if err := mapstructure.WeakDecode(p.p.Get(d.key), &p.c.Pagination); err != nil { return err } } return nil }, }, "privacy": { key: "privacy", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Privacy, err = privacy.DecodeConfig(p.p) return err }, }, "security": { key: "security", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Security, err = security.DecodeConfig(p.p) return err }, }, "services": { key: "services", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Services, err = services.DecodeConfig(p.p) return err }, }, "deployment": { key: "deployment", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Deployment, err = deployconfig.DecodeConfig(p.p) return err }, }, "author": { key: "author", decode: func(d decodeWeight, p decodeConfig) error { p.c.Author = maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) return nil }, internalOrDeprecated: true, }, "social": { key: "social", decode: func(d decodeWeight, p decodeConfig) error { p.c.Social = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, internalOrDeprecated: true, }, "uglyurls": { key: "uglyurls", decode: func(d decodeWeight, p decodeConfig) error { v := p.p.Get(d.key) switch vv := v.(type) { case bool: p.c.UglyURLs = vv case string: p.c.UglyURLs = vv == "true" case maps.Params: p.c.UglyURLs = cast.ToStringMapBool(maps.CleanConfigStringMap(vv)) default: p.c.UglyURLs = cast.ToStringMapBool(v) } return nil }, internalOrDeprecated: true, }, "internal": { key: "internal", decode: func(d decodeWeight, p decodeConfig) error { return mapstructure.WeakDecode(p.p.GetStringMap(d.key), &p.c.Internal) }, internalOrDeprecated: true, }, } func init() { for k, v := range allDecoderSetups { // Verify that k and v.key is all lower case. if k != strings.ToLower(k) { panic(fmt.Sprintf("key %q is not lower case", k)) } if v.key != strings.ToLower(v.key) { panic(fmt.Sprintf("key %q is not lower case", v.key)) } if k != v.key { panic(fmt.Sprintf("key %q is not the same as the map key %q", k, v.key)) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false