Debian Codegraph @

modules/collect.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 modules
15
16 import (
17 "bufio"
18 "encoding/json"
19 "errors"
20 "fmt"
21 "io/fs"
22 "net/url"
23 "os"
24 "path/filepath"
25 "regexp"
26 "slices"
27 "strings"
28 "time"
29
30 "github.com/bep/debounce"
31 "github.com/gobwas/glob"
32 "github.com/gohugoio/hugo/common/herrors"
33 "github.com/gohugoio/hugo/common/hmaps"
34 "github.com/gohugoio/hugo/common/loggers"
35 "github.com/gohugoio/hugo/common/paths"
36 "github.com/gohugoio/hugo/common/version"
37 "golang.org/x/mod/module"
38
39 "github.com/spf13/cast"
40
41 "github.com/gohugoio/hugo/parser/metadecoders"
42
43 "github.com/gohugoio/hugo/hugofs/files"
44
45 "github.com/gohugoio/hugo/config"
46 "github.com/spf13/afero"
47 )
48
49 var ErrNotExist = errors.New("module does not exist")
50
51 const vendorModulesFilename = "modules.txt"
52
53 func (h *Client) Collect() (ModulesConfig, error) {
54 mc, coll := h.collect(true)
55 if coll.err != nil {
56 return mc, coll.err
57 }
58
59 if err := (&mc).setActiveMods(h.logger); err != nil {
60 return mc, err
61 }
62
63 if h.ccfg.HookBeforeFinalize != nil {
64 if err := h.ccfg.HookBeforeFinalize(&mc); err != nil {
65 return mc, err
66 }
67 }
68
69 if err := (&mc).finalize(); err != nil {
70 return mc, err
71 }
72
73 return mc, nil
74 }
75
76 func (h *Client) collect(tidy bool) (ModulesConfig, *collector) {
77 if h == nil {
78 panic("nil client")
79 }
80 c := &collector{
81 Client: h,
82 }
83
84 c.collect()
85 if c.err != nil {
86 return ModulesConfig{}, c
87 }
88
89 // https://github.com/gohugoio/hugo/issues/6115
90 /*if !c.skipTidy && tidy {
91 if err := h.tidy(c.modules, true); err != nil {
92 c.err = err
93 return ModulesConfig{}, c
94 }
95 }*/
96
97 var workspaceFilename string
98 if h.ccfg.ModuleConfig.Workspace != WorkspaceDisabled {
99 workspaceFilename = h.ccfg.ModuleConfig.Workspace
100 }
101
102 return ModulesConfig{
103 AllModules: c.modules,
104 GoModulesFilename: c.GoModulesFilename,
105 GoWorkspaceFilename: workspaceFilename,
106 }, c
107 }
108
109 type ModulesConfig struct {
110 // All active modules.
111 AllModules Modules
112
113 // Set if this is a Go modules enabled project.
114 GoModulesFilename string
115
116 // Set if a Go workspace file is configured.
117 GoWorkspaceFilename string
118 }
119
120 func (m ModulesConfig) HasConfigFile() bool {
121 for _, mod := range m.AllModules {
122 if len(mod.ConfigFilenames()) > 0 {
123 return true
124 }
125 }
126 return false
127 }
128
129 func (m *ModulesConfig) setActiveMods(logger loggers.Logger) error {
130 for _, mod := range m.AllModules {
131 if !mod.Config().HugoVersion.IsValid() {
132 logger.Warnf(`Module %q is not compatible with this Hugo version: %s; run "hugo mod graph" for more information.`, mod.Path(), mod.Config().HugoVersion)
133 }
134 }
135
136 return nil
137 }
138
139 func (m *ModulesConfig) finalize() error {
140 for _, mod := range m.AllModules {
141 m := mod.(*moduleAdapter)
142 m.mounts = filterDuplicateMounts(m.mounts)
143 }
144 return nil
145 }
146
147 // filterDuplicateMounts removes duplicate mounts while preserving order.
148 // The input slice will not be modified.
149 func filterDuplicateMounts(mounts []Mount) []Mount {
150 var x []Mount
151 for _, m1 := range mounts {
152 var found bool
153 if slices.ContainsFunc(x, m1.Equal) {
154 found = true
155 }
156 if !found {
157 x = append(x, m1)
158 }
159 }
160 return x
161 }
162
163 type pathVersionKey struct {
164 path string
165 version string
166 }
167
168 type collected struct {
169 // Pick the first and prevent circular loops.
170 seenPaths map[string]*moduleAdapter
171
172 // Maps module path to a _vendor dir. These values are fetched from
173 // _vendor/modules.txt, and the first (top-most) will win.
174 vendored map[string]vendoredModule
175
176 // Set if a Go modules enabled project.
177 gomods goModules
178
179 // Ordered list of collected modules, including Go Modules and theme
180 // components stored below /themes.
181 modules Modules
182 }
183
184 // Collects and creates a module tree.
185 type collector struct {
186 *Client
187
188 // Store away any non-fatal error and return at the end.
189 err error
190
191 // Set to disable any Tidy operation in the end.
192 skipTidy bool
193
194 *collected
195 }
196
197 func (c *collector) initModules() error {
198 c.collected = &collected{
199 seenPaths: make(map[string]*moduleAdapter),
200 vendored: make(map[string]vendoredModule),
201 gomods: goModules{},
202 }
203
204 // If both these are true, we don't even need Go installed to build.
205 if c.ccfg.IgnoreVendor == nil && c.isVendored(c.ccfg.WorkingDir) {
206 return nil
207 }
208
209 // We may fail later if we don't find the mods.
210 return c.loadModules()
211 }
212
213 func (c *collector) isPathSeen(p string, owner *moduleAdapter) *moduleAdapter {
214 // Remove any major version suffix.
215 // We do allow multiple major versions in the same project,
216 // but not as transitive dependencies.
217 p = pathBase(p)
218 if v, ok := c.seenPaths[p]; ok {
219 return v
220 }
221 c.seenPaths[p] = owner
222 return nil
223 }
224
225 func (c *collector) getVendoredDir(path string) (vendoredModule, bool) {
226 v, found := c.vendored[path]
227 return v, found
228 }
229
230 func (c *collector) getAndCreateModule(owner *moduleAdapter, moduleImport Import) (*moduleAdapter, error) {
231 var (
232 mod *goModule
233 moduleDir string
234 versionMod string
235 requestedVersionQuery string = moduleImport.Version
236 vendored bool
237 )
238
239 modulePath := moduleImport.Path
240 vendorPath := modulePath
241 vendorPathEscaped := modulePath
242 if requestedVersionQuery != "" {
243 vendorPath += "@" + requestedVersionQuery
244 vendorPathEscaped += "@" + url.QueryEscape(requestedVersionQuery)
245 }
246
247 var realOwner Module = owner
248
249 if !(c.ccfg.shouldIgnoreVendor(vendorPath)) {
250 if err := c.collectModulesTXT(owner); err != nil {
251 return nil, err
252 }
253
254 // Try _vendor first.
255 var vm vendoredModule
256 vm, vendored = c.getVendoredDir(vendorPathEscaped)
257 if vendored {
258 moduleDir = vm.Dir
259 realOwner = vm.Owner
260 versionMod = vm.Version
261
262 if owner.projectMod {
263 // We want to keep the go.mod intact with the versions and all.
264 c.skipTidy = true
265 }
266
267 }
268 }
269
270 if moduleDir == "" {
271 if requestedVersionQuery == "" {
272 mod = c.gomods.GetByPath(modulePath)
273 if mod != nil {
274 moduleDir = mod.Dir
275 }
276 }
277
278 if moduleDir == "" {
279 if isProbablyModule(modulePath) {
280 if requestedVersionQuery != "" {
281 var err error
282 mod, err = c.downloadModuleVersion(modulePath, requestedVersionQuery)
283 if err != nil {
284 return nil, err
285 }
286 if mod == nil {
287 return nil, fmt.Errorf("module %q not found", modulePath)
288 }
289 moduleDir = mod.Dir
290 versionMod = mod.Version
291 } else if c.GoModulesFilename != "" {
292 // See https://golang.org/ref/mod#version-queries
293 // This will select the latest release-version (not beta etc.).
294 const versionQuery = "upgrade"
295 // Try to "go get" it and reload the module configuration.
296
297 // Note that we cannot use c.Get for this, as that may
298 // trigger a new module collection and potentially create a infinite loop.
299 if err := c.get(fmt.Sprintf("%s@%s", modulePath, versionQuery)); err != nil {
300 return nil, err
301 }
302 if err := c.loadModules(); err != nil {
303 return nil, err
304 }
305
306 mod = c.gomods.GetByPath(modulePath)
307 if mod != nil {
308 moduleDir = mod.Dir
309 }
310 }
311 }
312
313 // Fall back to project/themes/<mymodule>
314 if moduleDir == "" {
315 var err error
316 moduleDir, err = c.createThemeDirname(modulePath, owner.projectMod || moduleImport.pathProjectReplaced)
317 if err != nil {
318 c.err = err
319 return nil, nil
320 }
321 if found, _ := afero.Exists(c.fs, moduleDir); !found {
322 //lint:ignore ST1005 end user message.
323 c.err = c.wrapModuleNotFound(fmt.Errorf(`module %q not found in %q; either add it as a Hugo Module or store it in %q.`, modulePath, moduleDir, c.ccfg.ThemesDir))
324 return nil, nil
325 }
326 }
327 }
328 }
329
330 if found, _ := afero.Exists(c.fs, moduleDir); !found {
331 c.err = c.wrapModuleNotFound(fmt.Errorf("%q not found", moduleDir))
332 return nil, nil
333 }
334
335 if !strings.HasSuffix(moduleDir, fileSeparator) {
336 moduleDir += fileSeparator
337 }
338
339 ma := &moduleAdapter{
340 dir: moduleDir,
341 vendor: vendored,
342 gomod: mod,
343 version: versionMod,
344 versionQuery: requestedVersionQuery,
345 // This may be the owner of the _vendor dir
346 owner: realOwner,
347 }
348
349 if mod == nil {
350 ma.path = modulePath
351 }
352
353 if !moduleImport.IgnoreConfig {
354 if err := c.applyThemeConfig(ma); err != nil {
355 return nil, err
356 }
357 }
358
359 if err := c.applyMounts(moduleImport, ma); err != nil {
360 return nil, err
361 }
362
363 return ma, nil
364 }
365
366 func (c *collector) addAndRecurse(owner *moduleAdapter) error {
367 moduleConfig := owner.Config()
368 if owner.projectMod {
369 if err := c.applyMounts(Import{}, owner); err != nil {
370 return fmt.Errorf("failed to apply mounts for project: %w", err)
371 }
372 }
373 seen := make(map[pathVersionKey]bool)
374 for _, moduleImport := range moduleConfig.Imports {
375 if moduleImport.Disable {
376 continue
377 }
378
379 // Prevent cyclic references.
380 if v := c.isPathSeen(moduleImport.Path, owner); v != nil && v != owner {
381 continue
382 }
383
384 tc, err := c.getAndCreateModule(owner, moduleImport)
385 if err != nil {
386 return err
387 }
388
389 if tc == nil {
390 continue
391 }
392
393 pk := pathVersionKey{path: tc.Path(), version: tc.Version()}
394 seenInCurrent := seen[pk]
395 if seenInCurrent {
396 // Only one import of the same module per project, unless this is the main project.
397 if !owner.projectMod {
398 c.logger.Warnf("module with path %q is imported for the same version %q more than once; this is currently only allowed in the main project's config.", tc.Path(), tc.Version())
399 continue
400 }
401 }
402 seen[pk] = true
403
404 c.modules = append(c.modules, tc)
405
406 if moduleImport.IgnoreImports {
407 continue
408 }
409
410 if err := c.addAndRecurse(tc); err != nil {
411 return err
412 }
413
414 }
415 return nil
416 }
417
418 func (c *collector) applyMounts(moduleImport Import, mod *moduleAdapter) error {
419 if moduleImport.NoMounts {
420 mod.mounts = nil
421 return nil
422 }
423
424 mounts := moduleImport.Mounts
425
426 modConfig := mod.Config()
427
428 if len(mounts) == 0 {
429 // Mounts not defined by the import.
430 mounts = modConfig.Mounts
431 }
432
433 if !mod.projectMod && len(mounts) == 0 {
434 // Create default mount points for every component folder that
435 // exists in the module.
436 for _, componentFolder := range files.ComponentFolders {
437 sourceDir := filepath.Join(mod.Dir(), componentFolder)
438 _, err := c.fs.Stat(sourceDir)
439 if err == nil {
440 mounts = append(mounts, Mount{
441 Source: componentFolder,
442 Target: componentFolder,
443 })
444 }
445 }
446 }
447
448 var err error
449 mounts, err = c.normalizeMounts(mod, mounts)
450 if err != nil {
451 return err
452 }
453
454 mounts, err = c.mountCommonJSConfig(mod, mounts)
455 if err != nil {
456 return err
457 }
458
459 mod.mounts = mounts
460 return nil
461 }
462
463 func (c *collector) applyThemeConfig(tc *moduleAdapter) error {
464 var (
465 configFilename string
466 themeCfg map[string]any
467 hasConfigFile bool
468 err error
469 )
470
471 LOOP:
472 for _, configBaseName := range config.DefaultConfigNames {
473 for _, configFormats := range config.ValidConfigFileExtensions {
474 configFilename = filepath.Join(tc.Dir(), configBaseName+"."+configFormats)
475 hasConfigFile, _ = afero.Exists(c.fs, configFilename)
476 if hasConfigFile {
477 break LOOP
478 }
479 }
480 }
481
482 // The old theme information file.
483 themeTOML := filepath.Join(tc.Dir(), "theme.toml")
484
485 hasThemeTOML, _ := afero.Exists(c.fs, themeTOML)
486 if hasThemeTOML {
487 data, err := afero.ReadFile(c.fs, themeTOML)
488 if err != nil {
489 return err
490 }
491 themeCfg, err = metadecoders.Default.UnmarshalToMap(data, metadecoders.TOML)
492 if err != nil {
493 c.logger.Warnf("Failed to read module config for %q in %q: %s", tc.Path(), themeTOML, err)
494 } else {
495 hmaps.PrepareParams(themeCfg)
496 }
497 }
498
499 if hasConfigFile {
500 if configFilename != "" {
501 var err error
502 tc.cfg, err = config.FromFile(c.fs, configFilename)
503 if err != nil {
504 return err
505 }
506 }
507
508 tc.configFilenames = append(tc.configFilenames, configFilename)
509
510 }
511
512 // Also check for a config dir, which we overlay on top of the file configuration.
513 configDir := filepath.Join(tc.Dir(), "config")
514 dcfg, dirnames, err := config.LoadConfigFromDir(c.fs, configDir, c.ccfg.Environment)
515 if err != nil {
516 return err
517 }
518
519 if len(dirnames) > 0 {
520 tc.configFilenames = append(tc.configFilenames, dirnames...)
521
522 if hasConfigFile {
523 // Set will overwrite existing keys.
524 tc.cfg.Set("", dcfg.Get(""))
525 } else {
526 tc.cfg = dcfg
527 }
528 }
529
530 config, err := decodeConfig(c.logger.Logger(), tc.cfg, c.moduleConfig.replacementsMap)
531 if err != nil {
532 return err
533 }
534
535 const oldVersionKey = "min_version"
536
537 if hasThemeTOML {
538
539 // Merge old with new
540 if minVersion, found := themeCfg[oldVersionKey]; found {
541 if config.HugoVersion.Min == "" {
542 config.HugoVersion.Min = version.VersionString(cast.ToString(minVersion))
543 }
544 }
545
546 if config.Params == nil {
547 config.Params = make(map[string]any)
548 }
549
550 for k, v := range themeCfg {
551 if k == oldVersionKey {
552 continue
553 }
554 config.Params[k] = v
555 }
556
557 }
558
559 tc.config = config
560
561 return nil
562 }
563
564 func (c *collector) collect() {
565 defer c.logger.PrintTimerIfDelayed(time.Now(), "hugo: collected modules")
566 d := debounce.New(2 * time.Second)
567 d(func() {
568 c.logger.Println("hugo: downloading modules …")
569 })
570 defer d(func() {})
571
572 if err := c.initModules(); err != nil {
573 c.err = err
574 return
575 }
576
577 projectMod := createProjectModule(c.gomods.GetMain(), c.ccfg.WorkingDir, c.moduleConfig)
578
579 if err := c.addAndRecurse(projectMod); err != nil {
580 c.err = err
581 return
582 }
583
584 // Add the project mod on top.
585 c.modules = append(Modules{projectMod}, c.modules...)
586
587 if err := c.writeHugoDirectSum(c.modules); err != nil {
588 c.err = err
589 return
590 }
591 }
592
593 func (c *collector) isVendored(dir string) bool {
594 _, err := c.fs.Stat(filepath.Join(dir, vendord, vendorModulesFilename))
595 return err == nil
596 }
597
598 func (c *collector) collectModulesTXT(owner Module) error {
599 vendorDir := filepath.Join(owner.Dir(), vendord)
600 filename := filepath.Join(vendorDir, vendorModulesFilename)
601
602 f, err := c.fs.Open(filename)
603 if err != nil {
604 if herrors.IsNotExist(err) {
605 return nil
606 }
607
608 return err
609 }
610
611 defer f.Close()
612
613 scanner := bufio.NewScanner(f)
614
615 for scanner.Scan() {
616 // # github.com/alecthomas/chroma v0.6.3
617 line := scanner.Text()
618 line = strings.Trim(line, "# ")
619 line = strings.TrimSpace(line)
620 if line == "" {
621 continue
622 }
623 parts := strings.Fields(line)
624 if len(parts) != 2 {
625 return fmt.Errorf("invalid modules list: %q", filename)
626 }
627 path := parts[0]
628
629 shouldAdd := c.Client.moduleConfig.VendorClosest
630
631 if !shouldAdd {
632 if _, found := c.vendored[path]; !found {
633 shouldAdd = true
634 }
635 }
636
637 if shouldAdd {
638 c.vendored[path] = vendoredModule{
639 Owner: owner,
640 Dir: filepath.Join(vendorDir, path),
641 Version: parts[1],
642 }
643 }
644
645 }
646 return nil
647 }
648
649 func (c *collector) loadModules() error {
650 modules, err := c.listGoMods()
651 if err != nil {
652 return err
653 }
654 c.gomods = modules
655 return nil
656 }
657
658 // Matches postcss.config.js etc.
659 var commonJSConfigs = regexp.MustCompile(`^(babel|postcss|tailwind)\.config\.(c|m)?js$`)
660
661 func (c *collector) mountCommonJSConfig(owner *moduleAdapter, mounts []Mount) ([]Mount, error) {
662 for _, m := range mounts {
663 if strings.HasPrefix(m.Target, files.JsConfigFolderMountPrefix) {
664 // This follows the convention of the other component types (assets, content, etc.),
665 // if one or more is specified by the user, we skip the defaults.
666 // These mounts were added to Hugo in 0.75.
667 return mounts, nil
668 }
669 }
670
671 // Mount the common JS config files.
672 d, err := c.fs.Open(owner.Dir())
673 if err != nil {
674 return mounts, fmt.Errorf("failed to open dir %q: %q", owner.Dir(), err)
675 }
676 defer d.Close()
677 fis, err := d.(fs.ReadDirFile).ReadDir(-1)
678 if err != nil {
679 return mounts, fmt.Errorf("failed to read dir %q: %q", owner.Dir(), err)
680 }
681
682 hasPackageHugoJSON := false
683 for _, fi := range fis {
684 if fi.Name() == files.FilenamePackageHugoJSON {
685 hasPackageHugoJSON = true
686 break
687 }
688 }
689
690 for _, fi := range fis {
691 n := fi.Name()
692
693 should := n == files.FilenamePackageHugoJSON || (n == files.FilenamePackageJSON && !hasPackageHugoJSON)
694 should = should || commonJSConfigs.MatchString(n)
695
696 if should {
697 mounts = append(mounts, Mount{
698 Source: n,
699 Target: filepath.Join(files.ComponentFolderAssets, files.FolderJSConfig, n),
700 })
701 }
702
703 }
704
705 // Mount the project's hugoautogen workspace package.json (not from dependencies).
706 if owner.projectMod {
707 pkgAutoGen := filepath.Join(files.FolderPackagesHugoAutoGen, files.FilenamePackageJSON)
708 if fi, err := c.fs.Stat(filepath.Join(owner.Dir(), pkgAutoGen)); err == nil && !fi.IsDir() {
709 mounts = append(mounts, Mount{
710 Source: pkgAutoGen,
711 Target: filepath.Join(files.ComponentFolderAssets, files.FolderJSConfig, pkgAutoGen),
712 })
713 }
714 }
715
716 // Mount workspace package.json files (skipping hugoautogen from dependencies).
717 // Read workspaces from package.hugo.json if it exists, otherwise from package.json.
718 pkgFile := files.FilenamePackageJSON
719 if hasPackageHugoJSON {
720 pkgFile = files.FilenamePackageHugoJSON
721 }
722 if pkgData, err := afero.ReadFile(c.fs, filepath.Join(owner.Dir(), pkgFile)); err == nil {
723 var pkg map[string]any
724 if err := json.Unmarshal(pkgData, &pkg); err == nil {
725 for _, ws := range cast.ToStringSlice(pkg["workspaces"]) {
726 wsDirs := ResolveWorkspacePattern(c.fs, owner.Dir(), ws)
727 for _, wsDir := range wsDirs {
728 if filepath.ToSlash(wsDir) == filepath.ToSlash(files.FolderPackagesHugoAutoGen) {
729 continue
730 }
731 wsPackageJSON := filepath.Join(wsDir, files.FilenamePackageJSON)
732 if fi, err := c.fs.Stat(filepath.Join(owner.Dir(), wsPackageJSON)); err == nil && !fi.IsDir() {
733 mounts = append(mounts, Mount{
734 Source: wsPackageJSON,
735 Target: filepath.Join(files.ComponentFolderAssets, files.FolderJSConfig, wsPackageJSON),
736 })
737 }
738 }
739 }
740 }
741 }
742
743 return mounts, nil
744 }
745
746 // ResolveWorkspacePattern resolves an npm workspace pattern to actual directory paths.
747 // Supports globs (*, **) and brace expansion ({a,b}) via gobwas/glob.
748 // Literal paths are returned as-is.
749 func ResolveWorkspacePattern(fs afero.Fs, root, pattern string) []string {
750 if !strings.ContainsAny(pattern, "*?[{}") {
751 return []string{pattern}
752 }
753
754 g, err := glob.Compile(pattern, '/')
755 if err != nil {
756 return nil
757 }
758
759 var dirs []string
760 _ = afero.Walk(fs, root, func(path string, info os.FileInfo, err error) error {
761 if err != nil || info.IsDir() {
762 return nil
763 }
764 if info.Name() != files.FilenamePackageJSON {
765 return nil
766 }
767 rel, err := filepath.Rel(root, filepath.Dir(path))
768 if err != nil {
769 return nil
770 }
771 if g.Match(filepath.ToSlash(rel)) {
772 dirs = append(dirs, rel)
773 }
774 return nil
775 })
776 return dirs
777 }
778
779 func (c *collector) nodeModulesRoot(s string) string {
780 s = filepath.ToSlash(s)
781 if strings.HasPrefix(s, "node_modules/") {
782 return s
783 }
784 if strings.HasPrefix(s, "../../node_modules/") {
785 // See #14083. This was a common construct to mount node_modules from the project root.
786 // This started failing in v0.152.0 when we tightened the validation.
787 return strings.TrimPrefix(s, "../../")
788 }
789 return ""
790 }
791
792 func (c *collector) normalizeMounts(owner *moduleAdapter, mounts []Mount) ([]Mount, error) {
793 var out []Mount
794 dir := owner.Dir()
795
796 for _, mnt := range mounts {
797 errMsg := fmt.Sprintf("invalid module config for %q", owner.Path())
798
799 if mnt.Source == "" || mnt.Target == "" {
800 return nil, errors.New(errMsg + ": both source and target must be set")
801 }
802
803 // Special case for node_modules imports in themes/modules.
804 // See #14089.
805 var isModuleNodeModulesImport bool
806 if !owner.projectMod {
807 nodeModulesImportSource := c.nodeModulesRoot(mnt.Source)
808 if nodeModulesImportSource != "" {
809 isModuleNodeModulesImport = true
810 mnt.Source = nodeModulesImportSource
811 }
812 }
813
814 mnt.Source = filepath.Clean(mnt.Source)
815 mnt.Target = filepath.Clean(mnt.Target)
816 var sourceDir string
817
818 if !owner.projectMod && !filepath.IsLocal(mnt.Source) {
819 return nil, fmt.Errorf("%s: %q: mount source must be a local path for modules/themes", errMsg, mnt.Source)
820 }
821 if filepath.IsAbs(mnt.Source) {
822 // Abs paths in the main project is allowed.
823 sourceDir = mnt.Source
824 } else {
825 sourceDir = filepath.Join(dir, mnt.Source)
826 }
827
828 // Verify that Source exists
829 _, err := c.fs.Stat(sourceDir)
830 if err != nil {
831 if paths.IsSameFilePath(sourceDir, c.ccfg.PublishDir) {
832 // This is a little exotic, but there are use cases for mounting the public folder.
833 // This will typically also be in .gitingore, so create it.
834 if err := c.fs.MkdirAll(sourceDir, 0o755); err != nil {
835 return nil, fmt.Errorf("%s: %q", errMsg, err)
836 }
837 } else if strings.HasSuffix(sourceDir, files.FilenameHugoStatsJSON) {
838 // A common pattern for Tailwind 3 is to mount that file to get it on the server watch list.
839
840 // A common pattern is also to add hugo_stats.json to .gitignore.
841
842 // Create an empty file.
843 f, err := c.fs.Create(sourceDir)
844 if err != nil {
845 return nil, fmt.Errorf("%s: %q", errMsg, err)
846 }
847 f.Close()
848 } else {
849 if isModuleNodeModulesImport {
850 // A module imported a path inside node_modules, but it didn't exist.
851 // Make this a special case and also try relative to the project root.
852 sourceDir = filepath.Join(c.ccfg.WorkingDir, mnt.Source)
853 _, err := c.fs.Stat(sourceDir)
854 if err != nil {
855 continue
856 }
857 mnt.Source = sourceDir
858 } else {
859 continue
860 }
861 }
862 }
863
864 // Verify that target points to one of the predefined component dirs
865 targetBase := mnt.Target
866 idxPathSep := strings.Index(mnt.Target, string(os.PathSeparator))
867 if idxPathSep != -1 {
868 targetBase = mnt.Target[0:idxPathSep]
869 }
870 if !files.IsComponentFolder(targetBase) {
871 return nil, fmt.Errorf("%s: mount target must be one of: %v", errMsg, files.ComponentFolders)
872 }
873
874 if err := mnt.init(c.logger.Logger()); err != nil {
875 return nil, fmt.Errorf("%s: %w", errMsg, err)
876 }
877
878 out = append(out, mnt)
879 }
880
881 return out, nil
882 }
883
884 func (c *collector) wrapModuleNotFound(err error) error {
885 if c.Client.ccfg.IgnoreModuleDoesNotExist {
886 return nil
887 }
888 err = fmt.Errorf(err.Error()+": %w", ErrNotExist)
889 if c.GoModulesFilename == "" {
890 return err
891 }
892
893 baseMsg := "we found a go.mod file in your project, but"
894
895 switch c.goBinaryStatus {
896 case goBinaryStatusNotFound:
897 return fmt.Errorf(baseMsg+" you need to install Go to use it. See https://golang.org/dl/ : %q", err)
898 case goBinaryStatusTooOld:
899 return fmt.Errorf(baseMsg+" you need to a newer version of Go to use it. See https://golang.org/dl/ : %w", err)
900 }
901
902 return err
903 }
904
905 type vendoredModule struct {
906 Owner Module
907 Dir string
908 Version string
909 }
910
911 func createProjectModule(gomod *goModule, workingDir string, conf Config) *moduleAdapter {
912 // Create a pseudo module for the main project.
913 var path string
914 if gomod == nil {
915 path = "project"
916 }
917
918 return &moduleAdapter{
919 path: path,
920 dir: workingDir,
921 gomod: gomod,
922 projectMod: true,
923 config: conf,
924 }
925 }
926
927 func pathBase(p string) string {
928 prefix, _, _ := module.SplitPathVersion(p)
929 return strings.ToLower(prefix)
930 }