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/gobwas/glob"
26 "github.com/gohugoio/hugo/common/herrors"
27 "github.com/gohugoio/hugo/common/hexec"
28 "github.com/gohugoio/hugo/common/hmaps"
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 {
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 return nil
202 }
203
204 func (l configLoader) cleanExternalConfig(cfg config.Provider) error {
205 if cfg.IsSet("internal") {
206 cfg.Set("internal", nil)
207 }
208 return nil
209 }
210
211 func (l configLoader) applyFlagsOverrides(cfg config.Provider) error {
212 for _, k := range cfg.Keys() {
213 l.cfg.Set(k, cfg.Get(k))
214 }
215 return nil
216 }
217
218 func (l configLoader) applyOsEnvOverrides(environ []string) error {
219 if len(environ) == 0 {
220 return nil
221 }
222
223 const delim = "__env__delim"
224
225 // Extract all that start with the HUGO prefix.
226 // The delimiter is the following rune, usually "_".
227 const hugoEnvPrefix = "HUGO"
228 var hugoEnv []types.KeyValueStr
229 for _, v := range environ {
230 key, val := config.SplitEnvVar(v)
231 if after, ok := strings.CutPrefix(key, hugoEnvPrefix); ok {
232 delimiterAndKey := after
233 if len(delimiterAndKey) < 2 {
234 continue
235 }
236 // Allow delimiters to be case sensitive.
237 // It turns out there isn't that many allowed special
238 // chars in environment variables when used in Bash and similar,
239 // so variables on the form HUGOxPARAMSxFOO=bar is one option.
240 key := strings.ReplaceAll(delimiterAndKey[1:], delimiterAndKey[:1], delim)
241 key = strings.ToLower(key)
242 hugoEnv = append(hugoEnv, types.KeyValueStr{
243 Key: key,
244 Value: val,
245 })
246
247 }
248 }
249
250 for _, env := range hugoEnv {
251 existing, nestedKey, owner, err := hmaps.GetNestedParamFn(env.Key, delim, l.cfg.Get)
252 if err != nil {
253 return err
254 }
255
256 if existing != nil {
257 val, err := metadecoders.Default.UnmarshalStringTo(env.Value, existing)
258 if err == nil {
259 val = l.envValToVal(env.Key, val)
260 if owner != nil {
261 owner[nestedKey] = val
262 } else {
263 l.cfg.Set(env.Key, val)
264 }
265 continue
266 }
267 }
268
269 if owner != nil && nestedKey != "" {
270 owner[nestedKey] = env.Value
271 } else {
272 var val any
273 key := strings.ReplaceAll(env.Key, delim, ".")
274 _, ok := allDecoderSetups[key]
275 if ok {
276 // A map.
277 if v, err := metadecoders.Default.UnmarshalStringTo(env.Value, map[string]any{}); err == nil {
278 val = v
279 }
280 }
281
282 if val == nil {
283 // A string.
284 val = l.envStringToVal(key, env.Value)
285 }
286 l.cfg.Set(key, val)
287 }
288
289 }
290
291 return nil
292 }
293
294 func (l *configLoader) envValToVal(k string, v any) any {
295 switch v := v.(type) {
296 case string:
297 return l.envStringToVal(k, v)
298 default:
299 return v
300 }
301 }
302
303 func (l *configLoader) envStringToVal(k, v string) any {
304 switch k {
305 case "disablekinds", "disablelanguages", "ignorefiles", "ignorelogs":
306 v = strings.TrimSpace(v)
307 if strings.HasPrefix(v, "[") && strings.HasSuffix(v, "]") {
308 if parsed, err := metadecoders.Default.UnmarshalStringTo(v, []any{}); err == nil {
309 return parsed
310 }
311 }
312
313 if strings.Contains(v, ",") {
314 return strings.Split(v, ",")
315 } else {
316 return strings.Fields(v)
317 }
318 default:
319 return v
320 }
321 }
322
323 func (l *configLoader) loadConfigMain(d ConfigSourceDescriptor) (config.LoadConfigResult, modules.ModulesConfig, error) {
324 var res config.LoadConfigResult
325
326 if d.Flags != nil {
327 if err := l.normalizeCfg(d.Flags); err != nil {
328 return res, l.ModulesConfig, err
329 }
330 }
331
332 if d.Fs == nil {
333 return res, l.ModulesConfig, errors.New("no filesystem provided")
334 }
335
336 if d.Flags != nil {
337 if err := l.applyFlagsOverrides(d.Flags); err != nil {
338 return res, l.ModulesConfig, err
339 }
340 workingDir := filepath.Clean(l.cfg.GetString("workingDir"))
341
342 l.BaseConfig = config.BaseConfig{
343 WorkingDir: workingDir,
344 ThemesDir: paths.AbsPathify(workingDir, l.cfg.GetString("themesDir")),
345 }
346
347 }
348
349 names := d.configFilenames()
350
351 if names != nil {
352 for _, name := range names {
353 var filename string
354 filename, err := l.loadConfig(name)
355 if err == nil {
356 res.ConfigFiles = append(res.ConfigFiles, filename)
357 } else if err != ErrNoConfigFile {
358 return res, l.ModulesConfig, l.wrapFileError(err, filename)
359 }
360 }
361 } else {
362 for _, name := range config.DefaultConfigNames {
363 var filename string
364 filename, err := l.loadConfig(name)
365 if err == nil {
366 res.ConfigFiles = append(res.ConfigFiles, filename)
367 break
368 } else if err != ErrNoConfigFile {
369 return res, l.ModulesConfig, l.wrapFileError(err, filename)
370 }
371 }
372 }
373
374 if d.ConfigDir != "" {
375 absConfigDir := paths.AbsPathify(l.BaseConfig.WorkingDir, d.ConfigDir)
376 dcfg, dirnames, err := config.LoadConfigFromDir(l.Fs, absConfigDir, l.Environment)
377 if err == nil {
378 if len(dirnames) > 0 {
379 if err := l.normalizeCfg(dcfg); err != nil {
380 return res, l.ModulesConfig, err
381 }
382 if err := l.cleanExternalConfig(dcfg); err != nil {
383 return res, l.ModulesConfig, err
384 }
385 l.cfg.Set("", dcfg.Get(""))
386 res.ConfigFiles = append(res.ConfigFiles, dirnames...)
387 }
388 } else if err != ErrNoConfigFile {
389 if len(dirnames) > 0 {
390 return res, l.ModulesConfig, l.wrapFileError(err, dirnames[0])
391 }
392 return res, l.ModulesConfig, err
393 }
394 }
395
396 res.Cfg = l.cfg
397
398 if err := l.applyDefaultConfig(); err != nil {
399 return res, l.ModulesConfig, err
400 }
401
402 // Some settings are used before we're done collecting all settings,
403 // so apply OS environment both before and after.
404 if err := l.applyOsEnvOverrides(d.Environ); err != nil {
405 return res, l.ModulesConfig, err
406 }
407
408 workingDir := filepath.Clean(l.cfg.GetString("workingDir"))
409
410 l.BaseConfig = config.BaseConfig{
411 WorkingDir: workingDir,
412 CacheDir: l.cfg.GetString("cacheDir"),
413 ThemesDir: paths.AbsPathify(workingDir, l.cfg.GetString("themesDir")),
414 }
415
416 var err error
417 l.BaseConfig.CacheDir, err = helpers.GetCacheDir(l.Fs, l.BaseConfig.CacheDir)
418 if err != nil {
419 return res, l.ModulesConfig, err
420 }
421
422 res.BaseConfig = l.BaseConfig
423
424 l.cfg.SetDefaultMergeStrategy()
425
426 res.ConfigFiles = append(res.ConfigFiles, l.ModulesConfigFiles...)
427
428 if d.Flags != nil {
429 if err := l.applyFlagsOverrides(d.Flags); err != nil {
430 return res, l.ModulesConfig, err
431 }
432 }
433
434 if err := l.applyOsEnvOverrides(d.Environ); err != nil {
435 return res, l.ModulesConfig, err
436 }
437
438 if err = l.applyConfigAliases(); err != nil {
439 return res, l.ModulesConfig, err
440 }
441
442 return res, l.ModulesConfig, err
443 }
444
445 func (l *configLoader) loadModules(configs *Configs, ignoreModuleDoesNotExist bool) (modules.ModulesConfig, *modules.Client, error) {
446 bcfg := configs.LoadingInfo.BaseConfig
447 conf := configs.Base
448 workingDir := bcfg.WorkingDir
449 themesDir := bcfg.ThemesDir
450 publishDir := bcfg.PublishDir
451
452 cfg := configs.LoadingInfo.Cfg
453
454 var ignoreVendor glob.Glob
455 if s := conf.IgnoreVendorPaths; s != "" {
456 ignoreVendor, _ = hglob.GetGlob(hglob.NormalizePath(s))
457 }
458
459 ex := hexec.New(conf.Security, workingDir, l.Logger)
460
461 hook := func(m *modules.ModulesConfig) error {
462 for _, tc := range m.AllModules {
463 if len(tc.ConfigFilenames()) > 0 {
464 if tc.Watch() {
465 l.ModulesConfigFiles = append(l.ModulesConfigFiles, tc.ConfigFilenames()...)
466 }
467
468 // Merge in the theme config using the configured
469 // merge strategy.
470 cfg.Merge("", tc.Cfg().Get(""))
471
472 }
473 }
474
475 return nil
476 }
477
478 modulesClient := modules.NewClient(modules.ClientConfig{
479 Fs: l.Fs,
480 Logger: l.Logger,
481 Exec: ex,
482 HookBeforeFinalize: hook,
483 WorkingDir: workingDir,
484 ThemesDir: themesDir,
485 PublishDir: publishDir,
486 Environment: l.Environment,
487 CacheDir: conf.Caches.CacheDirModules(),
488 ModuleQueriesCache: configs.FileCaches.ModuleQueriesCache(),
489 ModuleConfig: conf.Module,
490 IgnoreVendor: ignoreVendor,
491 IgnoreModuleDoesNotExist: ignoreModuleDoesNotExist,
492 })
493
494 moduleConfig, err := modulesClient.Collect()
495
496 // We want to watch these for changes and trigger rebuild on version
497 // changes etc.
498 if moduleConfig.GoModulesFilename != "" {
499 l.ModulesConfigFiles = append(l.ModulesConfigFiles, moduleConfig.GoModulesFilename)
500 }
501
502 if moduleConfig.GoWorkspaceFilename != "" {
503 l.ModulesConfigFiles = append(l.ModulesConfigFiles, moduleConfig.GoWorkspaceFilename)
504 }
505
506 return moduleConfig, modulesClient, err
507 }
508
509 func (l configLoader) loadConfig(configName string) (string, error) {
510 baseDir := l.BaseConfig.WorkingDir
511 var baseFilename string
512 if filepath.IsAbs(configName) {
513 baseFilename = configName
514 } else {
515 baseFilename = filepath.Join(baseDir, configName)
516 }
517
518 var filename string
519 if paths.ExtNoDelimiter(configName) != "" {
520 exists, _ := helpers.Exists(baseFilename, l.Fs)
521 if exists {
522 filename = baseFilename
523 }
524 } else {
525 for _, ext := range config.ValidConfigFileExtensions {
526 filenameToCheck := baseFilename + "." + ext
527 exists, _ := helpers.Exists(filenameToCheck, l.Fs)
528 if exists {
529 filename = filenameToCheck
530 break
531 }
532 }
533 }
534
535 if filename == "" {
536 return "", ErrNoConfigFile
537 }
538
539 m, err := config.FromFileToMap(l.Fs, filename)
540 if err != nil {
541 return filename, err
542 }
543
544 // Set overwrites keys of the same name, recursively.
545 l.cfg.Set("", m)
546
547 if err := l.normalizeCfg(l.cfg); err != nil {
548 return filename, err
549 }
550
551 if err := l.cleanExternalConfig(l.cfg); err != nil {
552 return filename, err
553 }
554
555 return filename, nil
556 }
557
558 func (l configLoader) deleteMergeStrategies() (err error) {
559 l.cfg.WalkParams(func(params ...hmaps.KeyParams) bool {
560 params[len(params)-1].Params.DeleteMergeStrategy()
561 return false
562 })
563 return
564 }
565
566 func (l configLoader) wrapFileError(err error, filename string) error {
567 fe := herrors.UnwrapFileError(err)
568 if fe != nil {
569 pos := fe.Position()
570 pos.Filename = filename
571 fe.UpdatePosition(pos)
572 return err
573 }
574 return herrors.NewFileErrorFromFile(err, filename, l.Fs, nil)
575 }