Debian Codegraph @

config/allconfig/allconfig.go

raw
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 allconfig contains the full configuration for Hugo.
15 // <docsmeta>{ "name": "Configuration", "description": "This section holds all configuration options in Hugo." }</docsmeta>
16 package allconfig
17
18 import (
19 "errors"
20 "fmt"
21 "reflect"
22 "regexp"
23 "slices"
24 "sort"
25 "strconv"
26 "strings"
27 "sync"
28 "time"
29
30 "github.com/gohugoio/hugo/cache/filecache"
31 "github.com/gohugoio/hugo/cache/httpcache"
32 "github.com/gohugoio/hugo/common/hmaps"
33 "github.com/gohugoio/hugo/common/hstrings"
34 "github.com/gohugoio/hugo/common/hugo"
35 "github.com/gohugoio/hugo/common/loggers"
36 "github.com/gohugoio/hugo/common/paths"
37 "github.com/gohugoio/hugo/common/urls"
38 "github.com/gohugoio/hugo/config"
39 "github.com/gohugoio/hugo/config/privacy"
40 "github.com/gohugoio/hugo/config/security"
41 "github.com/gohugoio/hugo/config/services"
42 "github.com/gohugoio/hugo/deploy/deployconfig"
43 "github.com/gohugoio/hugo/helpers"
44 "github.com/gohugoio/hugo/hugolib/roles"
45 "github.com/gohugoio/hugo/hugolib/segments"
46 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
47 "github.com/gohugoio/hugo/hugolib/versions"
48 "github.com/gohugoio/hugo/langs"
49 gc "github.com/gohugoio/hugo/markup/goldmark/goldmark_config"
50 "github.com/gohugoio/hugo/markup/markup_config"
51 "github.com/gohugoio/hugo/media"
52 "github.com/gohugoio/hugo/minifiers"
53 "github.com/gohugoio/hugo/modules"
54 "github.com/gohugoio/hugo/navigation"
55 "github.com/gohugoio/hugo/output"
56 "github.com/gohugoio/hugo/related"
57 "github.com/gohugoio/hugo/resources/images"
58 "github.com/gohugoio/hugo/resources/kinds"
59 "github.com/gohugoio/hugo/resources/page"
60 "github.com/gohugoio/hugo/resources/page/pagemeta"
61 "github.com/spf13/afero"
62 )
63
64 // InternalConfig is the internal configuration for Hugo, not read from any user provided config file.
65 type InternalConfig struct {
66 // Server mode?
67 Running bool
68
69 Quiet bool
70 Verbose bool
71 Clock string
72 Watch bool
73 FastRenderMode bool
74 LiveReloadPort int
75 }
76
77 // InternalExternalConfig is read from the internalExternal config section in the project config file.
78 // It's meant for internal use and is not documented. These settings can be changed at any time and may be removed without notice.
79 type InternalExternalConfig struct {
80 // Used by the Hugo theme site's check command to allow us to build TailwindCSS sites with default security config without errors.
81 IgnoreTailwindCSSSecurityError bool
82 }
83
84 // All non-params config keys for language.
85 var configLanguageKeys map[string]bool
86
87 func init() {
88 skip := map[string]bool{
89 "internal": true,
90 "c": true,
91 "rootconfig": true,
92 }
93 configLanguageKeys = make(map[string]bool)
94 addKeys := func(v reflect.Value) {
95 for i := range v.NumField() {
96 name := strings.ToLower(v.Type().Field(i).Name)
97 if skip[name] {
98 continue
99 }
100 configLanguageKeys[name] = true
101 }
102 }
103 addKeys(reflect.ValueOf(Config{}))
104 addKeys(reflect.ValueOf(RootConfig{}))
105 addKeys(reflect.ValueOf(config.CommonDirs{}))
106 addKeys(reflect.ValueOf(langs.LanguageConfig{}))
107 }
108
109 type Config struct {
110 // For internal use only.
111 Internal InternalConfig `mapstructure:"-" json:"-"`
112 // For internal use only.
113 InternalExternal InternalExternalConfig `mapstructure:"-" json:"-"`
114 // For internal use only.
115 C *ConfigCompiled `mapstructure:"-" json:"-"`
116 isLanguageClone bool
117
118 RootConfig
119
120 // Author information.
121 // Deprecated: Use taxonomies instead.
122 Author map[string]any
123
124 // Social links.
125 // Deprecated: Use .Site.Params instead.
126 Social map[string]string
127
128 // The build configuration section contains build-related configuration options.
129 // <docsmeta>{"identifiers": ["build"] }</docsmeta>
130 Build config.BuildConfig `mapstructure:"-"`
131
132 // The caches configuration section contains cache-related configuration options.
133 // <docsmeta>{"identifiers": ["caches"] }</docsmeta>
134 Caches filecache.Configs `mapstructure:"-"`
135
136 // The httpcache configuration section contains HTTP-cache-related configuration options.
137 // <docsmeta>{"identifiers": ["httpcache"] }</docsmeta>
138 HTTPCache httpcache.Config `mapstructure:"-"`
139
140 // The markup configuration section contains markup-related configuration options.
141 // <docsmeta>{"identifiers": ["markup"] }</docsmeta>
142 Markup markup_config.Config `mapstructure:"-"`
143
144 // ContentTypes are the media types that's considered content in Hugo.
145 ContentTypes *config.ConfigNamespace[map[string]media.ContentTypeConfig, media.ContentTypes] `mapstructure:"-"`
146
147 // The mediatypes configuration section maps the MIME type (a string) to a configuration object for that type.
148 // <docsmeta>{"identifiers": ["mediatypes"], "refs": ["types:media:type"] }</docsmeta>
149 MediaTypes *config.ConfigNamespace[map[string]media.MediaTypeConfig, media.Types] `mapstructure:"-"`
150
151 Imaging *config.ConfigNamespace[images.ImagingConfig, images.ImagingConfigInternal] `mapstructure:"-"`
152
153 // The outputformats configuration sections maps a format name (a string) to a configuration object for that format.
154 OutputFormats *config.ConfigNamespace[map[string]output.OutputFormatConfig, output.Formats] `mapstructure:"-"`
155
156 // The languages configuration sections maps a language code (a string) to a configuration object for that language.
157 Languages *config.ConfigNamespace[map[string]langs.LanguageConfig, langs.LanguagesInternal] `mapstructure:"-"`
158
159 // The versions configuration section contains the top level versions configuration options.
160 Versions *config.ConfigNamespace[map[string]versions.VersionConfig, versions.VersionsInternal] `mapstructure:"-"`
161
162 // The roles configuration section contains the top level roles configuration options.
163 Roles *config.ConfigNamespace[map[string]roles.RoleConfig, roles.RolesInternal] `mapstructure:"-"`
164
165 // The outputs configuration section maps a Page Kind (a string) to a slice of output formats.
166 // This can be overridden in the front matter.
167 Outputs map[string][]string `mapstructure:"-"`
168
169 // The cascade configuration section contains the top level front matter cascade configuration options,
170 // a slice of page matcher and params to apply to those pages.
171 Cascade *page.PageMatcherParamsConfigs `mapstructure:"-"`
172
173 // The segments defines segments for the site. Used for partial/segmented builds.
174 Segments *config.ConfigNamespace[map[string]segments.SegmentConfig, *segments.Segments] `mapstructure:"-"`
175
176 // Menu configuration.
177 // <docsmeta>{"refs": ["config:languages:menus"] }</docsmeta>
178 Menus *config.ConfigNamespace[map[string]navigation.MenuConfig, navigation.Menus] `mapstructure:"-"`
179
180 // The deployment configuration section contains for hugo deployconfig.
181 Deployment deployconfig.DeployConfig `mapstructure:"-"`
182
183 // Module configuration.
184 Module modules.Config `mapstructure:"-"`
185
186 // Front matter configuration.
187 Frontmatter pagemeta.FrontmatterConfig `mapstructure:"-"`
188
189 // Minification configuration.
190 Minify minifiers.MinifyConfig `mapstructure:"-"`
191
192 // Permalink configuration.
193 Permalinks page.PermalinksConfig `mapstructure:"-"`
194
195 // Taxonomy configuration.
196 Taxonomies map[string]string `mapstructure:"-"`
197
198 // Sitemap configuration.
199 Sitemap config.SitemapConfig `mapstructure:"-"`
200
201 // Related content configuration.
202 Related related.Config `mapstructure:"-"`
203
204 // Server configuration.
205 Server config.Server `mapstructure:"-"`
206
207 // Pagination configuration.
208 Pagination config.Pagination `mapstructure:"-"`
209
210 // Page configuration.
211 Page config.PageConfig `mapstructure:"-"`
212
213 // Privacy configuration.
214 Privacy privacy.Config `mapstructure:"-"`
215
216 // Security configuration.
217 Security security.Config `mapstructure:"-"`
218
219 // Services configuration.
220 Services services.Config `mapstructure:"-"`
221
222 // User provided parameters.
223 // <docsmeta>{"refs": ["config:languages:params"] }</docsmeta>
224 Params hmaps.Params `mapstructure:"-"`
225
226 // UglyURLs configuration. Either a boolean or a sections map.
227 UglyURLs any `mapstructure:"-"`
228 }
229
230 // Early initialization of config.
231 type configCompiler interface {
232 CompileConfig(logger loggers.Logger) error
233 }
234
235 // Late initialization of config.
236 type configInitializer interface {
237 InitConfig(logger loggers.Logger, defaultSitesMatrix sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions) error
238 }
239
240 func (c Config) cloneForLang() *Config {
241 x := c
242 x.isLanguageClone = true
243 x.C = nil
244 copyStringSlice := func(in []string) []string {
245 if in == nil {
246 return nil
247 }
248 out := make([]string, len(in))
249 copy(out, in)
250 return out
251 }
252
253 // Copy all the slices to avoid sharing.
254 x.DisableKinds = copyStringSlice(x.DisableKinds)
255 x.DisableLanguages = copyStringSlice(x.DisableLanguages)
256 x.MainSections = copyStringSlice(x.MainSections)
257 x.IgnoreLogs = copyStringSlice(x.IgnoreLogs)
258 x.IgnoreFiles = copyStringSlice(x.IgnoreFiles)
259 x.Theme = copyStringSlice(x.Theme)
260
261 // Collapse all static dirs to one.
262 x.StaticDir = x.staticDirs()
263 // These will go away soon ...
264 x.StaticDir0 = nil
265 x.StaticDir1 = nil
266 x.StaticDir2 = nil
267 x.StaticDir3 = nil
268 x.StaticDir4 = nil
269 x.StaticDir5 = nil
270 x.StaticDir6 = nil
271 x.StaticDir7 = nil
272 x.StaticDir8 = nil
273 x.StaticDir9 = nil
274 x.StaticDir10 = nil
275
276 return &x
277 }
278
279 func (c *Config) CompileConfig(logger loggers.Logger) error {
280 var transientErr error
281 s := c.Timeout
282 if _, err := strconv.Atoi(s); err == nil {
283 // A number, assume seconds.
284 s = s + "s"
285 }
286 timeout, err := time.ParseDuration(s)
287 if err != nil {
288 return fmt.Errorf("failed to parse timeout: %s", err)
289 }
290 disabledKinds := make(map[string]bool)
291 for _, kind := range c.DisableKinds {
292 kind = strings.ToLower(kind)
293 if newKind := kinds.IsDeprecatedAndReplacedWith(kind); newKind != "" {
294 logger.Deprecatef(false, "Kind %q used in disableKinds is deprecated, use %q instead.", kind, newKind)
295 // Legacy config.
296 kind = newKind
297 }
298 if kinds.GetKindAny(kind) == "" {
299 logger.Warnf("Unknown kind %q in disableKinds configuration.", kind)
300 continue
301 }
302 disabledKinds[kind] = true
303 }
304 kindOutputFormats := make(map[string]output.Formats)
305 isRssDisabled := disabledKinds["rss"]
306 outputFormats := c.OutputFormats.Config
307 for kind, formats := range c.Outputs {
308 if newKind := kinds.IsDeprecatedAndReplacedWith(kind); newKind != "" {
309 logger.Deprecatef(false, "Kind %q used in outputs configuration is deprecated, use %q instead.", kind, newKind)
310 kind = newKind
311 }
312 if disabledKinds[kind] {
313 continue
314 }
315 if kinds.GetKindAny(kind) == "" {
316 logger.Warnf("Unknown kind %q in outputs configuration.", kind)
317 continue
318 }
319 for _, format := range formats {
320 if isRssDisabled && format == "rss" {
321 // Legacy config.
322 continue
323 }
324 f, found := outputFormats.GetByName(format)
325 if !found {
326 transientErr = fmt.Errorf("unknown output format %q for kind %q", format, kind)
327 continue
328 }
329 kindOutputFormats[kind] = append(kindOutputFormats[kind], f)
330 }
331 }
332
333 defaultOutputFormat := outputFormats[0]
334 c.DefaultOutputFormat = strings.ToLower(c.DefaultOutputFormat)
335 if c.DefaultOutputFormat != "" {
336 f, found := outputFormats.GetByName(c.DefaultOutputFormat)
337 if !found {
338 transientErr = fmt.Errorf("unknown default output format %q", c.DefaultOutputFormat)
339 } else {
340 defaultOutputFormat = f
341 }
342 } else {
343 c.DefaultOutputFormat = defaultOutputFormat.Name
344 }
345
346 disabledLangs := make(map[string]bool)
347 for _, lang := range c.DisableLanguages {
348 disabledLangs[lang] = true
349 }
350
351 for i, s := range c.IgnoreLogs {
352 c.IgnoreLogs[i] = strings.ToLower(s)
353 }
354
355 ignoredLogIDs := make(map[string]bool)
356 for _, err := range c.IgnoreLogs {
357 ignoredLogIDs[err] = true
358 }
359
360 baseURL, err := urls.NewBaseURLFromString(c.BaseURL)
361 if err != nil {
362 return err
363 }
364
365 isUglyURL := func(section string) bool {
366 switch v := c.UglyURLs.(type) {
367 case bool:
368 return v
369 case map[string]bool:
370 return v[section]
371 default:
372 return false
373 }
374 }
375
376 ignoreFile := func(s string) bool {
377 return false
378 }
379 if len(c.IgnoreFiles) > 0 {
380 regexps := make([]*regexp.Regexp, len(c.IgnoreFiles))
381 for i, pattern := range c.IgnoreFiles {
382 var err error
383 regexps[i], err = regexp.Compile(pattern)
384 if err != nil {
385 return fmt.Errorf("failed to compile ignoreFiles pattern %q: %s", pattern, err)
386 }
387 }
388 ignoreFile = func(s string) bool {
389 for _, r := range regexps {
390 if r.MatchString(s) {
391 return true
392 }
393 }
394 return false
395 }
396 }
397
398 var clock time.Time
399 if c.Internal.Clock != "" {
400 var err error
401 clock, err = time.Parse(time.RFC3339, c.Internal.Clock)
402 if err != nil {
403 return fmt.Errorf("failed to parse clock: %s", err)
404 }
405 }
406
407 httpCache, err := c.HTTPCache.Compile()
408 if err != nil {
409 return err
410 }
411
412 // Legacy language values.
413 if c.LanguageCode != "" {
414 if !c.isLanguageClone {
415 hugo.DeprecateWithLogger("project config key languageCode", "Use locale instead.", "v0.158.0", logger.Logger())
416 }
417 if c.Locale == "" {
418 c.Locale = c.LanguageCode
419 }
420 c.LanguageCode = ""
421 }
422 for k, v := range c.Languages.Config.LanguageConfigs {
423 //lint:ignore SA1019 Keep as adapter for now.
424 if v.LanguageCode != "" {
425 if !c.isLanguageClone {
426 hugo.DeprecateWithLogger(fmt.Sprintf("project config key languages.%s.languageCode", k), fmt.Sprintf("Use languages.%s.locale instead.", k), "v0.158.0", logger.Logger())
427 }
428 if v.Locale == "" {
429 //lint:ignore SA1019 Keep as adapter for now.
430 v.Locale = v.LanguageCode
431 }
432 //lint:ignore SA1019 Keep as adapter for now.
433 v.LanguageCode = ""
434 }
435 //lint:ignore SA1019 Keep as adapter for now.
436 if v.LanguageName != "" {
437 if !c.isLanguageClone {
438 hugo.DeprecateWithLogger(fmt.Sprintf("project config key languages.%s.languageName", k), fmt.Sprintf("Use languages.%s.label instead.", k), "v0.158.0", logger.Logger())
439 }
440 if v.Label == "" {
441 //lint:ignore SA1019 Keep as adapter for now.
442 v.Label = v.LanguageName
443 }
444 //lint:ignore SA1019 Keep as adapter for now.
445 v.LanguageName = ""
446 }
447 //lint:ignore SA1019 Keep as adapter for now.
448 if v.LanguageDirection != "" {
449 if !c.isLanguageClone {
450 hugo.DeprecateWithLogger(fmt.Sprintf("project config key languages.%s.languageDirection", k), fmt.Sprintf("Use languages.%s.direction instead.", k), "v0.158.0", logger.Logger())
451 }
452 if v.Direction == "" {
453 //lint:ignore SA1019 Keep as adapter for now.
454 v.Direction = v.LanguageDirection
455 }
456 //lint:ignore SA1019 Keep as adapter for now.
457 v.LanguageDirection = ""
458 }
459
460 c.Languages.Config.LanguageConfigs[k] = v
461 // Sorted is a snapshot of LanguageConfigs taken at decode time; keep it
462 // in sync so Configs.Init, which reads from Sorted, sees the migrated values.
463 for i, s := range c.Languages.Config.Sorted {
464 if s.Name == k {
465 c.Languages.Config.Sorted[i].LanguageConfig = v
466 break
467 }
468 }
469 }
470
471 // Legacy render hook values.
472 alternativeDetails := fmt.Sprintf(
473 "Set to %q if previous value was false, or set to %q if previous value was true.",
474 gc.RenderHookUseEmbeddedNever,
475 gc.RenderHookUseEmbeddedFallback,
476 )
477 if c.Markup.Goldmark.RenderHooks.Image.EnableDefault != nil {
478 alternative := "Use markup.goldmark.renderHooks.image.useEmbedded instead." + " " + alternativeDetails
479 hugo.DeprecateWithLogger("project config key markup.goldmark.renderHooks.image.enableDefault", alternative, "0.148.0", logger.Logger())
480 if *c.Markup.Goldmark.RenderHooks.Image.EnableDefault {
481 c.Markup.Goldmark.RenderHooks.Image.UseEmbedded = gc.RenderHookUseEmbeddedFallback
482 } else {
483 c.Markup.Goldmark.RenderHooks.Image.UseEmbedded = gc.RenderHookUseEmbeddedNever
484 }
485 }
486 if c.Markup.Goldmark.RenderHooks.Link.EnableDefault != nil {
487 alternative := "Use markup.goldmark.renderHooks.link.useEmbedded instead." + " " + alternativeDetails
488 hugo.DeprecateWithLogger("project config key markup.goldmark.renderHooks.link.enableDefault", alternative, "0.148.0", logger.Logger())
489 if *c.Markup.Goldmark.RenderHooks.Link.EnableDefault {
490 c.Markup.Goldmark.RenderHooks.Link.UseEmbedded = gc.RenderHookUseEmbeddedFallback
491 } else {
492 c.Markup.Goldmark.RenderHooks.Link.UseEmbedded = gc.RenderHookUseEmbeddedNever
493 }
494 }
495
496 // Validate render hook configuration.
497 renderHookUseEmbeddedModes := []string{
498 gc.RenderHookUseEmbeddedAlways,
499 gc.RenderHookUseEmbeddedAuto,
500 gc.RenderHookUseEmbeddedFallback,
501 gc.RenderHookUseEmbeddedNever,
502 }
503 if !slices.Contains(renderHookUseEmbeddedModes, c.Markup.Goldmark.RenderHooks.Image.UseEmbedded) {
504 return fmt.Errorf("project config markup.goldmark.renderHooks.image.useEmbedded must be one of %s", helpers.StringSliceToList(renderHookUseEmbeddedModes, "or"))
505 }
506 if !slices.Contains(renderHookUseEmbeddedModes, c.Markup.Goldmark.RenderHooks.Link.UseEmbedded) {
507 return fmt.Errorf("project config markup.goldmark.renderHooks.link.useEmbedded must be one of %s", helpers.StringSliceToList(renderHookUseEmbeddedModes, "or"))
508 }
509
510 c.C = &ConfigCompiled{
511 Timeout: timeout,
512 BaseURL: baseURL,
513 BaseURLLiveReload: baseURL,
514 DisabledKinds: disabledKinds,
515 DisabledLanguages: disabledLangs,
516 IgnoredLogs: ignoredLogIDs,
517 KindOutputFormats: kindOutputFormats,
518 DefaultOutputFormat: defaultOutputFormat,
519 CreateTitle: helpers.GetTitleFunc(c.TitleCaseStyle),
520 IsUglyURLSection: isUglyURL,
521 IgnoreFile: ignoreFile,
522 MainSections: c.MainSections,
523 Clock: clock,
524 HTTPCache: httpCache,
525 transientErr: transientErr,
526 }
527
528 for _, s := range allDecoderSetups {
529 if getCompiler := s.getCompiler; getCompiler != nil {
530 if err := getCompiler(c).CompileConfig(logger); err != nil {
531 return err
532 }
533 }
534 }
535
536 return nil
537 }
538
539 func (c *Config) IsKindEnabled(kind string) bool {
540 return !c.C.DisabledKinds[kind]
541 }
542
543 func (c *Config) IsLangDisabled(lang string) bool {
544 return c.C.DisabledLanguages[lang]
545 }
546
547 // ConfigCompiled holds values and functions that are derived from the config.
548 type ConfigCompiled struct {
549 Timeout time.Duration
550 BaseURL urls.BaseURL
551 BaseURLLiveReload urls.BaseURL
552 ServerInterface string
553 KindOutputFormats map[string]output.Formats
554 DefaultOutputFormat output.Format
555 DisabledKinds map[string]bool
556 DisabledLanguages map[string]bool
557 IgnoredLogs map[string]bool
558 CreateTitle func(s string) string
559 IsUglyURLSection func(section string) bool
560 IgnoreFile func(filename string) bool
561 MainSections []string
562 Clock time.Time
563 HTTPCache httpcache.ConfigCompiled
564
565 // This is set to the last transient error found during config compilation.
566 // With themes/modules we compute the configuration in multiple passes, and
567 // errors with missing output format definitions may resolve itself.
568 transientErr error
569
570 mu sync.Mutex
571 }
572
573 // This may be set after the config is compiled.
574 func (c *ConfigCompiled) SetMainSections(sections []string) {
575 c.mu.Lock()
576 defer c.mu.Unlock()
577 c.MainSections = sections
578 }
579
580 // IsMainSectionsSet returns whether the main sections have been set.
581 func (c *ConfigCompiled) IsMainSectionsSet() bool {
582 c.mu.Lock()
583 defer c.mu.Unlock()
584 return c.MainSections != nil
585 }
586
587 // This is set after the config is compiled by the server command.
588 func (c *ConfigCompiled) SetServerInfo(baseURL, baseURLLiveReload urls.BaseURL, serverInterface string) {
589 c.BaseURL = baseURL
590 c.BaseURLLiveReload = baseURLLiveReload
591 c.ServerInterface = serverInterface
592 }
593
594 // RootConfig holds all the top-level configuration options in Hugo
595 type RootConfig struct {
596 // The base URL of the site.
597 // Note that the default value is empty, but Hugo requires a valid URL (e.g. "https://example.com/") to work properly.
598 // <docsmeta>{"identifiers": ["URL"] }</docsmeta>
599 BaseURL string
600
601 // Whether to build content marked as draft.X
602 // <docsmeta>{"identifiers": ["draft"] }</docsmeta>
603 BuildDrafts bool
604
605 // Whether to build content with expiryDate in the past.
606 // <docsmeta>{"identifiers": ["expiryDate"] }</docsmeta>
607 BuildExpired bool
608
609 // Whether to build content with publishDate in the future.
610 // <docsmeta>{"identifiers": ["publishDate"] }</docsmeta>
611 BuildFuture bool
612
613 // Copyright information.
614 Copyright string
615
616 // The language to apply to content without any language indicator.
617 DefaultContentLanguage string
618
619 // By default, we put the default content language in the root and the others below their language ID, e.g. /no/.
620 // Set this to true to put all languages below their language ID.
621 DefaultContentLanguageInSubdir bool
622
623 // The default content role to use for the site.
624 DefaultContentRole string
625
626 // Set this to true to put the default role in a subdirectory.
627 DefaultContentRoleInSubdir bool
628
629 // The default content version to use for the site.
630 DefaultContentVersion string
631
632 // Set to true to render the default version in a subdirectory.
633 DefaultContentVersionInSubdir bool
634
635 // The default output format to use for the site.
636 // If not set, we will use the first output format.
637 DefaultOutputFormat string
638
639 // Disable generation of redirect to the default language when DefaultContentLanguageInSubdir is enabled.
640 // Note that this currently is an alias for DisableDefaultSiteRedirect introduced in v0.154.5.
641 // It's not obvious how a more fine grained setup would work.
642 DisableDefaultLanguageRedirect bool
643
644 // Disable generation of redirects to the default site when DefaultContentRoleInSubdir or DefaultContentVersionInSubdir or DefaultContentLanguageInSubdir is enabled.
645 // The default site is the site is the combination of defaultContentLanguage, defaultContentVersion and defaultContentRole.
646 DisableDefaultSiteRedirect bool
647
648 // Disable creation of alias redirect pages.
649 DisableAliases bool
650
651 // Disable lower casing of path segments.
652 DisablePathToLower bool
653
654 // Disable page kinds from build.
655 DisableKinds []string
656
657 // A list of languages to disable.
658 DisableLanguages []string
659
660 // The named segments to render.
661 // This needs to match the name of the segment in the segments configuration.
662 RenderSegments []string
663
664 // Disable the injection of the Hugo generator tag on the home page.
665 DisableHugoGeneratorInject bool
666
667 // Disable live reloading in server mode.
668 DisableLiveReload bool
669
670 // Enable replacement in Pages' Content of Emoji shortcodes with their equivalent Unicode characters.
671 // <docsmeta>{"identifiers": ["Content", "Unicode"] }</docsmeta>
672 EnableEmoji bool
673
674 // THe main section(s) of the site.
675 // If not set, Hugo will try to guess this from the content.
676 MainSections []string
677
678 // Enable robots.txt generation.
679 EnableRobotsTXT bool
680
681 // When enabled, Hugo will apply Git version information to each Page if possible, which
682 // can be used to keep lastUpdated in synch and to print version information.
683 // <docsmeta>{"identifiers": ["Page"] }</docsmeta>
684 EnableGitInfo bool
685
686 // Enable to track, calculate and print metrics.
687 TemplateMetrics bool
688
689 // Enable to track, print and calculate metric hints.
690 TemplateMetricsHints bool
691
692 // Enable to disable the build lock file.
693 NoBuildLock bool
694
695 // A list of log IDs to ignore.
696 IgnoreLogs []string
697
698 // A list of regexps that match paths to ignore.
699 // Deprecated: Use the settings on module imports.
700 IgnoreFiles []string
701
702 // Ignore cache.
703 IgnoreCache bool
704
705 // Enable to print greppable placeholders (on the form "[i18n] TRANSLATIONID") for missing translation strings.
706 EnableMissingTranslationPlaceholders bool
707
708 // Enable to panic on warning log entries. This may make it easier to detect the source.
709 PanicOnWarning bool
710
711 // The configured environment. Default is "development" for server and "production" for build.
712 Environment string
713
714 // Deprecated: Use Locale instead.
715 LanguageCode string `json:"-"`
716
717 // The default locale.
718 Locale string
719
720 // Enable if the site content has CJK language (Chinese, Japanese, or Korean). This affects how Hugo counts words.
721 HasCJKLanguage bool
722
723 // Whether to pluralize default list titles.
724 // Note that this currently only works for English, but you can provide your own title in the content file's front matter.
725 PluralizeListTitles bool
726
727 // Whether to capitalize automatic page titles, applicable to section, taxonomy, and term pages.
728 CapitalizeListTitles bool
729
730 // Make all relative URLs absolute using the baseURL.
731 // <docsmeta>{"identifiers": ["baseURL"] }</docsmeta>
732 CanonifyURLs bool
733
734 // Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs.
735 RelativeURLs bool
736
737 // Removes non-spacing marks from composite characters in content paths.
738 RemovePathAccents bool
739
740 // Whether to track and print unused templates during the build.
741 PrintUnusedTemplates bool
742
743 // Enable to print warnings for missing translation strings.
744 PrintI18nWarnings bool
745
746 // ENable to print warnings for multiple files published to the same destination.
747 PrintPathWarnings bool
748
749 // URL to be used as a placeholder when a page reference cannot be found in ref or relref. Is used as-is.
750 RefLinksNotFoundURL string
751
752 // When using ref or relref to resolve page links and a link cannot be resolved, it will be logged with this log level.
753 // Valid values are ERROR (default) or WARNING. Any ERROR will fail the build (exit -1).
754 RefLinksErrorLevel string
755
756 // This will create a menu with all the sections as menu items and all the sections’ pages as “shadow-members”.
757 SectionPagesMenu string
758
759 // The length of text in words to show in a .Summary.
760 SummaryLength int
761
762 // The site title.
763 Title string
764
765 // The theme(s) to use.
766 // See Modules for more a more flexible way to load themes.
767 Theme []string
768
769 // Timeout for generating page contents, specified as a duration or in seconds.
770 Timeout string
771
772 // The time zone (or location), e.g. Europe/Oslo, used to parse front matter dates without such information and in the time function.
773 TimeZone string
774
775 // Set titleCaseStyle to specify the title style used by the title template function and the automatic section titles in Hugo.
776 // It defaults to AP Stylebook for title casing, but you can also set it to Chicago or Go (every word starts with a capital letter).
777 TitleCaseStyle string
778
779 // The editor used for opening up new content.
780 NewContentEditor string
781
782 // Don't sync modification time of files for the static mounts.
783 NoTimes bool
784
785 // Don't sync modification time of files for the static mounts.
786 NoChmod bool
787
788 // Clean the destination folder before a new build.
789 // This currently only handles static files.
790 CleanDestinationDir bool
791
792 // A Glob pattern of module paths to ignore in the _vendor folder.
793 IgnoreVendorPaths string
794
795 config.CommonDirs `mapstructure:",squash"`
796
797 // The odd constructs below are kept for backwards compatibility.
798 // Deprecated: Use module mount config instead.
799 StaticDir []string
800 // Deprecated: Use module mount config instead.
801 StaticDir0 []string
802 // Deprecated: Use module mount config instead.
803 StaticDir1 []string
804 // Deprecated: Use module mount config instead.
805 StaticDir2 []string
806 // Deprecated: Use module mount config instead.
807 StaticDir3 []string
808 // Deprecated: Use module mount config instead.
809 StaticDir4 []string
810 // Deprecated: Use module mount config instead.
811 StaticDir5 []string
812 // Deprecated: Use module mount config instead.
813 StaticDir6 []string
814 // Deprecated: Use module mount config instead.
815 StaticDir7 []string
816 // Deprecated: Use module mount config instead.
817 StaticDir8 []string
818 // Deprecated: Use module mount config instead.
819 StaticDir9 []string
820 // Deprecated: Use module mount config instead.
821 StaticDir10 []string
822 }
823
824 func (c RootConfig) staticDirs() []string {
825 var dirs []string
826 dirs = append(dirs, c.StaticDir...)
827 dirs = append(dirs, c.StaticDir0...)
828 dirs = append(dirs, c.StaticDir1...)
829 dirs = append(dirs, c.StaticDir2...)
830 dirs = append(dirs, c.StaticDir3...)
831 dirs = append(dirs, c.StaticDir4...)
832 dirs = append(dirs, c.StaticDir5...)
833 dirs = append(dirs, c.StaticDir6...)
834 dirs = append(dirs, c.StaticDir7...)
835 dirs = append(dirs, c.StaticDir8...)
836 dirs = append(dirs, c.StaticDir9...)
837 dirs = append(dirs, c.StaticDir10...)
838 return hstrings.UniqueStringsReuse(dirs)
839 }
840
841 type Configs struct {
842 Base *Config
843 LoadingInfo config.LoadConfigResult
844 LanguageConfigMap map[string]*Config
845
846 IsMultihost bool
847
848 Modules modules.Modules
849 ModulesClient *modules.Client
850 FileCaches filecache.Caches
851
852 // All below is set in Init.
853 Languages langs.Languages
854 ContentPathParser *paths.PathParser
855 ConfiguredDimensions *sitesmatrix.ConfiguredDimensions
856 DefaultContentSitesMatrix *sitesmatrix.IntSets
857 AllSitesMatrix *sitesmatrix.IntSets
858
859 configLangs []config.AllProvider
860 }
861
862 func (c *Configs) Validate(logger loggers.Logger) error {
863 return nil
864 }
865
866 // transientErr returns the last transient error found during config compilation.
867 func (c *Configs) transientErr() error {
868 for _, l := range c.LanguageConfigMap {
869 if l.C.transientErr != nil {
870 return l.C.transientErr
871 }
872 }
873 return nil
874 }
875
876 func (c *Configs) IsZero() bool {
877 // A config always has at least one language.
878 return c == nil || len(c.Languages) == 0
879 }
880
881 func (c *Configs) Init(sourceFs afero.Fs, logger loggers.Logger) error {
882 var languages langs.Languages
883
884 for _, f := range c.Base.Languages.Config.Sorted {
885 v, found := c.LanguageConfigMap[f.Name]
886 if !found {
887 return fmt.Errorf("invalid language configuration for %q", f.Name)
888 }
889 language, err := langs.NewLanguage(f.Name, c.Base.DefaultContentLanguage, v.TimeZone, f.LanguageConfig, logger)
890 if err != nil {
891 return err
892 }
893 languages = append(languages, language)
894 }
895
896 // Filter out disabled languages.
897 var n int
898 for _, l := range languages {
899 if !l.Disabled {
900 languages[n] = l
901 n++
902 }
903 }
904 languages = languages[:n]
905
906 c.Languages = languages
907 c.ConfiguredDimensions = &sitesmatrix.ConfiguredDimensions{
908 ConfiguredLanguages: c.Base.Languages.Config,
909 ConfiguredVersions: c.Base.Versions.Config,
910 ConfiguredRoles: c.Base.Roles.Config,
911 }
912
913 if err := c.ConfiguredDimensions.Init(); err != nil {
914 return err
915 }
916
917 intSetsCfg := sitesmatrix.IntSetsConfig{
918 ApplyDefaults: sitesmatrix.IntSetsConfigApplyDefaultsIfNotSet,
919 }
920 matrix := sitesmatrix.NewIntSetsBuilder(c.ConfiguredDimensions).WithConfig(intSetsCfg)
921 c.DefaultContentSitesMatrix = matrix.Build()
922 c.AllSitesMatrix = sitesmatrix.NewIntSetsBuilder(c.ConfiguredDimensions).WithAllIfNotSet().Build()
923
924 c.ContentPathParser = &paths.PathParser{
925 ConfiguredDimensions: c.ConfiguredDimensions,
926 LanguageIndex: languages.AsIndexSet(),
927 IsLangDisabled: c.Base.IsLangDisabled,
928 IsContentExt: c.Base.ContentTypes.Config.IsContentSuffix,
929 IsOutputFormat: func(name, ext string) bool {
930 if name == "" {
931 return false
932 }
933
934 if of, ok := c.Base.OutputFormats.Config.GetByName(name); ok {
935 if ext != "" && !of.MediaType.HasSuffix(ext) {
936 return false
937 }
938 return true
939 }
940 return false
941 },
942 }
943
944 c.configLangs = make([]config.AllProvider, len(c.Languages))
945
946 // Config can be shared between languages,
947 // avoid initializing the same config more than once.
948 for i, l := range c.Languages {
949 langConfig := c.LanguageConfigMap[l.Lang]
950 for _, s := range allDecoderSetups {
951 if getInitializer := s.getInitializer; getInitializer != nil {
952 if err := getInitializer(langConfig).InitConfig(logger, nil, c.ConfiguredDimensions); err != nil {
953 return err
954 }
955 }
956 }
957
958 c.configLangs[i] = ConfigLanguage{
959 m: c,
960 config: langConfig,
961 baseConfig: c.LoadingInfo.BaseConfig,
962 language: l,
963 languageIndex: i,
964 }
965 }
966
967 if len(c.Modules) == 0 {
968 return errors.New("no modules loaded (need at least the main module)")
969 }
970
971 // Apply default project mounts.
972 if err := modules.ApplyProjectConfigDefaults(logger.Logger(), c.Modules[0], c.configLangs...); err != nil {
973 return err
974 }
975
976 // We should consolidate this, but to get a full view of the mounts in e.g. "hugo config" we need to
977 // transfer any default mounts added above to the config used to print the config.
978 for _, m := range c.Modules[0].Mounts() {
979 var found bool
980 for _, cm := range c.Base.Module.Mounts {
981 if cm.Equal(m) {
982 found = true
983 break
984 }
985 }
986 if !found {
987 c.Base.Module.Mounts = append(c.Base.Module.Mounts, m)
988 }
989 }
990
991 // Transfer the changed mounts to the language versions (all share the same mount set, but can be displayed in different languages).
992 for _, l := range c.LanguageConfigMap {
993 l.Module.Mounts = c.Base.Module.Mounts
994 }
995
996 return nil
997 }
998
999 func (c Configs) ConfigLangs() []config.AllProvider {
1000 return c.configLangs
1001 }
1002
1003 func (c Configs) GetFirstLanguageConfig() config.AllProvider {
1004 return c.configLangs[0]
1005 }
1006
1007 func (c Configs) GetByLang(lang string) config.AllProvider {
1008 for _, l := range c.configLangs {
1009 if l.Language().(*langs.Language).Lang == lang {
1010 return l
1011 }
1012 }
1013 return nil
1014 }
1015
1016 func newDefaultConfig() *Config {
1017 return &Config{
1018 Taxonomies: map[string]string{"tag": "tags", "category": "categories"},
1019 Sitemap: config.SitemapConfig{Priority: -1, Filename: "sitemap.xml"},
1020 Environment: hugo.EnvironmentProduction,
1021 TitleCaseStyle: "AP",
1022 PluralizeListTitles: true,
1023 CapitalizeListTitles: true,
1024 StaticDir: []string{"static"},
1025 SummaryLength: 70,
1026 Timeout: "60s",
1027
1028 //lint:ignore SA1019 Keep as adapter for now.
1029 ArcheTypeDir: "archetypes",
1030 ContentDir: "content",
1031 ResourceDir: "resources",
1032 PublishDir: "public",
1033 ThemesDir: "themes",
1034 //lint:ignore SA1019 Keep as adapter for now.
1035 AssetDir: "assets",
1036 //lint:ignore SA1019 Keep as adapter for now.
1037 LayoutDir: "layouts",
1038 //lint:ignore SA1019 Keep as adapter for now.
1039 I18nDir: "i18n",
1040 //lint:ignore SA1019 Keep as adapter for now.
1041 DataDir: "data",
1042 }
1043 }
1044
1045 // fromLoadConfigResult creates a new Config from res.
1046 func fromLoadConfigResult(fs afero.Fs, logger loggers.Logger, res config.LoadConfigResult) (*Configs, error) {
1047 if !res.Cfg.IsSet("languages") {
1048 // We need at least one
1049 lang := res.Cfg.GetString("defaultContentLanguage")
1050 if lang == "" {
1051 lang = "en"
1052 }
1053 res.Cfg.Set("languages", hmaps.Params{lang: hmaps.Params{}})
1054 }
1055 bcfg := res.BaseConfig
1056 cfg := res.Cfg
1057
1058 all := newDefaultConfig()
1059
1060 err := decodeConfigFromParams(fs, logger, bcfg, cfg, all, nil)
1061 if err != nil {
1062 return nil, err
1063 }
1064
1065 langConfigMap := make(map[string]*Config)
1066
1067 languagesConfig := cfg.GetStringMap("languages")
1068
1069 var isMultihost bool
1070
1071 if err := all.CompileConfig(logger); err != nil {
1072 return nil, err
1073 }
1074
1075 for k, v := range languagesConfig {
1076 mergedConfig := config.New()
1077 var differentRootKeys []string
1078 switch x := v.(type) {
1079 case nil:
1080 case hmaps.Params:
1081 _, found := x["params"]
1082 if !found {
1083 x["params"] = hmaps.Params{
1084 hmaps.MergeStrategyKey: hmaps.ParamsMergeStrategyDeep,
1085 }
1086 }
1087 for kk, vv := range x {
1088 if kk == "_merge" {
1089 continue
1090 }
1091 if kk == "baseurl" {
1092 // baseURL configure don the language level is a multihost setup.
1093 isMultihost = true
1094 }
1095
1096 if p, ok := vv.(hmaps.Params); ok {
1097 // With the introduction of YAML anchor and alias support, language config entries
1098 // may be contain shared references.
1099 // This also break potential cycles.
1100 vv = hmaps.CloneParamsDeep(p)
1101 }
1102
1103 if kk == "cascade" {
1104 // If not set, add the current language to make sure it does not get applied to other languages.
1105 page.AddLangToCascadeTargetMap(k, vv.(hmaps.Params))
1106 // Always clone cascade config to get the sites matrix right.
1107 differentRootKeys = append(differentRootKeys, kk)
1108 }
1109
1110 mergedConfig.Set(kk, vv)
1111 rootv := cfg.Get(kk)
1112 if rootv != nil && cfg.IsSet(kk) {
1113 // This overrides a root key and potentially needs a merge.
1114 if !reflect.DeepEqual(rootv, vv) {
1115 switch vvv := vv.(type) {
1116 case hmaps.Params:
1117 differentRootKeys = append(differentRootKeys, kk)
1118
1119 // Use the language value as base.
1120 // Note that this is already cloned above.
1121 mergedConfigEntry := vvv
1122 // Merge in the root value.
1123 hmaps.MergeParams(mergedConfigEntry, rootv.(hmaps.Params))
1124
1125 mergedConfig.Set(kk, mergedConfigEntry)
1126 default:
1127 // Apply new values to the root.
1128 differentRootKeys = append(differentRootKeys, "")
1129 }
1130 }
1131 } else {
1132 switch vv.(type) {
1133 case hmaps.Params:
1134 differentRootKeys = append(differentRootKeys, kk)
1135 default:
1136 // Apply new values to the root.
1137 differentRootKeys = append(differentRootKeys, "")
1138 }
1139 }
1140 }
1141 differentRootKeys = hstrings.UniqueStringsSorted(differentRootKeys)
1142
1143 if len(differentRootKeys) == 0 {
1144 langConfigMap[k] = all
1145 continue
1146 }
1147
1148 // Create a copy of the complete config and replace the root keys with the language specific ones.
1149 clone := all.cloneForLang()
1150
1151 if err := decodeConfigFromParams(fs, logger, bcfg, mergedConfig, clone, differentRootKeys); err != nil {
1152 return nil, fmt.Errorf("failed to decode config for language %q: %w", k, err)
1153 }
1154 if err := clone.CompileConfig(logger); err != nil {
1155 return nil, err
1156 }
1157
1158 // Adjust Goldmark config defaults for multilingual, single-host sites.
1159 if len(languagesConfig) > 1 && !isMultihost && !clone.Markup.Goldmark.DuplicateResourceFiles {
1160 if clone.Markup.Goldmark.RenderHooks.Image.UseEmbedded == gc.RenderHookUseEmbeddedAuto {
1161 clone.Markup.Goldmark.RenderHooks.Image.UseEmbedded = gc.RenderHookUseEmbeddedFallback
1162 }
1163 if clone.Markup.Goldmark.RenderHooks.Link.UseEmbedded == gc.RenderHookUseEmbeddedAuto {
1164 clone.Markup.Goldmark.RenderHooks.Link.UseEmbedded = gc.RenderHookUseEmbeddedFallback
1165 }
1166 }
1167
1168 langConfigMap[k] = clone
1169 case hmaps.ParamsMergeStrategy:
1170
1171 default:
1172 panic(fmt.Sprintf("unknown type in languages config: %T", v))
1173
1174 }
1175 }
1176
1177 bcfg.PublishDir = all.PublishDir
1178 res.BaseConfig = bcfg
1179 all.CommonDirs.CacheDir = bcfg.CacheDir
1180 for _, l := range langConfigMap {
1181 l.CommonDirs.CacheDir = bcfg.CacheDir
1182 }
1183
1184 caches, err := filecache.NewCaches(all.Caches, fs)
1185 if err != nil {
1186 return nil, fmt.Errorf("failed to create file caches from configuration: %w", err)
1187 }
1188
1189 cm := &Configs{
1190 Base: all,
1191 LanguageConfigMap: langConfigMap,
1192 LoadingInfo: res,
1193 FileCaches: caches,
1194 IsMultihost: isMultihost,
1195 }
1196
1197 return cm, nil
1198 }
1199
1200 func decodeConfigFromParams(fs afero.Fs, logger loggers.Logger, bcfg config.BaseConfig, p config.Provider, target *Config, keys []string) error {
1201 var decoderSetups []decodeWeight
1202
1203 if len(keys) == 0 {
1204 for _, v := range allDecoderSetups {
1205 decoderSetups = append(decoderSetups, v)
1206 }
1207 } else {
1208 for _, key := range keys {
1209 if v, found := allDecoderSetups[key]; found {
1210 decoderSetups = append(decoderSetups, v)
1211 } else {
1212 logger.Warnf("Skip unknown config key %q", key)
1213 }
1214 }
1215 }
1216
1217 // Sort them to get the dependency order right.
1218 sort.Slice(decoderSetups, func(i, j int) bool {
1219 ki, kj := decoderSetups[i], decoderSetups[j]
1220 if ki.weight == kj.weight {
1221 return ki.key < kj.key
1222 }
1223 return ki.weight < kj.weight
1224 })
1225
1226 for _, v := range decoderSetups {
1227 p := decodeConfig{p: p, c: target, fs: fs, bcfg: bcfg, logger: logger}
1228 if err := v.decode(v, p); err != nil {
1229 return fmt.Errorf("failed to decode %q: %w", v.key, err)
1230 }
1231 }
1232
1233 return nil
1234 }
1235
1236 func createDefaultOutputFormats(allFormats output.Formats) map[string][]string {
1237 if len(allFormats) == 0 {
1238 panic("no output formats")
1239 }
1240 rssOut, rssFound := allFormats.GetByName(output.RSSFormat.Name)
1241 htmlOut, _ := allFormats.GetByName(output.HTMLFormat.Name)
1242
1243 defaultListTypes := []string{htmlOut.Name}
1244 if rssFound {
1245 defaultListTypes = append(defaultListTypes, rssOut.Name)
1246 }
1247
1248 m := map[string][]string{
1249 kinds.KindPage: {htmlOut.Name},
1250 kinds.KindHome: defaultListTypes,
1251 kinds.KindSection: defaultListTypes,
1252 kinds.KindTerm: defaultListTypes,
1253 kinds.KindTaxonomy: defaultListTypes,
1254 }
1255
1256 // May be disabled
1257 if rssFound {
1258 m["rss"] = []string{rssOut.Name}
1259 }
1260
1261 return m
1262 }