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