| 1 |
// Copyright 2024 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package hugolib |
| 15 |
|
| 16 |
import ( |
| 17 |
"context" |
| 18 |
"errors" |
| 19 |
"fmt" |
| 20 |
"io" |
| 21 |
"iter" |
| 22 |
"slices" |
| 23 |
"strings" |
| 24 |
"sync" |
| 25 |
"sync/atomic" |
| 26 |
"time" |
| 27 |
|
| 28 |
"github.com/bep/helpers/maphelpers" |
| 29 |
"github.com/bep/logg" |
| 30 |
"github.com/gohugoio/go-radix" |
| 31 |
"github.com/gohugoio/hugo/cache/dynacache" |
| 32 |
"github.com/gohugoio/hugo/config/allconfig" |
| 33 |
"github.com/gohugoio/hugo/hugofs/hglob" |
| 34 |
"github.com/gohugoio/hugo/hugolib/doctree" |
| 35 |
"github.com/gohugoio/hugo/hugolib/sitesmatrix" |
| 36 |
"github.com/gohugoio/hugo/resources" |
| 37 |
|
| 38 |
"github.com/fsnotify/fsnotify" |
| 39 |
|
| 40 |
"github.com/gohugoio/hugo/output" |
| 41 |
"github.com/gohugoio/hugo/parser/metadecoders" |
| 42 |
|
| 43 |
"github.com/gohugoio/hugo/common/hmaps" |
| 44 |
"github.com/gohugoio/hugo/common/hsync" |
| 45 |
"github.com/gohugoio/hugo/common/htime" |
| 46 |
"github.com/gohugoio/hugo/common/loggers" |
| 47 |
"github.com/gohugoio/hugo/common/para" |
| 48 |
"github.com/gohugoio/hugo/common/terminal" |
| 49 |
"github.com/gohugoio/hugo/common/types" |
| 50 |
"github.com/gohugoio/hugo/hugofs" |
| 51 |
|
| 52 |
"github.com/gohugoio/hugo/source" |
| 53 |
|
| 54 |
"github.com/gohugoio/hugo/common/herrors" |
| 55 |
"github.com/gohugoio/hugo/deps" |
| 56 |
"github.com/gohugoio/hugo/helpers" |
| 57 |
|
| 58 |
"github.com/gohugoio/hugo/resources/page" |
| 59 |
) |
| 60 |
|
| 61 |
// HugoSites represents the sites to build. Each site represents a language. |
| 62 |
type HugoSites struct { |
| 63 |
// The current sites slice. |
| 64 |
// When rendering, this slice will be shifted out. |
| 65 |
Sites []*Site |
| 66 |
|
| 67 |
// All sites for all versions and roles. |
| 68 |
sitesVersionsRoles [][][]*Site |
| 69 |
sitesVersionsRolesMap map[sitesmatrix.Vector]*Site |
| 70 |
sitesLanguages []*Site // sample set with all languages. |
| 71 |
|
| 72 |
Configs *allconfig.Configs |
| 73 |
|
| 74 |
hugoInfo page.HugoInfo |
| 75 |
|
| 76 |
// Render output formats for all sites. |
| 77 |
renderFormats output.Formats |
| 78 |
|
| 79 |
// The currently rendered Site. |
| 80 |
currentSite *Site |
| 81 |
|
| 82 |
*deps.Deps |
| 83 |
|
| 84 |
gitInfo *gitInfo |
| 85 |
codeownerInfo *codeownerInfo |
| 86 |
|
| 87 |
// As loaded from the /data dirs |
| 88 |
data map[string]any |
| 89 |
|
| 90 |
// Cache for page listings. |
| 91 |
cachePages *dynacache.Partition[string, page.Pages] |
| 92 |
// Cache for content sources. |
| 93 |
cacheContentSource *dynacache.Partition[uint64, *resources.StaleValue[[]byte]] |
| 94 |
|
| 95 |
// Before Hugo 0.122.0 we managed all translations in a map using a translationKey |
| 96 |
// that could be overridden in front matter. |
| 97 |
// Now the different page dimensions (e.g. language) are built-in to the page trees above. |
| 98 |
// But we sill need to support the overridden translationKey, but that should |
| 99 |
// be relatively rare and low volume. |
| 100 |
translationKeyPages *hmaps.SliceCache[page.Page] |
| 101 |
|
| 102 |
pageTrees *pageTrees |
| 103 |
previousPageTreesWalkContext *doctree.WalkContext[contentNode] // Set for rebuilds only. |
| 104 |
previousSeenTerms *maphelpers.ConcurrentMap[term, sitesmatrix.Vectors] // Set for rebuilds only. |
| 105 |
|
| 106 |
printUnusedTemplatesInit sync.Once |
| 107 |
printPathWarningsInit sync.Once |
| 108 |
printSiteSitesDeprecationInit sync.Once |
| 109 |
printSiteDataDeprecationInit sync.Once |
| 110 |
printSiteAllPagesDeprecationInit sync.Once |
| 111 |
printSiteBuildDraftsDeprecationInit sync.Once |
| 112 |
printSiteLanguagesDeprecationInit sync.Once |
| 113 |
|
| 114 |
// File change events with filename stored in this map will be skipped. |
| 115 |
skipRebuildForFilenamesMu sync.Mutex |
| 116 |
skipRebuildForFilenames map[string]bool |
| 117 |
|
| 118 |
init *hugoSitesInit |
| 119 |
|
| 120 |
workersSite *para.Workers |
| 121 |
numWorkersSites int |
| 122 |
numWorkers int |
| 123 |
|
| 124 |
*progressReporter |
| 125 |
*fatalErrorHandler |
| 126 |
*buildCounters |
| 127 |
} |
| 128 |
|
| 129 |
// hugoSitesSitesProvider is a wrapper that implements page.SitesProvider. |
| 130 |
// This avoids naming conflict with HugoSites.Sites field. |
| 131 |
type hugoSitesSitesProvider struct { |
| 132 |
h *HugoSites |
| 133 |
} |
| 134 |
|
| 135 |
func (sp hugoSitesSitesProvider) Sites() page.Sites { |
| 136 |
return slices.Collect(sp.h.allSitesInterface(nil)) |
| 137 |
} |
| 138 |
|
| 139 |
func (sp hugoSitesSitesProvider) Data() map[string]any { |
| 140 |
return sp.h.Data() |
| 141 |
} |
| 142 |
|
| 143 |
type progressReporter struct { |
| 144 |
mu sync.Mutex |
| 145 |
t time.Time |
| 146 |
progress float64 |
| 147 |
queue []func() (state terminal.ProgressState, progress float64) |
| 148 |
state terminal.ProgressState |
| 149 |
renderProgressStart float64 |
| 150 |
numPagesToRender atomic.Uint64 |
| 151 |
} |
| 152 |
|
| 153 |
func (p *progressReporter) Start() { |
| 154 |
p.mu.Lock() |
| 155 |
defer p.mu.Unlock() |
| 156 |
p.t = htime.Now() |
| 157 |
} |
| 158 |
|
| 159 |
// allSites will range over all sites in the order of the sitesVersionsRoles matrix. |
| 160 |
// If include is not nil, it will be used to filter the sites. |
| 161 |
func (h *HugoSites) allSites(include func(s *Site) bool) iter.Seq[*Site] { |
| 162 |
if include == nil { |
| 163 |
include = func(s *Site) bool { |
| 164 |
return true |
| 165 |
} |
| 166 |
} |
| 167 |
return func(yield func(s *Site) bool) { |
| 168 |
for _, v := range h.sitesVersionsRoles { |
| 169 |
for _, r := range v { |
| 170 |
for _, s := range r { |
| 171 |
if !include(s) { |
| 172 |
continue |
| 173 |
} |
| 174 |
if !yield(s) { |
| 175 |
return |
| 176 |
} |
| 177 |
} |
| 178 |
} |
| 179 |
} |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
// allSitesInterface is the same as allSites but returns page.Site, which is used in some places where we don't want to expose the full *Site type. |
| 184 |
// If include is not nil, it will be used to filter the sites. |
| 185 |
func (h *HugoSites) allSitesInterface(include func(s page.Site) bool) iter.Seq[page.Site] { |
| 186 |
if include == nil { |
| 187 |
include = func(s page.Site) bool { |
| 188 |
return true |
| 189 |
} |
| 190 |
} |
| 191 |
return func(yield func(s page.Site) bool) { |
| 192 |
for _, v := range h.sitesVersionsRoles { |
| 193 |
for _, r := range v { |
| 194 |
for _, s := range r { |
| 195 |
if !include(s) { |
| 196 |
continue |
| 197 |
} |
| 198 |
// Site() returns a wrapped version of the site that only exposes the page.Site interface. |
| 199 |
if !yield(s.Site()) { |
| 200 |
return |
| 201 |
} |
| 202 |
} |
| 203 |
} |
| 204 |
} |
| 205 |
} |
| 206 |
} |
| 207 |
|
| 208 |
// allSiteLanguages will range over the first site in each language that's not skipped. |
| 209 |
func (h *HugoSites) allSiteLanguages(include func(s *Site) bool) iter.Seq[*Site] { |
| 210 |
return func(yield func(s *Site) bool) { |
| 211 |
LOOP: |
| 212 |
for _, v := range h.sitesVersionsRoles { |
| 213 |
for _, r := range v { |
| 214 |
for _, s := range r { |
| 215 |
if include != nil && !include(s) { |
| 216 |
continue LOOP |
| 217 |
} |
| 218 |
if !yield(r[0]) { |
| 219 |
return |
| 220 |
} |
| 221 |
continue LOOP |
| 222 |
} |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
func (h *HugoSites) getFirstTaxonomyConfig(s string) (v viewName) { |
| 229 |
for _, ss := range h.sitesLanguages { |
| 230 |
if v = ss.pageMap.cfg.getTaxonomyConfig(s); !v.IsZero() { |
| 231 |
return |
| 232 |
} |
| 233 |
} |
| 234 |
return |
| 235 |
} |
| 236 |
|
| 237 |
// returns one of the sites with the language of the given vector. |
| 238 |
func (h *HugoSites) languageSiteForSiteVector(v sitesmatrix.Vector) *Site { |
| 239 |
return h.sitesLanguages[v.Language()] |
| 240 |
} |
| 241 |
|
| 242 |
// ShouldSkipFileChangeEvent allows skipping filesystem event early before |
| 243 |
// the build is started. |
| 244 |
func (h *HugoSites) ShouldSkipFileChangeEvent(ev fsnotify.Event) bool { |
| 245 |
h.skipRebuildForFilenamesMu.Lock() |
| 246 |
defer h.skipRebuildForFilenamesMu.Unlock() |
| 247 |
return h.skipRebuildForFilenames[ev.Name] |
| 248 |
} |
| 249 |
|
| 250 |
func (h *HugoSites) Close() error { |
| 251 |
return h.Deps.Close() |
| 252 |
} |
| 253 |
|
| 254 |
func (h *HugoSites) isRebuild() bool { |
| 255 |
return h.BuildState.IsRebuild() |
| 256 |
} |
| 257 |
|
| 258 |
func (h *HugoSites) resolveFirstSite(matrix sitesmatrix.VectorStore) *Site { |
| 259 |
var s *Site |
| 260 |
var ok bool |
| 261 |
matrix.ForEachVector(func(v sitesmatrix.Vector) bool { |
| 262 |
if s, ok = h.sitesVersionsRolesMap[v]; ok { |
| 263 |
return false |
| 264 |
} |
| 265 |
return true |
| 266 |
}) |
| 267 |
if s == nil { |
| 268 |
panic(fmt.Sprintf("no site found for matrix %s", matrix)) |
| 269 |
} |
| 270 |
|
| 271 |
return s |
| 272 |
} |
| 273 |
|
| 274 |
type buildCounters struct { |
| 275 |
contentRenderCounter atomic.Uint64 |
| 276 |
pageRenderCounter atomic.Uint64 |
| 277 |
} |
| 278 |
|
| 279 |
func (c *buildCounters) loggFields() logg.Fields { |
| 280 |
return logg.Fields{ |
| 281 |
{Name: "pages", Value: c.pageRenderCounter.Load()}, |
| 282 |
{Name: "content", Value: c.contentRenderCounter.Load()}, |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
type fatalErrorHandler struct { |
| 287 |
mu sync.Mutex |
| 288 |
|
| 289 |
h *HugoSites |
| 290 |
|
| 291 |
err error |
| 292 |
|
| 293 |
done bool |
| 294 |
donec chan bool // will be closed when done |
| 295 |
} |
| 296 |
|
| 297 |
// FatalError error is used in some rare situations where it does not make sense to |
| 298 |
// continue processing, to abort as soon as possible and log the error. |
| 299 |
func (f *fatalErrorHandler) FatalError(err error) { |
| 300 |
f.mu.Lock() |
| 301 |
defer f.mu.Unlock() |
| 302 |
if !f.done { |
| 303 |
f.done = true |
| 304 |
close(f.donec) |
| 305 |
} |
| 306 |
f.err = err |
| 307 |
} |
| 308 |
|
| 309 |
// Stop stops the fatal error handler without setting an error. |
| 310 |
func (f *fatalErrorHandler) Stop() { |
| 311 |
f.mu.Lock() |
| 312 |
defer f.mu.Unlock() |
| 313 |
if !f.done { |
| 314 |
f.done = true |
| 315 |
close(f.donec) |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
func (f *fatalErrorHandler) getErr() error { |
| 320 |
f.mu.Lock() |
| 321 |
defer f.mu.Unlock() |
| 322 |
return f.err |
| 323 |
} |
| 324 |
|
| 325 |
func (f *fatalErrorHandler) Done() <-chan bool { |
| 326 |
return f.donec |
| 327 |
} |
| 328 |
|
| 329 |
type hugoSitesInit struct { |
| 330 |
// Loads the data from all of the /data folders. |
| 331 |
data hsync.FuncResetter |
| 332 |
|
| 333 |
// Loads the Git info and CODEOWNERS for all the pages if enabled. |
| 334 |
gitInfo hsync.FuncResetter |
| 335 |
} |
| 336 |
|
| 337 |
func (h *HugoSites) Data() map[string]any { |
| 338 |
if err := h.init.data.Do(context.Background()); err != nil { |
| 339 |
h.SendError(fmt.Errorf("failed to load data: %w", err)) |
| 340 |
return nil |
| 341 |
} |
| 342 |
return h.data |
| 343 |
} |
| 344 |
|
| 345 |
// Pages returns all pages for all sites. |
| 346 |
func (h *HugoSites) Pages() page.Pages { |
| 347 |
key := "pages" |
| 348 |
v, err := h.cachePages.GetOrCreate(key, func(string) (page.Pages, error) { |
| 349 |
var pages page.Pages |
| 350 |
for _, s := range h.Sites { |
| 351 |
pages = append(pages, s.Pages()...) |
| 352 |
} |
| 353 |
page.SortByDefault(pages) |
| 354 |
return pages, nil |
| 355 |
}) |
| 356 |
if err != nil { |
| 357 |
panic(err) |
| 358 |
} |
| 359 |
return v |
| 360 |
} |
| 361 |
|
| 362 |
// Pages returns all regularpages for all sites. |
| 363 |
func (h *HugoSites) RegularPages() page.Pages { |
| 364 |
key := "regular-pages" |
| 365 |
v, err := h.cachePages.GetOrCreate(key, func(string) (page.Pages, error) { |
| 366 |
var pages page.Pages |
| 367 |
for _, s := range h.Sites { |
| 368 |
pages = append(pages, s.RegularPages()...) |
| 369 |
} |
| 370 |
page.SortByDefault(pages) |
| 371 |
|
| 372 |
return pages, nil |
| 373 |
}) |
| 374 |
if err != nil { |
| 375 |
panic(err) |
| 376 |
} |
| 377 |
return v |
| 378 |
} |
| 379 |
|
| 380 |
func (h *HugoSites) gitInfoForPage(p page.Page) (*source.GitInfo, error) { |
| 381 |
if err := h.init.gitInfo.Do(context.Background()); err != nil { |
| 382 |
return nil, err |
| 383 |
} |
| 384 |
|
| 385 |
if h.gitInfo == nil { |
| 386 |
return nil, nil |
| 387 |
} |
| 388 |
|
| 389 |
return h.gitInfo.forPage(p), nil |
| 390 |
} |
| 391 |
|
| 392 |
func (h *HugoSites) codeownersForPage(p page.Page) ([]string, error) { |
| 393 |
if err := h.init.gitInfo.Do(context.Background()); err != nil { |
| 394 |
return nil, err |
| 395 |
} |
| 396 |
|
| 397 |
if h.codeownerInfo == nil { |
| 398 |
return nil, nil |
| 399 |
} |
| 400 |
|
| 401 |
return h.codeownerInfo.forPage(p), nil |
| 402 |
} |
| 403 |
|
| 404 |
func (h *HugoSites) reportProgress(f func() (state terminal.ProgressState, progress float64)) { |
| 405 |
h.progressReporter.mu.Lock() |
| 406 |
defer h.progressReporter.mu.Unlock() |
| 407 |
|
| 408 |
if h.progressReporter.t.IsZero() { |
| 409 |
// Not started yet, queue it up and return. |
| 410 |
h.progressReporter.queue = append(h.progressReporter.queue, f) |
| 411 |
return |
| 412 |
} |
| 413 |
|
| 414 |
handleOne := func(skip func(state terminal.ProgressState, progress float64) bool, handle func() (state terminal.ProgressState, progress float64)) { |
| 415 |
state, progress := handle() |
| 416 |
if skip != nil && skip(state, progress) { |
| 417 |
return |
| 418 |
} |
| 419 |
|
| 420 |
if h.progressReporter.progress > 0 && h.progressReporter.state == state && progress <= h.progressReporter.progress { |
| 421 |
// Only report progress forward. |
| 422 |
return |
| 423 |
} |
| 424 |
|
| 425 |
h.progressReporter.state = state |
| 426 |
h.progressReporter.progress = progress |
| 427 |
terminal.ReportProgress(h.Log.StdOut(), state, h.progressReporter.progress) |
| 428 |
} |
| 429 |
|
| 430 |
// Drain queue first. |
| 431 |
skip := func(state terminal.ProgressState, progress float64) bool { |
| 432 |
// Skip qued up intermediate states if we already are in normal state. |
| 433 |
return h.progressReporter.state == terminal.ProgressNormal && state == terminal.ProgressIntermediate |
| 434 |
} |
| 435 |
for _, ff := range h.progressReporter.queue { |
| 436 |
handleOne(skip, ff) |
| 437 |
} |
| 438 |
h.progressReporter.queue = nil |
| 439 |
|
| 440 |
handleOne(nil, f) |
| 441 |
} |
| 442 |
|
| 443 |
func (h *HugoSites) onPageRender() { |
| 444 |
pagesRendered := h.buildCounters.pageRenderCounter.Add(1) |
| 445 |
numPagesToRender := h.progressReporter.numPagesToRender.Load() |
| 446 |
n := numPagesToRender / 30 |
| 447 |
if n == 0 { |
| 448 |
n = 1 |
| 449 |
} |
| 450 |
if pagesRendered%n == 0 { |
| 451 |
h.reportProgress(func() (terminal.ProgressState, float64) { |
| 452 |
pr := h.progressReporter |
| 453 |
if pr.renderProgressStart == 0.0 && pr.state == terminal.ProgressNormal { |
| 454 |
pr.renderProgressStart = pr.progress |
| 455 |
} |
| 456 |
pagesProgress := pr.renderProgressStart + float64(pagesRendered)/float64(numPagesToRender)*(1.0-pr.renderProgressStart) |
| 457 |
return terminal.ProgressNormal, pagesProgress |
| 458 |
}) |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
func (h *HugoSites) filterAndJoinErrors(errs []error) error { |
| 463 |
if len(errs) == 0 { |
| 464 |
return nil |
| 465 |
} |
| 466 |
|
| 467 |
seen := map[string]bool{} |
| 468 |
var n int |
| 469 |
for _, err := range errs { |
| 470 |
if err == nil { |
| 471 |
continue |
| 472 |
} |
| 473 |
errMsg := herrors.Cause(err).Error() // We don't need to see many "Could not resolve "@alpinejs/persists"" |
| 474 |
if !seen[errMsg] { |
| 475 |
seen[errMsg] = true |
| 476 |
errs[n] = err |
| 477 |
n++ |
| 478 |
} |
| 479 |
} |
| 480 |
errs = errs[:n] |
| 481 |
|
| 482 |
for i, err := range errs { |
| 483 |
errs[i] = herrors.ImproveRenderErr(err) |
| 484 |
} |
| 485 |
|
| 486 |
const limit = 10 |
| 487 |
if len(errs) > limit { |
| 488 |
errs = errs[:limit] |
| 489 |
} |
| 490 |
return errors.Join(errs...) |
| 491 |
} |
| 492 |
|
| 493 |
// TODO(bep) consolidate |
| 494 |
func (h *HugoSites) LanguageSet() map[string]int { |
| 495 |
set := make(map[string]int) |
| 496 |
for i, s := range h.Sites { |
| 497 |
set[s.language.Lang] = i |
| 498 |
} |
| 499 |
return set |
| 500 |
} |
| 501 |
|
| 502 |
func (h *HugoSites) NumLogErrors() int { |
| 503 |
if h == nil { |
| 504 |
return 0 |
| 505 |
} |
| 506 |
return h.Log.LoggCount(logg.LevelError) |
| 507 |
} |
| 508 |
|
| 509 |
func (h *HugoSites) PrintProcessingStats(w io.Writer) { |
| 510 |
stats := make([]*helpers.ProcessingStats, len(h.Sites)) |
| 511 |
for i := range h.Sites { |
| 512 |
stats[i] = h.Sites[i].PathSpec.ProcessingStats |
| 513 |
} |
| 514 |
helpers.ProcessingStatsTable(w, stats...) |
| 515 |
} |
| 516 |
|
| 517 |
// GetContentPage finds a Page with content given the absolute filename. |
| 518 |
// Returns nil if none found. |
| 519 |
func (h *HugoSites) GetContentPage(filename string) page.Page { |
| 520 |
var p page.Page |
| 521 |
|
| 522 |
h.withPage(func(s string, p2 *pageState) bool { |
| 523 |
if p2.File() == nil { |
| 524 |
return false |
| 525 |
} |
| 526 |
|
| 527 |
if p2.File().FileInfo().Meta().Filename == filename { |
| 528 |
p = p2 |
| 529 |
return true |
| 530 |
} |
| 531 |
|
| 532 |
for _, r := range p2.Resources().ByType(pageResourceType) { |
| 533 |
p3 := r.(page.Page) |
| 534 |
if p3.File() != nil && p3.File().FileInfo().Meta().Filename == filename { |
| 535 |
p = p3 |
| 536 |
return true |
| 537 |
} |
| 538 |
} |
| 539 |
|
| 540 |
return false |
| 541 |
}) |
| 542 |
|
| 543 |
return p |
| 544 |
} |
| 545 |
|
| 546 |
func (h *HugoSites) loadGitInfo() error { |
| 547 |
if h.Configs.Base.EnableGitInfo { |
| 548 |
cfg := gitInfoConfig{ |
| 549 |
Deps: h.Deps, |
| 550 |
Modules: h.Configs.Modules, |
| 551 |
GitInfoCache: h.Configs.FileCaches.ModuleGitInfoCache(), |
| 552 |
Logger: h.Log, |
| 553 |
} |
| 554 |
gi, err := newGitInfo(cfg) |
| 555 |
if err != nil { |
| 556 |
return err |
| 557 |
} else { |
| 558 |
h.gitInfo = gi |
| 559 |
} |
| 560 |
|
| 561 |
co, err := newCodeOwners(h.Configs.LoadingInfo.BaseConfig.WorkingDir) |
| 562 |
if err != nil { |
| 563 |
h.Log.Errorln("Failed to read CODEOWNERS:", err) |
| 564 |
} else { |
| 565 |
h.codeownerInfo = co |
| 566 |
} |
| 567 |
} |
| 568 |
return nil |
| 569 |
} |
| 570 |
|
| 571 |
// Reset resets the sites and template caches etc., making it ready for a full rebuild. |
| 572 |
func (h *HugoSites) reset() { |
| 573 |
h.fatalErrorHandler = &fatalErrorHandler{ |
| 574 |
h: h, |
| 575 |
donec: make(chan bool), |
| 576 |
} |
| 577 |
} |
| 578 |
|
| 579 |
// resetLogs resets the log counters etc. Used to do a new build on the same sites. |
| 580 |
func (h *HugoSites) resetLogs() { |
| 581 |
h.Log.Reset() |
| 582 |
loggers.Log().Reset() |
| 583 |
|
| 584 |
// TODO(bep) Double-check this; I'm pretty sure there is only one logger. |
| 585 |
for _, s := range h.Sites { |
| 586 |
s.Deps.Log.Reset() |
| 587 |
} |
| 588 |
} |
| 589 |
|
| 590 |
func (h *HugoSites) withPage(fn func(s string, p *pageState) bool) { |
| 591 |
for s := range h.allSites(nil) { |
| 592 |
w := &doctree.NodeShiftTreeWalker[contentNode]{ |
| 593 |
Tree: s.pageMap.treePages, |
| 594 |
LockType: doctree.LockTypeRead, |
| 595 |
Handle: func(s string, n contentNode) (radix.WalkFlag, error) { |
| 596 |
if fn(s, n.(*pageState)) { |
| 597 |
return radix.WalkStop, nil |
| 598 |
} |
| 599 |
return radix.WalkContinue, nil |
| 600 |
}, |
| 601 |
} |
| 602 |
_ = w.Walk(context.Background()) |
| 603 |
} |
| 604 |
} |
| 605 |
|
| 606 |
// BuildCfg holds build options used to, as an example, skip the render step. |
| 607 |
type BuildCfg struct { |
| 608 |
// Skip rendering. Useful for testing. |
| 609 |
SkipRender bool |
| 610 |
|
| 611 |
// Use this to indicate what changed (for rebuilds). |
| 612 |
WhatChanged *WhatChanged |
| 613 |
|
| 614 |
// This is a partial re-render of some selected pages. |
| 615 |
PartialReRender bool |
| 616 |
|
| 617 |
// Set in server mode when the last build failed for some reason. |
| 618 |
ErrRecovery bool |
| 619 |
|
| 620 |
// Recently visited or touched URLs. This is used for partial re-rendering. |
| 621 |
RecentlyTouched *types.EvictingQueue[string] |
| 622 |
|
| 623 |
// Can be set to build only with a sub set of the content source. |
| 624 |
ContentInclusionFilter *hglob.FilenameFilter |
| 625 |
|
| 626 |
// Set when the buildlock is already acquired (e.g. the archetype content builder). |
| 627 |
NoBuildLock bool |
| 628 |
|
| 629 |
testCounters *buildCounters |
| 630 |
} |
| 631 |
|
| 632 |
// shouldRender returns whether this output format should be rendered or not. |
| 633 |
func (cfg *BuildCfg) shouldRender(infol logg.LevelLogger, p *pageState) bool { |
| 634 |
if p.skipRender() { |
| 635 |
return false |
| 636 |
} |
| 637 |
|
| 638 |
if !p.renderOnce { |
| 639 |
return true |
| 640 |
} |
| 641 |
|
| 642 |
// The render state is incremented on render and reset when a related change is detected. |
| 643 |
// Note that this is set per output format. |
| 644 |
shouldRender := p.renderState == 0 |
| 645 |
|
| 646 |
if !shouldRender { |
| 647 |
return false |
| 648 |
} |
| 649 |
|
| 650 |
fastRenderMode := p.s.Conf.FastRenderMode() |
| 651 |
|
| 652 |
if !fastRenderMode || !p.s.h.BuildState.IsRebuild() { |
| 653 |
return shouldRender |
| 654 |
} |
| 655 |
|
| 656 |
if !p.render { |
| 657 |
// Not be to rendered for this output format. |
| 658 |
return false |
| 659 |
} |
| 660 |
|
| 661 |
if relURL := p.getRelURL(); relURL != "" { |
| 662 |
if cfg.RecentlyTouched.Contains(relURL) { |
| 663 |
infol.Logf("render recently touched URL %q (%s)", relURL, p.outputFormat().Name) |
| 664 |
return true |
| 665 |
} |
| 666 |
} |
| 667 |
|
| 668 |
// In fast render mode, we want to avoid re-rendering the sitemaps etc. and |
| 669 |
// other big listings whenever we e.g. change a content file, |
| 670 |
// but we want partial renders of the recently touched pages to also include |
| 671 |
// alternative formats of the same HTML page (e.g. RSS, JSON). |
| 672 |
for _, po := range p.pageOutputs { |
| 673 |
if po.render && po.f.IsHTML && cfg.RecentlyTouched.Contains(po.getRelURL()) { |
| 674 |
infol.Logf("render recently touched URL %q, %s version of %s", po.getRelURL(), po.f.Name, p.outputFormat().Name) |
| 675 |
return true |
| 676 |
} |
| 677 |
} |
| 678 |
|
| 679 |
return false |
| 680 |
} |
| 681 |
|
| 682 |
func (s *Site) preparePagesForRender(isRenderingSite bool, idx int) error { |
| 683 |
var err error |
| 684 |
|
| 685 |
initPage := func(p *pageState) error { |
| 686 |
if err = p.shiftToOutputFormat(isRenderingSite, idx); err != nil { |
| 687 |
return err |
| 688 |
} |
| 689 |
return nil |
| 690 |
} |
| 691 |
|
| 692 |
return s.pageMap.forEeachPageIncludingBundledPages( |
| 693 |
nil, |
| 694 |
func(p *pageState) (bool, error) { |
| 695 |
return false, initPage(p) |
| 696 |
}, |
| 697 |
) |
| 698 |
} |
| 699 |
|
| 700 |
func (h *HugoSites) loadData() error { |
| 701 |
h.data = make(map[string]any) |
| 702 |
w := hugofs.NewWalkway( |
| 703 |
hugofs.WalkwayConfig{ |
| 704 |
Fs: h.PathSpec.BaseFs.Data.Fs, |
| 705 |
IgnoreFile: h.SourceSpec.IgnoreFile, |
| 706 |
PathParser: h.Conf.PathParser(), |
| 707 |
WalkFn: func(ctx context.Context, path string, fi hugofs.FileMetaInfo) error { |
| 708 |
if fi.IsDir() { |
| 709 |
return nil |
| 710 |
} |
| 711 |
pi := fi.Meta().PathInfo |
| 712 |
if pi == nil { |
| 713 |
panic("no path info") |
| 714 |
} |
| 715 |
return h.handleDataFile(source.NewFileInfo(fi)) |
| 716 |
}, |
| 717 |
}, |
| 718 |
) |
| 719 |
|
| 720 |
if err := w.Walk(); err != nil { |
| 721 |
return err |
| 722 |
} |
| 723 |
return nil |
| 724 |
} |
| 725 |
|
| 726 |
func (h *HugoSites) handleDataFile(r *source.File) error { |
| 727 |
var current map[string]any |
| 728 |
|
| 729 |
f, err := r.FileInfo().Meta().Open() |
| 730 |
if err != nil { |
| 731 |
return fmt.Errorf("data: failed to open %q: %w", r.LogicalName(), err) |
| 732 |
} |
| 733 |
defer f.Close() |
| 734 |
|
| 735 |
// Crawl in data tree to insert data |
| 736 |
current = h.data |
| 737 |
dataPath := r.FileInfo().Meta().PathInfo.Unnormalized().Dir()[1:] |
| 738 |
keyParts := strings.SplitSeq(dataPath, "/") |
| 739 |
|
| 740 |
for key := range keyParts { |
| 741 |
if key != "" { |
| 742 |
if _, ok := current[key]; !ok { |
| 743 |
current[key] = make(map[string]any) |
| 744 |
} |
| 745 |
current = current[key].(map[string]any) |
| 746 |
} |
| 747 |
} |
| 748 |
|
| 749 |
data, err := h.readData(r) |
| 750 |
if err != nil { |
| 751 |
return h.errWithFileContext(err, r) |
| 752 |
} |
| 753 |
|
| 754 |
if data == nil { |
| 755 |
return nil |
| 756 |
} |
| 757 |
|
| 758 |
// filepath.Walk walks the files in lexical order, '/' comes before '.' |
| 759 |
higherPrecedentData := current[r.BaseFileName()] |
| 760 |
|
| 761 |
switch data.(type) { |
| 762 |
case map[string]any: |
| 763 |
|
| 764 |
switch higherPrecedentData.(type) { |
| 765 |
case nil: |
| 766 |
current[r.BaseFileName()] = data |
| 767 |
case map[string]any: |
| 768 |
// merge maps: insert entries from data for keys that |
| 769 |
// don't already exist in higherPrecedentData |
| 770 |
higherPrecedentMap := higherPrecedentData.(map[string]any) |
| 771 |
for key, value := range data.(map[string]any) { |
| 772 |
if _, exists := higherPrecedentMap[key]; exists { |
| 773 |
// this warning could happen if |
| 774 |
// 1. A theme uses the same key; the main data folder wins |
| 775 |
// 2. A sub folder uses the same key: the sub folder wins |
| 776 |
// TODO(bep) figure out a way to detect 2) above and make that a WARN |
| 777 |
h.Log.Infof("Data for key '%s' in path '%s' is overridden by higher precedence data already in the data tree", key, r.Path()) |
| 778 |
} else { |
| 779 |
higherPrecedentMap[key] = value |
| 780 |
} |
| 781 |
} |
| 782 |
default: |
| 783 |
// can't merge: higherPrecedentData is not a map |
| 784 |
h.Log.Warnf("The %T data from '%s' overridden by "+ |
| 785 |
"higher precedence %T data already in the data tree", data, r.Path(), higherPrecedentData) |
| 786 |
} |
| 787 |
|
| 788 |
case []any: |
| 789 |
if higherPrecedentData == nil { |
| 790 |
current[r.BaseFileName()] = data |
| 791 |
} else { |
| 792 |
// we don't merge array data |
| 793 |
h.Log.Warnf("The %T data from '%s' overridden by "+ |
| 794 |
"higher precedence %T data already in the data tree", data, r.Path(), higherPrecedentData) |
| 795 |
} |
| 796 |
|
| 797 |
default: |
| 798 |
h.Log.Errorf("unexpected data type %T in file %s", data, r.LogicalName()) |
| 799 |
} |
| 800 |
|
| 801 |
return nil |
| 802 |
} |
| 803 |
|
| 804 |
func (h *HugoSites) errWithFileContext(err error, f *source.File) error { |
| 805 |
realFilename := f.FileInfo().Meta().Filename |
| 806 |
return herrors.NewFileErrorFromFile(err, realFilename, h.Fs.Source, nil) |
| 807 |
} |
| 808 |
|
| 809 |
func (h *HugoSites) readData(f *source.File) (any, error) { |
| 810 |
content, err := f.FileInfo().Meta().ReadAll() |
| 811 |
if err != nil { |
| 812 |
return nil, fmt.Errorf("readData: failed to read data file: %w", err) |
| 813 |
} |
| 814 |
|
| 815 |
format := metadecoders.FormatFromString(f.Ext()) |
| 816 |
return metadecoders.Default.Unmarshal(content, format) |
| 817 |
} |