github.com/zxy12/go_duplicate_112_new@v0.0.0-20200807091221-747231827200/src/cmd/go/internal/cmdflag/flag.go (about)

     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 cmdflag handles flag processing common to several go tools.
     6  package cmdflag
     7  
     8  import (
     9  	"flag"
    10  	"fmt"
    11  	"os"
    12  	"strconv"
    13  	"strings"
    14  
    15  	"cmd/go/internal/base"
    16  )
    17  
    18  // The flag handling part of go commands such as test is large and distracting.
    19  // We can't use the standard flag package because some of the flags from
    20  // our command line are for us, and some are for the binary we're running,
    21  // and some are for both.
    22  
    23  // Defn defines a flag we know about.
    24  type Defn struct {
    25  	Name       string     // Name on command line.
    26  	BoolVar    *bool      // If it's a boolean flag, this points to it.
    27  	Value      flag.Value // The flag.Value represented.
    28  	PassToTest bool       // Pass to the test binary? Used only by go test.
    29  	Present    bool       // Flag has been seen.
    30  }
    31  
    32  // IsBool reports whether v is a bool flag.
    33  func IsBool(v flag.Value) bool {
    34  	vv, ok := v.(interface {
    35  		IsBoolFlag() bool
    36  	})
    37  	if ok {
    38  		return vv.IsBoolFlag()
    39  	}
    40  	return false
    41  }
    42  
    43  // SetBool sets the addressed boolean to the value.
    44  func SetBool(cmd string, flag *bool, value string) {
    45  	x, err := strconv.ParseBool(value)
    46  	if err != nil {
    47  		SyntaxError(cmd, "illegal bool flag value "+value)
    48  	}
    49  	*flag = x
    50  }
    51  
    52  // SetInt sets the addressed integer to the value.
    53  func SetInt(cmd string, flag *int, value string) {
    54  	x, err := strconv.Atoi(value)
    55  	if err != nil {
    56  		SyntaxError(cmd, "illegal int flag value "+value)
    57  	}
    58  	*flag = x
    59  }
    60  
    61  // SyntaxError reports an argument syntax error and exits the program.
    62  func SyntaxError(cmd, msg string) {
    63  	fmt.Fprintf(os.Stderr, "go %s: %s\n", cmd, msg)
    64  	if cmd == "test" {
    65  		fmt.Fprintf(os.Stderr, `run "go help %s" or "go help testflag" for more information`+"\n", cmd)
    66  	} else {
    67  		fmt.Fprintf(os.Stderr, `run "go help %s" for more information`+"\n", cmd)
    68  	}
    69  	os.Exit(2)
    70  }
    71  
    72  // AddKnownFlags registers the flags in defns with base.AddKnownFlag.
    73  func AddKnownFlags(cmd string, defns []*Defn) {
    74  	for _, f := range defns {
    75  		base.AddKnownFlag(f.Name)
    76  		base.AddKnownFlag(cmd + "." + f.Name)
    77  	}
    78  }
    79  
    80  // Parse sees if argument i is present in the definitions and if so,
    81  // returns its definition, value, and whether it consumed an extra word.
    82  // If the flag begins (cmd.Name()+".") it is ignored for the purpose of this function.
    83  func Parse(cmd string, usage func(), defns []*Defn, args []string, i int) (f *Defn, value string, extra bool) {
    84  	arg := args[i]
    85  	if strings.HasPrefix(arg, "--") { // reduce two minuses to one
    86  		arg = arg[1:]
    87  	}
    88  	switch arg {
    89  	case "-?", "-h", "-help":
    90  		usage()
    91  	}
    92  	if arg == "" || arg[0] != '-' {
    93  		return
    94  	}
    95  	name := arg[1:]
    96  	// If there's already a prefix such as "test.", drop it for now.
    97  	name = strings.TrimPrefix(name, cmd+".")
    98  	equals := strings.Index(name, "=")
    99  	if equals >= 0 {
   100  		value = name[equals+1:]
   101  		name = name[:equals]
   102  	}
   103  	for _, f = range defns {
   104  		if name == f.Name {
   105  			// Booleans are special because they have modes -x, -x=true, -x=false.
   106  			if f.BoolVar != nil || IsBool(f.Value) {
   107  				if equals < 0 { // Otherwise, it's been set and will be verified in SetBool.
   108  					value = "true"
   109  				} else {
   110  					// verify it parses
   111  					SetBool(cmd, new(bool), value)
   112  				}
   113  			} else { // Non-booleans must have a value.
   114  				extra = equals < 0
   115  				if extra {
   116  					if i+1 >= len(args) {
   117  						SyntaxError(cmd, "missing argument for flag "+f.Name)
   118  					}
   119  					value = args[i+1]
   120  				}
   121  			}
   122  			if f.Present {
   123  				SyntaxError(cmd, f.Name+" flag may be set only once")
   124  			}
   125  			f.Present = true
   126  			return
   127  		}
   128  	}
   129  	f = nil
   130  	return
   131  }
   132  
   133  // FindGOFLAGS extracts and returns the flags matching defns from GOFLAGS.
   134  // Ideally the caller would mention that the flags were from GOFLAGS
   135  // when reporting errors, but that's too hard for now.
   136  func FindGOFLAGS(defns []*Defn) []string {
   137  	var flags []string
   138  	for _, flag := range base.GOFLAGS() {
   139  		// Flags returned by base.GOFLAGS are well-formed, one of:
   140  		//	-x
   141  		//	--x
   142  		//	-x=value
   143  		//	--x=value
   144  		if strings.HasPrefix(flag, "--") {
   145  			flag = flag[1:]
   146  		}
   147  		name := flag[1:]
   148  		if i := strings.Index(name, "="); i >= 0 {
   149  			name = name[:i]
   150  		}
   151  		for _, f := range defns {
   152  			if name == f.Name {
   153  				flags = append(flags, flag)
   154  				break
   155  			}
   156  		}
   157  	}
   158  	return flags
   159  }