Debian Codegraph @

config/allconfig/load.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 package allconfig
16
17 import (
18 "errors"
19 "fmt"
20 "os"
21 "path/filepath"
22 "runtime/debug"
23 "strings"
24
25 "github.com/gohugoio/hugo/common/herrors"
26 "github.com/gohugoio/hugo/common/hexec"
27 "github.com/gohugoio/hugo/common/hmaps"
28 "github.com/gohugoio/hugo/common/hstrings"
29 "github.com/gohugoio/hugo/common/hugo"
30 "github.com/gohugoio/hugo/common/loggers"
31 "github.com/gohugoio/hugo/common/paths"
32 "github.com/gohugoio/hugo/common/types"
33 "github.com/gohugoio/hugo/config"
34 "github.com/gohugoio/hugo/helpers"
35 hglob "github.com/gohugoio/hugo/hugofs/hglob"
36 "github.com/gohugoio/hugo/modules"
37 "github.com/gohugoio/hugo/modules/npm"
38 "github.com/gohugoio/hugo/parser/metadecoders"
39 "github.com/spf13/afero"
40 )
41
42 //lint:ignore ST1005 end user message.
43 var ErrNoConfigFile = errors.New("Unable to locate config file or config directory. Perhaps you need to create a new project.\n Run `hugo help new` for details.\n")
44
45 func LoadConfig(d ConfigSourceDescriptor) (configs *Configs, err error) {
46 defer func() {
47 if r := recover(); r != nil {
48 err = fmt.Errorf("failed to load config: %v", r)
49 debug.PrintStack()
50 }
51 }()
52
53 if len(d.Environ) == 0 && !hugo.IsRunningAsTest() {
54 d.Environ = os.Environ()
55 }
56
57 if d.Logger == nil {
58 d.Logger = loggers.NewDefault()
59 }
60
61 l := &configLoader{ConfigSourceDescriptor: d, cfg: config.New()}
62 // Make sure we always do this, even in error situations,
63 // as we have commands (e.g. "hugo mod init") that will
64 // use a partial configuration to do its job.
65 defer l.deleteMergeStrategies()
66 res, _, err := l.loadConfigMain(d)
67 if err != nil {
68 return nil, fmt.Errorf("failed to load config: %w", err)
69 }
70
71 configs, err = fromLoadConfigResult(d.Fs, d.Logger, res)
72 if err != nil {
73 return nil, fmt.Errorf("failed to create config from result: %w", err)
74 }
75
76 moduleConfig, modulesClient, err := l.loadModules(configs, d.IgnoreModuleDoesNotExist)
77 if err != nil {
78 return nil, fmt.Errorf("failed to load modules: %w", err)
79 }
80
81 if len(l.ModulesConfigFiles) > 0 {
82 // Config merged in from modules.
83 // Re-read the config.
84 configs, err = fromLoadConfigResult(d.Fs, d.Logger, res)
85 if err != nil {
86 return nil, fmt.Errorf("failed to create config from modules config: %w", err)
87 }
88 if err := configs.transientErr(); err != nil {
89 return nil, fmt.Errorf("failed to create config from modules config: %w", err)
90 }
91 configs.LoadingInfo.ConfigFiles = append(configs.LoadingInfo.ConfigFiles, l.ModulesConfigFiles...)
92 } else if err := configs.transientErr(); err != nil && !d.IgnoreModuleDoesNotExist {
93 return nil, fmt.Errorf("failed to create config: %w", err)
94 }
95
96 configs.Modules = moduleConfig.AllModules
97 configs.ModulesClient = modulesClient
98
99 if !d.SkipNpmCheck && npm.NpmPackNeedsUpdate(d.Fs, configs.Modules) {
100 d.Logger.Warnln(`npm dependencies are out of sync, please run "hugo mod npm pack" (you may also want to run "npm install" after that)`)
101 }
102
103 if err := configs.Init(d.Fs, d.Logger); err != nil {
104 return nil, fmt.Errorf("failed to init config: %w", err)
105 }
106
107 loggers.SetGlobalLogger(d.Logger)
108
109 return
110 }
111
112 // ConfigSourceDescriptor describes where to find the config (e.g. config.toml etc.).
113 type ConfigSourceDescriptor struct {
114 Fs afero.Fs
115 Logger loggers.Logger
116
117 // Config received from the command line.
118 // These will override any config file settings.
119 Flags config.Provider
120
121 // Path to the config file to use, e.g. /my/project/config.toml
122 Filename string
123
124 // The (optional) directory for additional configuration files.
125 ConfigDir string
126
127 // production, development
128 Environment string
129
130 // Defaults to os.Environ if not set.
131 Environ []string
132
133 // If set, this will be used to ignore the module does not exist error.
134 IgnoreModuleDoesNotExist bool
135
136 // If set, skip the npm pack staleness check (used by hugo mod npm pack).
137 SkipNpmCheck bool
138 }
139
140 func (d ConfigSourceDescriptor) configFilenames() []string {
141 if d.Filename == "" {
142 return nil
143 }
144 return strings.Split(d.Filename, ",")
145 }
146
147 type configLoader struct {
148 cfg config.Provider
149 BaseConfig config.BaseConfig
150 ConfigSourceDescriptor
151
152 // collected
153 ModulesConfig modules.ModulesConfig
154 ModulesConfigFiles []string
155 }
156
157 // Handle some legacy values.
158 func (l configLoader) applyConfigAliases() error {
159 aliases := []types.KeyValueStr{
160 {Key: "indexes", Value: "taxonomies"},
161 {Key: "logI18nWarnings", Value: "printI18nWarnings"},
162 {Key: "logPathWarnings", Value: "printPathWarnings"},
163 {Key: "ignoreErrors", Value: "ignoreLogs"},
164 }
165
166 for _, alias := range aliases {
167 if l.cfg.IsSet(alias.Key) {
168 vv := l.cfg.Get(alias.Key)
169 l.cfg.Set(alias.Value, vv)
170 }
171 }
172
173 return nil
174 }
175
176 func (l configLoader) applyDefaultConfig() error {
177 defaultSettings := hmaps.Params{
178 // These dirs are used early/before we build the config struct.
179 "themesDir": "themes",
180 "configDir": "config",
181 }
182
183 l.cfg.SetDefaults(defaultSettings)
184
185 return nil
186 }
187
188 func (l configLoader) normalizeCfg(cfg config.Provider) error {
189 if b, ok := cfg.Get("minifyOutput").(bool); ok {
190 hugo.Deprecate("project config minifyOutput", "Use minify.minifyOutput instead.", "v0.150.0")
191 if b {
192 cfg.Set("minify.minifyOutput", true)
193 }
194 } else if b, ok := cfg.Get("minify").(bool); ok {
195 hugo.Deprecate("project config minify", "Use minify.minifyOutput instead.", "v0.150.0")
196 if b {
197 cfg.Set("minify", hmaps.Params{"minifyOutput": true})
198 }
199 }
200
201 if b, ok := cfg.Get("cleanDestinationDir").(bool); ok {
202 hugo.Deprecate("project config cleanDestinationDir", "Use build.cleanDestinationDir.enable instead.", "v0.167.0")
203 if b {
204 cfg.Set("build.cleanDestinationDir.enable", true)
205 }
206 }
207
208 return nil
209 }
210
211 func (l configLoader) cleanExternalConfig(cfg config.Provider) error {
212 if cfg.IsSet("internal") {
213 cfg.Set("internal", nil)
214 }
215 return nil
216 }
217
218 func (l configLoader) applyFlagsOverrides(cfg config.Provider) error {
219 for _, k := range cfg.Keys() {
220 l.cfg.Set(k, cfg.Get(k))
221 }
222 return nil
223 }
224
225 func (l configLoader) applyOsEnvOverrides(environ []string) error {
226 if len(environ) == 0 {
227 return nil
228 }
229
230 const delim = "__env__delim"
231
232 // Extract all that start with the HUGO prefix.
233 // The delimiter is the following rune, usually "_".
234 const hugoEnvPrefix = "HUGO"
235 var hugoEnv []types.KeyValueStr
236 for _, v := range environ {
237 key, val := config.SplitEnvVar(v)
238 if after, ok := strings.CutPrefix(key, hugoEnvPrefix); ok {
239 delimiterAndKey := after
240 if len(delimiterAndKey) < 2 {
241 continue
242 }
243 // Allow delimiters to be case sensitive.
244 // It turns out there isn't that many allowed special
245 // chars in environment variables when used in Bash and similar,
246 // so variables on the form HUGOxPARAMSxFOO=bar is one option.
247 key := strings.ReplaceAll(delimiterAndKey[1:], delimiterAndKey[:1], delim)
248 key = strings.ToLower(key)
249 hugoEnv = append(hugoEnv, types.KeyValueStr{
250 Key: key,
251 Value: val,
252 })
253
254 }
255 }
256
257 for _, env := range hugoEnv {
258 existing, nestedKey, owner, err := hmaps.GetNestedParamFn(env.Key, delim, l.cfg.Get)
259 if err != nil {
260 return err
261 }
262
263 if existing != nil {
264 val, err := metadecoders.Default.UnmarshalStringTo(env.Value, existing)
265 if err == nil {
266 val = l.envValToVal(env.Key, val)
267 if owner != nil {
268 owner[nestedKey] = val
269 } else {
270 l.cfg.Set(env.Key, val)
271 }
272 continue
273 }
274 }
275
276 if owner != nil && nestedKey != "" {
277 owner[nestedKey] = env.Value
278 } else {
279 var val any
280 key := strings.ReplaceAll(env.Key, delim, ".")
281 _, ok := allDecoderSetups[key]
282 if ok {
283 // A map.
284 if v, err := metadecoders.Default.UnmarshalStringTo(env.Value, map[string]any{}); err == nil {
285 val = v
286 }
287 }
288
289 if val == nil {
290 // A string.
291 val = l.envStringToVal(key, env.Value)
292 }
293 l.cfg.Set(key, val)
294 }
295
296 }
297
298 return nil
299 }
300
301 func (l *configLoader) envValToVal(k string, v any) any {
302 switch v := v.(type) {
303 case string:
304 return l.envStringToVal(k, v)
305 default:
306 return v
307 }
308 }
309
310 func (l *configLoader) envStringToVal(k, v string) any {
311 switch k {
312 case "disablekinds", "disablelanguages", "ignorefiles", "ignorelogs":
313 v = strings.TrimSpace(v)
314 if strings.HasPrefix(v, "[") && strings.HasSuffix(v, "]") {
315 if parsed, err := metadecoders.Default.UnmarshalStringTo(v, []any{}); err == nil {
316 return parsed
317 }
318 }
319
320 if strings.Contains(v, ",") {
321 return strings.Split(v, ",")
322 } else {
323 return strings.Fields(v)
324 }
325 default:
326 return v
327 }
328 }
329
330 func (l *configLoader) loadConfigMain(d ConfigSourceDescriptor) (config.LoadConfigResult, modules.ModulesConfig, error) {
331 var res config.LoadConfigResult
332
333 if d.Flags != nil {
334 if err := l.normalizeCfg(d.Flags); err != nil {
335 return res, l.ModulesConfig, err
336 }
337 }
338
339 if d.Fs == nil {
340 return res, l.ModulesConfig, errors.New("no filesystem provided")
341 }
342
343 if d.Flags != nil {
344 if err := l.applyFlagsOverrides(d.Flags); err != nil {
345 return res, l.ModulesConfig, err
346 }
347 workingDir := filepath.Clean(l.cfg.GetString("workingDir"))
348
349 l.BaseConfig = config.BaseConfig{
350 WorkingDir: workingDir,
351 ThemesDir: paths.AbsPathify(workingDir, l.cfg.GetString("themesDir")),
352 }
353
354 }
355
356 names := d.configFilenames()
357
358 if names != nil {
359 for _, name := range names {
360 var filename string
361 filename, err := l.loadConfig(name)
362 if err == nil {
363 res.ConfigFiles = append(res.ConfigFiles, filename)
364 } else if err != ErrNoConfigFile {
365 return res, l.ModulesConfig, l.wrapFileError(err, filename)
366 }
367 }
368 } else {
369 for _, name := range config.DefaultConfigNames {
370 var filename string
371 filename, err := l.loadConfig(name)
372 if err == nil {
373 res.ConfigFiles = append(res.ConfigFiles, filename)
374 break
375 } else if err != ErrNoConfigFile {
376 return res, l.ModulesConfig, l.wrapFileError(err, filename)
377 }
378 }
379 }
380
381 if d.ConfigDir != "" {
382 absConfigDir := paths.AbsPathify(l.BaseConfig.WorkingDir, d.ConfigDir)
383 dcfg, dirnames, err := config.LoadConfigFromDir(l.Fs, absConfigDir, l.Environment)
384 if err == nil {
385 if len(dirnames) > 0 {
386 if err := l.normalizeCfg(dcfg); err != nil {
387 return res, l.ModulesConfig, err
388 }
389 if err := l.cleanExternalConfig(dcfg); err != nil {
390 return res, l.ModulesConfig, err
391 }
392 l.cfg.Set("", dcfg.Get(""))
393 res.ConfigFiles = append(res.ConfigFiles, dirnames...)
394 }
395 } else if err != ErrNoConfigFile {
396 if len(dirnames) > 0 {
397 return res, l.ModulesConfig, l.wrapFileError(err, dirnames[0])
398 }
399 return res, l.ModulesConfig, err
400 }
401 }
402
403 res.Cfg = l.cfg
404
405 if err := l.applyDefaultConfig(); err != nil {
406 return res, l.ModulesConfig, err
407 }
408
409 // Some settings are used before we're done collecting all settings,
410 // so apply OS environment both before and after.
411 if err := l.applyOsEnvOverrides(d.Environ); err != nil {
412 return res, l.ModulesConfig, err
413 }
414
415 workingDir := filepath.Clean(l.cfg.GetString("workingDir"))
416
417 l.BaseConfig = config.BaseConfig{
418 WorkingDir: workingDir,
419 CacheDir: l.cfg.GetString("cacheDir"),
420 ThemesDir: paths.AbsPathify(workingDir, l.cfg.GetString("themesDir")),
421 }
422
423 var err error
424 l.BaseConfig.CacheDir, err = helpers.GetCacheDir(l.Fs, l.BaseConfig.CacheDir)
425 if err != nil {
426 return res, l.ModulesConfig, err
427 }
428
429 res.BaseConfig = l.BaseConfig
430
431 l.cfg.SetDefaultMergeStrategy()
432
433 res.ConfigFiles = append(res.ConfigFiles, l.ModulesConfigFiles...)
434
435 if d.Flags != nil {
436 if err := l.applyFlagsOverrides(d.Flags); err != nil {
437 return res, l.ModulesConfig, err
438 }
439 }
440
441 if err := l.applyOsEnvOverrides(d.Environ); err != nil {
442 return res, l.ModulesConfig, err
443 }
444
445 if err = l.applyConfigAliases(); err != nil {
446 return res, l.ModulesConfig, err
447 }
448
449 return res, l.ModulesConfig, err
450 }
451
452 func (l *configLoader) loadModules(configs *Configs, ignoreModuleDoesNotExist bool) (modules.ModulesConfig, *modules.Client, error) {
453 bcfg := configs.LoadingInfo.BaseConfig
454 conf := configs.Base
455 workingDir := bcfg.WorkingDir
456 themesDir := bcfg.ThemesDir
457 publishDir := bcfg.PublishDir
458
459 cfg := configs.LoadingInfo.Cfg
460
461 var ignoreVendor hstrings.Matcher
462 if s := conf.IgnoreVendorPaths; s != "" {
463 ignoreVendor, _ = hglob.GetGlob(hglob.NormalizePath(s))
464 }
465
466 ex := hexec.New(conf.Security, workingDir, l.Logger)
467
468 hook := func(m *modules.ModulesConfig) error {
469 for _, tc := range m.AllModules {
470 if len(tc.ConfigFilenames()) > 0 {
471 if tc.Watch() {
472 l.ModulesConfigFiles = append(l.ModulesConfigFiles, tc.ConfigFilenames()...)
473 }
474
475 // Merge in the theme config using the configured
476 // merge strategy.
477 cfg.Merge("", tc.Cfg().Get(""))
478
479 }
480 }
481
482 return nil
483 }
484
485 modulesClient := modules.NewClient(modules.ClientConfig{
486 Fs: l.Fs,
487 Logger: l.Logger,
488 Exec: ex,
489 HookBeforeFinalize: hook,
490 WorkingDir: workingDir,
491 ThemesDir: themesDir,
492 PublishDir: publishDir,
493 Environment: l.Environment,
494 CacheDir: conf.Caches.CacheDirModules(),
495 ModuleQueriesCache: configs.FileCaches.ModuleQueriesCache(),
496 ModuleConfig: conf.Module,
497 IgnoreVendor: ignoreVendor,
498 IgnoreModuleDoesNotExist: ignoreModuleDoesNotExist,
499 })
500
501 moduleConfig, err := modulesClient.Collect()
502
503 // We want to watch these for changes and trigger rebuild on version
504 // changes etc.
505 if moduleConfig.GoModulesFilename != "" {
506 l.ModulesConfigFiles = append(l.ModulesConfigFiles, moduleConfig.GoModulesFilename)
507 }
508
509 if moduleConfig.GoWorkspaceFilename != "" {
510 l.ModulesConfigFiles = append(l.ModulesConfigFiles, moduleConfig.GoWorkspaceFilename)
511 }
512
513 return moduleConfig, modulesClient, err
514 }
515
516 func (l configLoader) loadConfig(configName string) (string, error) {
517 baseDir := l.BaseConfig.WorkingDir
518 var baseFilename string
519 if filepath.IsAbs(configName) {
520 baseFilename = configName
521 } else {
522 baseFilename = filepath.Join(baseDir, configName)
523 }
524
525 var filename string
526 if paths.ExtNoDelimiter(configName) != "" {
527 exists, _ := helpers.Exists(baseFilename, l.Fs)
528 if exists {
529 filename = baseFilename
530 }
531 } else {
532 for _, ext := range config.ValidConfigFileExtensions {
533 filenameToCheck := baseFilename + "." + ext
534 exists, _ := helpers.Exists(filenameToCheck, l.Fs)
535 if exists {
536 filename = filenameToCheck
537 break
538 }
539 }
540 }
541
542 if filename == "" {
543 return "", ErrNoConfigFile
544 }
545
546 m, err := config.FromFileToMap(l.Fs, filename)
547 if err != nil {
548 return filename, err
549 }
550
551 // Set overwrites keys of the same name, recursively.
552 l.cfg.Set("", m)
553
554 if err := l.normalizeCfg(l.cfg); err != nil {
555 return filename, err
556 }
557
558 if err := l.cleanExternalConfig(l.cfg); err != nil {
559 return filename, err
560 }
561
562 return filename, nil
563 }
564
565 func (l configLoader) deleteMergeStrategies() (err error) {
566 l.cfg.WalkParams(func(params ...hmaps.KeyParams) bool {
567 params[len(params)-1].Params.DeleteMergeStrategy()
568 return false
569 })
570 return
571 }
572
573 func (l configLoader) wrapFileError(err error, filename string) error {
574 fe := herrors.UnwrapFileError(err)
575 if fe != nil {
576 pos := fe.Position()
577 pos.Filename = filename
578 fe.UpdatePosition(pos)
579 return err
580 }
581 return herrors.NewFileErrorFromFile(err, filename, l.Fs, nil)
582 }