Debian Codegraph @

config/commonConfig.go

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