| 1 |
// Copyright 2019 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 config |
| 15 |
|
| 16 |
import ( |
| 17 |
"fmt" |
| 18 |
"net/http" |
| 19 |
"regexp" |
| 20 |
"slices" |
| 21 |
"sort" |
| 22 |
"strings" |
| 23 |
|
| 24 |
"github.com/bep/logg" |
| 25 |
"github.com/gobwas/glob" |
| 26 |
"github.com/gohugoio/hugo/common/hstrings" |
| 27 |
"github.com/gohugoio/hugo/common/loggers" |
| 28 |
"github.com/gohugoio/hugo/common/predicate" |
| 29 |
"github.com/gohugoio/hugo/common/types" |
| 30 |
"github.com/gohugoio/hugo/hugofs/hglob" |
| 31 |
|
| 32 |
"github.com/gohugoio/hugo/common/herrors" |
| 33 |
"github.com/mitchellh/mapstructure" |
| 34 |
"github.com/spf13/cast" |
| 35 |
) |
| 36 |
|
| 37 |
type BaseConfig struct { |
| 38 |
WorkingDir string |
| 39 |
CacheDir string |
| 40 |
ThemesDir string |
| 41 |
PublishDir string |
| 42 |
} |
| 43 |
|
| 44 |
type CommonDirs struct { |
| 45 |
// The directory where Hugo will look for themes. |
| 46 |
ThemesDir string |
| 47 |
|
| 48 |
// Where to put the generated files. |
| 49 |
PublishDir string |
| 50 |
|
| 51 |
// The directory to put the generated resources files. This directory should in most situations be considered temporary |
| 52 |
// and not be committed to version control. But there may be cached content in here that you want to keep, |
| 53 |
// e.g. resources/_gen/images for performance reasons or CSS built from SASS when your CI server doesn't have the full setup. |
| 54 |
ResourceDir string |
| 55 |
|
| 56 |
// The project root directory. |
| 57 |
WorkingDir string |
| 58 |
|
| 59 |
// The root directory for all cache files. |
| 60 |
CacheDir string |
| 61 |
|
| 62 |
// The content source directory. |
| 63 |
// Deprecated: Use module mounts. |
| 64 |
ContentDir string |
| 65 |
// Deprecated: Use module mounts. |
| 66 |
// The data source directory. |
| 67 |
DataDir string |
| 68 |
// Deprecated: Use module mounts. |
| 69 |
// The layout source directory. |
| 70 |
LayoutDir string |
| 71 |
// Deprecated: Use module mounts. |
| 72 |
// The i18n source directory. |
| 73 |
I18nDir string |
| 74 |
// Deprecated: Use module mounts. |
| 75 |
// The archetypes source directory. |
| 76 |
ArcheTypeDir string |
| 77 |
// Deprecated: Use module mounts. |
| 78 |
// The assets source directory. |
| 79 |
AssetDir string |
| 80 |
} |
| 81 |
|
| 82 |
type LoadConfigResult struct { |
| 83 |
Cfg Provider |
| 84 |
ConfigFiles []string |
| 85 |
BaseConfig BaseConfig |
| 86 |
} |
| 87 |
|
| 88 |
var defaultBuild = BuildConfig{ |
| 89 |
UseResourceCacheWhen: "fallback", |
| 90 |
BuildStats: BuildStats{}, |
| 91 |
CleanDestinationDir: CleanDestinationDir{ |
| 92 |
KeepFiles: []string{"{**/,}.{git,gitignore,gitattributes}"}, |
| 93 |
KeepDirs: []string{"{**/,}.*"}, |
| 94 |
}, |
| 95 |
|
| 96 |
CacheBusters: []CacheBuster{ |
| 97 |
{ |
| 98 |
Source: `(postcss|tailwind)\.config\.(js|mjs|cjs)`, |
| 99 |
Target: cssTargetCachebusterRe, |
| 100 |
}, |
| 101 |
}, |
| 102 |
} |
| 103 |
|
| 104 |
// BuildConfig holds some build related configuration. |
| 105 |
type BuildConfig struct { |
| 106 |
// When to use the resource file cache. |
| 107 |
// One of never, fallback, always. Default is fallback |
| 108 |
UseResourceCacheWhen string |
| 109 |
|
| 110 |
// When enabled, will collect and write a hugo_stats.json with some build |
| 111 |
// related aggregated data (e.g. CSS class names). |
| 112 |
// Note that this was a bool <= v0.115.0. |
| 113 |
BuildStats BuildStats |
| 114 |
|
| 115 |
// Can be used to toggle off writing of the IntelliSense /assets/jsconfig.js |
| 116 |
// file. |
| 117 |
NoJSConfigInAssets bool |
| 118 |
|
| 119 |
// Can used to control how the resource cache gets evicted on rebuilds. |
| 120 |
CacheBusters []CacheBuster |
| 121 |
|
| 122 |
// Removes files from the publish directory that are not found in the static source. |
| 123 |
CleanDestinationDir CleanDestinationDir |
| 124 |
} |
| 125 |
|
| 126 |
// CleanDestinationDir configures the removal of stale files from the publish directory. |
| 127 |
type CleanDestinationDir struct { |
| 128 |
// Whether to remove stale files. Can also be enabled with the --cleanDestinationDir flag. |
| 129 |
Enable bool |
| 130 |
|
| 131 |
// Glob patterns of files to keep, matched against the slash separated path relative to the publish directory, e.g. "dir/.gitignore". |
| 132 |
// A pattern prefixed with "! " is a negation. |
| 133 |
KeepFiles []string |
| 134 |
|
| 135 |
// Glob patterns of directories to keep with all of their content. |
| 136 |
KeepDirs []string |
| 137 |
|
| 138 |
keepFiles predicate.P[string] |
| 139 |
keepDirs predicate.P[string] |
| 140 |
} |
| 141 |
|
| 142 |
// Keep reports whether path, relative to the publish directory, should be kept. |
| 143 |
func (c CleanDestinationDir) Keep(path string, isDir bool) bool { |
| 144 |
if isDir { |
| 145 |
return c.keepDirs(path) |
| 146 |
} |
| 147 |
return c.keepFiles(path) |
| 148 |
} |
| 149 |
|
| 150 |
func (c *CleanDestinationDir) compile() error { |
| 151 |
var err error |
| 152 |
if c.keepFiles, err = predicate.NewStringPredicateFromGlobs(c.KeepFiles, hglob.GetGlob); err != nil { |
| 153 |
return err |
| 154 |
} |
| 155 |
c.keepDirs, err = predicate.NewStringPredicateFromGlobs(c.KeepDirs, hglob.GetGlob) |
| 156 |
return err |
| 157 |
} |
| 158 |
|
| 159 |
// BuildStats configures if and what to write to the hugo_stats.json file. |
| 160 |
type BuildStats struct { |
| 161 |
Enable bool |
| 162 |
DisableTags bool |
| 163 |
DisableClasses bool |
| 164 |
DisableIDs bool |
| 165 |
} |
| 166 |
|
| 167 |
func (w BuildStats) Enabled() bool { |
| 168 |
if !w.Enable { |
| 169 |
return false |
| 170 |
} |
| 171 |
return !w.DisableTags || !w.DisableClasses || !w.DisableIDs |
| 172 |
} |
| 173 |
|
| 174 |
func (b BuildConfig) clone() BuildConfig { |
| 175 |
b.CacheBusters = slices.Clone(b.CacheBusters) |
| 176 |
b.CleanDestinationDir.KeepFiles = slices.Clone(b.CleanDestinationDir.KeepFiles) |
| 177 |
b.CleanDestinationDir.KeepDirs = slices.Clone(b.CleanDestinationDir.KeepDirs) |
| 178 |
return b |
| 179 |
} |
| 180 |
|
| 181 |
func (b BuildConfig) UseResourceCache(err error) bool { |
| 182 |
if b.UseResourceCacheWhen == "never" { |
| 183 |
return false |
| 184 |
} |
| 185 |
|
| 186 |
if b.UseResourceCacheWhen == "fallback" { |
| 187 |
return herrors.IsFeatureNotAvailableError(err) |
| 188 |
} |
| 189 |
|
| 190 |
return true |
| 191 |
} |
| 192 |
|
| 193 |
// MatchCacheBuster returns the cache buster for the given path p, nil if none. |
| 194 |
func (s BuildConfig) MatchCacheBuster(logger loggers.Logger, p string) (func(string) bool, error) { |
| 195 |
var matchers []func(string) bool |
| 196 |
for _, cb := range s.CacheBusters { |
| 197 |
if matcher := cb.compiledSource(p); matcher != nil { |
| 198 |
matchers = append(matchers, matcher) |
| 199 |
} |
| 200 |
} |
| 201 |
if len(matchers) > 0 { |
| 202 |
return func(cacheKey string) bool { |
| 203 |
for _, m := range matchers { |
| 204 |
if m(cacheKey) { |
| 205 |
return true |
| 206 |
} |
| 207 |
} |
| 208 |
return false |
| 209 |
}, nil |
| 210 |
} |
| 211 |
return nil, nil |
| 212 |
} |
| 213 |
|
| 214 |
func (b *BuildConfig) CompileConfig(logger loggers.Logger) error { |
| 215 |
for i, cb := range b.CacheBusters { |
| 216 |
if err := cb.CompileConfig(logger); err != nil { |
| 217 |
return fmt.Errorf("failed to compile cache buster %q: %w", cb.Source, err) |
| 218 |
} |
| 219 |
b.CacheBusters[i] = cb |
| 220 |
} |
| 221 |
if err := b.CleanDestinationDir.compile(); err != nil { |
| 222 |
return fmt.Errorf("failed to compile build.cleanDestinationDir: %w", err) |
| 223 |
} |
| 224 |
return nil |
| 225 |
} |
| 226 |
|
| 227 |
func DecodeBuildConfig(cfg Provider) BuildConfig { |
| 228 |
m := cfg.GetStringMap("build") |
| 229 |
|
| 230 |
b := defaultBuild.clone() |
| 231 |
if m == nil { |
| 232 |
return b |
| 233 |
} |
| 234 |
|
| 235 |
// writeStats was a bool <= v0.115.0. |
| 236 |
if writeStats, ok := m["writestats"]; ok { |
| 237 |
if bb, ok := writeStats.(bool); ok { |
| 238 |
m["buildstats"] = BuildStats{Enable: bb} |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
err := mapstructure.WeakDecode(m, &b) |
| 243 |
if err != nil { |
| 244 |
return b |
| 245 |
} |
| 246 |
|
| 247 |
b.UseResourceCacheWhen = strings.ToLower(b.UseResourceCacheWhen) |
| 248 |
when := b.UseResourceCacheWhen |
| 249 |
if when != "never" && when != "always" && when != "fallback" { |
| 250 |
b.UseResourceCacheWhen = "fallback" |
| 251 |
} |
| 252 |
|
| 253 |
return b |
| 254 |
} |
| 255 |
|
| 256 |
// SitemapConfig configures the sitemap to be generated. |
| 257 |
type SitemapConfig struct { |
| 258 |
// The page change frequency. |
| 259 |
ChangeFreq string |
| 260 |
// The priority of the page. |
| 261 |
Priority float64 |
| 262 |
// The sitemap filename. |
| 263 |
Filename string |
| 264 |
// Whether to disable page inclusion. |
| 265 |
Disable bool |
| 266 |
} |
| 267 |
|
| 268 |
func DecodeSitemap(prototype SitemapConfig, input map[string]any) (SitemapConfig, error) { |
| 269 |
err := mapstructure.WeakDecode(input, &prototype) |
| 270 |
return prototype, err |
| 271 |
} |
| 272 |
|
| 273 |
// Config for the dev server. |
| 274 |
type Server struct { |
| 275 |
Headers []Headers |
| 276 |
Redirects []Redirect |
| 277 |
|
| 278 |
compiledHeaders []hstrings.Matcher |
| 279 |
compiledRedirects []redirect |
| 280 |
} |
| 281 |
|
| 282 |
type redirect struct { |
| 283 |
from hstrings.Matcher |
| 284 |
fromRe *regexp.Regexp |
| 285 |
headers map[string]hstrings.Matcher |
| 286 |
} |
| 287 |
|
| 288 |
func (r redirect) matchHeader(header http.Header) bool { |
| 289 |
for k, v := range r.headers { |
| 290 |
if !v.Match(header.Get(k)) { |
| 291 |
return false |
| 292 |
} |
| 293 |
} |
| 294 |
return true |
| 295 |
} |
| 296 |
|
| 297 |
func (s *Server) CompileConfig(logger loggers.Logger) error { |
| 298 |
if s.compiledHeaders != nil { |
| 299 |
return nil |
| 300 |
} |
| 301 |
for _, h := range s.Headers { |
| 302 |
g, err := glob.Compile(h.For) |
| 303 |
if err != nil { |
| 304 |
return fmt.Errorf("failed to compile Headers glob %q: %w", h.For, err) |
| 305 |
} |
| 306 |
s.compiledHeaders = append(s.compiledHeaders, g) |
| 307 |
} |
| 308 |
for _, r := range s.Redirects { |
| 309 |
if r.From == "" && r.FromRe == "" { |
| 310 |
return fmt.Errorf("redirects must have either From or FromRe set") |
| 311 |
} |
| 312 |
rd := redirect{ |
| 313 |
headers: make(map[string]hstrings.Matcher), |
| 314 |
} |
| 315 |
if r.From != "" { |
| 316 |
g, err := glob.Compile(r.From) |
| 317 |
if err != nil { |
| 318 |
return fmt.Errorf("failed to compile Redirect glob %q: %w", r.From, err) |
| 319 |
} |
| 320 |
rd.from = g |
| 321 |
} |
| 322 |
if r.FromRe != "" { |
| 323 |
re, err := regexp.Compile(r.FromRe) |
| 324 |
if err != nil { |
| 325 |
return fmt.Errorf("failed to compile Redirect regexp %q: %w", r.FromRe, err) |
| 326 |
} |
| 327 |
rd.fromRe = re |
| 328 |
} |
| 329 |
for k, v := range r.FromHeaders { |
| 330 |
g, err := glob.Compile(v) |
| 331 |
if err != nil { |
| 332 |
return fmt.Errorf("failed to compile Redirect header glob %q: %w", v, err) |
| 333 |
} |
| 334 |
rd.headers[k] = g |
| 335 |
} |
| 336 |
s.compiledRedirects = append(s.compiledRedirects, rd) |
| 337 |
} |
| 338 |
|
| 339 |
return nil |
| 340 |
} |
| 341 |
|
| 342 |
func (s *Server) MatchHeaders(pattern string) []types.KeyValueStr { |
| 343 |
if s.compiledHeaders == nil { |
| 344 |
return nil |
| 345 |
} |
| 346 |
|
| 347 |
var matches []types.KeyValueStr |
| 348 |
|
| 349 |
for i, g := range s.compiledHeaders { |
| 350 |
if g.Match(pattern) { |
| 351 |
h := s.Headers[i] |
| 352 |
for k, v := range h.Values { |
| 353 |
matches = append(matches, types.KeyValueStr{Key: k, Value: cast.ToString(v)}) |
| 354 |
} |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
sort.Slice(matches, func(i, j int) bool { |
| 359 |
return matches[i].Key < matches[j].Key |
| 360 |
}) |
| 361 |
|
| 362 |
return matches |
| 363 |
} |
| 364 |
|
| 365 |
func (s *Server) MatchRedirect(pattern string, header http.Header) Redirect { |
| 366 |
if s.compiledRedirects == nil { |
| 367 |
return Redirect{} |
| 368 |
} |
| 369 |
|
| 370 |
pattern = strings.TrimSuffix(pattern, "index.html") |
| 371 |
|
| 372 |
for i, r := range s.compiledRedirects { |
| 373 |
redir := s.Redirects[i] |
| 374 |
|
| 375 |
var found bool |
| 376 |
|
| 377 |
if r.from != nil { |
| 378 |
if r.from.Match(pattern) { |
| 379 |
found = header == nil || r.matchHeader(header) |
| 380 |
// We need to do regexp group replacements if needed. |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
if r.fromRe != nil { |
| 385 |
m := r.fromRe.FindStringSubmatch(pattern) |
| 386 |
if m != nil { |
| 387 |
if !found { |
| 388 |
found = header == nil || r.matchHeader(header) |
| 389 |
} |
| 390 |
|
| 391 |
if found { |
| 392 |
// Replace $1, $2 etc. in To. |
| 393 |
for i, g := range m[1:] { |
| 394 |
redir.To = strings.ReplaceAll(redir.To, fmt.Sprintf("$%d", i+1), g) |
| 395 |
} |
| 396 |
} |
| 397 |
} |
| 398 |
} |
| 399 |
|
| 400 |
if found { |
| 401 |
return redir |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
return Redirect{} |
| 406 |
} |
| 407 |
|
| 408 |
type Headers struct { |
| 409 |
For string |
| 410 |
Values map[string]any |
| 411 |
} |
| 412 |
|
| 413 |
type Redirect struct { |
| 414 |
// From is the Glob pattern to match. |
| 415 |
// One of From or FromRe must be set. |
| 416 |
From string |
| 417 |
|
| 418 |
// FromRe is the regexp to match. |
| 419 |
// This regexp can contain group matches (e.g. $1) that can be used in the To field. |
| 420 |
// One of From or FromRe must be set. |
| 421 |
FromRe string |
| 422 |
|
| 423 |
// To is the target URL. |
| 424 |
To string |
| 425 |
|
| 426 |
// Headers to match for the redirect. |
| 427 |
// This maps the HTTP header name to a Glob pattern with values to match. |
| 428 |
// If the map is empty, the redirect will always be triggered. |
| 429 |
FromHeaders map[string]string |
| 430 |
|
| 431 |
// HTTP status code to use for the redirect. |
| 432 |
// A status code of 200 will trigger a URL rewrite. |
| 433 |
Status int |
| 434 |
|
| 435 |
// Forcode redirect, even if original request path exists. |
| 436 |
Force bool |
| 437 |
} |
| 438 |
|
| 439 |
// CacheBuster configures cache busting for assets. |
| 440 |
type CacheBuster struct { |
| 441 |
// Trigger for files matching this regexp. |
| 442 |
Source string |
| 443 |
|
| 444 |
// Cache bust targets matching this regexp. |
| 445 |
// This regexp can contain group matches (e.g. $1) from the source regexp. |
| 446 |
Target string |
| 447 |
|
| 448 |
compiledSource func(string) func(string) bool |
| 449 |
} |
| 450 |
|
| 451 |
func (c *CacheBuster) CompileConfig(logger loggers.Logger) error { |
| 452 |
if c.compiledSource != nil { |
| 453 |
return nil |
| 454 |
} |
| 455 |
|
| 456 |
source := c.Source |
| 457 |
sourceRe, err := regexp.Compile(source) |
| 458 |
if err != nil { |
| 459 |
return fmt.Errorf("failed to compile cache buster source %q: %w", c.Source, err) |
| 460 |
} |
| 461 |
target := c.Target |
| 462 |
var compileErr error |
| 463 |
debugl := logger.Logger().WithLevel(logg.LevelDebug).WithField(loggers.FieldNameCmd, "cachebuster") |
| 464 |
|
| 465 |
c.compiledSource = func(s string) func(string) bool { |
| 466 |
m := sourceRe.FindStringSubmatch(s) |
| 467 |
matchString := "no match" |
| 468 |
match := m != nil |
| 469 |
if match { |
| 470 |
matchString = "match!" |
| 471 |
} |
| 472 |
debugl.Logf("Matching %q with source %q: %s", s, source, matchString) |
| 473 |
if !match { |
| 474 |
return nil |
| 475 |
} |
| 476 |
groups := m[1:] |
| 477 |
currentTarget := target |
| 478 |
// Replace $1, $2 etc. in target. |
| 479 |
for i, g := range groups { |
| 480 |
currentTarget = strings.ReplaceAll(target, fmt.Sprintf("$%d", i+1), g) |
| 481 |
} |
| 482 |
targetRe, err := regexp.Compile(currentTarget) |
| 483 |
if err != nil { |
| 484 |
compileErr = fmt.Errorf("failed to compile cache buster target %q: %w", currentTarget, err) |
| 485 |
return nil |
| 486 |
} |
| 487 |
return func(ss string) bool { |
| 488 |
match := targetRe.MatchString(ss) |
| 489 |
matchString := "no match" |
| 490 |
if match { |
| 491 |
matchString = "match!" |
| 492 |
} |
| 493 |
logger.Debugf("Matching %q with target %q: %s", ss, currentTarget, matchString) |
| 494 |
|
| 495 |
return match |
| 496 |
} |
| 497 |
} |
| 498 |
return compileErr |
| 499 |
} |
| 500 |
|
| 501 |
func (r Redirect) IsZero() bool { |
| 502 |
return r.From == "" && r.FromRe == "" |
| 503 |
} |
| 504 |
|
| 505 |
const ( |
| 506 |
// Keep this a little coarse grained, some false positives are OK. |
| 507 |
cssTargetCachebusterRe = `(css|styles|scss|sass)` |
| 508 |
) |
| 509 |
|
| 510 |
func DecodeServer(cfg Provider) (Server, error) { |
| 511 |
s := &Server{} |
| 512 |
|
| 513 |
_ = mapstructure.WeakDecode(cfg.GetStringMap("server"), s) |
| 514 |
|
| 515 |
for i, redir := range s.Redirects { |
| 516 |
redir.To = strings.TrimSuffix(redir.To, "index.html") |
| 517 |
s.Redirects[i] = redir |
| 518 |
} |
| 519 |
|
| 520 |
if len(s.Redirects) == 0 { |
| 521 |
// Set up a default redirect for 404s. |
| 522 |
s.Redirects = []Redirect{ |
| 523 |
{ |
| 524 |
From: "/**", |
| 525 |
To: "/404.html", |
| 526 |
Status: 404, |
| 527 |
}, |
| 528 |
} |
| 529 |
} |
| 530 |
|
| 531 |
return *s, nil |
| 532 |
} |
| 533 |
|
| 534 |
// Pagination configures the pagination behavior. |
| 535 |
type Pagination struct { |
| 536 |
// Default number of elements per pager in pagination. |
| 537 |
PagerSize int |
| 538 |
|
| 539 |
// The path element used during pagination. |
| 540 |
Path string |
| 541 |
|
| 542 |
// Whether to disable generation of alias for the first pagination page. |
| 543 |
DisableAliases bool |
| 544 |
} |
| 545 |
|
| 546 |
// PageConfig configures the behavior of pages. |
| 547 |
type PageConfig struct { |
| 548 |
// Sort order for Page.Next and Page.Prev. Default "desc" (the default page sort order in Hugo). |
| 549 |
NextPrevSortOrder string |
| 550 |
|
| 551 |
// Sort order for Page.NextInSection and Page.PrevInSection. Default "desc". |
| 552 |
NextPrevInSectionSortOrder string |
| 553 |
} |
| 554 |
|
| 555 |
func (c *PageConfig) CompileConfig(loggers.Logger) error { |
| 556 |
c.NextPrevInSectionSortOrder = strings.ToLower(c.NextPrevInSectionSortOrder) |
| 557 |
c.NextPrevSortOrder = strings.ToLower(c.NextPrevSortOrder) |
| 558 |
return nil |
| 559 |
} |