Debian Codegraph @

get.go

raw symbols SCIP
1 // Copyright (c) Bartłomiej Płotka @bwplotka
2 // Licensed under the Apache License 2.0.
3
4 package main
5
6 import (
7 "bufio"
8 "context"
9 "fmt"
10 "log"
11 "os"
12 "path"
13 "path/filepath"
14 "regexp"
15 "strconv"
16 "strings"
17 "time"
18 "unicode"
19
20 "github.com/Masterminds/semver"
21 "github.com/bwplotka/bingo/pkg/bingo"
22 "github.com/bwplotka/bingo/pkg/mod"
23 "github.com/bwplotka/bingo/pkg/runner"
24 "github.com/bwplotka/bingo/pkg/version"
25 "github.com/efficientgo/core/errcapture"
26 "github.com/efficientgo/core/errors"
27 "golang.org/x/mod/module"
28 )
29
30 var (
31 goModVersionRegexp = regexp.MustCompile("^v[0-9]*$")
32 )
33
34 func parseTarget(rawTarget string) (name string, pkgPath string, versions []string, err error) {
35 if rawTarget == "" {
36 return "", "", nil, errors.New("target is empty, this should be filtered earlier")
37 }
38
39 s := strings.Split(rawTarget, "@")
40 nameOrPackage := s[0]
41 if len(s) > 1 {
42 versions = strings.Split(s[1], ",")
43 } else {
44 versions = []string{""}
45 }
46
47 if len(versions) > 1 {
48 // Check for duplicates or/and none.
49 dup := map[string]struct{}{}
50 for _, v := range versions {
51 if _, ok := dup[v]; ok {
52 return "", "", nil, errors.Newf("version duplicates are not allowed, got: %v", versions)
53 }
54 dup[v] = struct{}{}
55 if v == "none" {
56 return "", "", nil, errors.Newf("none is not allowed when there are more than one specified Version, got: %v", versions)
57 }
58 }
59 }
60
61 name = nameOrPackage
62 if strings.Contains(nameOrPackage, "/") {
63 // Binary referenced by path, get default name from package path.
64 pkgPath = nameOrPackage
65 name = path.Base(pkgPath)
66 if pkgSplit := strings.Split(pkgPath, "/"); len(pkgSplit) > 3 && goModVersionRegexp.MatchString(name) {
67 // It's common pattern to name urls with versions in go modules. Exclude that.
68 name = pkgSplit[len(pkgSplit)-2]
69 }
70 }
71 return strings.ToLower(name), pkgPath, versions, nil
72 }
73
74 type installPackageConfig struct {
75 runner *runner.Runner
76 modDir string
77 relModDir string
78 link bool
79
80 verbose bool
81 }
82
83 type getConfig struct {
84 runner *runner.Runner
85 modDir string
86 relModDir string
87 name string
88 rename string
89 link bool
90
91 timeOut uint
92 verbose bool
93 }
94
95 func (c getConfig) forPackage() installPackageConfig {
96 return installPackageConfig{
97 modDir: c.modDir,
98 relModDir: c.relModDir,
99 runner: c.runner,
100 verbose: c.verbose,
101 link: c.link,
102 }
103 }
104
105 func getAll(ctx context.Context, logger *log.Logger, c getConfig) (err error) {
106 if c.name != "" {
107 return errors.New("name cannot by specified if no target was given")
108 }
109 if c.rename != "" {
110 return errors.New("rename cannot by specified if no target was given")
111 }
112
113 pkgs, err := bingo.ListPinnedMainPackages(logger, c.relModDir, false)
114 if err != nil {
115 return err
116 }
117 for _, p := range pkgs {
118 for i, targetPkg := range p.ToPackages() {
119 if err := getPackage(ctx, logger, c.forPackage(), i, p.Name, targetPkg); err != nil {
120 return errors.Wrapf(err, "%d: getting %s", i, targetPkg.String())
121 }
122 }
123 }
124 return nil
125 }
126
127 func existingModFiles(modDir string, targetName string) (existingModFiles []string, _ error) {
128 existingModFiles, err := filepath.Glob(filepath.Join(modDir, targetName+".mod"))
129 if err != nil {
130 return nil, err
131 }
132 existingModArrFiles, err := filepath.Glob(filepath.Join(modDir, targetName+".*.mod"))
133 if err != nil {
134 return nil, err
135 }
136 return append(existingModFiles, existingModArrFiles...), nil
137 }
138
139 // get performs bingo get: it's like go get, but package aware, without go source files and on dedicated mod file.
140 // rawTarget is name or target package path, optionally with module version or array versions.
141 func get(ctx context.Context, logger *log.Logger, c getConfig, rawTarget string) (err error) {
142 var cancel context.CancelFunc = func() {}
143
144 if c.timeOut > 0 {
145 ctx, cancel = context.WithTimeout(ctx, time.Duration(c.timeOut)*time.Minute)
146 }
147
148 defer cancel()
149
150 // Cleanup all bingo modules' tmp files for fresh start.
151 if err := cleanGoGetTmpFiles(c.modDir); err != nil {
152 return err
153 }
154 if err := ensureModDirExists(logger, c.relModDir); err != nil {
155 return errors.Wrap(err, "ensure mod dir")
156 }
157
158 if rawTarget == "" {
159 // Empty target means to get all. It recursively invokes get for each existing binary.
160 return getAll(ctx, logger, c)
161 }
162
163 // NOTE: pkgPath can be empty. This means that tool was referenced by name.
164 name, pkgPath, versions, err := parseTarget(rawTarget)
165 if err != nil {
166 return errors.Wrapf(err, "parse %v", rawTarget)
167 }
168
169 if c.rename != "" {
170 // Treat rename specially.
171 if pkgPath != "" {
172 return errors.Newf("-r rename has to reference installed tool by name not path, got: %v", pkgPath)
173 }
174 if versions[0] != "" || len(versions) > 1 {
175 return errors.Newf("-r rename cannot take version arguments (string after @), got %v", versions)
176 }
177 if err := validateNewName(versions, name, c.rename); err != nil {
178 return errors.Wrap(err, "-r")
179 }
180 newExisting, err := existingModFiles(c.modDir, c.rename)
181 if err != nil {
182 return errors.Wrapf(err, "existing mod files for %v", c.rename)
183 }
184 if len(newExisting) > 0 {
185 return errors.Newf("found existing installed binaries %v under name you want to rename on. Remove target name %s or use different one", newExisting, c.rename)
186 }
187
188 existing, err := existingModFiles(c.modDir, name)
189 if err != nil {
190 return errors.Wrapf(err, "existing mod files for %v", name)
191 }
192
193 if len(existing) == 0 {
194 return errors.Newf("nothing to rename, tool %v not installed", name)
195 }
196
197 targets := make([]bingo.Package, 0, len(existing))
198 for _, e := range existing {
199 mf, err := bingo.OpenModFile(e)
200 if err != nil {
201 return errors.Wrapf(err, "found unparsable mod file %v. Uninstall it first via get %v@none or fix it manually.", e, name)
202 }
203
204 dpkg := mf.DirectPackage()
205
206 if err := mf.Close(); err != nil {
207 return errors.Wrapf(err, "unable to close mod file %v", e)
208 }
209
210 if dpkg == nil {
211 return errors.Wrapf(err, "failed to rename tool %v to %v name; found empty mod file %v; Use full path to install tool again", name, c.rename, e)
212 }
213 targets = append(targets, *dpkg)
214 }
215
216 for i, t := range targets {
217 if err := getPackage(ctx, logger, c.forPackage(), i, c.rename, t); err != nil {
218 return errors.Wrapf(err, "%s.mod: getting %s", c.rename, t)
219 }
220 }
221
222 // Remove old mod files.
223 return removeAllGlob(filepath.Join(c.modDir, name+".*"))
224 }
225
226 targetName := name
227 if c.name != "" {
228 if err := validateNewName(versions, name, c.name); err != nil {
229 return errors.Wrap(err, "-n")
230 }
231 targetName = c.name
232 }
233
234 existing, err := existingModFiles(c.modDir, targetName)
235 if err != nil {
236 return errors.Wrapf(err, "existing mod files for %v", targetName)
237 }
238
239 switch versions[0] {
240 case "none":
241 if pkgPath != "" {
242 return errors.Newf("cannot delete tool by full path. Use just %v@none name instead", targetName)
243 }
244 if len(existing) == 0 {
245 return errors.Newf("nothing to delete, tool %v is not installed", targetName)
246 }
247 // None means we no longer want to version this package.
248 // NOTE: We don't remove binaries.
249 return removeAllGlob(filepath.Join(c.modDir, name+".*"))
250 case "":
251 if len(existing) > 1 {
252 // Edge case. If no version is specified requested, allow to pull all array versions at once.
253 versions = make([]string, len(existing))
254 }
255 }
256
257 targets := make([]bingo.Package, 0, len(versions))
258 pathWasSpecified := pkgPath != ""
259 for i, v := range versions {
260 target := bingo.Package{Module: module.Version{Version: v}, RelPath: pkgPath} // "Unknown" module mode.
261 if len(existing) > i {
262 e := existing[i]
263
264 mf, err := bingo.OpenModFile(e)
265 if err != nil {
266 return errors.Wrapf(err, "found unparsable mod file %v. Uninstall it first via get %v@none or fix it manually.", e, name)
267 }
268
269 dpkg := mf.DirectPackage()
270
271 if err := mf.Close(); err != nil {
272 return errors.Wrapf(err, "unable to close mod file %v", e)
273 }
274
275 if dpkg != nil {
276 if target.Path() != "" && target.Path() != dpkg.Path() {
277 if pathWasSpecified {
278 return errors.Newf("found mod file %v that has different package path %q than given %q"+
279 "Uninstall existing tool using `%v@none` or use `-n` flag to choose different name", e, dpkg.Path(), target.Path(), targetName)
280 }
281 return errors.Newf("found array mod file %v that has different package path %q than previous in array %q. Manual edit?"+
282 "Uninstall existing tool using `%v@none` or use `-n` flag to choose different name", e, dpkg.Path(), target.Path(), targetName)
283 }
284
285 target.Module.Path = dpkg.Module.Path
286 if target.Module.Version == "" {
287 // If no version is requested, use the existing version.
288 target.Module.Version = dpkg.Module.Version
289 }
290 target.RelPath = dpkg.RelPath
291
292 // Save for future versions without potentially existing files.
293 pkgPath = target.Path()
294 } else if target.Path() == "" {
295 return errors.Wrapf(err, "failed to install tool %v found empty mod file %v; Use full path to install tool again", targetName, e)
296 }
297 }
298 if target.Path() == "" {
299 return errors.Newf("tool referenced by name %v that was never installed before; Use full path to install a tool", name)
300 }
301 targets = append(targets, target)
302 }
303
304 for i, t := range targets {
305 if err := getPackage(ctx, logger, c.forPackage(), i, targetName, t); err != nil {
306 return errors.Wrapf(err, "%s.mod: getting %s", targetName, t)
307 }
308 }
309
310 // Remove target unused arr mod files based on version file.
311 existingTargetModArrFiles, gerr := filepath.Glob(filepath.Join(c.modDir, targetName+".*.mod"))
312 if gerr != nil {
313 err = gerr
314 return
315 }
316 for _, f := range existingTargetModArrFiles {
317 i, perr := strconv.ParseInt(strings.Split(filepath.Base(f), ".")[1], 10, 64)
318 if perr != nil || int(i) >= len(versions) {
319 if rerr := os.RemoveAll(f); rerr != nil {
320 err = rerr
321 return
322 }
323 }
324 }
325 return nil
326 }
327
328 func validateNewName(versions []string, old, new string) error {
329 if new == old {
330 return errors.Newf("cannot be the same as module name %v", new)
331 }
332 if versions[0] == "none" {
333 return errors.New("cannot use with @none logic")
334 }
335 return nil
336 }
337
338 func cleanGoGetTmpFiles(modDir string) error {
339 // Remove all tmp files
340 if err := removeAllGlob(filepath.Join(modDir, "*.*.tmp.*")); err != nil {
341 return err
342 }
343 return removeAllGlob(filepath.Join(modDir, "*.tmp.*"))
344 }
345
346 func validateTargetName(targetName string) error {
347 if targetName == "cmd" {
348 return errors.Newf("package would be installed with ambiguous name %s. This is a common, but slightly annoying package layout"+
349 "It's advised to choose unique name with -n flag", targetName)
350 }
351 if targetName == strings.TrimSuffix(bingo.FakeRootModFileName, ".mod") {
352 return errors.Newf("requested binary with name %q`. This is impossible, choose different name using -n flag", strings.TrimSuffix(bingo.FakeRootModFileName, ".mod"))
353 }
354 return nil
355 }
356
357 func resolvePackage(logger *log.Logger, verbose bool, tmpModFile string, runnable runner.Runnable, target *bingo.Package) (err error) {
358 // Do initial go get -d and remember output.
359 // NOTE: We have to use get -d to resolve version and tell us what is the module and what package.
360 // If go get will not succeed, or will not update go mod, we will try manual lookup.
361 // This is required to support modules depending on broken modules (and using exclude/replace statements).
362 out, gerr := runnable.GetD(target.String())
363 if gerr == nil {
364 mods, err := bingo.ModIndirectModules(tmpModFile)
365 if err != nil {
366 return err
367 }
368
369 switch len(mods) {
370 case 0:
371 return errors.Newf("no indirect module found on %v", tmpModFile)
372 case 1:
373 target.RelPath = strings.TrimPrefix(strings.TrimPrefix(target.RelPath, mods[0].Path), "/")
374 target.Module = mods[0]
375 return nil
376 default:
377 if target.Module.Path != "" {
378 for _, m := range mods {
379 if m.Path == target.Module.Path {
380 target.RelPath = strings.TrimPrefix(strings.TrimPrefix(target.RelPath, m.Path), "/")
381 target.Module = m
382 return nil
383 }
384 }
385 return errors.Newf("no indirect module found on %v for %v module", tmpModFile, target.Module.Path)
386 }
387
388 for _, m := range mods {
389 if m.Path == target.Path() {
390 target.RelPath = strings.TrimPrefix(strings.TrimPrefix(target.RelPath, m.Path), "/")
391 target.Module = m
392 return nil
393 }
394 }
395
396 // In this case it is not successful from our perspective.
397 gerr = errors.New(out)
398 }
399 }
400
401 cacheModPath, err := gomodcache(runnable)
402 if err != nil {
403 return errors.Wrapf(err, "can't find GOMODCACHE or deduct it from GOPATH")
404 }
405
406 // We fallback only if go-get failed which happens when it does not know what version to choose.
407 // In this case
408 if err := resolveInGoModCache(logger, verbose, cacheModPath, target); err != nil {
409 return errors.Wrapf(err, "fallback to local go mod cache resolution failed after go get failure: %v", gerr)
410 }
411 return nil
412 }
413
414 func gomodcache(runnable runner.Runnable) (string, error) {
415 cachepath, err := runnable.GoEnv("GOMODCACHE")
416 if err != nil {
417 return "", errors.Wrap(err, "go env GOMODCACHE")
418 }
419 if cachepath != "" {
420 return cachepath, nil
421 }
422 gpath, err := runnable.GoEnv("GOPATH")
423 if err != nil {
424 return "", errors.Wrap(err, "go env GOPATH")
425 }
426 return filepath.Join(gpath, "pkg/mod"), nil
427 }
428
429 func latestModVersion(listFile string) (_ string, err error) {
430 f, err := os.Open(listFile)
431 if err != nil {
432 return "", err
433 }
434 defer errcapture.Do(&err, f.Close, "list file close")
435
436 scanner := bufio.NewScanner(f)
437 var lastVersion string
438 for scanner.Scan() {
439 lastVersion = scanner.Text()
440 }
441 if err := scanner.Err(); err != nil {
442 return "", err
443 }
444 if lastVersion == "" {
445 return "", errors.New("empty file")
446 }
447 return lastVersion, nil
448 }
449
450 // encodePath returns the safe encoding of the given module path.
451 // It fails if the module path is invalid.
452 // Copied & modified from https://github.com/golang/go/blob/c54bc3448390d4ae4495d6d2c03c9dd4111b08f1/src/cmd/go/internal/module/module.go#L421
453 func encodePath(path string) string {
454 haveUpper := false
455 for _, r := range path {
456 if 'A' <= r && r <= 'Z' {
457 haveUpper = true
458 }
459 }
460
461 if !haveUpper {
462 return path
463 }
464
465 var buf []byte
466 for _, r := range path {
467 if 'A' <= r && r <= 'Z' {
468 buf = append(buf, '!', byte(r+'a'-'A'))
469 } else {
470 buf = append(buf, byte(r))
471 }
472 }
473 return string(buf)
474 }
475
476 // resolveInGoModCache will try to find a referenced module in the Go modules cache.
477 func resolveInGoModCache(logger *log.Logger, verbose bool, cacheModPath string, target *bingo.Package) error {
478 modMetaCache := filepath.Join(cacheModPath, "cache/download")
479 modulePath := target.Path()
480 // Case sensitivity problem is fixed by replacing upper case with '/!<lower case letter>` signature.
481 // See https://tip.golang.org/cmd/go/#hdr-Module_proxy_protocol
482 lookupModulePath := encodePath(modulePath)
483
484 // Since we don't know which part of full path is package, which part is module.
485 // Start from longest and go until we find one.
486 for ; len(strings.Split(lookupModulePath, "/")) >= 2; func() {
487 lookupModulePath = filepath.Dir(lookupModulePath)
488 modulePath = filepath.Dir(modulePath)
489 }() {
490 modMetaDir := filepath.Join(modMetaCache, lookupModulePath, "@v")
491 if _, err := os.Stat(modMetaDir); err != nil {
492 if !os.IsNotExist(err) {
493 return err
494 }
495 if verbose {
496 logger.Println("resolveInGoModCache:", modMetaDir, "directory does not exists")
497 }
498 continue
499
500 }
501 if verbose {
502 logger.Println("resolveInGoModCache: Found", modMetaDir, "directory")
503 }
504
505 // There are 2 major cases:
506 // 1. We have @latest or version is not pinned: find latest module having this package.
507 if target.Module.Version == "" || target.Module.Version == "latest" {
508 latest, err := latestModVersion(filepath.Join(modMetaDir, "list"))
509 if err != nil {
510 return errors.Wrapf(err, "get latest version from %v", filepath.Join(modMetaDir, "list"))
511 }
512
513 target.Module.Path = modulePath
514 target.Module.Version = latest
515 target.RelPath = strings.TrimPrefix(strings.TrimPrefix(target.RelPath, target.Module.Path), "/")
516 return nil
517 }
518
519 // 2. We don't @latest and have version pinned: find exact version then.
520 // Look for .info files that have exact version or sha.
521 if strings.HasPrefix(target.Module.Version, "v") {
522 if _, err := os.Stat(filepath.Join(modMetaDir, target.Module.Version+".info")); err != nil {
523 if !os.IsNotExist(err) {
524 return err
525 }
526
527 if verbose {
528 logger.Println("resolveInGoModCache:", filepath.Join(modMetaDir, target.Module.Version+".info"),
529 "file not exists. Looking for +incompatible info file")
530 }
531
532 // Try +incompatible.
533 if _, err := os.Stat(filepath.Join(modMetaDir, target.Module.Version+"+incompatible.info")); err != nil {
534 if !os.IsNotExist(err) {
535 return err
536 }
537
538 if verbose {
539 logger.Println("resolveInGoModCache:", filepath.Join(modMetaDir, target.Module.Version+"+incompatible.info"),
540 "file not exists. Looking for different module")
541 }
542 continue
543 }
544 target.Module.Version += "+incompatible"
545 }
546 target.Module.Path = modulePath
547 target.RelPath = strings.TrimPrefix(strings.TrimPrefix(target.RelPath, target.Module.Path), "/")
548 return nil
549 }
550
551 // We have commit sha.
552 files, err := os.ReadDir(modMetaDir)
553 if err != nil {
554 return err
555 }
556
557 for _, f := range files {
558 if f.IsDir() {
559 continue
560 }
561 if len(target.Module.Version) > 12 && strings.HasSuffix(f.Name(), fmt.Sprintf("%v.info", target.Module.Version[:12])) {
562 target.Module.Path = modulePath
563 target.Module.Version = strings.TrimSuffix(f.Name(), ".info")
564 target.RelPath = strings.TrimPrefix(strings.TrimPrefix(target.RelPath, target.Module.Path), "/")
565 return nil
566 }
567 }
568
569 if verbose {
570 ver := target.Module.Version
571 if len(ver) > 12 {
572 ver = ver[:12]
573 }
574 logger.Println("resolveInGoModCache: .info file for sha", ver, "does not exists. Looking for different module")
575 }
576 }
577 return errors.Newf("no module was cached matching given package %v", target.Path())
578 }
579
580 // getPackage takes package array index, tool name and package path (also module path and version which are optional) and
581 // generates new module with the given package's module as the only dependency (direct require statement).
582 // For generation purposes we take the existing <name>.mod file (if exists, if paths matches). This allows:
583 // - Comments to be preserved.
584 // - First direct require module will be preserved (unless version changes)
585 // - Replace to be preserved if the // bingo:no_replace_fetch commend is found it such mod file.
586 //
587 // As resolution of module vs package for Go Module is convoluted and all code is under internal dir, we have to rely on `go` binary
588 // capabilities and output.
589 // TODO(bwplotka): Consider copying code for it? Of course it's would be easier if such tool would exist in Go project itself (:
590 func getPackage(ctx context.Context, logger *log.Logger, c installPackageConfig, i int, name string, target bingo.Package) (err error) {
591 if c.verbose {
592 logger.Println("getting target", target.String(), "(module", target.Module.Path, ")")
593 }
594
595 // The out module file we generate/maintain keep in modDir.
596 outModFile := filepath.Join(c.modDir, name+".mod")
597 tmpEmptyModFilePath := filepath.Join(c.modDir, name+"-e.tmp.mod")
598 tmpModFilePath := filepath.Join(c.modDir, name+".tmp.mod")
599 if i > 0 {
600 // Handle array go modules.
601 outModFile = filepath.Join(c.modDir, fmt.Sprintf("%s.%d.mod", name, i))
602 tmpEmptyModFilePath = filepath.Join(c.modDir, fmt.Sprintf("%s.%d-e.tmp.mod", name, i))
603 tmpModFilePath = filepath.Join(c.modDir, fmt.Sprintf("%s.%d.tmp.mod", name, i))
604 }
605
606 outSumFile := strings.TrimSuffix(outModFile, ".mod") + ".sum"
607
608 // If we don't have all information, resolve version.
609 var fetchedDirectives nonRequireDirectives
610 if target.Module.Version == "" || !strings.HasPrefix(target.Module.Version, "v") || target.Module.Path == "" {
611 // Set up totally empty mod file to get clear version to install.
612 tmpEmptyModFile, err := bingo.CreateFromExistingOrNew(ctx, c.runner, logger, "", tmpEmptyModFilePath)
613 if err != nil {
614 return errors.Wrap(err, "create empty tmp mod file")
615 }
616
617 defer errcapture.Do(&err, tmpEmptyModFile.Close, "close")
618
619 runnable := c.runner.With(ctx, tmpEmptyModFile.Filepath(), c.modDir, nil)
620 if err := resolvePackage(logger, c.verbose, tmpEmptyModFile.Filepath(), runnable, &target); err != nil {
621 return err
622 }
623
624 if !strings.HasSuffix(target.Module.Version, "+incompatible") {
625 fetchedDirectives, err = autoFetchDirectives(runnable, logger, target)
626 if err != nil {
627 return err
628 }
629 }
630 }
631
632 // Now we should have target with all required info, prepare tmp file.
633 // TODO(bwplotka): Is this still needed?
634 if err := cleanGoGetTmpFiles(c.modDir); err != nil {
635 return err
636 }
637
638 tmpModFile, err := bingo.CreateFromExistingOrNew(ctx, c.runner, logger, outModFile, tmpModFilePath)
639 if err != nil {
640 return errors.Wrap(err, "create tmp mod file")
641 }
642
643 var closed bool
644 defer func() {
645 // This defer func is only to handle below set directive method failures since they still need to keep the file open.
646 if !closed {
647 errcapture.Do(&err, tmpModFile.Close, "close")
648 }
649 }()
650
651 if !tmpModFile.IsDirectivesAutoFetchDisabled() && !fetchedDirectives.isEmpty() {
652 if err := tmpModFile.SetReplaceDirectives(fetchedDirectives.replace...); err != nil {
653 return err
654 }
655 if err := tmpModFile.SetExcludeDirectives(fetchedDirectives.exclude...); err != nil {
656 return err
657 }
658 if err := tmpModFile.SetRetractDirectives(fetchedDirectives.retract...); err != nil {
659 return err
660 }
661 }
662
663 // Currently user can't specify build flags and envvars from CLI, take if from optionally, manually updated mod file.
664 if old := tmpModFile.DirectPackage(); old != nil {
665 target.BuildEnvs = old.BuildEnvs
666 target.BuildFlags = old.BuildFlags
667 }
668 if err := tmpModFile.SetDirectRequire(target); err != nil {
669 return err
670 }
671
672 if err := install(ctx, logger, c.runner, c.modDir, name, c.link, tmpModFile); err != nil {
673 return errors.Wrap(err, "install")
674 }
675
676 tmpModFileFilepath := tmpModFile.Filepath()
677
678 // We have close it once here so the defer func does not need to close it again.
679 closed = true
680 if err := tmpModFile.Close(); err != nil {
681 return err
682 }
683
684 // We were working on tmp file, do atomic rename.
685 if err := os.Rename(tmpModFileFilepath, outModFile); err != nil {
686 return errors.Wrap(err, "rename mod file")
687 }
688 if err := os.Rename(bingo.SumFilePath(tmpModFileFilepath), outSumFile); err != nil {
689 return errors.Wrap(err, "rename sum file")
690 }
691 return nil
692 }
693
694 func localGoModFileAfterGet(gopath string, target bingo.Package) string {
695 modulePath := target.Module.String()
696
697 // Go get uses special notation for non-supported names. See https://github.com/bwplotka/bingo/issues/65.
698 var b strings.Builder
699 b.Grow(len(modulePath))
700 for i := 0; i < len(modulePath); i++ {
701 c := rune(modulePath[i])
702 if 'A' <= c && c <= 'Z' {
703 b.WriteByte('!')
704 c = unicode.To(unicode.LowerCase, c)
705 }
706 b.WriteRune(c)
707 }
708 return filepath.Join(gopath, "pkg", "mod", b.String(), "go.mod")
709 }
710
711 type nonRequireDirectives struct {
712 replace []mod.ReplaceDirective
713 exclude []mod.ExcludeDirective
714 retract []mod.RetractDirective
715 }
716
717 func (d nonRequireDirectives) isEmpty() bool {
718 return len(d.replace) == 0 && len(d.exclude) == 0 && len(d.retract) == 0
719 }
720
721 // autoFetchDirectives is returning all non-require directives, that allows bingo to use exactly the same exclude, replace and retract statement
722 // as the target module we want to install.
723 // It's a very common case where modules mitigate faulty modules or conflicts with replace directives.
724 // Since we always download single tool dependency module per tool module, we can copy its non-require statements if exists to fix this common case.
725 func autoFetchDirectives(runnable runner.Runnable, logger *log.Logger, target bingo.Package) (d nonRequireDirectives, _ error) {
726 gopath, err := runnable.GoEnv("GOPATH")
727 if err != nil {
728 return d, errors.Wrap(err, "go env")
729 }
730
731 // We leverage fact that when go get runs if downloads the version we find as relevant locally
732 // in the GOPATH/pkg/mod/...
733 targetModFile := localGoModFileAfterGet(gopath, target)
734 if _, err := os.Stat(targetModFile); err != nil {
735 if os.IsNotExist(err) {
736 // Pre module package.
737 return d, nil
738 }
739 return d, errors.Wrapf(err, "stat target mod directory %v", targetModFile)
740 }
741
742 // Mod directory has only read permissions.
743 targetModParsed, err := mod.OpenFileForRead(targetModFile)
744 if err != nil {
745 return d, errors.Wrapf(err, "parse target mod file %v", targetModFile)
746 }
747
748 if semver.MustParse(targetModParsed.GoVersion()).GreaterThan(runnable.GoVersion()) {
749 logger.Printf("WARNING: Go module you are trying to install requires higher Go version (%v) than you are using (%v). Use newer Go version to install it if you encounter build errors (e.g when generics were used).\n", targetModParsed.GoVersion(), runnable.GoVersion().String())
750 }
751
752 d.replace = targetModParsed.ReplaceDirectives()
753 d.exclude = targetModParsed.ExcludeDirectives()
754 d.retract = targetModParsed.RetractDirectives()
755
756 if len(d.retract) > 0 && runnable.GoVersion().LessThan(version.Go116) {
757 return d, errors.Newf("target Go module is using new 'retract' directive. Use Go1.16+ to build it")
758 }
759 return d, nil
760 }
761
762 // gobin mimics the way go install finds where to install go tool.
763 func gobin(runnable runner.Runnable) (string, error) {
764 binPath, err := runnable.GoEnv("GOBIN")
765 if err != nil {
766 return "", errors.Wrap(err, "go env GOBIN")
767 }
768 if binPath != "" {
769 return binPath, nil
770 }
771
772 gpath, err := runnable.GoEnv("GOPATH")
773 if err != nil {
774 return "", errors.Wrap(err, "go env GOPATH")
775 }
776 return filepath.Join(gpath, "bin"), nil
777 }
778
779 func install(ctx context.Context, logger *log.Logger, r *runner.Runner, modDir string, name string, link bool, modFile *bingo.ModFile) (err error) {
780 pkg := modFile.DirectPackage()
781 if err := validateTargetName(name); err != nil {
782 return errors.Wrap(err, pkg.String())
783 }
784
785 modCtx := r.With(ctx, modFile.Filepath(), modDir, nil)
786
787 // Check if path is pointing to non-buildable package.
788 var listArgs []string
789 listArgs = append(listArgs, modFile.DirectPackage().BuildFlags...)
790 listArgs = append(listArgs, "-mod=mod", "-f={{.Name}}", pkg.Path())
791 if listOutput, err := modCtx.List(listArgs...); err != nil {
792 return errors.Wrap(err, "list")
793 } else if !strings.HasSuffix(listOutput, "main") {
794 return errors.Newf("package %s is non-main (go list output %q), nothing to get and build", pkg.Path(), listOutput)
795 }
796
797 // Use go get -d to recreate .sum file
798 // TODO(bwplotka): Do it only if not present or if we update mod to new version?
799 if out, err := modCtx.GetD(modFile.DirectPackage().String()); err != nil {
800 return errors.Wrap(err, out)
801 }
802
803 gobin, err := gobin(modCtx)
804 if err != nil {
805 return errors.Wrap(err, "deduct GOBIN")
806 }
807
808 // go install does not define -modfile flag, so we mimic go install with go build -o instead.
809 binPath := filepath.Join(gobin, fmt.Sprintf("%s-%s", name, pkg.Module.Version))
810
811 // New context with new environment files.
812 modCtx = r.With(ctx, modFile.Filepath(), modDir, pkg.BuildEnvs)
813 if err := modCtx.Build(pkg.Path(), binPath, pkg.BuildFlags...); err != nil {
814 if strings.Contains(err.Error(), "module declares its path as: ") &&
815 strings.Contains(err.Error(), fmt.Sprintf("but was required as: %v", modFile.DirectPackage().Path())) {
816
817 // TODO(bwplotka): Add native mode for forks.
818 logger.Println("The", modFile.DirectPackage().Path(), "module is a potential fork, since go.mod has mismatching module."+
819 " Building forks is not supported yet. See https://github.com/bwplotka/bingo/issues/110.")
820 }
821 return errors.Wrap(err, "build versioned")
822 }
823
824 if !link {
825 return nil
826 }
827
828 if err := os.RemoveAll(filepath.Join(gobin, name)); err != nil {
829 return errors.Wrap(err, "rm")
830 }
831 if err := os.Symlink(binPath, filepath.Join(gobin, name)); err != nil {
832 return errors.Wrap(err, "symlink")
833 }
834 return nil
835 }
836
837 const modREADMEFmt = `# Project Development Dependencies.
838
839 This is directory which stores Go modules with pinned buildable package that is used within this repository, managed by <https://github.com/bwplotka/bingo>.
840
841 * Run ` + "`" + "bingo get" + "`" + ` to install all tools having each own module file in this directory.
842 * Run ` + "`" + "bingo get <tool>" + "`" + ` to install ` + "`" + "<tool>" + "`" + ` that have own module file in this directory.
843 * For Makefile: Make sure to put ` + "`" + "include %s/Variables.mk" + "`" + ` in your Makefile, then use ` + "`" + "\\$(<UPPER_CASE_TOOL_NAME>)" + "`" + ` variable where ` + "`" + "<tool>" + "`" + ` is the %s/` + "`" + "<tool>.mod" + "`" + `.
844 * For shell: Run ` + "`" + "source %s/variables.env" + "`" + ` to source all environment variable for each tool.
845 * See <https://github.com/bwplotka/bingo> or -h on how to add, remove or change binaries dependencies.
846
847 ## Requirements
848
849 * Go 1.24.x or 1.25.x
850 `
851
852 const gitignore = `
853 # Ignore everything
854 *
855
856 # But not these files:
857 !.gitignore
858 !*.mod
859 !*.sum
860 !README.md
861 !Variables.mk
862 !variables.env
863
864 *tmp.mod
865 *tmp.sum
866 `
867
868 func ensureModDirExists(logger *log.Logger, relModDir string) error {
869 _, err := os.Stat(relModDir)
870 if err != nil {
871 if !os.IsNotExist(err) {
872 return errors.Wrapf(err, "stat bingo module dir %s", relModDir)
873 }
874
875 logger.Printf("Bingo not used before here, creating directory for pinned modules for you at %s\n", relModDir)
876 if err := os.MkdirAll(relModDir, os.ModePerm); err != nil {
877 return errors.Wrapf(err, "create moddir %s", relModDir)
878 }
879 }
880
881 // Hack against:
882 // "A file named go.mod must still be present in order to determine the module root directory, but it is not accessed."
883 // Ref: https://golang.org/doc/go1.14#go-flags
884 // TODO(bwplotka): Remove it: https://github.com/bwplotka/bingo/issues/20
885 if err := os.WriteFile(
886 filepath.Join(relModDir, bingo.FakeRootModFileName),
887 []byte("module _ // Fake go.mod auto-created by 'bingo' for go -moddir compatibility with non-Go projects. Commit this file, together with other .mod files."),
888 0666,
889 ); err != nil {
890 return err
891 }
892
893 // README.
894 if err := os.WriteFile(
895 filepath.Join(relModDir, "README.md"),
896 []byte(fmt.Sprintf(modREADMEFmt, relModDir, relModDir, relModDir)),
897 0666,
898 ); err != nil {
899 return err
900 }
901 // gitignore.
902 return os.WriteFile(filepath.Join(relModDir, ".gitignore"), []byte(gitignore), 0666)
903 }
904
905 func removeAllGlob(glob string) error {
906 files, err := filepath.Glob(glob)
907 if err != nil {
908 return err
909 }
910 for _, f := range files {
911 if err := os.RemoveAll(f); err != nil {
912 return err
913 }
914 }
915 return nil
916 }