| 1 |
// Copyright 2025 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 deps |
| 15 |
|
| 16 |
import ( |
| 17 |
"context" |
| 18 |
"fmt" |
| 19 |
"io" |
| 20 |
"os" |
| 21 |
"path/filepath" |
| 22 |
"sort" |
| 23 |
"strings" |
| 24 |
"sync" |
| 25 |
"sync/atomic" |
| 26 |
|
| 27 |
"github.com/bep/logg" |
| 28 |
"github.com/gohugoio/hugo/cache/dynacache" |
| 29 |
"github.com/gohugoio/hugo/cache/filecache" |
| 30 |
"github.com/gohugoio/hugo/common/hexec" |
| 31 |
"github.com/gohugoio/hugo/common/hmaps" |
| 32 |
"github.com/gohugoio/hugo/common/loggers" |
| 33 |
"github.com/gohugoio/hugo/common/types" |
| 34 |
"github.com/gohugoio/hugo/config" |
| 35 |
"github.com/gohugoio/hugo/config/allconfig" |
| 36 |
"github.com/gohugoio/hugo/config/security" |
| 37 |
"github.com/gohugoio/hugo/helpers" |
| 38 |
"github.com/gohugoio/hugo/hugofs" |
| 39 |
"github.com/gohugoio/hugo/identity" |
| 40 |
"github.com/gohugoio/hugo/internal/js" |
| 41 |
"github.com/gohugoio/hugo/internal/warpc" |
| 42 |
"github.com/gohugoio/hugo/media" |
| 43 |
"github.com/gohugoio/hugo/resources/page" |
| 44 |
"github.com/gohugoio/hugo/resources/postpub" |
| 45 |
"github.com/gohugoio/hugo/tpl/tplimpl" |
| 46 |
|
| 47 |
"github.com/gohugoio/hugo/metrics" |
| 48 |
"github.com/gohugoio/hugo/resources" |
| 49 |
"github.com/gohugoio/hugo/source" |
| 50 |
"github.com/gohugoio/hugo/tpl" |
| 51 |
"github.com/spf13/afero" |
| 52 |
) |
| 53 |
|
| 54 |
// Deps holds dependencies used by many. |
| 55 |
// There will be normally only one instance of deps in play |
| 56 |
// at a given time, i.e. one per Site built. |
| 57 |
type Deps struct { |
| 58 |
// The logger to use. |
| 59 |
Log loggers.Logger `json:"-"` |
| 60 |
|
| 61 |
ExecHelper *hexec.Exec |
| 62 |
|
| 63 |
// The file systems to use. |
| 64 |
Fs *hugofs.Fs `json:"-"` |
| 65 |
|
| 66 |
// The PathSpec to use |
| 67 |
*helpers.PathSpec `json:"-"` |
| 68 |
|
| 69 |
// The ContentSpec to use |
| 70 |
*helpers.ContentSpec `json:"-"` |
| 71 |
|
| 72 |
// The SourceSpec to use |
| 73 |
SourceSpec *source.SourceSpec `json:"-"` |
| 74 |
|
| 75 |
// The Resource Spec to use |
| 76 |
ResourceSpec *resources.Spec |
| 77 |
|
| 78 |
// The configuration to use |
| 79 |
Conf config.AllProvider `json:"-"` |
| 80 |
|
| 81 |
// The memory cache to use. |
| 82 |
MemCache *dynacache.Cache |
| 83 |
|
| 84 |
// The translation func to use |
| 85 |
Translate func(ctx context.Context, translationID string, templateData any) string `json:"-"` |
| 86 |
|
| 87 |
// The site building. |
| 88 |
Site page.Site |
| 89 |
|
| 90 |
TemplateStore *tplimpl.TemplateStore |
| 91 |
|
| 92 |
// Used in tests |
| 93 |
OverloadedTemplateFuncs map[string]any |
| 94 |
|
| 95 |
TranslationProvider ResourceProvider |
| 96 |
|
| 97 |
Metrics metrics.Provider |
| 98 |
|
| 99 |
// BuildStartListeners will be notified before a build starts. |
| 100 |
BuildStartListeners *Listeners[any] |
| 101 |
|
| 102 |
// BuildEndListeners will be notified after a build finishes. |
| 103 |
BuildEndListeners *Listeners[any] |
| 104 |
|
| 105 |
// OnChangeListeners will be notified when something changes. |
| 106 |
OnChangeListeners *Listeners[identity.Identity] |
| 107 |
|
| 108 |
// Resources that gets closed when the build is done or the server shuts down. |
| 109 |
BuildClosers *types.Closers |
| 110 |
|
| 111 |
// This is common/global for all sites. |
| 112 |
BuildState *BuildState |
| 113 |
|
| 114 |
// Misc counters. |
| 115 |
Counters *Counters |
| 116 |
|
| 117 |
// Holds RPC dispatchers for Katex etc. |
| 118 |
// TODO(bep) rethink this re. a plugin setup, but this will have to do for now. |
| 119 |
WasmDispatchers *warpc.Dispatchers |
| 120 |
|
| 121 |
// The JS batcher client. |
| 122 |
JSBatcherClient js.BatcherClient |
| 123 |
|
| 124 |
isClosed bool |
| 125 |
|
| 126 |
*globalErrHandler |
| 127 |
} |
| 128 |
|
| 129 |
func (d Deps) Clone(s page.Site, conf config.AllProvider) (*Deps, error) { |
| 130 |
d.Conf = conf |
| 131 |
d.Site = s |
| 132 |
d.ExecHelper = nil |
| 133 |
d.ContentSpec = nil |
| 134 |
|
| 135 |
if err := d.Init(); err != nil { |
| 136 |
return nil, err |
| 137 |
} |
| 138 |
|
| 139 |
return &d, nil |
| 140 |
} |
| 141 |
|
| 142 |
func (d *Deps) GetTemplateStore() *tplimpl.TemplateStore { |
| 143 |
return d.TemplateStore |
| 144 |
} |
| 145 |
|
| 146 |
func (d *Deps) Init() error { |
| 147 |
if d.Conf == nil { |
| 148 |
panic("conf is nil") |
| 149 |
} |
| 150 |
|
| 151 |
if d.Fs == nil { |
| 152 |
// For tests. |
| 153 |
d.Fs = hugofs.NewFrom(afero.NewMemMapFs(), d.Conf.BaseConfig()) |
| 154 |
} |
| 155 |
|
| 156 |
if d.Log == nil { |
| 157 |
d.Log = loggers.NewDefault() |
| 158 |
} |
| 159 |
|
| 160 |
if d.globalErrHandler == nil { |
| 161 |
d.globalErrHandler = &globalErrHandler{ |
| 162 |
logger: d.Log, |
| 163 |
} |
| 164 |
} |
| 165 |
if d.BuildState == nil { |
| 166 |
d.BuildState = &BuildState{} |
| 167 |
} |
| 168 |
if d.Counters == nil { |
| 169 |
d.Counters = &Counters{} |
| 170 |
} |
| 171 |
if d.BuildState.DeferredExecutions == nil { |
| 172 |
if d.BuildState.DeferredExecutionsGroupedByRenderingContext == nil { |
| 173 |
d.BuildState.DeferredExecutionsGroupedByRenderingContext = make(map[tpl.RenderingContext]*DeferredExecutions) |
| 174 |
} |
| 175 |
d.BuildState.DeferredExecutions = &DeferredExecutions{ |
| 176 |
Executions: hmaps.NewCache[string, *tpl.DeferredExecution](), |
| 177 |
FilenamesWithPostPrefix: hmaps.NewCache[string, bool](), |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
if d.BuildStartListeners == nil { |
| 182 |
d.BuildStartListeners = &Listeners[any]{} |
| 183 |
} |
| 184 |
|
| 185 |
if d.BuildEndListeners == nil { |
| 186 |
d.BuildEndListeners = &Listeners[any]{} |
| 187 |
} |
| 188 |
|
| 189 |
if d.BuildClosers == nil { |
| 190 |
d.BuildClosers = &types.Closers{} |
| 191 |
} |
| 192 |
|
| 193 |
if d.OnChangeListeners == nil { |
| 194 |
d.OnChangeListeners = &Listeners[identity.Identity]{} |
| 195 |
} |
| 196 |
|
| 197 |
if d.Metrics == nil && d.Conf.TemplateMetrics() { |
| 198 |
d.Metrics = metrics.NewProvider(d.Conf.TemplateMetricsHints()) |
| 199 |
} |
| 200 |
|
| 201 |
if d.ExecHelper == nil { |
| 202 |
d.ExecHelper = hexec.New(d.Conf.GetConfigSection("security").(security.Config), d.Conf.WorkingDir(), d.Log) |
| 203 |
} |
| 204 |
|
| 205 |
if d.MemCache == nil { |
| 206 |
d.MemCache = dynacache.New(dynacache.Options{Watching: d.Conf.Watching(), Log: d.Log}) |
| 207 |
} |
| 208 |
|
| 209 |
if d.PathSpec == nil { |
| 210 |
hashBytesReceiverFunc := func(name string, match []byte) { |
| 211 |
s := string(match) |
| 212 |
switch s { |
| 213 |
case postpub.PostProcessPrefix: |
| 214 |
d.BuildState.AddFilenameWithPostPrefix(name) |
| 215 |
case tpl.HugoDeferredTemplatePrefix: |
| 216 |
d.BuildState.DeferredExecutions.FilenamesWithPostPrefix.Set(name, true) |
| 217 |
} |
| 218 |
} |
| 219 |
|
| 220 |
// Skip binary files. |
| 221 |
mediaTypes := d.Conf.GetConfigSection("mediaTypes").(media.Types) |
| 222 |
hashBytesShouldCheck := func(name string) bool { |
| 223 |
ext := strings.TrimPrefix(filepath.Ext(name), ".") |
| 224 |
return mediaTypes.IsTextSuffix(ext) |
| 225 |
} |
| 226 |
d.Fs.PublishDir = hugofs.NewHasBytesReceiver( |
| 227 |
d.Fs.PublishDir, |
| 228 |
hashBytesShouldCheck, |
| 229 |
hashBytesReceiverFunc, |
| 230 |
[]byte(tpl.HugoDeferredTemplatePrefix), |
| 231 |
[]byte(postpub.PostProcessPrefix)) |
| 232 |
|
| 233 |
pathSpec, err := helpers.NewPathSpec(d.Fs, d.Conf, d.Log, nil) |
| 234 |
if err != nil { |
| 235 |
return err |
| 236 |
} |
| 237 |
d.PathSpec = pathSpec |
| 238 |
} else { |
| 239 |
var err error |
| 240 |
d.PathSpec, err = helpers.NewPathSpec(d.Fs, d.Conf, d.Log, d.PathSpec.BaseFs) |
| 241 |
if err != nil { |
| 242 |
return err |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
d.ExecHelper.SetNodeReadPaths(d.BaseFs.Assets.RealPaths("")) |
| 247 |
|
| 248 |
if d.ContentSpec == nil { |
| 249 |
contentSpec, err := helpers.NewContentSpec(d.Conf, d.Log, d.Content.Fs, d.ExecHelper) |
| 250 |
if err != nil { |
| 251 |
return err |
| 252 |
} |
| 253 |
d.ContentSpec = contentSpec |
| 254 |
} |
| 255 |
|
| 256 |
if d.SourceSpec == nil { |
| 257 |
d.SourceSpec = source.NewSourceSpec(d.PathSpec, nil, d.Fs.Source) |
| 258 |
} |
| 259 |
|
| 260 |
var common *resources.SpecCommon |
| 261 |
if d.ResourceSpec != nil { |
| 262 |
common = d.ResourceSpec.SpecCommon |
| 263 |
} |
| 264 |
|
| 265 |
d.Cfg.BaseConfig() |
| 266 |
|
| 267 |
fileCaches := d.Cfg.FileCaches().(filecache.Caches) |
| 268 |
fileCaches.SetResourceFs(d.BaseFs.ResourcesCache) |
| 269 |
|
| 270 |
resourceSpec, err := resources.NewSpec(d.PathSpec, common, d.WasmDispatchers, fileCaches, d.MemCache, d.BuildState, d.Log, d, d.ExecHelper, d.BuildClosers, d.BuildState) |
| 271 |
if err != nil { |
| 272 |
return fmt.Errorf("failed to create resource spec: %w", err) |
| 273 |
} |
| 274 |
d.ResourceSpec = resourceSpec |
| 275 |
|
| 276 |
return nil |
| 277 |
} |
| 278 |
|
| 279 |
// TODO(bep) rework this to get it in line with how we manage templates. |
| 280 |
func (d *Deps) Compile(prototype *Deps) error { |
| 281 |
var err error |
| 282 |
if prototype == nil { |
| 283 |
|
| 284 |
if err = d.TranslationProvider.NewResource(d); err != nil { |
| 285 |
return err |
| 286 |
} |
| 287 |
return nil |
| 288 |
} |
| 289 |
|
| 290 |
if err = d.TranslationProvider.CloneResource(d, prototype); err != nil { |
| 291 |
return err |
| 292 |
} |
| 293 |
|
| 294 |
return nil |
| 295 |
} |
| 296 |
|
| 297 |
// MkdirTemp returns a temporary directory path that will be cleaned up on exit. |
| 298 |
func (d Deps) MkdirTemp(pattern string) (string, error) { |
| 299 |
filename, err := os.MkdirTemp("", pattern) |
| 300 |
if err != nil { |
| 301 |
return "", err |
| 302 |
} |
| 303 |
d.BuildClosers.Add( |
| 304 |
types.CloserFunc( |
| 305 |
func() error { |
| 306 |
return os.RemoveAll(filename) |
| 307 |
}, |
| 308 |
), |
| 309 |
) |
| 310 |
|
| 311 |
return filename, nil |
| 312 |
} |
| 313 |
|
| 314 |
type globalErrHandler struct { |
| 315 |
logger loggers.Logger |
| 316 |
|
| 317 |
// Channel for some "hard to get to" build errors |
| 318 |
buildErrors chan error |
| 319 |
// Used to signal that the build is done. |
| 320 |
quit chan struct{} |
| 321 |
} |
| 322 |
|
| 323 |
// SendError sends the error on a channel to be handled later. |
| 324 |
// This can be used in situations where returning and aborting the current |
| 325 |
// operation isn't practical. |
| 326 |
func (e *globalErrHandler) SendError(err error) { |
| 327 |
if e.buildErrors != nil { |
| 328 |
select { |
| 329 |
case <-e.quit: |
| 330 |
case e.buildErrors <- err: |
| 331 |
default: |
| 332 |
} |
| 333 |
return |
| 334 |
} |
| 335 |
e.logger.Errorln(err) |
| 336 |
} |
| 337 |
|
| 338 |
func (e *globalErrHandler) StartErrorCollector() chan error { |
| 339 |
e.quit = make(chan struct{}) |
| 340 |
e.buildErrors = make(chan error, 10) |
| 341 |
return e.buildErrors |
| 342 |
} |
| 343 |
|
| 344 |
func (e *globalErrHandler) StopErrorCollector() { |
| 345 |
if e.buildErrors != nil { |
| 346 |
close(e.quit) |
| 347 |
close(e.buildErrors) |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
// Listeners represents an event listener. |
| 352 |
type Listeners[T any] struct { |
| 353 |
sync.Mutex |
| 354 |
|
| 355 |
// A list of funcs to be notified about an event. |
| 356 |
// If the return value is true, the listener will be removed. |
| 357 |
listeners []func(...T) bool |
| 358 |
} |
| 359 |
|
| 360 |
// Add adds a function to a Listeners instance. |
| 361 |
func (b *Listeners[T]) Add(f func(...T) bool) { |
| 362 |
if b == nil { |
| 363 |
return |
| 364 |
} |
| 365 |
b.Lock() |
| 366 |
defer b.Unlock() |
| 367 |
b.listeners = append(b.listeners, f) |
| 368 |
} |
| 369 |
|
| 370 |
// Notify executes all listener functions. |
| 371 |
func (b *Listeners[T]) Notify(vs ...T) { |
| 372 |
b.Lock() |
| 373 |
defer b.Unlock() |
| 374 |
temp := b.listeners[:0] |
| 375 |
for _, notify := range b.listeners { |
| 376 |
if !notify(vs...) { |
| 377 |
temp = append(temp, notify) |
| 378 |
} |
| 379 |
} |
| 380 |
b.listeners = temp |
| 381 |
} |
| 382 |
|
| 383 |
// ResourceProvider is used to create and refresh, and clone resources needed. |
| 384 |
type ResourceProvider interface { |
| 385 |
NewResource(dst *Deps) error |
| 386 |
CloneResource(dst, src *Deps) error |
| 387 |
} |
| 388 |
|
| 389 |
func (d *Deps) Close() error { |
| 390 |
if d.isClosed { |
| 391 |
return nil |
| 392 |
} |
| 393 |
d.isClosed = true |
| 394 |
|
| 395 |
if d.MemCache != nil { |
| 396 |
d.MemCache.Stop() |
| 397 |
} |
| 398 |
if d.WasmDispatchers != nil { |
| 399 |
d.WasmDispatchers.Close() |
| 400 |
} |
| 401 |
return d.BuildClosers.Close() |
| 402 |
} |
| 403 |
|
| 404 |
// DepsCfg contains configuration options that can be used to configure Hugo |
| 405 |
// on a global level, i.e. logging etc. |
| 406 |
// Nil values will be given default values. |
| 407 |
type DepsCfg struct { |
| 408 |
// The logger to use. Only set in some tests. |
| 409 |
// TODO(bep) get rid of this. |
| 410 |
TestLogger loggers.Logger |
| 411 |
|
| 412 |
// The logging level to use. |
| 413 |
LogLevel logg.Level |
| 414 |
|
| 415 |
// Logging output. |
| 416 |
StdErr io.Writer |
| 417 |
|
| 418 |
// The console output. |
| 419 |
StdOut io.Writer |
| 420 |
|
| 421 |
// The file systems to use |
| 422 |
Fs *hugofs.Fs |
| 423 |
|
| 424 |
// The Site in use |
| 425 |
Site page.Site |
| 426 |
|
| 427 |
Configs *allconfig.Configs |
| 428 |
|
| 429 |
// Template handling. |
| 430 |
TemplateProvider ResourceProvider |
| 431 |
|
| 432 |
// i18n handling. |
| 433 |
TranslationProvider ResourceProvider |
| 434 |
|
| 435 |
// Build triggered by the IntegrationTest framework. |
| 436 |
IsIntegrationTest bool |
| 437 |
|
| 438 |
// TestCfg holds configuration used only in tests. |
| 439 |
// It is a programming error to set this when IsIntegrationTest is not set, |
| 440 |
// and doing so will panic. |
| 441 |
TestCfg TestConfig |
| 442 |
|
| 443 |
// ChangesFromBuild for changes passed back to the server/watch process. |
| 444 |
ChangesFromBuild chan []identity.Identity |
| 445 |
} |
| 446 |
|
| 447 |
// TestConfig holds configuration used only in tests. |
| 448 |
// See DepsCfg.TestCfg. |
| 449 |
type TestConfig struct { |
| 450 |
// WarpcMemory, if set, overrides the memory limit in MiB for the WASM based |
| 451 |
// image processors (WebP and AVIF). Used to provoke memory allocation failures. |
| 452 |
WarpcMemory int |
| 453 |
} |
| 454 |
|
| 455 |
// IsZero reports whether c holds no test configuration. |
| 456 |
func (c TestConfig) IsZero() bool { |
| 457 |
return c == TestConfig{} |
| 458 |
} |
| 459 |
|
| 460 |
// BuildState are state used during a build. |
| 461 |
type BuildState struct { |
| 462 |
counter atomic.Uint64 |
| 463 |
|
| 464 |
// Tracks invocations of the Build method. |
| 465 |
BuildCounter atomic.Uint64 |
| 466 |
|
| 467 |
mu sync.Mutex // protects state below. |
| 468 |
|
| 469 |
OnSignalRebuild func(ids ...identity.Identity) |
| 470 |
|
| 471 |
// A set of filenames in /public that |
| 472 |
// contains a post-processing prefix. |
| 473 |
filenamesWithPostPrefix map[string]bool |
| 474 |
|
| 475 |
DeferredExecutions *DeferredExecutions |
| 476 |
|
| 477 |
// Deferred executions grouped by rendering context. |
| 478 |
DeferredExecutionsGroupedByRenderingContext map[tpl.RenderingContext]*DeferredExecutions |
| 479 |
} |
| 480 |
|
| 481 |
// Misc counters. |
| 482 |
type Counters struct { |
| 483 |
// Counter for the math.Counter function. |
| 484 |
MathCounter atomic.Uint64 |
| 485 |
} |
| 486 |
|
| 487 |
type DeferredExecutions struct { |
| 488 |
// A set of filenames in /public that |
| 489 |
// contains a post-processing prefix. |
| 490 |
FilenamesWithPostPrefix *hmaps.Cache[string, bool] |
| 491 |
|
| 492 |
// Maps a placeholder to a deferred execution. |
| 493 |
Executions *hmaps.Cache[string, *tpl.DeferredExecution] |
| 494 |
} |
| 495 |
|
| 496 |
var _ identity.SignalRebuilder = (*BuildState)(nil) |
| 497 |
|
| 498 |
// IsRebuild reports whether this is a rebuild. |
| 499 |
func (b *BuildState) IsRebuild() bool { |
| 500 |
return b.BuildCounter.Load() > 0 |
| 501 |
} |
| 502 |
|
| 503 |
// StartStageRender will be called before a stage is rendered. |
| 504 |
func (b *BuildState) StartStageRender(stage tpl.RenderingContext) { |
| 505 |
} |
| 506 |
|
| 507 |
// StopStageRender will be called after a stage is rendered. |
| 508 |
func (b *BuildState) StopStageRender(stage tpl.RenderingContext) { |
| 509 |
b.DeferredExecutionsGroupedByRenderingContext[stage] = b.DeferredExecutions |
| 510 |
b.DeferredExecutions = &DeferredExecutions{ |
| 511 |
Executions: hmaps.NewCache[string, *tpl.DeferredExecution](), |
| 512 |
FilenamesWithPostPrefix: hmaps.NewCache[string, bool](), |
| 513 |
} |
| 514 |
} |
| 515 |
|
| 516 |
func (b *BuildState) SignalRebuild(ids ...identity.Identity) { |
| 517 |
b.OnSignalRebuild(ids...) |
| 518 |
} |
| 519 |
|
| 520 |
func (b *BuildState) AddFilenameWithPostPrefix(filename string) { |
| 521 |
b.mu.Lock() |
| 522 |
defer b.mu.Unlock() |
| 523 |
if b.filenamesWithPostPrefix == nil { |
| 524 |
b.filenamesWithPostPrefix = make(map[string]bool) |
| 525 |
} |
| 526 |
b.filenamesWithPostPrefix[filename] = true |
| 527 |
} |
| 528 |
|
| 529 |
func (b *BuildState) GetFilenamesWithPostPrefix() []string { |
| 530 |
b.mu.Lock() |
| 531 |
defer b.mu.Unlock() |
| 532 |
var filenames []string |
| 533 |
for filename := range b.filenamesWithPostPrefix { |
| 534 |
filenames = append(filenames, filename) |
| 535 |
} |
| 536 |
sort.Strings(filenames) |
| 537 |
return filenames |
| 538 |
} |
| 539 |
|
| 540 |
func (b *BuildState) Incr() int { |
| 541 |
return int(b.counter.Add(uint64(1))) |
| 542 |
} |