| 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 |
"bytes" |
| 18 |
"context" |
| 19 |
"encoding/json" |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"os" |
| 23 |
"path" |
| 24 |
"path/filepath" |
| 25 |
"strings" |
| 26 |
"time" |
| 27 |
|
| 28 |
"github.com/bep/debounce" |
| 29 |
"github.com/bep/helpers/maphelpers" |
| 30 |
"github.com/bep/logg" |
| 31 |
"github.com/gohugoio/go-radix" |
| 32 |
"github.com/gohugoio/hugo/bufferpool" |
| 33 |
"github.com/gohugoio/hugo/deps" |
| 34 |
"github.com/gohugoio/hugo/hugofs" |
| 35 |
"github.com/gohugoio/hugo/hugofs/files" |
| 36 |
"github.com/gohugoio/hugo/hugofs/hglob" |
| 37 |
"github.com/gohugoio/hugo/hugolib/doctree" |
| 38 |
"github.com/gohugoio/hugo/hugolib/pagesfromdata" |
| 39 |
"github.com/gohugoio/hugo/hugolib/segments" |
| 40 |
"github.com/gohugoio/hugo/identity" |
| 41 |
"github.com/gohugoio/hugo/output" |
| 42 |
"github.com/gohugoio/hugo/publisher" |
| 43 |
"github.com/gohugoio/hugo/source" |
| 44 |
"github.com/gohugoio/hugo/tpl" |
| 45 |
|
| 46 |
"github.com/gohugoio/hugo/common/herrors" |
| 47 |
"github.com/gohugoio/hugo/common/loggers" |
| 48 |
"github.com/gohugoio/hugo/common/para" |
| 49 |
"github.com/gohugoio/hugo/common/paths" |
| 50 |
"github.com/gohugoio/hugo/common/rungroup" |
| 51 |
"github.com/gohugoio/hugo/common/terminal" |
| 52 |
"github.com/gohugoio/hugo/config" |
| 53 |
"github.com/gohugoio/hugo/resources/page" |
| 54 |
"github.com/gohugoio/hugo/resources/page/siteidentities" |
| 55 |
"github.com/gohugoio/hugo/resources/postpub" |
| 56 |
|
| 57 |
"github.com/spf13/afero" |
| 58 |
|
| 59 |
"github.com/fsnotify/fsnotify" |
| 60 |
) |
| 61 |
|
| 62 |
// Build builds all sites. If filesystem events are provided, |
| 63 |
// this is considered to be a potential partial rebuild. |
| 64 |
func (h *HugoSites) Build(config BuildCfg, events ...fsnotify.Event) error { |
| 65 |
if h.isRebuild() && !h.Conf.Watching() && !h.Conf.Running() { |
| 66 |
return errors.New("Build called multiple times when not in watch or server mode (typically with hugolib.Test(t, files).Build(); Build() is already called once by Test)") |
| 67 |
} |
| 68 |
if !h.isRebuild() && terminal.PrintANSIColors(os.Stdout) { |
| 69 |
// Don't show progress for fast builds. |
| 70 |
d := debounce.New(250 * time.Millisecond) |
| 71 |
d(func() { |
| 72 |
h.progressReporter.Start() |
| 73 |
h.reportProgress(func() (state terminal.ProgressState, progress float64) { |
| 74 |
// We don't know how many files to process below, so use the intermediate state as the first progress. |
| 75 |
return terminal.ProgressIntermediate, 1.0 |
| 76 |
}) |
| 77 |
}) |
| 78 |
defer d(func() {}) |
| 79 |
} |
| 80 |
|
| 81 |
infol := h.Log.InfoCommand("build") |
| 82 |
defer loggers.TimeTrackf(infol, time.Now(), nil, "") |
| 83 |
defer func() { |
| 84 |
h.reportProgress(func() (state terminal.ProgressState, progress float64) { |
| 85 |
return terminal.ProgressHidden, 1.0 |
| 86 |
}) |
| 87 |
h.BuildState.BuildCounter.Add(1) |
| 88 |
}() |
| 89 |
|
| 90 |
if h.Deps == nil { |
| 91 |
panic("must have deps") |
| 92 |
} |
| 93 |
|
| 94 |
if !config.NoBuildLock { |
| 95 |
unlock, err := h.BaseFs.LockBuild() |
| 96 |
if err != nil { |
| 97 |
return fmt.Errorf("failed to acquire a build lock: %w", err) |
| 98 |
} |
| 99 |
defer unlock() |
| 100 |
} |
| 101 |
|
| 102 |
defer func() { |
| 103 |
for _, s := range h.Sites { |
| 104 |
s.Deps.BuildEndListeners.Notify() |
| 105 |
} |
| 106 |
}() |
| 107 |
|
| 108 |
errCollector := h.StartErrorCollector() |
| 109 |
errs := make(chan error) |
| 110 |
|
| 111 |
go func(from, to chan error) { |
| 112 |
var errors []error |
| 113 |
i := 0 |
| 114 |
for e := range from { |
| 115 |
i++ |
| 116 |
if i > 50 { |
| 117 |
break |
| 118 |
} |
| 119 |
errors = append(errors, e) |
| 120 |
} |
| 121 |
to <- h.filterAndJoinErrors(errors) |
| 122 |
|
| 123 |
close(to) |
| 124 |
}(errCollector, errs) |
| 125 |
|
| 126 |
for _, s := range h.Sites { |
| 127 |
s.state = siteStateInit |
| 128 |
} |
| 129 |
|
| 130 |
if h.Metrics != nil { |
| 131 |
h.Metrics.Reset() |
| 132 |
} |
| 133 |
|
| 134 |
h.buildCounters = config.testCounters |
| 135 |
if h.buildCounters == nil { |
| 136 |
h.buildCounters = &buildCounters{} |
| 137 |
} |
| 138 |
|
| 139 |
// Need a pointer as this may be modified. |
| 140 |
conf := &config |
| 141 |
if conf.WhatChanged == nil { |
| 142 |
// Assume everything has changed |
| 143 |
conf.WhatChanged = &WhatChanged{needsPagesAssembly: true} |
| 144 |
} |
| 145 |
|
| 146 |
var prepareErr error |
| 147 |
|
| 148 |
if !config.PartialReRender { |
| 149 |
prepare := func() error { |
| 150 |
init := func(conf *BuildCfg) error { |
| 151 |
for _, s := range h.Sites { |
| 152 |
s.Deps.BuildStartListeners.Notify() |
| 153 |
} |
| 154 |
|
| 155 |
if len(events) > 0 || len(conf.WhatChanged.Changes()) > 0 { |
| 156 |
// Rebuild |
| 157 |
if err := h.initRebuild(conf); err != nil { |
| 158 |
return fmt.Errorf("initRebuild: %w", err) |
| 159 |
} |
| 160 |
} else { |
| 161 |
if err := h.initSites(); err != nil { |
| 162 |
return fmt.Errorf("initSites: %w", err) |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
return nil |
| 167 |
} |
| 168 |
|
| 169 |
ctx := context.Background() |
| 170 |
|
| 171 |
if err := h.process(ctx, infol, conf, init, events...); err != nil { |
| 172 |
return fmt.Errorf("process: %w", err) |
| 173 |
} |
| 174 |
h.reportProgress(func() (state terminal.ProgressState, progress float64) { |
| 175 |
return terminal.ProgressNormal, 0.15 |
| 176 |
}) |
| 177 |
if err := h.assemble(ctx, infol, conf); err != nil { |
| 178 |
return fmt.Errorf("assemble: %w", err) |
| 179 |
} |
| 180 |
h.reportProgress(func() (state terminal.ProgressState, progress float64) { |
| 181 |
return terminal.ProgressNormal, 0.20 |
| 182 |
}) |
| 183 |
|
| 184 |
return nil |
| 185 |
} |
| 186 |
|
| 187 |
if prepareErr = prepare(); prepareErr != nil { |
| 188 |
h.SendError(prepareErr) |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
for s := range h.allSites(nil) { |
| 193 |
s.state = siteStateReady |
| 194 |
} |
| 195 |
|
| 196 |
if prepareErr == nil { |
| 197 |
if err := h.render(infol, conf); err != nil { |
| 198 |
h.SendError(fmt.Errorf("render: %w", err)) |
| 199 |
} |
| 200 |
|
| 201 |
// Make sure to write any build stats to disk first so it's available |
| 202 |
// to the post processors. |
| 203 |
if err := h.writeBuildStats(); err != nil { |
| 204 |
return err |
| 205 |
} |
| 206 |
|
| 207 |
// We need to do this before render deferred. |
| 208 |
if err := h.printPathWarningsOnce(); err != nil { |
| 209 |
h.SendError(fmt.Errorf("printPathWarnings: %w", err)) |
| 210 |
} |
| 211 |
|
| 212 |
if err := h.renderDeferred(infol); err != nil { |
| 213 |
h.SendError(fmt.Errorf("renderDeferred: %w", err)) |
| 214 |
} |
| 215 |
|
| 216 |
// This needs to be done after the deferred rendering to get complete template usage coverage. |
| 217 |
if err := h.printUnusedTemplatesOnce(); err != nil { |
| 218 |
h.SendError(fmt.Errorf("printPathWarnings: %w", err)) |
| 219 |
} |
| 220 |
|
| 221 |
if err := h.postProcess(infol); err != nil { |
| 222 |
h.SendError(fmt.Errorf("postProcess: %w", err)) |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
if h.Metrics != nil { |
| 227 |
var b bytes.Buffer |
| 228 |
h.Metrics.WriteMetrics(&b) |
| 229 |
|
| 230 |
h.Log.Printf("\nTemplate Metrics:\n\n") |
| 231 |
h.Log.Println(b.String()) |
| 232 |
} |
| 233 |
|
| 234 |
h.StopErrorCollector() |
| 235 |
|
| 236 |
err := <-errs |
| 237 |
if err != nil { |
| 238 |
return err |
| 239 |
} |
| 240 |
|
| 241 |
if err := h.fatalErrorHandler.getErr(); err != nil { |
| 242 |
return err |
| 243 |
} |
| 244 |
|
| 245 |
errorCount := h.Log.LoggCount(logg.LevelError) + loggers.Log().LoggCount(logg.LevelError) |
| 246 |
if errorCount > 0 { |
| 247 |
return fmt.Errorf("logged %d error(s)", errorCount) |
| 248 |
} |
| 249 |
|
| 250 |
return nil |
| 251 |
} |
| 252 |
|
| 253 |
// Build lifecycle methods below. |
| 254 |
// The order listed matches the order of execution. |
| 255 |
|
| 256 |
func (h *HugoSites) initSites() error { |
| 257 |
h.reset() |
| 258 |
return nil |
| 259 |
} |
| 260 |
|
| 261 |
func (h *HugoSites) initRebuild(config *BuildCfg) error { |
| 262 |
if !h.Configs.Base.Internal.Watch { |
| 263 |
return errors.New("rebuild called when not in watch mode") |
| 264 |
} |
| 265 |
|
| 266 |
h.pageTrees.treePagesResources.WalkPrefixRaw("", func(key string, n contentNode) (radix.WalkFlag, contentNode, error) { |
| 267 |
cnh.resetBuildState(n) |
| 268 |
return radix.WalkContinue, nil, nil |
| 269 |
}) |
| 270 |
|
| 271 |
for _, s := range h.Sites { |
| 272 |
s.resetBuildState(config.WhatChanged.needsPagesAssembly) |
| 273 |
} |
| 274 |
|
| 275 |
h.reset() |
| 276 |
h.resetLogs() |
| 277 |
|
| 278 |
return nil |
| 279 |
} |
| 280 |
|
| 281 |
// process prepares the Sites' sources for a full or partial rebuild. |
| 282 |
// This will also parse the source and create all the Page objects. |
| 283 |
func (h *HugoSites) process(ctx context.Context, l logg.LevelLogger, config *BuildCfg, init func(config *BuildCfg) error, events ...fsnotify.Event) error { |
| 284 |
l = l.WithField("step", "process") |
| 285 |
defer loggers.TimeTrackf(l, time.Now(), nil, "") |
| 286 |
|
| 287 |
if len(events) > 0 { |
| 288 |
// This is a rebuild triggered from file events. |
| 289 |
return h.processPartialFileEvents(ctx, l, config, init, events) |
| 290 |
} else if len(config.WhatChanged.Changes()) > 0 { |
| 291 |
// Rebuild triggered from remote events. |
| 292 |
if err := init(config); err != nil { |
| 293 |
return err |
| 294 |
} |
| 295 |
return h.processPartialRebuildChanges(ctx, l, config) |
| 296 |
} |
| 297 |
return h.processFull(ctx, l, config) |
| 298 |
} |
| 299 |
|
| 300 |
// assemble creates missing sections, applies aggregate values (e.g. dates, cascading params), |
| 301 |
// removes disabled pages etc. |
| 302 |
func (h *HugoSites) assemble(ctx context.Context, l logg.LevelLogger, bcfg *BuildCfg) error { |
| 303 |
l = l.WithField("step", "assemble") |
| 304 |
defer loggers.TimeTrackf(l, time.Now(), nil, "") |
| 305 |
|
| 306 |
if !bcfg.WhatChanged.needsPagesAssembly { |
| 307 |
changes := bcfg.WhatChanged.Drain() |
| 308 |
if len(changes) > 0 { |
| 309 |
if err := h.resolveAndClearStateForIdentities(ctx, l, nil, changes); err != nil { |
| 310 |
return err |
| 311 |
} |
| 312 |
} |
| 313 |
return nil |
| 314 |
} |
| 315 |
|
| 316 |
h.translationKeyPages.Reset() |
| 317 |
|
| 318 |
var assemblers []*sitePagesAssembler |
| 319 |
// Changes detected during assembly (e.g. aggregate date changes) |
| 320 |
for s := range h.allSites(nil) { |
| 321 |
assemblers = append(assemblers, &sitePagesAssembler{ |
| 322 |
s: s, |
| 323 |
assembleChanges: bcfg.WhatChanged, |
| 324 |
ctx: ctx, |
| 325 |
}) |
| 326 |
} |
| 327 |
|
| 328 |
apa := newAllPagesAssembler( |
| 329 |
ctx, |
| 330 |
h, |
| 331 |
assemblers[0].s.pageMap, |
| 332 |
bcfg.WhatChanged, |
| 333 |
) |
| 334 |
for _, s := range assemblers { |
| 335 |
s.a = apa |
| 336 |
} |
| 337 |
|
| 338 |
if h.Conf.Watching() { |
| 339 |
defer func() { |
| 340 |
// Store previous walk context to detect cascade changes on next rebuild. |
| 341 |
h.previousPageTreesWalkContext = apa.rwRoot.WalkContext |
| 342 |
}() |
| 343 |
} |
| 344 |
|
| 345 |
if err := apa.createAllPages(); err != nil { |
| 346 |
return err |
| 347 |
} |
| 348 |
|
| 349 |
g, _ := h.workersSite.Start(ctx) |
| 350 |
for _, s := range assemblers { |
| 351 |
g.Run(func() error { |
| 352 |
return s.assemblePagesStep1() |
| 353 |
}) |
| 354 |
} |
| 355 |
if err := g.Wait(); err != nil { |
| 356 |
return err |
| 357 |
} |
| 358 |
|
| 359 |
changes := bcfg.WhatChanged.Drain() |
| 360 |
|
| 361 |
// Changes from the assemble step (e.g. lastMod, cascade) needs a re-calculation |
| 362 |
// of what needs to be re-built. |
| 363 |
if len(changes) > 0 { |
| 364 |
if err := h.resolveAndClearStateForIdentities(ctx, l, nil, changes); err != nil { |
| 365 |
return err |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
for _, s := range assemblers { |
| 370 |
if err := s.assemblePagesStep2(); err != nil { |
| 371 |
return err |
| 372 |
} |
| 373 |
} |
| 374 |
|
| 375 |
// Handle new terms from assemblePagesStep2. |
| 376 |
changes = bcfg.WhatChanged.Drain() |
| 377 |
if len(changes) > 0 { |
| 378 |
if err := h.resolveAndClearStateForIdentities(ctx, l, nil, changes); err != nil { |
| 379 |
return err |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
h.renderFormats = output.Formats{} |
| 384 |
for s := range h.allSites(nil) { |
| 385 |
s.initRenderFormats() |
| 386 |
h.renderFormats = append(h.renderFormats, s.renderFormats...) |
| 387 |
} |
| 388 |
|
| 389 |
for _, s := range assemblers { |
| 390 |
if err := s.assemblePagesStepFinal(); err != nil { |
| 391 |
return err |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
return nil |
| 396 |
} |
| 397 |
|
| 398 |
// render renders the sites. |
| 399 |
func (h *HugoSites) render(l logg.LevelLogger, config *BuildCfg) error { |
| 400 |
l = l.WithField("step", "render") |
| 401 |
start := time.Now() |
| 402 |
defer func() { |
| 403 |
loggers.TimeTrackf(l, start, h.buildCounters.loggFields(), "") |
| 404 |
}() |
| 405 |
|
| 406 |
siteRenderContext := &siteRenderContext{cfg: config, infol: l, multihost: h.Configs.IsMultihost} |
| 407 |
|
| 408 |
renderErr := func(err error) error { |
| 409 |
if err == nil { |
| 410 |
return nil |
| 411 |
} |
| 412 |
// In Hugo 0.141.0 we replaced the special error handling for resources.GetRemote |
| 413 |
// with the more general try. |
| 414 |
if strings.Contains(err.Error(), "can't evaluate field Err in type") { |
| 415 |
if strings.Contains(err.Error(), "resource.Resource") { |
| 416 |
return fmt.Errorf("%s: Resource.Err was removed in Hugo v0.141.0 and replaced with a new try keyword, see https://gohugo.io/functions/go-template/try/", err) |
| 417 |
} else if strings.Contains(err.Error(), "template.HTML") { |
| 418 |
return fmt.Errorf("%s: the return type of transform.ToMath was changed in Hugo v0.141.0 and the error handling replaced with a new try keyword, see https://gohugo.io/functions/go-template/try/", err) |
| 419 |
} |
| 420 |
} |
| 421 |
return err |
| 422 |
} |
| 423 |
|
| 424 |
i := 0 |
| 425 |
|
| 426 |
for s := range h.allSites(nil) { |
| 427 |
if s.conf.Segments.Config.SegmentFilter.ShouldExcludeCoarse(segments.SegmentQuery{Site: s.siteVector}) { |
| 428 |
l.Logf("skip site %s not matching segments set in --renderSegments", s.resolveDimensionNames()) |
| 429 |
continue |
| 430 |
} |
| 431 |
siteRenderContext.languageIdx = s.siteVector.Language() |
| 432 |
h.currentSite = s |
| 433 |
for siteOutIdx, renderFormat := range s.renderFormats { |
| 434 |
if s.conf.Segments.Config.SegmentFilter.ShouldExcludeCoarse(segments.SegmentQuery{Output: renderFormat.Name, Site: s.siteVector}) { |
| 435 |
l.Logf("skip output format %q for site %s not matching segments set in --renderSegments", renderFormat.Name, s.resolveDimensionNames()) |
| 436 |
continue |
| 437 |
} |
| 438 |
|
| 439 |
if err := func() error { |
| 440 |
rc := tpl.RenderingContext{Site: s, SiteOutIdx: siteOutIdx} |
| 441 |
h.BuildState.StartStageRender(rc) |
| 442 |
defer h.BuildState.StopStageRender(rc) |
| 443 |
|
| 444 |
siteRenderContext.outIdx = siteOutIdx |
| 445 |
siteRenderContext.sitesOutIdx = i |
| 446 |
i++ |
| 447 |
|
| 448 |
select { |
| 449 |
case <-h.Done(): |
| 450 |
return nil |
| 451 |
default: |
| 452 |
for s2 := range h.allSites(nil) { |
| 453 |
if err := s2.preparePagesForRender(s == s2, siteRenderContext.sitesOutIdx); err != nil { |
| 454 |
return err |
| 455 |
} |
| 456 |
} |
| 457 |
if !config.SkipRender { |
| 458 |
ll := l.WithField("substep", "pages"). |
| 459 |
WithField("site", s.language.Lang). |
| 460 |
WithField("outputFormat", renderFormat.Name) |
| 461 |
|
| 462 |
start := time.Now() |
| 463 |
|
| 464 |
if config.PartialReRender { |
| 465 |
if err := s.renderPages(siteRenderContext); err != nil { |
| 466 |
return err |
| 467 |
} |
| 468 |
} else { |
| 469 |
if err := s.render(siteRenderContext); err != nil { |
| 470 |
return renderErr(err) |
| 471 |
} |
| 472 |
} |
| 473 |
loggers.TimeTrackf(ll, start, nil, "") |
| 474 |
} |
| 475 |
} |
| 476 |
return nil |
| 477 |
}(); err != nil { |
| 478 |
return err |
| 479 |
} |
| 480 |
|
| 481 |
} |
| 482 |
|
| 483 |
} |
| 484 |
|
| 485 |
return nil |
| 486 |
} |
| 487 |
|
| 488 |
func (h *HugoSites) renderDeferred(l logg.LevelLogger) error { |
| 489 |
l = l.WithField("step", "render deferred") |
| 490 |
start := time.Now() |
| 491 |
|
| 492 |
var deferredCount int |
| 493 |
|
| 494 |
for rc, de := range h.Deps.BuildState.DeferredExecutionsGroupedByRenderingContext { |
| 495 |
if de.FilenamesWithPostPrefix.Len() == 0 { |
| 496 |
continue |
| 497 |
} |
| 498 |
|
| 499 |
deferredCount += de.FilenamesWithPostPrefix.Len() |
| 500 |
|
| 501 |
s := rc.Site.(*Site) |
| 502 |
for _, s2 := range h.Sites { |
| 503 |
if err := s2.preparePagesForRender(s == s2, rc.SiteOutIdx); err != nil { |
| 504 |
return err |
| 505 |
} |
| 506 |
} |
| 507 |
if err := s.executeDeferredTemplates(de); err != nil { |
| 508 |
return herrors.ImproveRenderErr(err) |
| 509 |
} |
| 510 |
} |
| 511 |
|
| 512 |
loggers.TimeTrackf(l, start, logg.Fields{ |
| 513 |
logg.Field{Name: "count", Value: deferredCount}, |
| 514 |
}, "") |
| 515 |
|
| 516 |
return nil |
| 517 |
} |
| 518 |
|
| 519 |
func (s *Site) executeDeferredTemplates(de *deps.DeferredExecutions) error { |
| 520 |
handleFile := func(filename string) error { |
| 521 |
content, err := afero.ReadFile(s.BaseFs.PublishFs, filename) |
| 522 |
if err != nil { |
| 523 |
return err |
| 524 |
} |
| 525 |
|
| 526 |
k := 0 |
| 527 |
changed := false |
| 528 |
|
| 529 |
for { |
| 530 |
if k >= len(content) { |
| 531 |
break |
| 532 |
} |
| 533 |
l := bytes.Index(content[k:], []byte(tpl.HugoDeferredTemplatePrefix)) |
| 534 |
if l == -1 { |
| 535 |
break |
| 536 |
} |
| 537 |
m := bytes.Index(content[k+l:], []byte(tpl.HugoDeferredTemplateSuffix)) + len(tpl.HugoDeferredTemplateSuffix) |
| 538 |
|
| 539 |
low, high := k+l, k+l+m |
| 540 |
|
| 541 |
forward := l + m |
| 542 |
id := string(content[low:high]) |
| 543 |
|
| 544 |
if err := func() error { |
| 545 |
deferred, found := de.Executions.Get(id) |
| 546 |
if !found { |
| 547 |
panic(fmt.Sprintf("deferred execution with id %q not found", id)) |
| 548 |
} |
| 549 |
deferred.Mu.Lock() |
| 550 |
defer deferred.Mu.Unlock() |
| 551 |
|
| 552 |
if !deferred.Executed { |
| 553 |
tmpl := s.Deps.GetTemplateStore() |
| 554 |
ti := s.TemplateStore.LookupByPath(deferred.TemplatePath) |
| 555 |
if ti == nil { |
| 556 |
panic(fmt.Sprintf("template %q not found", deferred.TemplatePath)) |
| 557 |
} |
| 558 |
|
| 559 |
if err := func() error { |
| 560 |
buf := bufferpool.GetBuffer() |
| 561 |
defer bufferpool.PutBuffer(buf) |
| 562 |
|
| 563 |
err = tmpl.ExecuteWithContext(deferred.Ctx, ti, buf, deferred.Data) |
| 564 |
if err != nil { |
| 565 |
return err |
| 566 |
} |
| 567 |
deferred.Result = buf.String() |
| 568 |
deferred.Executed = true |
| 569 |
|
| 570 |
return nil |
| 571 |
}(); err != nil { |
| 572 |
return err |
| 573 |
} |
| 574 |
} |
| 575 |
|
| 576 |
content = append(content[:low], append([]byte(deferred.Result), content[high:]...)...) |
| 577 |
forward = len(deferred.Result) |
| 578 |
changed = true |
| 579 |
|
| 580 |
return nil |
| 581 |
}(); err != nil { |
| 582 |
return err |
| 583 |
} |
| 584 |
|
| 585 |
k += forward |
| 586 |
} |
| 587 |
|
| 588 |
if changed { |
| 589 |
return afero.WriteFile(s.BaseFs.PublishFs, filename, content, 0o666) |
| 590 |
} |
| 591 |
|
| 592 |
return nil |
| 593 |
} |
| 594 |
|
| 595 |
g := rungroup.Run(context.Background(), rungroup.Config[string]{ |
| 596 |
NumWorkers: s.h.numWorkers, |
| 597 |
Handle: func(ctx context.Context, filename string) error { |
| 598 |
return handleFile(filename) |
| 599 |
}, |
| 600 |
}) |
| 601 |
|
| 602 |
de.FilenamesWithPostPrefix.ForEeach(func(filename string, _ bool) bool { |
| 603 |
g.Enqueue(filename) |
| 604 |
return true |
| 605 |
}) |
| 606 |
|
| 607 |
return g.Wait() |
| 608 |
} |
| 609 |
|
| 610 |
// printPathWarningsOnce prints path warnings if enabled. |
| 611 |
func (h *HugoSites) printPathWarningsOnce() error { |
| 612 |
h.printPathWarningsInit.Do(func() { |
| 613 |
conf := h.Configs.Base |
| 614 |
if conf.PrintPathWarnings { |
| 615 |
// We need to do this before any post processing, as that may write to the same files twice |
| 616 |
// and create false positives. |
| 617 |
hugofs.WalkFilesystems(h.Fs.PublishDir, func(fs afero.Fs) bool { |
| 618 |
if dfs, ok := fs.(hugofs.DuplicatesReporter); ok { |
| 619 |
dupes := dfs.ReportDuplicates() |
| 620 |
if dupes != "" { |
| 621 |
h.Log.Warnln("Duplicate target paths:", dupes) |
| 622 |
} |
| 623 |
} |
| 624 |
return false |
| 625 |
}) |
| 626 |
} |
| 627 |
}) |
| 628 |
return nil |
| 629 |
} |
| 630 |
|
| 631 |
// / printUnusedTemplatesOnce prints unused templates if enabled. |
| 632 |
func (h *HugoSites) printUnusedTemplatesOnce() error { |
| 633 |
h.printUnusedTemplatesInit.Do(func() { |
| 634 |
conf := h.Configs.Base |
| 635 |
if conf.PrintUnusedTemplates { |
| 636 |
unusedTemplates := h.GetTemplateStore().UnusedTemplates() |
| 637 |
for _, unusedTemplate := range unusedTemplates { |
| 638 |
if unusedTemplate.Fi != nil { |
| 639 |
h.Log.Warnf("Template %s is unused, source %q", unusedTemplate.PathInfo.Path(), unusedTemplate.Fi.Meta().Filename) |
| 640 |
} else { |
| 641 |
h.Log.Warnf("Template %s is unused", unusedTemplate.PathInfo.Path()) |
| 642 |
} |
| 643 |
} |
| 644 |
} |
| 645 |
}) |
| 646 |
return nil |
| 647 |
} |
| 648 |
|
| 649 |
// postProcess runs the post processors, e.g. writing the hugo_stats.json file. |
| 650 |
func (h *HugoSites) postProcess(l logg.LevelLogger) error { |
| 651 |
l = l.WithField("step", "postProcess") |
| 652 |
defer loggers.TimeTrackf(l, time.Now(), nil, "") |
| 653 |
|
| 654 |
// This will only be set when js.Build have been triggered with |
| 655 |
// imports that resolves to the project or a module. |
| 656 |
// Write a jsconfig.json file to the project's /asset directory |
| 657 |
// to help JS IntelliSense in VS Code etc. |
| 658 |
if !h.ResourceSpec.BuildConfig().NoJSConfigInAssets { |
| 659 |
handleJSConfig := func(fi os.FileInfo) { |
| 660 |
m := fi.(hugofs.FileMetaInfo).Meta() |
| 661 |
if !m.IsProject { |
| 662 |
return |
| 663 |
} |
| 664 |
|
| 665 |
if jsConfig := h.ResourceSpec.JSConfigBuilder.Build(m.SourceRoot); jsConfig != nil { |
| 666 |
b, err := json.MarshalIndent(jsConfig, "", " ") |
| 667 |
if err != nil { |
| 668 |
h.Log.Warnf("Failed to create jsconfig.json: %s", err) |
| 669 |
} else { |
| 670 |
filename := filepath.Join(m.SourceRoot, "jsconfig.json") |
| 671 |
if h.Configs.Base.Internal.Running { |
| 672 |
h.skipRebuildForFilenamesMu.Lock() |
| 673 |
h.skipRebuildForFilenames[filename] = true |
| 674 |
h.skipRebuildForFilenamesMu.Unlock() |
| 675 |
} |
| 676 |
// Make sure it's written to the OS fs as this is used by |
| 677 |
// editors. |
| 678 |
if err := afero.WriteFile(hugofs.Os, filename, b, 0o666); err != nil { |
| 679 |
h.Log.Warnf("Failed to write jsconfig.json: %s", err) |
| 680 |
} |
| 681 |
} |
| 682 |
} |
| 683 |
} |
| 684 |
|
| 685 |
fi, err := h.BaseFs.Assets.Fs.Stat("") |
| 686 |
if err != nil { |
| 687 |
if !herrors.IsNotExist(err) { |
| 688 |
h.Log.Warnf("Failed to resolve jsconfig.json dir: %s", err) |
| 689 |
} |
| 690 |
} else { |
| 691 |
handleJSConfig(fi) |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
var toPostProcess []postpub.PostPublishedResource |
| 696 |
for _, r := range h.ResourceSpec.PostProcessResources.All() { |
| 697 |
toPostProcess = append(toPostProcess, r) |
| 698 |
} |
| 699 |
|
| 700 |
if len(toPostProcess) == 0 { |
| 701 |
// Nothing more to do. |
| 702 |
return nil |
| 703 |
} |
| 704 |
|
| 705 |
workers := para.New(config.GetNumWorkerMultiplier()) |
| 706 |
g, _ := workers.Start(context.Background()) |
| 707 |
|
| 708 |
handleFile := func(filename string) error { |
| 709 |
content, err := afero.ReadFile(h.BaseFs.PublishFs, filename) |
| 710 |
if err != nil { |
| 711 |
return err |
| 712 |
} |
| 713 |
|
| 714 |
k := 0 |
| 715 |
changed := false |
| 716 |
|
| 717 |
for { |
| 718 |
l := bytes.Index(content[k:], []byte(postpub.PostProcessPrefix)) |
| 719 |
if l == -1 { |
| 720 |
break |
| 721 |
} |
| 722 |
m := bytes.Index(content[k+l:], []byte(postpub.PostProcessSuffix)) + len(postpub.PostProcessSuffix) |
| 723 |
|
| 724 |
low, high := k+l, k+l+m |
| 725 |
|
| 726 |
field := content[low:high] |
| 727 |
|
| 728 |
forward := l + m |
| 729 |
|
| 730 |
for i, r := range toPostProcess { |
| 731 |
if r == nil { |
| 732 |
panic(fmt.Sprintf("resource %d to post process is nil", i+1)) |
| 733 |
} |
| 734 |
v, ok := r.GetFieldString(string(field)) |
| 735 |
if ok { |
| 736 |
content = append(content[:low], append([]byte(v), content[high:]...)...) |
| 737 |
changed = true |
| 738 |
forward = len(v) |
| 739 |
break |
| 740 |
} |
| 741 |
} |
| 742 |
|
| 743 |
k += forward |
| 744 |
} |
| 745 |
|
| 746 |
if changed { |
| 747 |
return afero.WriteFile(h.BaseFs.PublishFs, filename, content, 0o666) |
| 748 |
} |
| 749 |
|
| 750 |
return nil |
| 751 |
} |
| 752 |
|
| 753 |
filenames := h.Deps.BuildState.GetFilenamesWithPostPrefix() |
| 754 |
for _, filename := range filenames { |
| 755 |
g.Run(func() error { |
| 756 |
return handleFile(filename) |
| 757 |
}) |
| 758 |
} |
| 759 |
|
| 760 |
// Prepare for a new build. |
| 761 |
for _, s := range h.Sites { |
| 762 |
s.ResourceSpec.PostProcessResources = maphelpers.NewConcurrentMap[string, postpub.PostPublishedResource]() |
| 763 |
} |
| 764 |
|
| 765 |
return g.Wait() |
| 766 |
} |
| 767 |
|
| 768 |
func (h *HugoSites) writeBuildStats() error { |
| 769 |
if h.ResourceSpec == nil { |
| 770 |
panic("h.ResourceSpec is nil") |
| 771 |
} |
| 772 |
if !h.ResourceSpec.BuildConfig().BuildStats.Enabled() { |
| 773 |
return nil |
| 774 |
} |
| 775 |
|
| 776 |
htmlElements := &publisher.HTMLElements{} |
| 777 |
for _, s := range h.Sites { |
| 778 |
stats := s.publisher.PublishStats() |
| 779 |
htmlElements.Merge(stats.HTMLElements) |
| 780 |
} |
| 781 |
|
| 782 |
filename := filepath.Join(h.Configs.LoadingInfo.BaseConfig.WorkingDir, files.FilenameHugoStatsJSON) |
| 783 |
|
| 784 |
existingContent, _ := afero.ReadFile(hugofs.Os, filename) |
| 785 |
|
| 786 |
// When rendering only a subset of the site, merge with any existing |
| 787 |
// hugo_stats.json so that elements from pages not rendered in this build |
| 788 |
// are preserved (e.g. so Tailwind doesn't strip their classes). |
| 789 |
// See issue 14939. |
| 790 |
if len(h.Configs.Base.RenderSegments) > 0 && len(existingContent) > 0 { |
| 791 |
var existing publisher.PublishStats |
| 792 |
if err := json.Unmarshal(existingContent, &existing); err == nil { |
| 793 |
htmlElements.Merge(existing.HTMLElements) |
| 794 |
} else { |
| 795 |
h.Log.Warnf("Failed to unmarshal existing hugo_stats.json: %s", err) |
| 796 |
} |
| 797 |
} |
| 798 |
|
| 799 |
htmlElements.Sort() |
| 800 |
|
| 801 |
stats := publisher.PublishStats{ |
| 802 |
HTMLElements: *htmlElements, |
| 803 |
} |
| 804 |
|
| 805 |
var buf bytes.Buffer |
| 806 |
enc := json.NewEncoder(&buf) |
| 807 |
enc.SetEscapeHTML(false) |
| 808 |
enc.SetIndent("", " ") |
| 809 |
err := enc.Encode(stats) |
| 810 |
if err != nil { |
| 811 |
return err |
| 812 |
} |
| 813 |
js := buf.Bytes() |
| 814 |
|
| 815 |
if bytes.Equal(existingContent, js) { |
| 816 |
return nil |
| 817 |
} |
| 818 |
|
| 819 |
// Make sure it's always written to the OS fs. |
| 820 |
if err := afero.WriteFile(hugofs.Os, filename, js, 0o666); err != nil { |
| 821 |
return err |
| 822 |
} |
| 823 |
|
| 824 |
// Write to the destination as well if it's a in-memory fs. |
| 825 |
if !hugofs.IsOsFs(h.Fs.Source) { |
| 826 |
if err := afero.WriteFile(h.Fs.WorkingDirWritable, filename, js, 0o666); err != nil { |
| 827 |
return err |
| 828 |
} |
| 829 |
} |
| 830 |
|
| 831 |
// This step may be followed by a post process step that may |
| 832 |
// rebuild e.g. CSS, so clear any cache that's defined for the hugo_stats.json. |
| 833 |
h.dynacacheGCFilenameIfNotWatchedAndDrainMatching(filename) |
| 834 |
|
| 835 |
return nil |
| 836 |
} |
| 837 |
|
| 838 |
type pathChange struct { |
| 839 |
// The path to the changed file. |
| 840 |
p *paths.Path |
| 841 |
|
| 842 |
// If true, this is a structural change (e.g. a delete or a rename). |
| 843 |
structural bool |
| 844 |
|
| 845 |
// If true, this is a directory. |
| 846 |
isDir bool |
| 847 |
} |
| 848 |
|
| 849 |
func (p pathChange) isStructuralChange() bool { |
| 850 |
return p.structural || p.isDir |
| 851 |
} |
| 852 |
|
| 853 |
func (h *HugoSites) processPartialRebuildChanges(ctx context.Context, l logg.LevelLogger, config *BuildCfg) error { |
| 854 |
if err := h.resolveAndClearStateForIdentities(ctx, l, nil, config.WhatChanged.Drain()); err != nil { |
| 855 |
return err |
| 856 |
} |
| 857 |
|
| 858 |
if err := h.processContentAdaptersOnRebuild(ctx, config); err != nil { |
| 859 |
return err |
| 860 |
} |
| 861 |
return nil |
| 862 |
} |
| 863 |
|
| 864 |
// processPartialFileEvents prepares the Sites' sources for a partial rebuild. |
| 865 |
func (h *HugoSites) processPartialFileEvents(ctx context.Context, l logg.LevelLogger, config *BuildCfg, init func(config *BuildCfg) error, events []fsnotify.Event) error { |
| 866 |
h.Log.Trace(logg.StringFunc(func() string { |
| 867 |
var sb strings.Builder |
| 868 |
sb.WriteString("File events:\n") |
| 869 |
for _, ev := range events { |
| 870 |
sb.WriteString(ev.String()) |
| 871 |
sb.WriteString("\n") |
| 872 |
} |
| 873 |
return sb.String() |
| 874 |
})) |
| 875 |
|
| 876 |
// For a list of events for the different OSes, see the test output in https://github.com/bep/fsnotifyeventlister/. |
| 877 |
events = h.fileEventsFilter(events) |
| 878 |
events = h.fileEventsTrim(events) |
| 879 |
eventInfos := h.fileEventsApplyInfo(events) |
| 880 |
|
| 881 |
logger := h.Log |
| 882 |
|
| 883 |
var ( |
| 884 |
tmplAdded bool |
| 885 |
tmplChanged bool |
| 886 |
i18nChanged bool |
| 887 |
needsPagesAssemble bool |
| 888 |
) |
| 889 |
|
| 890 |
changedPaths := struct { |
| 891 |
changedFiles []*paths.Path |
| 892 |
addedFiles []*paths.Path |
| 893 |
changedDirs []*paths.Path |
| 894 |
deleted []*paths.Path |
| 895 |
}{} |
| 896 |
|
| 897 |
removeDuplicatePaths := func(ps []*paths.Path) []*paths.Path { |
| 898 |
seen := make(map[string]bool) |
| 899 |
var filtered []*paths.Path |
| 900 |
for _, p := range ps { |
| 901 |
if !seen[p.Path()] { |
| 902 |
seen[p.Path()] = true |
| 903 |
filtered = append(filtered, p) |
| 904 |
} |
| 905 |
} |
| 906 |
return filtered |
| 907 |
} |
| 908 |
|
| 909 |
var ( |
| 910 |
cacheBusters []func(string) bool |
| 911 |
deletedDirs []string |
| 912 |
addedContentPaths []*paths.Path |
| 913 |
) |
| 914 |
|
| 915 |
var ( |
| 916 |
addedOrChangedContent []pathChange |
| 917 |
changes []identity.Identity |
| 918 |
) |
| 919 |
|
| 920 |
for _, ev := range eventInfos { |
| 921 |
cpss := h.BaseFs.ResolvePaths(ev.Name) |
| 922 |
pss := make([]*paths.Path, len(cpss)) |
| 923 |
for i, cps := range cpss { |
| 924 |
p := cps.Path |
| 925 |
if ev.removed && !paths.HasExt(p) { |
| 926 |
// Assume this is a renamed/removed directory. |
| 927 |
// For deletes, we walk up the tree to find the container (e.g. branch bundle), |
| 928 |
// so we will catch this even if it is a file without extension. |
| 929 |
// This avoids us walking up to the home page bundle for the common case |
| 930 |
// of renaming root sections. |
| 931 |
p = p + "/_index.md" |
| 932 |
deletedDirs = append(deletedDirs, cps.Path) |
| 933 |
} |
| 934 |
|
| 935 |
pss[i] = h.Configs.ContentPathParser.Parse(cps.Component, p) |
| 936 |
if ev.added && !ev.isChangedDir && cps.Component == files.ComponentFolderContent { |
| 937 |
addedContentPaths = append(addedContentPaths, pss[i]) |
| 938 |
} |
| 939 |
|
| 940 |
// Compile cache buster. |
| 941 |
np := hglob.NormalizePath(path.Join(cps.Component, cps.Path)) |
| 942 |
g, err := h.ResourceSpec.BuildConfig().MatchCacheBuster(h.Log, np) |
| 943 |
if err == nil && g != nil { |
| 944 |
cacheBusters = append(cacheBusters, g) |
| 945 |
} |
| 946 |
|
| 947 |
if ev.added { |
| 948 |
changes = append(changes, identity.StructuralChangeAdd) |
| 949 |
} |
| 950 |
if ev.removed { |
| 951 |
changes = append(changes, identity.StructuralChangeRemove) |
| 952 |
} |
| 953 |
} |
| 954 |
|
| 955 |
if ev.removed { |
| 956 |
changedPaths.deleted = append(changedPaths.deleted, pss...) |
| 957 |
} else if ev.isChangedDir { |
| 958 |
changedPaths.changedDirs = append(changedPaths.changedDirs, pss...) |
| 959 |
} else if ev.added { |
| 960 |
changedPaths.addedFiles = append(changedPaths.addedFiles, pss...) |
| 961 |
} else { |
| 962 |
changedPaths.changedFiles = append(changedPaths.changedFiles, pss...) |
| 963 |
} |
| 964 |
} |
| 965 |
|
| 966 |
// Find the most specific identity possible. |
| 967 |
handleChange := func(pathInfo *paths.Path, delete, add, isDir bool) { |
| 968 |
switch pathInfo.Component() { |
| 969 |
case files.ComponentFolderContent: |
| 970 |
logger.Println("Source changed", pathInfo.Path()) |
| 971 |
isContentDataFile := pathInfo.IsContentData() |
| 972 |
if !isContentDataFile { |
| 973 |
if ids := h.pageTrees.collectAndMarkStaleIdentities(pathInfo); len(ids) > 0 { |
| 974 |
changes = append(changes, ids...) |
| 975 |
} |
| 976 |
} else { |
| 977 |
h.pageTrees.treePagesFromTemplateAdapters.DeleteAllFunc(pathInfo.Base(), |
| 978 |
func(s string, n *pagesfromdata.PagesFromTemplate) bool { |
| 979 |
changes = append(changes, n.DependencyManager) |
| 980 |
|
| 981 |
// Try to open the file to see if has been deleted. |
| 982 |
f, err := n.GoTmplFi.Meta().Open() |
| 983 |
if err == nil { |
| 984 |
f.Close() |
| 985 |
} |
| 986 |
|
| 987 |
if err != nil { |
| 988 |
// Remove all pages and resources below. |
| 989 |
prefix := paths.AddTrailingSlash(pathInfo.Base()) |
| 990 |
|
| 991 |
h.pageTrees.treePages.DeletePrefixRaw(prefix) |
| 992 |
h.pageTrees.resourceTrees.DeletePrefixRaw(prefix) |
| 993 |
changes = append(changes, hglob.NewGlobIdentity(prefix+"**")) |
| 994 |
} |
| 995 |
return err != nil |
| 996 |
}) |
| 997 |
} |
| 998 |
|
| 999 |
needsPagesAssemble = true |
| 1000 |
|
| 1001 |
if config.RecentlyTouched != nil { |
| 1002 |
// Fast render mode. Adding them to the visited queue |
| 1003 |
// avoids rerendering them on navigation. |
| 1004 |
for _, id := range changes { |
| 1005 |
if p, ok := id.(page.Page); ok { |
| 1006 |
config.RecentlyTouched.Add(p.RelPermalink()) |
| 1007 |
} |
| 1008 |
} |
| 1009 |
} |
| 1010 |
|
| 1011 |
h.pageTrees.treeTaxonomyEntries.DeletePrefix("") |
| 1012 |
|
| 1013 |
if delete && !isContentDataFile { |
| 1014 |
_, ok := h.pageTrees.treePages.LongestPrefixRaw(pathInfo.Base()) |
| 1015 |
if ok { |
| 1016 |
h.pageTrees.treePages.DeletePrefixRaw(pathInfo.Base()) |
| 1017 |
h.pageTrees.resourceTrees.DeletePrefixRaw(pathInfo.Base()) |
| 1018 |
if pathInfo.IsBundle() { |
| 1019 |
// Assume directory removed. |
| 1020 |
h.pageTrees.treePages.DeletePrefixRaw(pathInfo.Base() + "/") |
| 1021 |
h.pageTrees.resourceTrees.DeletePrefixRaw(pathInfo.Base() + "/") |
| 1022 |
} |
| 1023 |
} else { |
| 1024 |
h.pageTrees.resourceTrees.DeletePrefixRaw(pathInfo.Base()) |
| 1025 |
} |
| 1026 |
} |
| 1027 |
|
| 1028 |
structural := delete |
| 1029 |
structural = structural || (add && pathInfo.IsLeafBundle()) |
| 1030 |
|
| 1031 |
addedOrChangedContent = append(addedOrChangedContent, pathChange{p: pathInfo, structural: structural, isDir: isDir}) |
| 1032 |
|
| 1033 |
case files.ComponentFolderLayouts: |
| 1034 |
tmplChanged = true |
| 1035 |
templatePath := pathInfo.Unnormalized().TrimLeadingSlash().PathNoLang() |
| 1036 |
if !h.GetTemplateStore().HasTemplate(templatePath) { |
| 1037 |
tmplAdded = true |
| 1038 |
} |
| 1039 |
|
| 1040 |
if tmplAdded { |
| 1041 |
logger.Println("Template added", pathInfo.Path()) |
| 1042 |
// A new template may require a more coarse grained build. |
| 1043 |
base := pathInfo.Base() |
| 1044 |
if strings.Contains(base, "_markup") { |
| 1045 |
// It's hard to determine the exact change set of this, |
| 1046 |
// so be very coarse grained. |
| 1047 |
changes = append(changes, identity.GenghisKhan) |
| 1048 |
} |
| 1049 |
if strings.Contains(base, "shortcodes") { |
| 1050 |
// Add both the shortcode file itself (for template refresh) and a glob for dependent content |
| 1051 |
changes = append(changes, pathInfo) |
| 1052 |
changes = append(changes, hglob.NewGlobIdentity(fmt.Sprintf("/_shortcodes/%s*", pathInfo.BaseNameNoIdentifier()))) |
| 1053 |
} else { |
| 1054 |
changes = append(changes, pathInfo) |
| 1055 |
} |
| 1056 |
} else { |
| 1057 |
logger.Println("Template changed", pathInfo.Path()) |
| 1058 |
id := h.GetTemplateStore().GetIdentity(pathInfo.Path()) |
| 1059 |
if id != nil { |
| 1060 |
changes = append(changes, id) |
| 1061 |
} else { |
| 1062 |
changes = append(changes, pathInfo) |
| 1063 |
} |
| 1064 |
} |
| 1065 |
case files.ComponentFolderAssets: |
| 1066 |
logger.Println("Asset changed", pathInfo.Path()) |
| 1067 |
changes = append(changes, pathInfo) |
| 1068 |
case files.ComponentFolderData: |
| 1069 |
logger.Println("Data changed", pathInfo.Path()) |
| 1070 |
|
| 1071 |
// This should cover all usage of hugo.Data. |
| 1072 |
// Currently very coarse grained. |
| 1073 |
changes = append(changes, siteidentities.Data) |
| 1074 |
h.init.data.Reset() |
| 1075 |
case files.ComponentFolderI18n: |
| 1076 |
logger.Println("i18n changed", pathInfo.Path()) |
| 1077 |
i18nChanged = true |
| 1078 |
// It's hard to determine the exact change set of this, |
| 1079 |
// so be very coarse grained for now. |
| 1080 |
changes = append(changes, identity.GenghisKhan) |
| 1081 |
case files.ComponentFolderArchetypes: |
| 1082 |
// Ignore for now. |
| 1083 |
case files.ComponentFolderStatic: |
| 1084 |
// Handled by the static file syncer. |
| 1085 |
default: |
| 1086 |
panic(fmt.Sprintf("unknown component: %q", pathInfo.Component())) |
| 1087 |
} |
| 1088 |
} |
| 1089 |
|
| 1090 |
changedPaths.deleted = removeDuplicatePaths(changedPaths.deleted) |
| 1091 |
changedPaths.addedFiles = removeDuplicatePaths(changedPaths.addedFiles) |
| 1092 |
changedPaths.changedFiles = removeDuplicatePaths(changedPaths.changedFiles) |
| 1093 |
|
| 1094 |
h.Log.Trace(logg.StringFunc(func() string { |
| 1095 |
var sb strings.Builder |
| 1096 |
sb.WriteString("Resolved paths:\n") |
| 1097 |
sb.WriteString("Deleted:\n") |
| 1098 |
for _, p := range changedPaths.deleted { |
| 1099 |
sb.WriteString("path: " + p.Path()) |
| 1100 |
sb.WriteString("\n") |
| 1101 |
} |
| 1102 |
sb.WriteString("Added:\n") |
| 1103 |
for _, p := range changedPaths.addedFiles { |
| 1104 |
sb.WriteString("path: " + p.Path()) |
| 1105 |
sb.WriteString("\n") |
| 1106 |
} |
| 1107 |
sb.WriteString("Changed:\n") |
| 1108 |
for _, p := range changedPaths.changedFiles { |
| 1109 |
sb.WriteString("path: " + p.Path()) |
| 1110 |
sb.WriteString("\n") |
| 1111 |
} |
| 1112 |
return sb.String() |
| 1113 |
})) |
| 1114 |
|
| 1115 |
for _, deletedDir := range deletedDirs { |
| 1116 |
prefix := deletedDir + "/" |
| 1117 |
predicate := func(id identity.Identity) bool { |
| 1118 |
// This will effectively reset all pages below this dir. |
| 1119 |
return strings.HasPrefix(paths.AddLeadingSlash(id.IdentifierBase()), prefix) |
| 1120 |
} |
| 1121 |
// Test in both directions. |
| 1122 |
changes = append(changes, identity.NewPredicateIdentity( |
| 1123 |
// Is dependent. |
| 1124 |
predicate, |
| 1125 |
// Is dependency. |
| 1126 |
predicate, |
| 1127 |
), |
| 1128 |
) |
| 1129 |
} |
| 1130 |
|
| 1131 |
if len(addedContentPaths) > 0 { |
| 1132 |
// These content files are new and not in use anywhere. |
| 1133 |
// To make sure that these gets listed in any site.RegularPages ranges or similar |
| 1134 |
// we could invalidate everything, but first try to collect a sample set |
| 1135 |
// from the surrounding pages. |
| 1136 |
var surroundingIDs []identity.Identity |
| 1137 |
for _, p := range addedContentPaths { |
| 1138 |
if ids := h.pageTrees.collectIdentitiesSurrounding(p.Base(), 10); len(ids) > 0 { |
| 1139 |
surroundingIDs = append(surroundingIDs, ids...) |
| 1140 |
} |
| 1141 |
} |
| 1142 |
|
| 1143 |
if len(surroundingIDs) > 0 { |
| 1144 |
changes = append(changes, surroundingIDs...) |
| 1145 |
} else { |
| 1146 |
// No surrounding pages found, so invalidate everything. |
| 1147 |
changes = append(changes, identity.GenghisKhan) |
| 1148 |
} |
| 1149 |
} |
| 1150 |
|
| 1151 |
for _, deleted := range changedPaths.deleted { |
| 1152 |
handleChange(deleted, true, false, false) |
| 1153 |
} |
| 1154 |
|
| 1155 |
for _, id := range changedPaths.addedFiles { |
| 1156 |
handleChange(id, false, true, false) |
| 1157 |
} |
| 1158 |
|
| 1159 |
for _, id := range changedPaths.changedFiles { |
| 1160 |
handleChange(id, false, false, false) |
| 1161 |
} |
| 1162 |
|
| 1163 |
for _, id := range changedPaths.changedDirs { |
| 1164 |
handleChange(id, false, false, true) |
| 1165 |
} |
| 1166 |
|
| 1167 |
for _, id := range changes { |
| 1168 |
if id == identity.GenghisKhan { |
| 1169 |
for i, cp := range addedOrChangedContent { |
| 1170 |
cp.structural = true |
| 1171 |
addedOrChangedContent[i] = cp |
| 1172 |
} |
| 1173 |
break |
| 1174 |
} |
| 1175 |
} |
| 1176 |
|
| 1177 |
resourceFiles := h.fileEventsContentPaths(addedOrChangedContent) |
| 1178 |
|
| 1179 |
changed := &WhatChanged{ |
| 1180 |
needsPagesAssembly: needsPagesAssemble, |
| 1181 |
} |
| 1182 |
changed.Add(changes...) |
| 1183 |
|
| 1184 |
config.WhatChanged = changed |
| 1185 |
|
| 1186 |
if err := init(config); err != nil { |
| 1187 |
return err |
| 1188 |
} |
| 1189 |
|
| 1190 |
var cacheBusterOr func(string) bool |
| 1191 |
if len(cacheBusters) > 0 { |
| 1192 |
cacheBusterOr = func(s string) bool { |
| 1193 |
for _, cb := range cacheBusters { |
| 1194 |
if cb(s) { |
| 1195 |
return true |
| 1196 |
} |
| 1197 |
} |
| 1198 |
return false |
| 1199 |
} |
| 1200 |
} |
| 1201 |
|
| 1202 |
changes2 := changed.Changes() |
| 1203 |
h.Deps.OnChangeListeners.Notify(changes2...) |
| 1204 |
|
| 1205 |
if err := h.resolveAndClearStateForIdentities(ctx, l, cacheBusterOr, changed.Drain()); err != nil { |
| 1206 |
return err |
| 1207 |
} |
| 1208 |
|
| 1209 |
if tmplChanged { |
| 1210 |
if err := loggers.TimeTrackfn(func() (logg.LevelLogger, error) { |
| 1211 |
depsFinder := identity.NewFinder(identity.FinderConfig{}) |
| 1212 |
ll := l.WithField("substep", "rebuild templates") |
| 1213 |
s := h.Sites[0] |
| 1214 |
if err := s.Deps.TemplateStore.RefreshFiles(func(fi hugofs.FileMetaInfo) bool { |
| 1215 |
pi := fi.Meta().PathInfo |
| 1216 |
for _, id := range changes2 { |
| 1217 |
if depsFinder.Contains(pi, id, -1) > 0 { |
| 1218 |
return true |
| 1219 |
} |
| 1220 |
} |
| 1221 |
return false |
| 1222 |
}); err != nil { |
| 1223 |
return ll, err |
| 1224 |
} |
| 1225 |
|
| 1226 |
return ll, nil |
| 1227 |
}); err != nil { |
| 1228 |
return err |
| 1229 |
} |
| 1230 |
} |
| 1231 |
|
| 1232 |
if i18nChanged { |
| 1233 |
if err := loggers.TimeTrackfn(func() (logg.LevelLogger, error) { |
| 1234 |
ll := l.WithField("substep", "rebuild i18n") |
| 1235 |
var prototype *deps.Deps |
| 1236 |
for i, s := range h.Sites { |
| 1237 |
if err := s.Deps.Compile(prototype); err != nil { |
| 1238 |
return ll, err |
| 1239 |
} |
| 1240 |
if i == 0 { |
| 1241 |
prototype = s.Deps |
| 1242 |
} |
| 1243 |
} |
| 1244 |
return ll, nil |
| 1245 |
}); err != nil { |
| 1246 |
return err |
| 1247 |
} |
| 1248 |
} |
| 1249 |
|
| 1250 |
if resourceFiles != nil { |
| 1251 |
if err := h.processFiles(ctx, l, config, resourceFiles...); err != nil { |
| 1252 |
return err |
| 1253 |
} |
| 1254 |
} |
| 1255 |
|
| 1256 |
if h.isRebuild() { |
| 1257 |
if err := h.processContentAdaptersOnRebuild(ctx, config); err != nil { |
| 1258 |
return err |
| 1259 |
} |
| 1260 |
} |
| 1261 |
|
| 1262 |
return nil |
| 1263 |
} |
| 1264 |
|
| 1265 |
func (h *HugoSites) LogServerAddresses() { |
| 1266 |
if h.hugoInfo.IsMultihost() { |
| 1267 |
for _, s := range h.Sites { |
| 1268 |
h.Log.Printf("Web Server is available at %s (bind address %s) %s\n", s.conf.C.BaseURL, s.conf.C.ServerInterface, s.Language().Lang) |
| 1269 |
} |
| 1270 |
} else { |
| 1271 |
s := h.Sites[0] |
| 1272 |
h.Log.Printf("Web Server is available at %s (bind address %s)\n", s.conf.C.BaseURL, s.conf.C.ServerInterface) |
| 1273 |
} |
| 1274 |
} |
| 1275 |
|
| 1276 |
func (h *HugoSites) processFull(ctx context.Context, l logg.LevelLogger, config *BuildCfg) (err error) { |
| 1277 |
if err = h.processFiles(ctx, l, config); err != nil { |
| 1278 |
err = fmt.Errorf("readAndProcessContent: %w", err) |
| 1279 |
return |
| 1280 |
} |
| 1281 |
return err |
| 1282 |
} |
| 1283 |
|
| 1284 |
func (s *Site) handleContentAdapterChanges(bi pagesfromdata.BuildInfo, buildConfig *BuildCfg) { |
| 1285 |
if !s.h.isRebuild() { |
| 1286 |
return |
| 1287 |
} |
| 1288 |
|
| 1289 |
if len(bi.ChangedIdentities) > 0 { |
| 1290 |
buildConfig.WhatChanged.Add(bi.ChangedIdentities...) |
| 1291 |
buildConfig.WhatChanged.needsPagesAssembly = true |
| 1292 |
} |
| 1293 |
|
| 1294 |
for _, p := range bi.DeletedPaths { |
| 1295 |
pp := paths.AddLeadingSlash(path.Join(bi.Path.Base(), p.Path)) |
| 1296 |
df := func(n contentNode) bool { |
| 1297 |
if len(p.Hashes) == 0 { |
| 1298 |
return true |
| 1299 |
} |
| 1300 |
if nn, ok := n.(contentNodeSourceEntryIDProvider); ok { |
| 1301 |
if i, ok := nn.nodeSourceEntryID().(uint64); ok && i != 0 { |
| 1302 |
if _, found := p.Hashes[i]; found { |
| 1303 |
return true |
| 1304 |
} |
| 1305 |
} |
| 1306 |
} |
| 1307 |
return false |
| 1308 |
} |
| 1309 |
|
| 1310 |
if v, count := s.pageMap.treePages.DeleteFuncRaw(pp, df); count > 0 { |
| 1311 |
buildConfig.WhatChanged.Add(cnh.GetIdentity(v)) |
| 1312 |
} |
| 1313 |
if v, count := s.pageMap.treeResources.DeleteFuncRaw(pp, df); count > 0 { |
| 1314 |
buildConfig.WhatChanged.Add(cnh.GetIdentity(v)) |
| 1315 |
|
| 1316 |
// A deleted resource may affect its parent page. |
| 1317 |
if _, v := s.pageMap.treePages.LongestPrefiValueRaw(pp); v != nil { |
| 1318 |
buildConfig.WhatChanged.Add(cnh.GetIdentity(v)) |
| 1319 |
} |
| 1320 |
} |
| 1321 |
} |
| 1322 |
} |
| 1323 |
|
| 1324 |
func (h *HugoSites) processContentAdaptersOnRebuild(ctx context.Context, buildConfig *BuildCfg) error { |
| 1325 |
g := rungroup.Run(ctx, rungroup.Config[*pagesfromdata.PagesFromTemplate]{ |
| 1326 |
NumWorkers: h.numWorkers, |
| 1327 |
Handle: func(ctx context.Context, p *pagesfromdata.PagesFromTemplate) error { |
| 1328 |
bi, err := p.Execute(ctx) |
| 1329 |
if err != nil { |
| 1330 |
return err |
| 1331 |
} |
| 1332 |
s := p.Site.(*Site) |
| 1333 |
s.handleContentAdapterChanges(bi, buildConfig) |
| 1334 |
return nil |
| 1335 |
}, |
| 1336 |
}) |
| 1337 |
|
| 1338 |
h.pageTrees.treePagesFromTemplateAdapters.WalkPrefixRaw(doctree.LockTypeRead, "", func(key string, p *pagesfromdata.PagesFromTemplate) (bool, error) { |
| 1339 |
if p.StaleVersion() > 0 { |
| 1340 |
g.Enqueue(p) |
| 1341 |
} |
| 1342 |
return false, nil |
| 1343 |
}) |
| 1344 |
|
| 1345 |
return g.Wait() |
| 1346 |
} |
| 1347 |
|
| 1348 |
func (s *HugoSites) processFiles(ctx context.Context, l logg.LevelLogger, buildConfig *BuildCfg, filenames ...pathChange) error { |
| 1349 |
if s.Deps == nil { |
| 1350 |
panic("nil deps on site") |
| 1351 |
} |
| 1352 |
|
| 1353 |
sourceSpec := source.NewSourceSpec(s.PathSpec, buildConfig.ContentInclusionFilter, s.BaseFs.Content.Fs) |
| 1354 |
|
| 1355 |
// For inserts, we can pick an arbitrary pageMap. |
| 1356 |
pageMap := s.Sites[0].pageMap |
| 1357 |
|
| 1358 |
c := newPagesCollector(ctx, s.h, sourceSpec, s.Log, l, pageMap, buildConfig, filenames) |
| 1359 |
|
| 1360 |
if err := c.Collect(); err != nil { |
| 1361 |
return err |
| 1362 |
} |
| 1363 |
|
| 1364 |
return nil |
| 1365 |
} |