Debian Codegraph @

config/configLoader.go

raw
1 // Copyright 2025 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 config
15
16 import (
17 "fmt"
18 "os"
19 "path/filepath"
20 "strings"
21
22 "github.com/gohugoio/hugo/common/herrors"
23 "github.com/gohugoio/hugo/common/hmaps"
24 "github.com/gohugoio/hugo/parser"
25
26 "github.com/gohugoio/hugo/common/paths"
27
28 "github.com/gohugoio/hugo/parser/metadecoders"
29 "github.com/spf13/afero"
30 )
31
32 var (
33 // See issue #8979 for context.
34 // Hugo has always used config.toml etc. as the default config file name.
35 // But hugo.toml is a more descriptive name, but we need to check for both.
36 DefaultConfigNames = []string{"hugo", "config"}
37
38 DefaultConfigNamesSet = make(map[string]bool)
39
40 ValidConfigFileExtensions = []string{"toml", "yaml", "yml", "json"}
41 validConfigFileExtensionsMap map[string]bool = make(map[string]bool)
42 )
43
44 func init() {
45 for _, name := range DefaultConfigNames {
46 DefaultConfigNamesSet[name] = true
47 }
48
49 for _, ext := range ValidConfigFileExtensions {
50 validConfigFileExtensionsMap[ext] = true
51 }
52 }
53
54 // IsValidConfigFilename returns whether filename is one of the supported
55 // config formats in Hugo.
56 func IsValidConfigFilename(filename string) bool {
57 ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(filename), "."))
58 return validConfigFileExtensionsMap[ext]
59 }
60
61 // FromTOMLConfigString creates a config from the given TOML config. This is useful in tests.
62 func FromTOMLConfigString(config string) Provider {
63 cfg, err := FromConfigString(config, "toml")
64 if err != nil {
65 panic(err)
66 }
67 return cfg
68 }
69
70 // FromMapToTOMLString converts the given map to a TOML string. This is useful in tests.
71 func FromMapToTOMLString(v map[string]any) string {
72 var sb strings.Builder
73 err := parser.InterfaceToConfig(v, metadecoders.TOML, &sb)
74 if err != nil {
75 panic(err)
76 }
77 return sb.String()
78 }
79
80 // FromConfigString creates a config from the given YAML, JSON or TOML config. This is useful in tests.
81 func FromConfigString(config, configType string) (Provider, error) {
82 m, err := readConfig(metadecoders.FormatFromString(configType), []byte(config))
83 if err != nil {
84 return nil, err
85 }
86 return NewFrom(m), nil
87 }
88
89 // FromFile loads the configuration from the given filename.
90 func FromFile(fs afero.Fs, filename string) (Provider, error) {
91 m, err := loadConfigFromFile(fs, filename)
92 if err != nil {
93 fe := herrors.UnwrapFileError(err)
94 if fe != nil {
95 pos := fe.Position()
96 pos.Filename = filename
97 fe.UpdatePosition(pos)
98 return nil, err
99 }
100 return nil, herrors.NewFileErrorFromFile(err, filename, fs, nil)
101 }
102 return NewFrom(m), nil
103 }
104
105 // FromFileToMap is the same as FromFile, but it returns the config values
106 // as a simple map.
107 func FromFileToMap(fs afero.Fs, filename string) (map[string]any, error) {
108 return loadConfigFromFile(fs, filename)
109 }
110
111 func readConfig(format metadecoders.Format, data []byte) (map[string]any, error) {
112 m, err := metadecoders.Default.UnmarshalToMap(data, format)
113 if err != nil {
114 return nil, err
115 }
116
117 RenameKeys(m)
118
119 return m, nil
120 }
121
122 func loadConfigFromFile(fs afero.Fs, filename string) (map[string]any, error) {
123 m, err := metadecoders.Default.UnmarshalFileToMap(fs, filename)
124 if err != nil {
125 return nil, err
126 }
127 RenameKeys(m)
128 return m, nil
129 }
130
131 func LoadConfigFromDir(sourceFs afero.Fs, configDir, environment string) (Provider, []string, error) {
132 defaultConfigDir := filepath.Join(configDir, "_default")
133 environmentConfigDir := filepath.Join(configDir, environment)
134 cfg := New()
135
136 var configDirs []string
137 // Merge from least to most specific.
138 for _, dir := range []string{defaultConfigDir, environmentConfigDir} {
139 if _, err := sourceFs.Stat(dir); err == nil {
140 configDirs = append(configDirs, dir)
141 }
142 }
143
144 if len(configDirs) == 0 {
145 return nil, nil, nil
146 }
147
148 // Keep track of these so we can watch them for changes.
149 var dirnames []string
150
151 for _, configDir := range configDirs {
152 err := afero.Walk(sourceFs, configDir, func(path string, fi os.FileInfo, err error) error {
153 if fi == nil || err != nil {
154 return nil
155 }
156
157 if fi.IsDir() {
158 dirnames = append(dirnames, path)
159 return nil
160 }
161
162 if !IsValidConfigFilename(path) {
163 return nil
164 }
165
166 name := paths.Filename(filepath.Base(path))
167
168 item, err := metadecoders.Default.UnmarshalFileToMap(sourceFs, path)
169 if err != nil {
170 // This will be used in error reporting, use the most specific value.
171 dirnames = []string{path}
172 return fmt.Errorf("failed to unmarshal config for path %q: %w", path, err)
173 }
174
175 var keyPath []string
176 var unwrapKey string
177 if !DefaultConfigNamesSet[name] {
178 // Can be params.jp, menus.en etc.
179 name, lang := paths.FileAndExtNoDelimiter(name)
180 unwrapKey = name
181
182 keyPath = []string{name}
183
184 if lang != "" {
185 keyPath = []string{"languages", lang}
186 switch name {
187 case "menu", "menus":
188 keyPath = append(keyPath, "menus")
189 case "params":
190 keyPath = append(keyPath, "params")
191 }
192 }
193 }
194
195 // TOML/YAML can't represent a headless top-level array, so allow a
196 // file to wrap its content under a single top-level key matching
197 // the basename (e.g. cascade.yaml with `cascade: [...]`).
198 var itemValue any = item
199 if unwrapKey != "" && len(item) == 1 {
200 if inner, ok := item[unwrapKey]; ok {
201 itemValue = inner
202 }
203 }
204
205 root := item
206 if len(keyPath) > 0 {
207 root = make(map[string]any)
208 m := root
209 for i, key := range keyPath {
210 if i >= len(keyPath)-1 {
211 m[key] = itemValue
212 } else {
213 nm := make(map[string]any)
214 m[key] = nm
215 m = nm
216 }
217 }
218 }
219
220 // Migrate menu => menus etc.
221 RenameKeys(root)
222
223 // Set will overwrite keys with the same name, recursively.
224 cfg.Set("", root)
225
226 return nil
227 })
228 if err != nil {
229 return nil, dirnames, err
230 }
231
232 }
233
234 return cfg, dirnames, nil
235 }
236
237 var keyAliases hmaps.KeyRenamer
238
239 func init() {
240 var err error
241 keyAliases, err = hmaps.NewKeyRenamer(
242 // Before 0.53 we used singular for "menu".
243 "{menu,languages/*/menu}", "menus",
244 )
245 if err != nil {
246 panic(err)
247 }
248 }
249
250 // RenameKeys renames config keys in m recursively according to a global Hugo
251 // alias definition.
252 func RenameKeys(m map[string]any) {
253 keyAliases.Rename(m)
254 }