Debian Codegraph @

modules/client.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 "bufio"
18 "bytes"
19 "context"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "io"
24 "os"
25 "os/exec"
26 "path/filepath"
27 "regexp"
28 "sort"
29 "strings"
30 "time"
31
32 "github.com/gohugoio/hugo/common/collections"
33 "github.com/gohugoio/hugo/common/hashing"
34 "github.com/gohugoio/hugo/common/herrors"
35 "github.com/gohugoio/hugo/common/hexec"
36 "github.com/gohugoio/hugo/common/hstrings"
37 "github.com/gohugoio/hugo/common/hugio"
38 "github.com/gohugoio/hugo/common/loggers"
39 "github.com/gohugoio/hugo/config"
40
41 hglob "github.com/gohugoio/hugo/hugofs/hglob"
42
43 "github.com/gohugoio/hugo/hugofs"
44
45 "github.com/gohugoio/hugo/hugofs/files"
46
47 "golang.org/x/mod/module"
48
49 "github.com/spf13/afero"
50 )
51
52 var fileSeparator = string(os.PathSeparator)
53
54 const (
55 goBinaryStatusOK goBinaryStatus = iota
56 goBinaryStatusNotFound
57 goBinaryStatusTooOld
58 )
59
60 // The "vendor" dir is reserved for Go Modules.
61 const vendord = "_vendor"
62
63 const (
64 goModFilename = "go.mod"
65 goSumFilename = "go.sum"
66
67 // Checksum file for direct dependencies only,
68 // that is, module imports with version set.
69 hugoDirectSumFilename = "hugo.direct.sum"
70 )
71
72 // NewClient creates a new Client that can be used to manage the Hugo Components
73 // in a given workingDir.
74 // The Client will resolve the dependencies recursively, but needs the top
75 // level imports to start out.
76 func NewClient(cfg ClientConfig) *Client {
77 fs := cfg.Fs
78 n := filepath.Join(cfg.WorkingDir, goModFilename)
79 goModEnabled, _ := afero.Exists(fs, n)
80 var goModFilename string
81 if goModEnabled {
82 goModFilename = n
83 }
84
85 logger := cfg.Logger
86 if logger == nil {
87 logger = loggers.NewDefault()
88 }
89
90 var noVendor hstrings.Matcher
91 if cfg.ModuleConfig.NoVendor != "" {
92 noVendor, _ = hglob.GetGlob(hglob.NormalizePath(cfg.ModuleConfig.NoVendor))
93 }
94
95 return &Client{
96 fs: fs,
97 ccfg: cfg,
98 logger: logger,
99 noVendor: noVendor,
100 moduleConfig: cfg.ModuleConfig,
101 environ: cfg.toEnv(),
102 GoModulesFilename: goModFilename,
103 }
104 }
105
106 // Client contains most of the API provided by this package.
107 type Client struct {
108 fs afero.Fs
109 logger loggers.Logger
110
111 noVendor hstrings.Matcher
112
113 ccfg ClientConfig
114
115 // The top level module config
116 moduleConfig Config
117
118 // Environment variables used in "go get" etc.
119 environ []string
120
121 // Set when Go modules are initialized in the current repo, that is:
122 // a go.mod file exists.
123 GoModulesFilename string
124
125 // Set if we get a exec.ErrNotFound when running Go, which is most likely
126 // due to being run on a system without Go installed. We record it here
127 // so we can give an instructional error at the end if module/theme
128 // resolution fails.
129 goBinaryStatus goBinaryStatus
130 }
131
132 // Graph writes a module dependency graph to the given writer.
133 func (c *Client) Graph(w io.Writer) error {
134 mc, coll := c.collect(true)
135 if coll.err != nil {
136 return coll.err
137 }
138 for _, module := range mc.AllModules {
139 if module.Owner() == nil {
140 continue
141 }
142
143 dep := pathVersion(module.Owner()) + " " + pathVersion(module)
144 if replace := module.Replace(); replace != nil {
145 if replace.Version() != "" {
146 dep += " => " + pathVersion(replace)
147 } else {
148 // Local dir.
149 dep += " => " + replace.Dir()
150 }
151 }
152 fmt.Fprintln(w, dep)
153 }
154
155 return nil
156 }
157
158 // Tidy can be used to remove unused dependencies from go.mod and go.sum.
159 func (c *Client) Tidy() error {
160 tc, coll := c.collect(false)
161 if coll.err != nil {
162 return coll.err
163 }
164
165 if coll.skipTidy {
166 return nil
167 }
168
169 return c.tidy(tc.AllModules, false)
170 }
171
172 // Vendor writes all the module dependencies to a _vendor folder.
173 //
174 // Unlike Go, we support it for any level.
175 //
176 // We, by default, use the /_vendor folder first, if found. To disable,
177 // run with
178 //
179 // hugo --ignoreVendorPaths=".*"
180 //
181 // Given a module tree, Hugo will pick the first module for a given path,
182 // meaning that if the top-level module is vendored, that will be the full
183 // set of dependencies.
184 func (c *Client) Vendor() error {
185 vendorDir := filepath.Join(c.ccfg.WorkingDir, vendord)
186 if err := c.rmVendorDir(vendorDir); err != nil {
187 return err
188 }
189 if err := c.fs.MkdirAll(vendorDir, 0o755); err != nil {
190 return err
191 }
192
193 // Write the modules list to modules.txt.
194 //
195 // On the form:
196 //
197 // # github.com/alecthomas/chroma v0.6.3
198 //
199 // This is how "go mod vendor" does it. Go also lists
200 // the packages below it, but that is currently not applicable to us.
201 //
202 var modulesContent bytes.Buffer
203
204 tc, coll := c.collect(true)
205 if coll.err != nil {
206 return coll.err
207 }
208
209 for _, t := range tc.AllModules {
210 if t.Owner() == nil {
211 // This is the project.
212 continue
213 }
214
215 if c.shouldNotVendor(t.PathVersionQuery(false)) || c.shouldNotVendor(t.PathVersionQuery(true)) {
216 continue
217 }
218
219 if !t.IsGoMod() && !t.Vendor() {
220 // We currently do not vendor components living in the
221 // theme directory, see https://github.com/gohugoio/hugo/issues/5993
222 continue
223 }
224
225 // See https://github.com/gohugoio/hugo/issues/8239
226 // This is an error situation. We need something to vendor.
227 if t.Mounts() == nil {
228 return fmt.Errorf("cannot vendor module %q, need at least one mount", t.PathVersionQuery(false))
229 }
230
231 fmt.Fprintln(&modulesContent, "# "+t.PathVersionQuery(true)+" "+t.Version())
232
233 dir := t.Dir()
234
235 for _, mount := range t.Mounts() {
236 sourceFilename := filepath.Join(dir, mount.Source)
237 targetFilename := filepath.Join(vendorDir, t.PathVersionQuery(true), mount.Source)
238 fi, err := c.fs.Stat(sourceFilename)
239 if err != nil {
240 return fmt.Errorf("failed to vendor module: %w", err)
241 }
242
243 if fi.IsDir() {
244 if err := hugio.CopyDir(c.fs, sourceFilename, targetFilename, nil); err != nil {
245 return fmt.Errorf("failed to copy module to vendor dir: %w", err)
246 }
247 } else {
248 targetDir := filepath.Dir(targetFilename)
249
250 if err := c.fs.MkdirAll(targetDir, 0o755); err != nil {
251 return fmt.Errorf("failed to make target dir: %w", err)
252 }
253
254 if err := hugio.CopyFile(c.fs, sourceFilename, targetFilename); err != nil {
255 return fmt.Errorf("failed to copy module file to vendor: %w", err)
256 }
257 }
258 }
259
260 // Include the resource cache if present.
261 resourcesDir := filepath.Join(dir, files.FolderResources)
262 _, err := c.fs.Stat(resourcesDir)
263 if err == nil {
264 if err := hugio.CopyDir(c.fs, resourcesDir, filepath.Join(vendorDir, t.PathVersionQuery(true), files.FolderResources), nil); err != nil {
265 return fmt.Errorf("failed to copy resources to vendor dir: %w", err)
266 }
267 }
268
269 // Include the config directory if present.
270 configDir := filepath.Join(dir, "config")
271 _, err = c.fs.Stat(configDir)
272 if err == nil {
273 if err := hugio.CopyDir(c.fs, configDir, filepath.Join(vendorDir, t.PathVersionQuery(true), "config"), nil); err != nil {
274 return fmt.Errorf("failed to copy config dir to vendor dir: %w", err)
275 }
276 }
277
278 // Also include any theme.toml or config.* or hugo.* files in the root.
279 configFiles, _ := afero.Glob(c.fs, filepath.Join(dir, "config.*"))
280 configFiles2, _ := afero.Glob(c.fs, filepath.Join(dir, "hugo.*"))
281 configFiles = append(configFiles, configFiles2...)
282 configFiles = append(configFiles, filepath.Join(dir, "theme.toml"))
283 for _, configFile := range configFiles {
284 if err := hugio.CopyFile(c.fs, configFile, filepath.Join(vendorDir, t.PathVersionQuery(true), filepath.Base(configFile))); err != nil {
285 if !herrors.IsNotExist(err) {
286 return err
287 }
288 }
289 }
290 }
291
292 if modulesContent.Len() > 0 {
293 if err := afero.WriteFile(c.fs, filepath.Join(vendorDir, vendorModulesFilename), modulesContent.Bytes(), 0o666); err != nil {
294 return err
295 }
296 }
297
298 return nil
299 }
300
301 // Get runs "go get" with the supplied arguments.
302 func (c *Client) Get(args ...string) error {
303 if len(args) == 0 || (len(args) == 1 && strings.Contains(args[0], "-u")) {
304 update := len(args) != 0
305 patch := update && (args[0] == "-u=patch") //
306
307 // We need to be explicit about the modules to get.
308 var modules []string
309 // Update all active modules if the -u flag presents.
310 if update {
311 mc, coll := c.collect(true)
312 if coll.err != nil {
313 return coll.err
314 }
315 for _, m := range mc.AllModules {
316 if m.Owner() == nil || !isProbablyModule(m.Path()) {
317 continue
318 }
319 modules = append(modules, m.Path())
320 }
321 } else {
322 for _, m := range c.moduleConfig.Imports {
323 if !isProbablyModule(m.Path) {
324 // Skip themes/components stored below /themes etc.
325 // There may be false positives in the above, but those
326 // should be rare, and they will fail below with an
327 // "cannot find module providing ..." message.
328 continue
329 }
330 modules = append(modules, m.Path)
331 }
332 }
333
334 for _, m := range modules {
335 var args []string
336
337 if update && !patch {
338 args = append(args, "-u")
339 } else if update && patch {
340 args = append(args, "-u=patch")
341 }
342 args = append(args, m)
343
344 if err := c.get(args...); err != nil {
345 return err
346 }
347 }
348
349 return nil
350 }
351
352 return c.get(args...)
353 }
354
355 func (c *Client) get(args ...string) error {
356 if err := c.runGo(context.Background(), c.logger.StdOut(), append([]string{"get"}, args...)...); err != nil {
357 return fmt.Errorf("failed to get %q: %w", args, err)
358 }
359 return nil
360 }
361
362 // Init initializes this as a Go Module with the given path.
363 // If path is empty, Go will try to guess.
364 // If this succeeds, this project will be marked as Go Module.
365 func (c *Client) Init(path string) error {
366 err := c.runGo(context.Background(), c.logger.StdOut(), "mod", "init", path)
367 if err != nil {
368 return fmt.Errorf("failed to init modules: %w", err)
369 }
370
371 c.GoModulesFilename = filepath.Join(c.ccfg.WorkingDir, goModFilename)
372
373 return nil
374 }
375
376 var verifyErrorDirRe = regexp.MustCompile(`dir has been modified \((.*?)\)`)
377
378 // Verify checks that the dependencies of the current module,
379 // which are stored in a local downloaded source cache, have not been
380 // modified since being downloaded.
381 func (c *Client) Verify(clean bool) error {
382 // TODO(bep) add path to mod clean
383 err := c.runVerify()
384 if err != nil {
385 if clean {
386 m := verifyErrorDirRe.FindAllStringSubmatch(err.Error(), -1)
387 for i := range m {
388 c, err := hugofs.MakeReadableAndRemoveAllModulePkgDir(c.fs, m[i][1])
389 if err != nil {
390 return err
391 }
392 fmt.Println("Cleaned", c)
393 }
394 // Try to verify it again.
395 err = c.runVerify()
396 }
397 }
398 return err
399 }
400
401 func (c *Client) Clean(pattern string) error {
402 mods, err := c.listGoMods()
403 if err != nil {
404 return err
405 }
406
407 var g hstrings.Matcher
408
409 if pattern != "" {
410 var err error
411 g, err = hglob.GetGlob(pattern)
412 if err != nil {
413 return err
414 }
415 }
416
417 for _, m := range mods {
418 if m.Replace != nil || m.Main {
419 continue
420 }
421
422 if g != nil && !g.Match(m.Path) {
423 continue
424 }
425 dirCount, err := hugofs.MakeReadableAndRemoveAllModulePkgDir(c.fs, m.Dir)
426 if err == nil {
427 c.logger.Printf("hugo: removed %d dirs in module cache for %q", dirCount, m.Path)
428 }
429 }
430 return err
431 }
432
433 func (c *Client) runVerify() error {
434 return c.runGo(context.Background(), io.Discard, "mod", "verify")
435 }
436
437 func isProbablyModule(path string) bool {
438 return module.CheckPath(path) == nil
439 }
440
441 func (c *Client) downloadModuleVersion(path, version string) (*goModule, error) {
442 // If it's already cached, use it.
443 const keyPrefix = "downloadmoduleversion_"
444 cacheKey := keyPrefix + hashing.XxHashFromStringHexEncoded(c.ccfg.CacheDir, path, version) + ".json"
445 if b, _ := c.ccfg.ModuleQueriesCache.GetBytes(cacheKey); len(b) > 0 {
446 var cm goModule
447 if err := json.Unmarshal(b, &cm); err == nil && cm.Dir != "" {
448 if c.isDirNonEmpty(cm.Dir) {
449 return &cm, nil
450 }
451 }
452 }
453
454 // No valid cache, need to query.
455 args := []string{"mod", "download", "-json", fmt.Sprintf("%s@%s", path, version)}
456
457 b := &bytes.Buffer{}
458 err := c.runGo(context.Background(), b, args...)
459 if err != nil {
460 // The -json flag makes Go output error details as JSON to stdout
461 // even on failure. Try to extract the error message from the JSON output.
462 if jsonErr := extractGoModDownloadError(b.Bytes()); jsonErr != "" {
463 return nil, fmt.Errorf("failed to download module %s@%s: %s: %s", path, version, err, jsonErr)
464 }
465 return nil, fmt.Errorf("failed to download module %s@%s: %w", path, version, err)
466 }
467
468 jsonResult := b.Bytes()
469
470 m := &goModule{}
471 if err := json.NewDecoder(bytes.NewReader(jsonResult)).Decode(m); err != nil {
472 return nil, fmt.Errorf("failed to decode module download result: %w", err)
473 }
474
475 if m.Error != nil {
476 return nil, errors.New(m.Error.Err)
477 }
478
479 // Cache the successful result if it has a Dir field.
480 if m.Dir != "" {
481 _ = c.ccfg.ModuleQueriesCache.SetBytes(cacheKey, jsonResult)
482 }
483
484 return m, nil
485 }
486
487 // isDirNonEmpty returns true if dir exists and contains at least one file or subdirectory.
488 func (c *Client) isDirNonEmpty(dir string) bool {
489 f, err := c.fs.Open(dir)
490 if err != nil {
491 return false
492 }
493 defer f.Close()
494 // Read just one entry to check if directory is non-empty.
495 _, err = f.Readdirnames(1)
496 return err == nil
497 }
498
499 func (c *Client) listGoMods() (goModules, error) {
500 if c.GoModulesFilename == "" || !c.moduleConfig.hasModuleImport() {
501 return nil, nil
502 }
503
504 downloadModules := func(modules ...string) error {
505 args := []string{"mod", "download"}
506 args = append(args, modules...)
507 out := io.Discard
508 err := c.runGo(context.Background(), out, args...)
509 if err != nil {
510 return fmt.Errorf("failed to download modules: %w", err)
511 }
512 return nil
513 }
514
515 if err := downloadModules(); err != nil {
516 return nil, err
517 }
518
519 listAndDecodeModules := func(handle func(m *goModule) error, modules ...string) error {
520 b := &bytes.Buffer{}
521 args := []string{"list", "-m", "-json"}
522 if len(modules) > 0 {
523 args = append(args, modules...)
524 } else {
525 args = append(args, "all")
526 }
527 err := c.runGo(context.Background(), b, args...)
528 if err != nil {
529 return fmt.Errorf("failed to list modules: %w", err)
530 }
531
532 dec := json.NewDecoder(b)
533 for {
534 m := &goModule{}
535 if err := dec.Decode(m); err != nil {
536 if err == io.EOF {
537 break
538 }
539 return fmt.Errorf("failed to decode modules list: %w", err)
540 }
541
542 if err := handle(m); err != nil {
543 return err
544 }
545 }
546 return nil
547 }
548
549 var modules goModules
550 err := listAndDecodeModules(func(m *goModule) error {
551 modules = append(modules, m)
552 return nil
553 })
554 if err != nil {
555 return nil, err
556 }
557
558 // From Go 1.17, go lazy loads transitive dependencies.
559 // That does not work for us.
560 // So, download these modules and update the Dir in the modules list.
561 var modulesToDownload []string
562 for _, m := range modules {
563 if m.Dir == "" {
564 modulesToDownload = append(modulesToDownload, fmt.Sprintf("%s@%s", m.Path, m.Version))
565 }
566
567 // See https://github.com/golang/go/issues/67363
568 // Origin isn't always set.
569 if m.Origin == nil && m.GoMod != "" {
570 // There's sometimes an Info field with a JSON filename with this info, but that is also not always set.
571 // But we seem to always get the go.mod filename, so we can determine the info filename from that,
572 // just replace the .mod suffix with .info.
573 infoFilename := strings.TrimSuffix(m.GoMod, ".mod") + ".info"
574 // JSON on the form {"Version":"v0.0.0-20260225095909-668663b54d09","Time":"2026-02-25T09:59:09Z","Origin":{"VCS":"git","URL":"https://github.com/bep/hugo-mod-testing-content","Hash":"668663b54d0937df05185d144765d13c3ffda489"}}
575 if b, err := afero.ReadFile(c.fs, infoFilename); err == nil {
576 var info struct {
577 Version string
578 Time time.Time
579 Origin *goModuleOrigin
580 }
581 if err := json.Unmarshal(b, &info); err == nil {
582 m.Origin = info.Origin
583 }
584 }
585 }
586 }
587
588 if len(modulesToDownload) > 0 {
589 if err := downloadModules(modulesToDownload...); err != nil {
590 return nil, err
591 }
592 err := listAndDecodeModules(func(m *goModule) error {
593 if mm := modules.GetByPath(m.Path); mm != nil {
594 mm.Dir = m.Dir
595 }
596 return nil
597 }, modulesToDownload...)
598 if err != nil {
599 return nil, err
600 }
601 }
602
603 return modules, err
604 }
605
606 func (c *Client) writeHugoDirectSum(mods Modules) error {
607 if c.GoModulesFilename == "" {
608 return nil
609 }
610 var sums []modSum
611 for _, m := range mods {
612 if m.Owner() == nil {
613 // This is the project.
614 continue
615 }
616 if m.IsGoMod() && m.VersionQuery() != "" {
617 sums = append(sums, modSum{path: m.Path(), version: m.Version(), sum: m.Sum()})
618 }
619 }
620
621 // Read the existing sums.
622 existingSums, err := c.readModSumFile(hugoDirectSumFilename)
623 if err != nil {
624 return err
625 }
626 if len(sums) == 0 && len(existingSums) == 0 {
627 // Nothing to do.
628 return nil
629 }
630
631 dirty := len(sums) != len(existingSums)
632 for _, s1 := range sums {
633 if s2, ok := existingSums[s1.pathVersionKey]; ok {
634 if s1.sum != s2 {
635 return fmt.Errorf("verifying %s@%s: checksum mismatch: %s != %s", s1.path, s1.version, s1.sum, s2)
636 }
637 } else if !dirty {
638 dirty = true
639 }
640 }
641 if !dirty {
642 // Nothing changed.
643 return nil
644 }
645
646 // Write the sums file.
647 // First sort the sums for reproducible output.
648 sort.Slice(sums, func(i, j int) bool {
649 pvi, pvj := sums[i].pathVersionKey, sums[j].pathVersionKey
650 return pvi.path < pvj.path || (pvi.path == pvj.path && pvi.version < pvj.version)
651 })
652
653 f, err := c.fs.OpenFile(filepath.Join(c.ccfg.WorkingDir, hugoDirectSumFilename), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o666)
654 if err != nil {
655 return err
656 }
657 defer f.Close()
658
659 for _, s := range sums {
660 fmt.Fprintf(f, "%s %s %s\n", s.pathVersionKey.path, s.pathVersionKey.version, s.sum)
661 }
662
663 return nil
664 }
665
666 func (c *Client) readModSumFile(filename string) (map[pathVersionKey]string, error) {
667 b, err := afero.ReadFile(c.fs, filepath.Join(c.ccfg.WorkingDir, filename))
668 if err != nil {
669 if herrors.IsNotExist(err) {
670 return make(map[pathVersionKey]string), nil
671 }
672 return nil, err
673 }
674 lines := bytes.Split(b, []byte{'\n'})
675 sums := make(map[pathVersionKey]string)
676 for _, line := range lines {
677 parts := bytes.Fields(line)
678 if len(parts) == 3 {
679 sums[pathVersionKey{path: string(parts[0]), version: string(parts[1])}] = string(parts[2])
680 }
681 }
682
683 return sums, nil
684 }
685
686 func (c *Client) rewriteGoMod(name string, isGoMod map[string]bool) error {
687 data, err := c.rewriteGoModRewrite(name, isGoMod)
688 if err != nil {
689 return err
690 }
691 if data != nil {
692 if err := afero.WriteFile(c.fs, filepath.Join(c.ccfg.WorkingDir, name), data, 0o666); err != nil {
693 return err
694 }
695 }
696
697 return nil
698 }
699
700 func (c *Client) rewriteGoModRewrite(name string, isGoMod map[string]bool) ([]byte, error) {
701 if name == goModFilename && c.GoModulesFilename == "" {
702 // Already checked.
703 return nil, nil
704 }
705
706 modlineSplitter := getModlineSplitter(name == goModFilename)
707
708 b := &bytes.Buffer{}
709 f, err := c.fs.Open(filepath.Join(c.ccfg.WorkingDir, name))
710 if err != nil {
711 if herrors.IsNotExist(err) {
712 // It's been deleted.
713 return nil, nil
714 }
715 return nil, err
716 }
717 defer f.Close()
718
719 scanner := bufio.NewScanner(f)
720 var dirty bool
721
722 for scanner.Scan() {
723 line := scanner.Text()
724 var doWrite bool
725
726 if parts := modlineSplitter(line); parts != nil {
727 modname, modver := parts[0], parts[1]
728 modver = strings.TrimSuffix(modver, "/"+goModFilename)
729 modnameVer := modname + " " + modver
730 doWrite = isGoMod[modnameVer]
731 } else {
732 doWrite = true
733 }
734
735 if doWrite {
736 fmt.Fprintln(b, line)
737 } else {
738 dirty = true
739 }
740 }
741
742 if !dirty {
743 // Nothing changed
744 return nil, nil
745 }
746
747 return b.Bytes(), nil
748 }
749
750 func (c *Client) rmVendorDir(vendorDir string) error {
751 modulestxt := filepath.Join(vendorDir, vendorModulesFilename)
752
753 if _, err := c.fs.Stat(vendorDir); err != nil {
754 return nil
755 }
756
757 _, err := c.fs.Stat(modulestxt)
758 if err != nil {
759 // If we have a _vendor dir without modules.txt it sounds like
760 // a _vendor dir created by others.
761 return errors.New("found _vendor dir without modules.txt, skip delete")
762 }
763
764 return c.fs.RemoveAll(vendorDir)
765 }
766
767 func (c *Client) runGo(
768 ctx context.Context,
769 stdout io.Writer,
770 args ...string,
771 ) error {
772 if c.goBinaryStatus != 0 {
773 return nil
774 }
775
776 stderr := new(bytes.Buffer)
777
778 argsv := collections.StringSliceToInterfaceSlice(args)
779 argsv = append(argsv, hexec.WithEnviron(c.environ))
780 argsv = append(argsv, hexec.WithStderr(goOutputReplacerWriter{w: io.MultiWriter(stderr, os.Stderr)}))
781 argsv = append(argsv, hexec.WithStdout(stdout))
782 argsv = append(argsv, hexec.WithDir(c.ccfg.WorkingDir))
783 argsv = append(argsv, hexec.WithContext(ctx))
784
785 cmd, err := c.ccfg.Exec.New("go", argsv...)
786 if err != nil {
787 return err
788 }
789
790 if err := cmd.Run(); err != nil {
791 if ee, ok := err.(*exec.Error); ok && ee.Err == exec.ErrNotFound {
792 c.goBinaryStatus = goBinaryStatusNotFound
793 return nil
794 }
795
796 if strings.Contains(stderr.String(), "invalid version: unknown revision") {
797 // See https://github.com/gohugoio/hugo/issues/6825
798 c.logger.Println(`An unknown revision most likely means that someone has deleted the remote ref (e.g. with a force push to GitHub).
799 To resolve this, you need to manually edit your go.mod file and replace the version for the module in question with a valid ref.
800
801 The easiest is to just enter a valid branch name there, e.g. master, which would be what you put in place of 'v0.5.1' in the example below.
802
803 require github.com/gohugoio/hugo-mod-jslibs/instantpage v0.5.1
804
805 If you then run 'hugo mod graph' it should resolve itself to the most recent version (or commit if no semver versions are available).`)
806 }
807
808 _, ok := err.(*exec.ExitError)
809 if !ok {
810 return fmt.Errorf("failed to execute 'go %v': %s %T", args, err, err)
811 }
812
813 // Too old Go version
814 if strings.Contains(stderr.String(), "flag provided but not defined") {
815 c.goBinaryStatus = goBinaryStatusTooOld
816 return nil
817 }
818
819 return fmt.Errorf("go command failed: %s", stderr)
820
821 }
822
823 return nil
824 }
825
826 var goOutputReplacer = strings.NewReplacer(
827 "go: to add module requirements and sums:", "hugo: to add module requirements and sums:",
828 "go mod tidy", "hugo mod tidy",
829 )
830
831 type goOutputReplacerWriter struct {
832 w io.Writer
833 }
834
835 func (w goOutputReplacerWriter) Write(p []byte) (n int, err error) {
836 s := goOutputReplacer.Replace(string(p))
837 _, err = w.w.Write([]byte(s))
838 if err != nil {
839 return 0, err
840 }
841 return len(p), nil
842 }
843
844 func (c *Client) tidy(mods Modules, goModOnly bool) error {
845 isGoMod := make(map[string]bool)
846 for _, m := range mods {
847 if m.Owner() == nil {
848 continue
849 }
850 if m.IsGoMod() {
851 // Matching the format in go.mod
852 pathVer := m.Path() + " " + m.Version()
853 isGoMod[pathVer] = true
854 }
855 }
856
857 if err := c.rewriteGoMod(goModFilename, isGoMod); err != nil {
858 return err
859 }
860
861 if goModOnly {
862 return nil
863 }
864
865 if err := c.rewriteGoMod(goSumFilename, isGoMod); err != nil {
866 return err
867 }
868
869 return nil
870 }
871
872 func (c *Client) shouldNotVendor(path string) bool {
873 return c.noVendor != nil && c.noVendor.Match(path)
874 }
875
876 func (c *Client) createThemeDirname(modulePath string, isProjectMod bool) (string, error) {
877 invalid := fmt.Errorf("invalid module path %q; must be relative to themesDir when defined outside of the project", modulePath)
878
879 modulePath = filepath.Clean(modulePath)
880 if filepath.IsAbs(modulePath) {
881 if isProjectMod {
882 return modulePath, nil
883 }
884 return "", invalid
885 }
886
887 moduleDir := filepath.Join(c.ccfg.ThemesDir, modulePath)
888 if !isProjectMod && !strings.HasPrefix(moduleDir, c.ccfg.ThemesDir) {
889 return "", invalid
890 }
891 return moduleDir, nil
892 }
893
894 // ClientConfig configures the module Client.
895 type ClientConfig struct {
896 Fs afero.Fs
897 Logger loggers.Logger
898
899 // If set, it will be run before we do any duplicate checks for modules
900 // etc.
901 HookBeforeFinalize func(m *ModulesConfig) error
902
903 // Ignore any _vendor directory for module paths matching the given pattern.
904 // This can be nil.
905 IgnoreVendor hstrings.Matcher
906
907 // Ignore any module not found errors.
908 IgnoreModuleDoesNotExist bool
909
910 // Absolute path to the project dir.
911 WorkingDir string
912
913 // Absolute path to the project's themes dir.
914 ThemesDir string
915
916 // The publish dir.
917 PublishDir string
918
919 // Eg. "production"
920 Environment string
921
922 Exec *hexec.Exec
923
924 CacheDir string // Module cache
925 ModuleQueriesCache ModuleQueriesCache
926 ModuleConfig Config
927 }
928
929 // ModuleQueriesCache is a cache for module version queries.
930 type ModuleQueriesCache interface {
931 GetBytes(id string) ([]byte, error)
932 SetBytes(id string, data []byte) error
933 }
934
935 func (c ClientConfig) shouldIgnoreVendor(path string) bool {
936 return c.IgnoreVendor != nil && c.IgnoreVendor.Match(path)
937 }
938
939 func (cfg ClientConfig) toEnv() []string {
940 mcfg := cfg.ModuleConfig
941 var env []string
942 keyVals := []string{
943 "PWD", cfg.WorkingDir,
944 "GO111MODULE", "on",
945 "GOFLAGS", "-modcacherw",
946 "GOPATH", cfg.CacheDir,
947 "GOWORK", mcfg.Workspace, // Requires Go 1.18, see https://tip.golang.org/doc/go1.18
948 // GOCACHE was introduced in Go 1.15. This matches the location derived from GOPATH above.
949 "GOCACHE", filepath.Join(cfg.CacheDir, "pkg", "mod"),
950 }
951
952 if mcfg.Proxy != "" {
953 keyVals = append(keyVals, "GOPROXY", mcfg.Proxy)
954 }
955 if mcfg.Private != "" {
956 keyVals = append(keyVals, "GOPRIVATE", mcfg.Private)
957 }
958 if mcfg.NoProxy != "" {
959 keyVals = append(keyVals, "GONOPROXY", mcfg.NoProxy)
960 }
961 if mcfg.Auth != "" {
962 // GOAUTH was introduced in Go 1.24, see https://tip.golang.org/doc/go1.24.
963 keyVals = append(keyVals, "GOAUTH", mcfg.Auth)
964 }
965
966 config.SetEnvVars(&env, keyVals...)
967
968 return env
969 }
970
971 type goBinaryStatus int
972
973 type goModule struct {
974 Path string // module path
975 Version string // module version
976 Versions []string // available module versions (with -versions)
977 Replace *goModule // replaced by this module
978 Time *time.Time // time version was created
979 Update *goModule // available update, if any (with -u)
980 Sum string // checksum
981 GoModSum string // checksum for go.mod
982 Main bool // is this the main module?
983 Indirect bool // is this module only an indirect dependency of main module?
984 Dir string // directory holding files for this module, if any
985 GoMod string // path to go.mod file for this module, if any
986 Error *goModuleError // error loading module
987 Origin *goModuleOrigin
988 }
989
990 type goModuleOrigin struct {
991 VCS string // version control system, e.g. "git"
992 URL string // repository URL, e.g. "https://github.com/bep/hugo-testing-git-versions"
993 Subdir string // subdirectory within the repo where the module lives, e.g. "site"
994 Hash string // commit hash
995 TagSum string
996 Ref string // e.g. "refs/tags/v3.0.1"
997 }
998
999 type goModuleError struct {
1000 Err string // the error itself
1001 }
1002
1003 func extractGoModDownloadError(b []byte) string {
1004 // go mod download -json outputs Error as a plain string,
1005 // unlike go list -m -json which uses {"Err": "..."}.
1006 var m struct {
1007 Error string
1008 }
1009 if err := json.Unmarshal(b, &m); err == nil && m.Error != "" {
1010 return m.Error
1011 }
1012 return ""
1013 }
1014
1015 type goModules []*goModule
1016
1017 type modSum struct {
1018 pathVersionKey
1019 sum string
1020 }
1021
1022 func (modules goModules) GetByPath(p string) *goModule {
1023 if modules == nil {
1024 return nil
1025 }
1026
1027 for _, m := range modules {
1028 if strings.EqualFold(p, m.Path) {
1029 return m
1030 }
1031 }
1032
1033 return nil
1034 }
1035
1036 func (modules goModules) GetMain() *goModule {
1037 for _, m := range modules {
1038 if m.Main {
1039 return m
1040 }
1041 }
1042
1043 return nil
1044 }
1045
1046 func getModlineSplitter(isGoMod bool) func(line string) []string {
1047 if isGoMod {
1048 var inRequireBlock bool
1049 return func(line string) []string {
1050 if strings.HasPrefix(line, "require (") {
1051 inRequireBlock = true
1052 return nil
1053 }
1054 if inRequireBlock {
1055 if strings.HasPrefix(line, ")") {
1056 inRequireBlock = false
1057 return nil
1058 }
1059 if !strings.HasPrefix(line, "\t") {
1060 return nil
1061 }
1062 } else if !strings.HasPrefix(line, "require ") {
1063 return nil
1064 }
1065 line = strings.TrimPrefix(line, "require")
1066 line = strings.TrimSpace(line)
1067 line = strings.TrimSuffix(line, "// indirect")
1068
1069 parts := strings.Fields(line)
1070 if len(parts) < 2 {
1071 return nil
1072 }
1073 return parts
1074 }
1075 }
1076
1077 return func(line string) []string {
1078 return strings.Fields(line)
1079 }
1080 }
1081
1082 func pathVersion(m Module) string {
1083 versionStr := m.Version()
1084 if m.Vendor() {
1085 versionStr += "+vendor"
1086 }
1087 if versionStr == "" {
1088 return m.Path()
1089 }
1090 return fmt.Sprintf("%s@%s", m.Path(), versionStr)
1091 }