mirror of
https://github.com/gohugoio/hugo.git
synced 2024-11-07 20:30:36 -05:00
7285e74090
There are some breaking changes in this commit, see #11455. Closes #11455 Closes #11549 This fixes a set of bugs (see issue list) and it is also paying some technical debt accumulated over the years. We now build with Staticcheck enabled in the CI build. The performance should be about the same as before for regular sized Hugo sites, but it should perform and scale much better to larger data sets, as objects that uses lots of memory (e.g. rendered Markdown, big JSON files read into maps with transform.Unmarshal etc.) will now get automatically garbage collected if needed. Performance on partial rebuilds when running the server in fast render mode should be the same, but the change detection should be much more accurate. A list of the notable new features: * A new dependency tracker that covers (almost) all of Hugo's API and is used to do fine grained partial rebuilds when running the server. * A new and simpler tree document store which allows fast lookups and prefix-walking in all dimensions (e.g. language) concurrently. * You can now configure an upper memory limit allowing for much larger data sets and/or running on lower specced PCs. We have lifted the "no resources in sub folders" restriction for branch bundles (e.g. sections). Memory Limit * Hugos will, by default, set aside a quarter of the total system memory, but you can set this via the OS environment variable HUGO_MEMORYLIMIT (in gigabytes). This is backed by a partitioned LRU cache used throughout Hugo. A cache that gets dynamically resized in low memory situations, allowing Go's Garbage Collector to free the memory. New Dependency Tracker: Hugo has had a rule based coarse grained approach to server rebuilds that has worked mostly pretty well, but there have been some surprises (e.g. stale content). This is now revamped with a new dependency tracker that can quickly calculate the delta given a changed resource (e.g. a content file, template, JS file etc.). This handles transitive relations, e.g. $page -> js.Build -> JS import, or $page1.Content -> render hook -> site.GetPage -> $page2.Title, or $page1.Content -> shortcode -> partial -> site.RegularPages -> $page2.Content -> shortcode ..., and should also handle changes to aggregated values (e.g. site.Lastmod) effectively. This covers all of Hugo's API with 2 known exceptions (a list that may not be fully exhaustive): Changes to files loaded with template func os.ReadFile may not be handled correctly. We recommend loading resources with resources.Get Changes to Hugo objects (e.g. Page) passed in the template context to lang.Translate may not be detected correctly. We recommend having simple i18n templates without too much data context passed in other than simple types such as strings and numbers. Note that the cachebuster configuration (when A changes then rebuild B) works well with the above, but we recommend that you revise that configuration, as it in most situations should not be needed. One example where it is still needed is with TailwindCSS and using changes to hugo_stats.json to trigger new CSS rebuilds. Document Store: Previously, a little simplified, we split the document store (where we store pages and resources) in a tree per language. This worked pretty well, but the structure made some operations harder than they needed to be. We have now restructured it into one Radix tree for all languages. Internally the language is considered to be a dimension of that tree, and the tree can be viewed in all dimensions concurrently. This makes some operations re. language simpler (e.g. finding translations is just a slice range), but the idea is that it should also be relatively inexpensive to add more dimensions if needed (e.g. role). Fixes #10169 Fixes #10364 Fixes #10482 Fixes #10630 Fixes #10656 Fixes #10694 Fixes #10918 Fixes #11262 Fixes #11439 Fixes #11453 Fixes #11457 Fixes #11466 Fixes #11540 Fixes #11551 Fixes #11556 Fixes #11654 Fixes #11661 Fixes #11663 Fixes #11664 Fixes #11669 Fixes #11671 Fixes #11807 Fixes #11808 Fixes #11809 Fixes #11815 Fixes #11840 Fixes #11853 Fixes #11860 Fixes #11883 Fixes #11904 Fixes #7388 Fixes #7425 Fixes #7436 Fixes #7544 Fixes #7882 Fixes #7960 Fixes #8255 Fixes #8307 Fixes #8863 Fixes #8927 Fixes #9192 Fixes #9324
551 lines
14 KiB
Go
551 lines
14 KiB
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"
|
|
"html/template"
|
|
"os"
|
|
"sort"
|
|
"time"
|
|
|
|
"github.com/bep/logg"
|
|
"github.com/gohugoio/hugo/cache/dynacache"
|
|
"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/config"
|
|
"github.com/gohugoio/hugo/config/allconfig"
|
|
"github.com/gohugoio/hugo/deps"
|
|
"github.com/gohugoio/hugo/hugolib/doctree"
|
|
"github.com/gohugoio/hugo/identity"
|
|
"github.com/gohugoio/hugo/langs"
|
|
"github.com/gohugoio/hugo/langs/i18n"
|
|
"github.com/gohugoio/hugo/lazy"
|
|
"github.com/gohugoio/hugo/modules"
|
|
"github.com/gohugoio/hugo/navigation"
|
|
"github.com/gohugoio/hugo/output"
|
|
"github.com/gohugoio/hugo/publisher"
|
|
"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/gohugoio/hugo/tpl"
|
|
"github.com/gohugoio/hugo/tpl/tplimpl"
|
|
)
|
|
|
|
var _ page.Site = (*Site)(nil)
|
|
|
|
type Site struct {
|
|
conf *allconfig.Config
|
|
language *langs.Language
|
|
languagei int
|
|
pageMap *pageMap
|
|
|
|
// The owning container.
|
|
h *HugoSites
|
|
|
|
*deps.Deps
|
|
|
|
// Page navigation.
|
|
*pageFinder
|
|
taxonomies page.TaxonomyList
|
|
menus navigation.Menus
|
|
|
|
// 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
|
|
|
|
relatedDocsHandler *page.RelatedDocsHandler
|
|
siteRefLinker
|
|
publisher publisher.Publisher
|
|
frontmatterHandler pagemeta.FrontMatterHandler
|
|
|
|
// We render each site for all the relevant output formats in serial with
|
|
// this rendering context pointing to the current one.
|
|
rc *siteRenderingContext
|
|
|
|
// 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
|
|
|
|
// Lazily loaded site dependencies
|
|
init *siteInit
|
|
}
|
|
|
|
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()
|
|
|
|
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.LogOut == nil {
|
|
cfg.LogOut = os.Stdout
|
|
}
|
|
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.LogOut,
|
|
Stderr: cfg.LogOut,
|
|
StoreErrors: conf.Running(),
|
|
SuppressStatements: conf.IgnoredErrors(),
|
|
}
|
|
logger = loggers.New(logOpts)
|
|
}
|
|
|
|
memCache := dynacache.New(dynacache.Options{Running: conf.Running(), Log: logger})
|
|
|
|
firstSiteDeps := &deps.Deps{
|
|
Fs: cfg.Fs,
|
|
Log: logger,
|
|
Conf: conf,
|
|
MemCache: memCache,
|
|
TemplateProvider: tplimpl.DefaultTemplateProvider,
|
|
TranslationProvider: i18n.NewTranslationProvider(),
|
|
}
|
|
|
|
if err := firstSiteDeps.Init(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
confm := cfg.Configs
|
|
var sites []*Site
|
|
|
|
ns := &contentNodeShifter{
|
|
numLanguages: len(confm.Languages),
|
|
}
|
|
|
|
treeConfig := doctree.Config[contentNodeI]{
|
|
Shifter: ns,
|
|
}
|
|
|
|
pageTrees := &pageTrees{
|
|
treePages: doctree.New(
|
|
treeConfig,
|
|
),
|
|
treeResources: doctree.New(
|
|
treeConfig,
|
|
),
|
|
treeTaxonomyEntries: doctree.NewTreeShiftTree[*weightedContentNode](doctree.DimensionLanguage.Index(), len(confm.Languages)),
|
|
}
|
|
|
|
pageTrees.treePagesResources = doctree.WalkableTrees[contentNodeI]{
|
|
pageTrees.treePages,
|
|
pageTrees.treeResources,
|
|
}
|
|
|
|
pageTrees.resourceTrees = doctree.MutableTrees{
|
|
pageTrees.treeResources,
|
|
}
|
|
|
|
for i, confp := range confm.ConfigLangs() {
|
|
language := confp.Language()
|
|
if language.Disabled {
|
|
continue
|
|
}
|
|
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,
|
|
languagei: i,
|
|
frontmatterHandler: frontmatterHandler,
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
s.pageMap = newPageMap(i, s, memCache, pageTrees)
|
|
|
|
s.pageFinder = newPageFinder(s.pageMap)
|
|
s.siteRefLinker, err = newSiteRefLinker(s)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// 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.
|
|
|
|
s.prepareInits()
|
|
sites = append(sites, s)
|
|
}
|
|
|
|
if len(sites) == 0 {
|
|
return nil, errors.New("no sites to build")
|
|
}
|
|
|
|
// Pull the default content language to the top, then sort the sites by language weight (if set) or lang.
|
|
defaultContentLanguage := confm.Base.DefaultContentLanguage
|
|
sort.Slice(sites, func(i, j int) bool {
|
|
li := sites[i].language
|
|
lj := sites[j].language
|
|
if li.Lang == defaultContentLanguage {
|
|
return true
|
|
}
|
|
|
|
if lj.Lang == defaultContentLanguage {
|
|
return false
|
|
}
|
|
|
|
if li.Weight != lj.Weight {
|
|
return li.Weight < lj.Weight
|
|
}
|
|
return li.Lang < lj.Lang
|
|
})
|
|
|
|
h, err := newHugoSites(cfg, firstSiteDeps, pageTrees, sites)
|
|
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, sites []*Site) (*HugoSites, error) {
|
|
numWorkers := config.GetNumWorkerMultiplier()
|
|
numWorkersSite := numWorkers
|
|
if numWorkersSite > len(sites) {
|
|
numWorkersSite = len(sites)
|
|
}
|
|
workersSite := para.New(numWorkersSite)
|
|
|
|
h := &HugoSites{
|
|
Sites: sites,
|
|
Deps: sites[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},
|
|
),
|
|
translationKeyPages: maps.NewSliceCache[page.Page](),
|
|
currentSite: sites[0],
|
|
skipRebuildForFilenames: make(map[string]bool),
|
|
init: &hugoSitesInit{
|
|
data: lazy.New(),
|
|
layouts: lazy.New(),
|
|
gitInfo: lazy.New(),
|
|
},
|
|
}
|
|
|
|
// 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
|
|
for i, s := range sites {
|
|
s.h = h
|
|
if err := s.Deps.Compile(prototype); err != nil {
|
|
return nil, err
|
|
}
|
|
if i == 0 {
|
|
prototype = s.Deps
|
|
}
|
|
}
|
|
|
|
h.fatalErrorHandler = &fatalErrorHandler{
|
|
h: h,
|
|
donec: make(chan bool),
|
|
}
|
|
|
|
h.init.data.Add(func(context.Context) (any, error) {
|
|
err := h.loadData()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to load data: %w", err)
|
|
}
|
|
return nil, nil
|
|
})
|
|
|
|
h.init.layouts.Add(func(context.Context) (any, error) {
|
|
for _, s := range h.Sites {
|
|
if err := s.Tmpl().(tpl.TemplateManager).MarkReady(); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return nil, nil
|
|
})
|
|
|
|
h.init.gitInfo.Add(func(context.Context) (any, error) {
|
|
err := h.loadGitInfo()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to load Git info: %w", err)
|
|
}
|
|
return nil, nil
|
|
})
|
|
|
|
return h, nil
|
|
}
|
|
|
|
// Returns true if we're running in a server.
|
|
// Deprecated: use hugo.IsServer instead
|
|
func (s *Site) IsServer() bool {
|
|
hugo.Deprecate(".Site.IsServer", "Use hugo.IsServer instead.", "v0.120.0")
|
|
return s.conf.Internal.Running
|
|
}
|
|
|
|
// 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) RSSLink() template.URL {
|
|
hugo.Deprecate("Site.RSSLink", "Use the Output Format's Permalink method instead, e.g. .OutputFormats.Get \"RSS\".Permalink", "v0.114.0")
|
|
rssOutputFormat := s.home.OutputFormats().Get("rss")
|
|
return template.URL(rssOutputFormat.Permalink())
|
|
}
|
|
|
|
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 {
|
|
return s.conf.C.MainSections
|
|
}
|
|
|
|
// Returns a struct with some information about the build.
|
|
func (s *Site) Hugo() hugo.HugoInfo {
|
|
if s.h == nil || 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
|
|
}
|
|
|
|
// Returns the last modification date of the content.
|
|
// Deprecated: Use .Lastmod instead.
|
|
func (s *Site) LastChange() time.Time {
|
|
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
|
|
}
|
|
|
|
func (s *Site) Author() map[string]any {
|
|
return s.conf.Author
|
|
}
|
|
|
|
func (s *Site) Authors() page.AuthorList {
|
|
return page.AuthorList{}
|
|
}
|
|
|
|
func (s *Site) Social() map[string]string {
|
|
return s.conf.Social
|
|
}
|
|
|
|
// Deprecated: Use .Site.Config.Services.Disqus.Shortname instead
|
|
func (s *Site) DisqusShortname() string {
|
|
hugo.Deprecate(".Site.DisqusShortname", "Use .Site.Config.Services.Disqus.Shortname instead.", "v0.120.0")
|
|
return s.Config().Services.Disqus.Shortname
|
|
}
|
|
|
|
// Deprecated: Use .Site.Config.Services.GoogleAnalytics.ID instead
|
|
func (s *Site) GoogleAnalytics() string {
|
|
hugo.Deprecate(".Site.GoogleAnalytics", "Use .Site.Config.Services.GoogleAnalytics.ID instead.", "v0.120.0")
|
|
return s.Config().Services.GoogleAnalytics.ID
|
|
}
|
|
|
|
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.s.h.Data()
|
|
}
|
|
|
|
func (s *Site) BuildDrafts() bool {
|
|
return s.conf.BuildDrafts
|
|
}
|
|
|
|
func (s *Site) IsMultiLingual() bool {
|
|
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 {
|
|
return s.pageMap.getPagesInSection(
|
|
pageMapQueryPagesInSection{
|
|
pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{
|
|
Path: "",
|
|
KeyPart: "global",
|
|
Include: pagePredicates.ShouldListGlobal,
|
|
},
|
|
Recursive: true,
|
|
IncludeSelf: true,
|
|
},
|
|
)
|
|
}
|
|
|
|
// RegularPages returns all the regular pages.
|
|
// This is for the current language only.
|
|
func (s *Site) RegularPages() page.Pages {
|
|
return s.pageMap.getPagesInSection(
|
|
pageMapQueryPagesInSection{
|
|
pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{
|
|
Path: "",
|
|
KeyPart: "global",
|
|
Include: pagePredicates.ShouldListGlobal.And(pagePredicates.KindPage),
|
|
},
|
|
Recursive: true,
|
|
},
|
|
)
|
|
}
|
|
|
|
// AllPages returns all pages for all sites.
|
|
func (s *Site) AllPages() page.Pages {
|
|
return s.h.Pages()
|
|
}
|
|
|
|
// AllRegularPages returns all regular pages for all sites.
|
|
func (s *Site) AllRegularPages() page.Pages {
|
|
return s.h.RegularPages()
|
|
}
|