1// Copyright 2017 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 5package base 6 7import ( 8 "flag" 9 "fmt" 10 11 "cmd/go/internal/cfg" 12 "cmd/go/internal/fsys" 13 "cmd/internal/quoted" 14) 15 16// A StringsFlag is a command-line flag that interprets its argument 17// as a space-separated list of possibly-quoted strings. 18type StringsFlag []string 19 20func (v *StringsFlag) Set(s string) error { 21 var err error 22 *v, err = quoted.Split(s) 23 if *v == nil { 24 *v = []string{} 25 } 26 return err 27} 28 29func (v *StringsFlag) String() string { 30 return "<StringsFlag>" 31} 32 33// explicitStringFlag is like a regular string flag, but it also tracks whether 34// the string was set explicitly to a non-empty value. 35type explicitStringFlag struct { 36 value *string 37 explicit *bool 38} 39 40func (f explicitStringFlag) String() string { 41 if f.value == nil { 42 return "" 43 } 44 return *f.value 45} 46 47func (f explicitStringFlag) Set(v string) error { 48 *f.value = v 49 if v != "" { 50 *f.explicit = true 51 } 52 return nil 53} 54 55// AddBuildFlagsNX adds the -n and -x build flags to the flag set. 56func AddBuildFlagsNX(flags *flag.FlagSet) { 57 flags.BoolVar(&cfg.BuildN, "n", false, "") 58 flags.BoolVar(&cfg.BuildX, "x", false, "") 59} 60 61// AddChdirFlag adds the -C flag to the flag set. 62func AddChdirFlag(flags *flag.FlagSet) { 63 // The usage message is never printed, but it's used in chdir_test.go 64 // to identify that the -C flag is from AddChdirFlag. 65 flags.Func("C", "AddChdirFlag", ChdirFlag) 66} 67 68// AddModFlag adds the -mod build flag to the flag set. 69func AddModFlag(flags *flag.FlagSet) { 70 flags.Var(explicitStringFlag{value: &cfg.BuildMod, explicit: &cfg.BuildModExplicit}, "mod", "") 71} 72 73// AddModCommonFlags adds the module-related flags common to build commands 74// and 'go mod' subcommands. 75func AddModCommonFlags(flags *flag.FlagSet) { 76 flags.BoolVar(&cfg.ModCacheRW, "modcacherw", false, "") 77 flags.StringVar(&cfg.ModFile, "modfile", "", "") 78 flags.StringVar(&fsys.OverlayFile, "overlay", "", "") 79} 80 81func ChdirFlag(s string) error { 82 // main handles -C by removing it from the command line. 83 // If we see one during flag parsing, that's an error. 84 return fmt.Errorf("-C flag must be first flag on command line") 85} 86