Debian Codegraph @

modules/config.go

raw
1 // Copyright 2019 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 modules
15
16 import (
17 "fmt"
18 "os"
19 "path/filepath"
20 "slices"
21 "strings"
22
23 "github.com/bep/logg"
24 "github.com/gohugoio/hugo/common/hstrings"
25 "github.com/gohugoio/hugo/common/hugo"
26 "github.com/gohugoio/hugo/common/types"
27 "github.com/gohugoio/hugo/common/version"
28 "github.com/gohugoio/hugo/hugofs/files"
29 hglob "github.com/gohugoio/hugo/hugofs/hglob"
30 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
31 "github.com/gohugoio/hugo/langs"
32
33 "github.com/gohugoio/hugo/config"
34 "github.com/mitchellh/mapstructure"
35 )
36
37 const WorkspaceDisabled = "off"
38
39 var DefaultModuleConfig = Config{
40 // Default to direct, which means "git clone" and similar. We
41 // will investigate proxy settings in more depth later.
42 // See https://github.com/golang/go/issues/26334
43 Proxy: "direct",
44
45 // Comma separated glob list matching paths that should not use the
46 // proxy configured above.
47 NoProxy: "none",
48
49 // Comma separated glob list matching paths that should be
50 // treated as private.
51 Private: "*.*",
52
53 // Default is no workspace resolution.
54 Workspace: WorkspaceDisabled,
55
56 // A list of replacement directives mapping a module path to a directory
57 // or a theme component in the themes folder.
58 // Note that this will turn the component into a traditional theme component
59 // that does not partake in vendoring etc.
60 // The syntax is the similar to the replacement directives used in go.mod, e.g:
61 // github.com/mod1 -> ../mod1,github.com/mod2 -> ../mod2
62 Replacements: nil,
63 }
64
65 // ApplyProjectConfigDefaults applies default/missing module configuration for
66 // the main project.
67 func ApplyProjectConfigDefaults(logger logg.Logger, mod Module, cfgs ...config.AllProvider) error {
68 moda := mod.(*moduleAdapter)
69
70 // To bridge between old and new configuration format we need
71 // a way to make sure all of the core components are configured on
72 // the basic level.
73 componentsConfigured := make(map[string]bool)
74 for _, mnt := range moda.mounts {
75 if !strings.HasPrefix(mnt.Target, files.JsConfigFolderMountPrefix) {
76 componentsConfigured[mnt.Component()] = true
77 }
78 }
79
80 var mounts []Mount
81
82 for _, component := range []string{
83 files.ComponentFolderContent,
84 files.ComponentFolderData,
85 files.ComponentFolderLayouts,
86 files.ComponentFolderI18n,
87 files.ComponentFolderArchetypes,
88 files.ComponentFolderAssets,
89 files.ComponentFolderStatic,
90 } {
91 if componentsConfigured[component] {
92 continue
93 }
94
95 first := cfgs[0]
96 dirsBase := first.DirsBase()
97 isMultihost := first.IsMultihost()
98
99 for i, cfg := range cfgs {
100 dirs := cfg.Dirs()
101 var dir string
102 var dropLang bool
103 switch component {
104 case files.ComponentFolderContent:
105 dir = dirs.ContentDir
106 dropLang = dir == dirsBase.ContentDir
107 case files.ComponentFolderData:
108 //lint:ignore SA1019 Keep as adapter for now.
109 dir = dirs.DataDir
110 case files.ComponentFolderLayouts:
111 //lint:ignore SA1019 Keep as adapter for now.
112 dir = dirs.LayoutDir
113 case files.ComponentFolderI18n:
114 //lint:ignore SA1019 Keep as adapter for now.
115 dir = dirs.I18nDir
116 case files.ComponentFolderArchetypes:
117 //lint:ignore SA1019 Keep as adapter for now.
118 dir = dirs.ArcheTypeDir
119 case files.ComponentFolderAssets:
120 //lint:ignore SA1019 Keep as adapter for now.
121 dir = dirs.AssetDir
122 case files.ComponentFolderStatic:
123 // For static dirs, we only care about the language in multihost setups.
124 dropLang = !isMultihost
125 }
126
127 var perLang bool
128 switch component {
129 case files.ComponentFolderContent, files.ComponentFolderStatic:
130 perLang = true
131 default:
132 }
133 if i > 0 && !perLang {
134 continue
135 }
136
137 var lang string
138 var sites sitesmatrix.Sites
139
140 if perLang && !dropLang {
141 l := cfg.Language().(*langs.Language)
142 lang = l.Lang
143 sites = sitesmatrix.Sites{
144 Matrix: sitesmatrix.StringSlices{
145 Languages: []string{l.Lang},
146 },
147 }
148 }
149
150 // Static mounts are a little special.
151 if component == files.ComponentFolderStatic {
152 staticDirs := cfg.StaticDirs()
153 for _, dir := range staticDirs {
154 mounts = append(mounts, Mount{Sites: sites, Source: dir, Target: component})
155 }
156 continue
157 }
158
159 if dir != "" {
160 mnt := Mount{Source: dir, Target: component, Sites: sites}
161 if err := mnt.init(logger); err != nil {
162 return fmt.Errorf("failed to init mount %q %d: %w", lang, i, err)
163 }
164 mounts = append(mounts, mnt)
165 }
166 }
167 }
168
169 moda.mounts = append(moda.mounts, mounts...)
170
171 moda.mounts = filterDuplicateMounts(moda.mounts)
172
173 return nil
174 }
175
176 // DecodeConfig creates a modules Config from a given Hugo configuration.
177 func DecodeConfig(logger logg.Logger, cfg config.Provider) (Config, error) {
178 return decodeConfig(logger, cfg, nil)
179 }
180
181 func decodeConfig(logger logg.Logger, cfg config.Provider, pathReplacements map[string]string) (Config, error) {
182 c := DefaultModuleConfig
183 c.replacementsMap = pathReplacements
184
185 if cfg == nil {
186 return c, nil
187 }
188
189 themeSet := cfg.IsSet("theme")
190 moduleSet := cfg.IsSet("module")
191
192 if moduleSet {
193 m := cfg.GetStringMap("module")
194 if err := mapstructure.WeakDecode(m, &c); err != nil {
195 return c, err
196 }
197
198 if c.replacementsMap == nil {
199
200 if len(c.Replacements) == 1 {
201 c.Replacements = strings.Split(c.Replacements[0], ",")
202 }
203
204 for i, repl := range c.Replacements {
205 c.Replacements[i] = strings.TrimSpace(repl)
206 }
207
208 c.replacementsMap = make(map[string]string)
209 for _, repl := range c.Replacements {
210 parts := strings.Split(repl, "->")
211 if len(parts) != 2 {
212 return c, fmt.Errorf(`invalid module.replacements: %q; configure replacement pairs on the form "oldpath->newpath" `, repl)
213 }
214
215 c.replacementsMap[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
216 }
217 }
218
219 if c.replacementsMap != nil && c.Imports != nil {
220 for i, imp := range c.Imports {
221 if newImp, found := c.replacementsMap[imp.Path]; found {
222 imp.Path = newImp
223 imp.pathProjectReplaced = true
224 c.Imports[i] = imp
225 }
226 }
227 }
228
229 for i, mnt := range c.Mounts {
230 mnt.Source = filepath.Clean(mnt.Source)
231 mnt.Target = filepath.Clean(mnt.Target)
232 if err := mnt.init(logger); err != nil {
233 return c, fmt.Errorf("failed to init mount %d: %w", i, err)
234 }
235 c.Mounts[i] = mnt
236 }
237
238 if c.Workspace == "" {
239 c.Workspace = WorkspaceDisabled
240 }
241 if c.Workspace != WorkspaceDisabled {
242 c.Workspace = filepath.Clean(c.Workspace)
243 if !filepath.IsAbs(c.Workspace) {
244 workingDir := cfg.GetString("workingDir")
245 c.Workspace = filepath.Join(workingDir, c.Workspace)
246 }
247 if _, err := os.Stat(c.Workspace); err != nil {
248 //lint:ignore ST1005 end user message.
249 return c, fmt.Errorf("module workspace %q does not exist. Check your module.workspace setting (or HUGO_MODULE_WORKSPACE env var).", c.Workspace)
250 }
251 }
252 }
253
254 if themeSet {
255 imports := config.GetStringSlicePreserveString(cfg, "theme")
256 for _, imp := range imports {
257 c.Imports = append(c.Imports, Import{
258 Path: imp,
259 })
260 }
261 }
262
263 return c, nil
264 }
265
266 // Config holds a module config.
267 type Config struct {
268 // File system mounts.
269 Mounts []Mount
270
271 // Module imports.
272 Imports []Import
273
274 // Meta info about this module (license information etc.).
275 Params map[string]any
276
277 // Will be validated against the running Hugo version.
278 HugoVersion HugoVersion
279
280 // Optional Glob pattern matching module paths to skip when vendoring, e.g. “github.com/**”
281 NoVendor string
282
283 // When enabled, we will pick the vendored module closest to the module
284 // using it.
285 // The default behavior is to pick the first.
286 // Note that there can still be only one dependency of a given module path,
287 // so once it is in use it cannot be redefined.
288 VendorClosest bool
289
290 // A comma separated (or a slice) list of module path to directory replacement mapping,
291 // e.g. github.com/bep/my-theme -> ../..,github.com/bep/shortcodes -> /some/path.
292 // This is mostly useful for temporary locally development of a module, and then it makes sense to set it as an
293 // OS environment variable, e.g: env HUGO_MODULE_REPLACEMENTS="github.com/bep/my-theme -> ../..".
294 // Any relative path is relate to themesDir, and absolute paths are allowed.
295 Replacements []string
296 replacementsMap map[string]string
297
298 // Defines the proxy server to use to download remote modules. Default is direct, which means “git clone” and similar.
299 // Configures GOPROXY when running the Go command for module operations.
300 Proxy string
301
302 // Comma separated glob list matching paths that should not use the proxy configured above.
303 // Configures GONOPROXY when running the Go command for module operations.
304 NoProxy string
305
306 // Comma separated glob list matching paths that should be treated as private.
307 // Configures GOPRIVATE when running the Go command for module operations.
308 Private string
309
310 // Configures GOAUTH when running the Go command for module operations.
311 // This is a semicolon-separated list of authentication commands for go-import and HTTPS module mirror interactions.
312 // This is useful for private repositories.
313 // See `go help goauth` for more information.
314 Auth string
315
316 // Defaults to "off".
317 // Set to a work file, e.g. hugo.work, to enable Go "Workspace" mode.
318 // Can be relative to the working directory or absolute.
319 // Requires Go 1.18+.
320 // Note that this can also be set via OS env, e.g. export HUGO_MODULE_WORKSPACE=/my/hugo.work.
321 Workspace string
322 }
323
324 // hasModuleImport reports whether the project config have one or more
325 // modules imports, e.g. github.com/bep/myshortcodes.
326 func (c Config) hasModuleImport() bool {
327 for _, imp := range c.Imports {
328 if isProbablyModule(imp.Path) {
329 return true
330 }
331 }
332 return false
333 }
334
335 // HugoVersion holds Hugo binary version requirements for a module.
336 type HugoVersion struct {
337 // The minimum Hugo version that this module works with.
338 Min version.VersionString
339
340 // The maximum Hugo version that this module works with.
341 Max version.VersionString
342
343 // Set if the extended version is needed.
344 Extended bool
345 }
346
347 func (v HugoVersion) String() string {
348 extended := ""
349 if v.Extended {
350 extended = " extended"
351 }
352
353 if v.Min != "" && v.Max != "" {
354 return fmt.Sprintf("%s/%s%s", v.Min, v.Max, extended)
355 }
356
357 if v.Min != "" {
358 return fmt.Sprintf("Min %s%s", v.Min, extended)
359 }
360
361 if v.Max != "" {
362 return fmt.Sprintf("Max %s%s", v.Max, extended)
363 }
364
365 return extended
366 }
367
368 // IsValid reports whether this version is valid compared to the running
369 // Hugo binary.
370 func (v HugoVersion) IsValid() bool {
371 current := hugo.CurrentVersion.Version()
372
373 if v.Min != "" && current.Compare(v.Min) > 0 {
374 return false
375 }
376
377 if v.Max != "" && current.Compare(v.Max) < 0 {
378 return false
379 }
380
381 return true
382 }
383
384 type Import struct {
385 // Module path
386 Path string
387
388 // The common case is to leave this empty and let Go Modules resolve the version.
389 // Can be set to a version query, e.g. "v1.2.3", ">=v1.2.0", "latest", which will
390 // make this a direct dependency.
391 Version string
392 // Set when Path is replaced in project config.
393 pathProjectReplaced bool
394 // Ignore any config in config.toml (will still follow imports).
395 IgnoreConfig bool
396 // Do not follow any configured imports.
397 IgnoreImports bool
398 // Do not mount any folder in this import.
399 NoMounts bool
400 // Never vendor this import (only allowed in main project).
401 NoVendor bool
402 // Turn off this module.
403 Disable bool
404 // File mounts.
405 Mounts []Mount
406
407 // Controls whether npm package files (package.json/package.hugo.json) are
408 // read from this module. Values: "auto" (default), "always", "never".
409 // "auto" reads package files when a Hugo config file or package.hugo.json
410 // is present in the module root.
411 UsePackageJSON string
412 }
413
414 const (
415 UsePackageJSONAuto = "auto"
416 UsePackageJSONAlways = "always"
417 UsePackageJSONNever = "never"
418 )
419
420 type Mount struct {
421 // Relative path in source repo, e.g. "scss".
422 Source string
423
424 // Relative target path, e.g. "assets/bootstrap/scss".
425 Target string
426
427 // Any file in this mount will be associated with this language.
428 // Deprecated, use Sites instead.
429 Lang string `json:"-"`
430
431 // Sites defines which sites this mount applies to.
432 Sites sitesmatrix.Sites
433
434 // A slice of Glob patterns (string or slice) to exclude or include in this mount.
435 // To exclude, prefix with "! ".
436 Files []string
437
438 // Include only files matching the given Glob patterns (string or slice).
439 // Deprecated, use Files instead.
440 IncludeFiles any `json:"-"`
441
442 // Exclude all files matching the given Glob patterns (string or slice).
443 // Deprecated, use Files instead.
444 ExcludeFiles any `json:"-"`
445
446 // Disable watching in watch mode for this mount.
447 DisableWatch bool
448 }
449
450 func (m Mount) Equal(o Mount) bool {
451 if m.Lang != o.Lang {
452 return false
453 }
454 if m.Source != o.Source {
455 return false
456 }
457 if m.Target != o.Target {
458 return false
459 }
460 if m.DisableWatch != o.DisableWatch {
461 return false
462 }
463
464 if !m.Sites.Equal(o.Sites) {
465 return false
466 }
467
468 patterns, hasLegacy11, hasLegacy12 := m.FilesToFilter()
469 patterns2, hasLegacy21, hasLegacy22 := o.FilesToFilter()
470
471 if hasLegacy11 != hasLegacy21 || hasLegacy12 != hasLegacy22 {
472 return false
473 }
474
475 return slices.Equal(patterns, patterns2)
476 }
477
478 func (m Mount) FilesToFilter() (patterns []string, hasLegacyIncludeFiles, hasLegacyExcludeFiles bool) {
479 patterns = m.Files
480
481 // Legacy config, add IncludeFiles first.
482 for _, pattern := range types.ToStringSlicePreserveString(m.IncludeFiles) {
483 hasLegacyIncludeFiles = true
484 patterns = append(patterns, pattern)
485 }
486
487 for _, pattern := range types.ToStringSlicePreserveString(m.ExcludeFiles) {
488 hasLegacyExcludeFiles = true
489 patterns = append(patterns, hglob.NegationPrefix+pattern)
490 }
491
492 return patterns, hasLegacyIncludeFiles, hasLegacyExcludeFiles
493 }
494
495 func (m Mount) Component() string {
496 return strings.Split(m.Target, fileSeparator)[0]
497 }
498
499 func (m Mount) ComponentAndName() (string, string) {
500 c, n, _ := strings.Cut(m.Target, fileSeparator)
501 return c, n
502 }
503
504 func (m *Mount) init(logger logg.Logger) error {
505 if m.Lang != "" {
506 // We moved this to a more flixeble setup in Hugo 0.153.0.
507 m.Sites.Matrix.Languages = append(m.Sites.Matrix.Languages, m.Lang)
508 m.Lang = ""
509
510 hugo.DeprecateWithLogger("module.mounts.lang", "Replaced by the more powerful 'sites.matrix' setting, see https://gohugo.io/configuration/module/#mounts", "v0.153.0", logger)
511
512 }
513
514 m.Sites.Matrix.Languages = hstrings.UniqueStringsReuse(m.Sites.Matrix.Languages)
515
516 return nil
517 }