Source file src/cmd/go/internal/base/flag.go

     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  
     5  package base
     6  
     7  import (
     8  	"flag"
     9  
    10  	"cmd/go/internal/cfg"
    11  	"cmd/go/internal/fsys"
    12  	"cmd/internal/quoted"
    13  )
    14  
    15  // A StringsFlag is a command-line flag that interprets its argument
    16  // as a space-separated list of possibly-quoted strings.
    17  type StringsFlag []string
    18  
    19  func (v *StringsFlag) Set(s string) error {
    20  	var err error
    21  	*v, err = quoted.Split(s)
    22  	if *v == nil {
    23  		*v = []string{}
    24  	}
    25  	return err
    26  }
    27  
    28  func (v *StringsFlag) String() string {
    29  	return "<StringsFlag>"
    30  }
    31  
    32  // explicitStringFlag is like a regular string flag, but it also tracks whether
    33  // the string was set explicitly to a non-empty value.
    34  type explicitStringFlag struct {
    35  	value    *string
    36  	explicit *bool
    37  }
    38  
    39  func (f explicitStringFlag) String() string {
    40  	if f.value == nil {
    41  		return ""
    42  	}
    43  	return *f.value
    44  }
    45  
    46  func (f explicitStringFlag) Set(v string) error {
    47  	*f.value = v
    48  	if v != "" {
    49  		*f.explicit = true
    50  	}
    51  	return nil
    52  }
    53  
    54  // AddBuildFlagsNX adds the -n and -x build flags to the flag set.
    55  func AddBuildFlagsNX(flags *flag.FlagSet) {
    56  	flags.BoolVar(&cfg.BuildN, "n", false, "")
    57  	flags.BoolVar(&cfg.BuildX, "x", false, "")
    58  }
    59  
    60  // AddModFlag adds the -mod build flag to the flag set.
    61  func AddModFlag(flags *flag.FlagSet) {
    62  	flags.Var(explicitStringFlag{value: &cfg.BuildMod, explicit: &cfg.BuildModExplicit}, "mod", "")
    63  }
    64  
    65  // AddModCommonFlags adds the module-related flags common to build commands
    66  // and 'go mod' subcommands.
    67  func AddModCommonFlags(flags *flag.FlagSet) {
    68  	flags.BoolVar(&cfg.ModCacheRW, "modcacherw", false, "")
    69  	flags.StringVar(&cfg.ModFile, "modfile", "", "")
    70  	flags.StringVar(&fsys.OverlayFile, "overlay", "", "")
    71  }
    72  

View as plain text