github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/cmd/go/fix/fix.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package fix implements the “go fix” command. 6 package fix 7 8 import ( 9 "context" 10 "fmt" 11 "go/build" 12 "os" 13 14 "github.com/go-asm/go/cmd/go/base" 15 "github.com/go-asm/go/cmd/go/cfg" 16 "github.com/go-asm/go/cmd/go/load" 17 "github.com/go-asm/go/cmd/go/modload" 18 "github.com/go-asm/go/cmd/go/str" 19 "github.com/go-asm/go/cmd/go/work" 20 ) 21 22 var CmdFix = &base.Command{ 23 UsageLine: "go fix [-fix list] [packages]", 24 Short: "update packages to use new APIs", 25 Long: ` 26 Fix runs the Go fix command on the packages named by the import paths. 27 28 The -fix flag sets a comma-separated list of fixes to run. 29 The default is all known fixes. 30 (Its value is passed to 'go tool fix -r'.) 31 32 For more about fix, see 'go doc cmd/fix'. 33 For more about specifying packages, see 'go help packages'. 34 35 To run fix with other options, run 'go tool fix'. 36 37 See also: go fmt, go vet. 38 `, 39 } 40 41 var fixes = CmdFix.Flag.String("fix", "", "comma-separated list of fixes to apply") 42 43 func init() { 44 work.AddBuildFlags(CmdFix, work.DefaultBuildFlags) 45 CmdFix.Run = runFix // fix cycle 46 } 47 48 func runFix(ctx context.Context, cmd *base.Command, args []string) { 49 pkgs := load.PackagesAndErrors(ctx, load.PackageOpts{}, args) 50 w := 0 51 for _, pkg := range pkgs { 52 if pkg.Error != nil { 53 base.Errorf("%v", pkg.Error) 54 continue 55 } 56 pkgs[w] = pkg 57 w++ 58 } 59 pkgs = pkgs[:w] 60 61 printed := false 62 for _, pkg := range pkgs { 63 if modload.Enabled() && pkg.Module != nil && !pkg.Module.Main { 64 if !printed { 65 fmt.Fprintf(os.Stderr, "go: not fixing packages in dependency modules\n") 66 printed = true 67 } 68 continue 69 } 70 // Use pkg.gofiles instead of pkg.Dir so that 71 // the command only applies to this package, 72 // not to packages in subdirectories. 73 files := base.RelPaths(pkg.InternalAllGoFiles()) 74 goVersion := "" 75 if pkg.Module != nil { 76 goVersion = "go" + pkg.Module.GoVersion 77 } else if pkg.Standard { 78 goVersion = build.Default.ReleaseTags[len(build.Default.ReleaseTags)-1] 79 } 80 var fixArg []string 81 if *fixes != "" { 82 fixArg = []string{"-r=" + *fixes} 83 } 84 base.Run(str.StringList(cfg.BuildToolexec, base.Tool("fix"), "-go="+goVersion, fixArg, files)) 85 } 86 }