}
}
}
+
+// InGOFLAGS returns whether GOFLAGS contains the given flag, such as "-mod".
+func InGOFLAGS(flag string) bool {
+ for _, goflag := range GOFLAGS() {
+ name := goflag
+ if strings.HasPrefix(name, "--") {
+ name = name[1:]
+ }
+ if i := strings.Index(name, "="); i >= 0 {
+ name = name[:i]
+ }
+ if name == flag {
+ return true
+ }
+ }
+ return false
+}
func runVersion(ctx context.Context, cmd *base.Command, args []string) {
if len(args) == 0 {
- if *versionM || *versionV {
+ // If any of this command's flags were passed explicitly, error
+ // out, because they only make sense with arguments.
+ //
+ // Don't error if the flags came from GOFLAGS, since that can be
+ // a reasonable use case. For example, imagine GOFLAGS=-v to
+ // turn "verbose mode" on for all Go commands, which should not
+ // break "go version".
+ if (!base.InGOFLAGS("-m") && *versionM) || (!base.InGOFLAGS("-v") && *versionV) {
fmt.Fprintf(os.Stderr, "go version: flags can only be used with arguments\n")
base.SetExitStatus(2)
return
case "":
// Behavior will be determined automatically, as if no flag were passed.
case "readonly", "vendor", "mod":
- if !cfg.ModulesEnabled && !inGOFLAGS("-mod") {
+ if !cfg.ModulesEnabled && !base.InGOFLAGS("-mod") {
base.Fatalf("build flag -mod=%s only valid when using modules", cfg.BuildMod)
}
default:
base.Fatalf("-mod=%s not supported (can be '', 'mod', 'readonly', or 'vendor')", cfg.BuildMod)
}
if !cfg.ModulesEnabled {
- if cfg.ModCacheRW && !inGOFLAGS("-modcacherw") {
+ if cfg.ModCacheRW && !base.InGOFLAGS("-modcacherw") {
base.Fatalf("build flag -modcacherw only valid when using modules")
}
- if cfg.ModFile != "" && !inGOFLAGS("-mod") {
+ if cfg.ModFile != "" && !base.InGOFLAGS("-mod") {
base.Fatalf("build flag -modfile only valid when using modules")
}
}
}
-
-func inGOFLAGS(flag string) bool {
- for _, goflag := range base.GOFLAGS() {
- name := goflag
- if strings.HasPrefix(name, "--") {
- name = name[1:]
- }
- if i := strings.Index(name, "="); i >= 0 {
- name = name[:i]
- }
- if name == flag {
- return true
- }
- }
- return false
-}