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 if c.BaseURL == "" {
361 c.BaseURL = "https://example.org/"
362 }
363
364 baseURL, err := urls.NewBaseURLFromString(c.BaseURL)
365 if err != nil {
366 return err
367 }
368
369 isUglyURL := func(section string) bool {
370 switch v := c.UglyURLs.(type) {
371 case bool:
372 return v
373 case map[string]bool:
374 return v[section]
375 default:
376 return false
377 }
378 }
379
380 ignoreFile := func(s string) bool {
381 return false
382 }
383 if len(c.IgnoreFiles) > 0 {
384 regexps := make([]*regexp.Regexp, len(c.IgnoreFiles))
385 for i, pattern := range c.IgnoreFiles {
386 var err error
387 regexps[i], err = regexp.Compile(pattern)
388 if err != nil {
389 return fmt.Errorf("failed to compile ignoreFiles pattern %q: %s", pattern, err)
390 }
391 }
392 ignoreFile = func(s string) bool {
393 for _, r := range regexps {
394 if r.MatchString(s) {
395 return true
396 }
397 }
398 return false
399 }
400 }
401
402 var clock time.Time
403 if c.Internal.Clock != "" {
404 var err error
405 clock, err = time.Parse(time.RFC3339, c.Internal.Clock)
406 if err != nil {
407 return fmt.Errorf("failed to parse clock: %s", err)
408 }
409 }
410
411 httpCache, err := c.HTTPCache.Compile()
412 if err != nil {
413 return err
414 }
415
416 // Legacy language values.
417 if c.LanguageCode != "" {
418 if !c.isLanguageClone {
419 hugo.DeprecateWithLogger("project config key languageCode", "Use locale instead.", "v0.158.0", logger.Logger())
420 }
421 if c.Locale == "" {
422 c.Locale = c.LanguageCode
423 }
424 c.LanguageCode = ""
425 }
426 for k, v := range c.Languages.Config.LanguageConfigs {
427 //lint:ignore SA1019 Keep as adapter for now.
428 if v.LanguageCode != "" {
429 if !c.isLanguageClone {
430 hugo.DeprecateWithLogger(fmt.Sprintf("project config key languages.%s.languageCode", k), fmt.Sprintf("Use languages.%s.locale instead.", k), "v0.158.0", logger.Logger())
431 }
432 if v.Locale == "" {
433 //lint:ignore SA1019 Keep as adapter for now.
434 v.Locale = v.LanguageCode
435 }
436 //lint:ignore SA1019 Keep as adapter for now.
437 v.LanguageCode = ""
438 }
439 //lint:ignore SA1019 Keep as adapter for now.
440 if v.LanguageName != "" {
441 if !c.isLanguageClone {
442 hugo.DeprecateWithLogger(fmt.Sprintf("project config key languages.%s.languageName", k), fmt.Sprintf("Use languages.%s.label instead.", k), "v0.158.0", logger.Logger())
443 }
444 if v.Label == "" {
445 //lint:ignore SA1019 Keep as adapter for now.
446 v.Label = v.LanguageName
447 }
448 //lint:ignore SA1019 Keep as adapter for now.
449 v.LanguageName = ""
450 }
451 //lint:ignore SA1019 Keep as adapter for now.
452 if v.LanguageDirection != "" {
453 if !c.isLanguageClone {
454 hugo.DeprecateWithLogger(fmt.Sprintf("project config key languages.%s.languageDirection", k), fmt.Sprintf("Use languages.%s.direction instead.", k), "v0.158.0", logger.Logger())
455 }
456 if v.Direction == "" {
457 //lint:ignore SA1019 Keep as adapter for now.
458 v.Direction = v.LanguageDirection
459 }
460 //lint:ignore SA1019 Keep as adapter for now.
461 v.LanguageDirection = ""
462 }
463
464 c.Languages.Config.LanguageConfigs[k] = v
465 // Sorted is a snapshot of LanguageConfigs taken at decode time; keep it
466 // in sync so Configs.Init, which reads from Sorted, sees the migrated values.
467 for i, s := range c.Languages.Config.Sorted {
468 if s.Name == k {
469 c.Languages.Config.Sorted[i].LanguageConfig = v
470 break
471 }
472 }
473 }
474
475 // Legacy render hook values.
476 alternativeDetails := fmt.Sprintf(
477 "Set to %q if previous value was false, or set to %q if previous value was true.",
478 gc.RenderHookUseEmbeddedNever,
479 gc.RenderHookUseEmbeddedFallback,
480 )
481 if c.Markup.Goldmark.RenderHooks.Image.EnableDefault != nil {
482 alternative := "Use markup.goldmark.renderHooks.image.useEmbedded instead." + " " + alternativeDetails
483 hugo.DeprecateWithLogger("project config key markup.goldmark.renderHooks.image.enableDefault", alternative, "0.148.0", logger.Logger())
484 if *c.Markup.Goldmark.RenderHooks.Image.EnableDefault {
485 c.Markup.Goldmark.RenderHooks.Image.UseEmbedded = gc.RenderHookUseEmbeddedFallback
486 } else {
487 c.Markup.Goldmark.RenderHooks.Image.UseEmbedded = gc.RenderHookUseEmbeddedNever
488 }
489 }
490 if c.Markup.Goldmark.RenderHooks.Link.EnableDefault != nil {
491 alternative := "Use markup.goldmark.renderHooks.link.useEmbedded instead." + " " + alternativeDetails
492 hugo.DeprecateWithLogger("project config key markup.goldmark.renderHooks.link.enableDefault", alternative, "0.148.0", logger.Logger())
493 if *c.Markup.Goldmark.RenderHooks.Link.EnableDefault {
494 c.Markup.Goldmark.RenderHooks.Link.UseEmbedded = gc.RenderHookUseEmbeddedFallback
495 } else {
496 c.Markup.Goldmark.RenderHooks.Link.UseEmbedded = gc.RenderHookUseEmbeddedNever
497 }
498 }
499
500 // Validate render hook configuration.
501 renderHookUseEmbeddedModes := []string{
502 gc.RenderHookUseEmbeddedAlways,
503 gc.RenderHookUseEmbeddedAuto,
504 gc.RenderHookUseEmbeddedFallback,
505 gc.RenderHookUseEmbeddedNever,
506 }
507 if !slices.Contains(renderHookUseEmbeddedModes, c.Markup.Goldmark.RenderHooks.Image.UseEmbedded) {
508 return fmt.Errorf("project config markup.goldmark.renderHooks.image.useEmbedded must be one of %s", helpers.StringSliceToList(renderHookUseEmbeddedModes, "or"))
509 }
510 if !slices.Contains(renderHookUseEmbeddedModes, c.Markup.Goldmark.RenderHooks.Link.UseEmbedded) {
511 return fmt.Errorf("project config markup.goldmark.renderHooks.link.useEmbedded must be one of %s", helpers.StringSliceToList(renderHookUseEmbeddedModes, "or"))
512 }
513
514 c.C = &ConfigCompiled{
515 Timeout: timeout,
516 BaseURL: baseURL,
517 BaseURLLiveReload: baseURL,
518 DisabledKinds: disabledKinds,
519 DisabledLanguages: disabledLangs,
520 IgnoredLogs: ignoredLogIDs,
521 KindOutputFormats: kindOutputFormats,
522 DefaultOutputFormat: defaultOutputFormat,
523 CreateTitle: helpers.GetTitleFunc(c.TitleCaseStyle),
524 IsUglyURLSection: isUglyURL,
525 IgnoreFile: ignoreFile,
526 MainSections: c.MainSections,
527 Clock: clock,
528 HTTPCache: httpCache,
529 transientErr: transientErr,
530 }
531
532 for _, s := range allDecoderSetups {
533 if getCompiler := s.getCompiler; getCompiler != nil {
534 if err := getCompiler(c).CompileConfig(logger); err != nil {
535 return err
536 }
537 }
538 }
539
540 return nil
541 }
542
543 func (c *Config) IsKindEnabled(kind string) bool {
544 return !c.C.DisabledKinds[kind]
545 }
546
547 func (c *Config) IsLangDisabled(lang string) bool {
548 return c.C.DisabledLanguages[lang]
549 }
550
551 // ConfigCompiled holds values and functions that are derived from the config.
552 type ConfigCompiled struct {
553 Timeout time.Duration
554 BaseURL urls.BaseURL
555 BaseURLLiveReload urls.BaseURL
556 ServerInterface string
557 KindOutputFormats map[string]output.Formats
558 DefaultOutputFormat output.Format
559 DisabledKinds map[string]bool
560 DisabledLanguages map[string]bool
561 IgnoredLogs map[string]bool
562 CreateTitle func(s string) string
563 IsUglyURLSection func(section string) bool
564 IgnoreFile func(filename string) bool
565 MainSections []string
566 Clock time.Time
567 HTTPCache httpcache.ConfigCompiled
568
569 // This is set to the last transient error found during config compilation.
570 // With themes/modules we compute the configuration in multiple passes, and
571 // errors with missing output format definitions may resolve itself.
572 transientErr error
573
574 mu sync.Mutex
575 }
576
577 // This may be set after the config is compiled.
578 func (c *ConfigCompiled) SetMainSections(sections []string) {
579 c.mu.Lock()
580 defer c.mu.Unlock()
581 c.MainSections = sections
582 }
583
584 // IsMainSectionsSet returns whether the main sections have been set.
585 func (c *ConfigCompiled) IsMainSectionsSet() bool {
586 c.mu.Lock()
587 defer c.mu.Unlock()
588 return c.MainSections != nil
589 }
590
591 // This is set after the config is compiled by the server command.
592 func (c *ConfigCompiled) SetServerInfo(baseURL, baseURLLiveReload urls.BaseURL, serverInterface string) {
593 c.BaseURL = baseURL
594 c.BaseURLLiveReload = baseURLLiveReload
595 c.ServerInterface = serverInterface
596 }
597
598 // RootConfig holds all the top-level configuration options in Hugo
599 type RootConfig struct {
600 // The base URL of the site.
601 // It defaults to https://example.org/
602 // <docsmeta>{"identifiers": ["URL"] }</docsmeta>
603 BaseURL string
604
605 // Whether to build content marked as draft.X
606 // <docsmeta>{"identifiers": ["draft"] }</docsmeta>
607 BuildDrafts bool
608
609 // Whether to build content with expiryDate in the past.
610 // <docsmeta>{"identifiers": ["expiryDate"] }</docsmeta>
611 BuildExpired bool
612
613 // Whether to build content with publishDate in the future.
614 // <docsmeta>{"identifiers": ["publishDate"] }</docsmeta>
615 BuildFuture bool
616
617 // Copyright information.
618 Copyright string
619
620 // The language to apply to content without any language indicator.
621 DefaultContentLanguage string
622
623 // By default, we put the default content language in the root and the others below their language ID, e.g. /no/.
624 // Set this to true to put all languages below their language ID.
625 DefaultContentLanguageInSubdir bool
626
627 // The default content role to use for the site.
628 DefaultContentRole string
629
630 // Set this to true to put the default role in a subdirectory.
631 DefaultContentRoleInSubdir bool
632
633 // The default content version to use for the site.
634 DefaultContentVersion string
635
636 // Set to true to render the default version in a subdirectory.
637 DefaultContentVersionInSubdir bool
638
639 // The default output format to use for the site.
640 // If not set, we will use the first output format.
641 DefaultOutputFormat string
642
643 // Disable generation of redirect to the default language when DefaultContentLanguageInSubdir is enabled.
644 // Note that this currently is an alias for DisableDefaultSiteRedirect introduced in v0.154.5.
645 // It's not obvious how a more fine grained setup would work.
646 DisableDefaultLanguageRedirect bool
647
648 // Disable generation of redirects to the default site when DefaultContentRoleInSubdir or DefaultContentVersionInSubdir or DefaultContentLanguageInSubdir is enabled.
649 // The default site is the site is the combination of defaultContentLanguage, defaultContentVersion and defaultContentRole.
650 DisableDefaultSiteRedirect bool
651
652 // Disable creation of alias redirect pages.
653 DisableAliases bool
654
655 // Disable lower casing of path segments.
656 DisablePathToLower bool
657
658 // Disable page kinds from build.
659 DisableKinds []string
660
661 // A list of languages to disable.
662 DisableLanguages []string
663
664 // The named segments to render.
665 // This needs to match the name of the segment in the segments configuration.
666 RenderSegments []string
667
668 // Disable the injection of the Hugo generator tag on the home page.
669 DisableHugoGeneratorInject bool
670
671 // Disable live reloading in server mode.
672 DisableLiveReload bool
673
674 // Enable replacement in Pages' Content of Emoji shortcodes with their equivalent Unicode characters.
675 // <docsmeta>{"identifiers": ["Content", "Unicode"] }</docsmeta>
676 EnableEmoji bool
677
678 // THe main section(s) of the site.
679 // If not set, Hugo will try to guess this from the content.
680 MainSections []string
681
682 // Enable robots.txt generation.
683 EnableRobotsTXT bool
684
685 // When enabled, Hugo will apply Git version information to each Page if possible, which
686 // can be used to keep lastUpdated in synch and to print version information.
687 // <docsmeta>{"identifiers": ["Page"] }</docsmeta>
688 EnableGitInfo bool
689
690 // Enable to track, calculate and print metrics.
691 TemplateMetrics bool
692
693 // Enable to track, print and calculate metric hints.
694 TemplateMetricsHints bool
695
696 // Enable to disable the build lock file.
697 NoBuildLock bool
698
699 // A list of log IDs to ignore.
700 IgnoreLogs []string
701
702 // A list of regexps that match paths to ignore.
703 // Deprecated: Use the settings on module imports.
704 IgnoreFiles []string
705
706 // Ignore cache.
707 IgnoreCache bool
708
709 // Enable to print greppable placeholders (on the form "[i18n] TRANSLATIONID") for missing translation strings.
710 EnableMissingTranslationPlaceholders bool
711
712 // Enable to panic on warning log entries. This may make it easier to detect the source.
713 PanicOnWarning bool
714
715 // The configured environment. Default is "development" for server and "production" for build.
716 Environment string
717
718 // Deprecated: Use Locale instead.
719 LanguageCode string `json:"-"`
720
721 // The default locale.
722 Locale string
723
724 // Enable if the site content has CJK language (Chinese, Japanese, or Korean). This affects how Hugo counts words.
725 HasCJKLanguage bool
726
727 // Whether to pluralize default list titles.
728 // Note that this currently only works for English, but you can provide your own title in the content file's front matter.
729 PluralizeListTitles bool
730
731 // Whether to capitalize automatic page titles, applicable to section, taxonomy, and term pages.
732 CapitalizeListTitles bool
733
734 // Make all relative URLs absolute using the baseURL.
735 // <docsmeta>{"identifiers": ["baseURL"] }</docsmeta>
736 CanonifyURLs bool
737
738 // Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs.
739 RelativeURLs bool
740
741 // Removes non-spacing marks from composite characters in content paths.
742 RemovePathAccents bool
743
744 // Whether to track and print unused templates during the build.
745 PrintUnusedTemplates bool
746
747 // Enable to print warnings for missing translation strings.
748 PrintI18nWarnings bool
749
750 // ENable to print warnings for multiple files published to the same destination.
751 PrintPathWarnings bool
752
753 // URL to be used as a placeholder when a page reference cannot be found in ref or relref. Is used as-is.
754 RefLinksNotFoundURL string
755
756 // When using ref or relref to resolve page links and a link cannot be resolved, it will be logged with this log level.
757 // Valid values are ERROR (default) or WARNING. Any ERROR will fail the build (exit -1).
758 RefLinksErrorLevel string
759
760 // This will create a menu with all the sections as menu items and all the sections’ pages as “shadow-members”.
761 SectionPagesMenu string
762
763 // The length of text in words to show in a .Summary.
764 SummaryLength int
765
766 // The site title.
767 Title string
768
769 // The theme(s) to use.
770 // See Modules for more a more flexible way to load themes.
771 Theme []string
772
773 // Timeout for generating page contents, specified as a duration or in seconds.
774 Timeout string
775
776 // The time zone (or location), e.g. Europe/Oslo, used to parse front matter dates without such information and in the time function.
777 TimeZone string
778
779 // Set titleCaseStyle to specify the title style used by the title template function and the automatic section titles in Hugo.
780 // 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).
781 TitleCaseStyle string
782
783 // The editor used for opening up new content.
784 NewContentEditor string
785
786 // Don't sync modification time of files for the static mounts.
787 NoTimes bool
788
789 // Don't sync modification time of files for the static mounts.
790 NoChmod 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 }