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