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

     1  // Copyright 2018 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  	"fmt"
    10  	"runtime"
    11  	"strings"
    12  
    13  	"cmd/go/internal/cfg"
    14  )
    15  
    16  var goflags []string // cached $GOFLAGS list; can be -x or --x form
    17  
    18  // GOFLAGS returns the flags from $GOFLAGS.
    19  // The list can be assumed to contain one string per flag,
    20  // with each string either beginning with -name or --name.
    21  func GOFLAGS() []string {
    22  	InitGOFLAGS()
    23  	return goflags
    24  }
    25  
    26  // InitGOFLAGS initializes the goflags list from $GOFLAGS.
    27  // If goflags is already initialized, it does nothing.
    28  func InitGOFLAGS() {
    29  	if goflags != nil { // already initialized
    30  		return
    31  	}
    32  
    33  	goflags = strings.Fields(cfg.Getenv("GOFLAGS"))
    34  	if len(goflags) == 0 {
    35  		// nothing to do; avoid work on later InitGOFLAGS call
    36  		goflags = []string{}
    37  		return
    38  	}
    39  
    40  	// Ignore bad flag in go env and go bug, because
    41  	// they are what people reach for when debugging
    42  	// a problem, and maybe they're debugging GOFLAGS.
    43  	// (Both will show the GOFLAGS setting if let succeed.)
    44  	hideErrors := cfg.CmdName == "env" || cfg.CmdName == "bug"
    45  
    46  	// Each of the words returned by strings.Fields must be its own flag.
    47  	// To set flag arguments use -x=value instead of -x value.
    48  	// For boolean flags, -x is fine instead of -x=true.
    49  	for _, f := range goflags {
    50  		// Check that every flag looks like -x --x -x=value or --x=value.
    51  		if !strings.HasPrefix(f, "-") || f == "-" || f == "--" || strings.HasPrefix(f, "---") || strings.HasPrefix(f, "-=") || strings.HasPrefix(f, "--=") {
    52  			if hideErrors {
    53  				continue
    54  			}
    55  			Fatalf("go: parsing $GOFLAGS: non-flag %q", f)
    56  		}
    57  
    58  		name := f[1:]
    59  		if name[0] == '-' {
    60  			name = name[1:]
    61  		}
    62  		if i := strings.Index(name, "="); i >= 0 {
    63  			name = name[:i]
    64  		}
    65  		if !hasFlag(Go, name) {
    66  			if hideErrors {
    67  				continue
    68  			}
    69  			Fatalf("go: parsing $GOFLAGS: unknown flag -%s", name)
    70  		}
    71  	}
    72  }
    73  
    74  // boolFlag is the optional interface for flag.Value known to the flag package.
    75  // (It is not clear why package flag does not export this interface.)
    76  type boolFlag interface {
    77  	flag.Value
    78  	IsBoolFlag() bool
    79  }
    80  
    81  // SetFromGOFLAGS sets the flags in the given flag set using settings in $GOFLAGS.
    82  func SetFromGOFLAGS(flags *flag.FlagSet) {
    83  	InitGOFLAGS()
    84  
    85  	// This loop is similar to flag.Parse except that it ignores
    86  	// unknown flags found in goflags, so that setting, say, GOFLAGS=-ldflags=-w
    87  	// does not break commands that don't have a -ldflags.
    88  	// It also adjusts the output to be clear that the reported problem is from $GOFLAGS.
    89  	where := "$GOFLAGS"
    90  	if runtime.GOOS == "windows" {
    91  		where = "%GOFLAGS%"
    92  	}
    93  	for _, goflag := range goflags {
    94  		name, value, hasValue := goflag, "", false
    95  		// Ignore invalid flags like '=' or '=value'.
    96  		// If it is not reported in InitGOFlags it means we don't want to report it.
    97  		if i := strings.Index(goflag, "="); i == 0 {
    98  			continue
    99  		} else if i > 0 {
   100  			name, value, hasValue = goflag[:i], goflag[i+1:], true
   101  		}
   102  		if strings.HasPrefix(name, "--") {
   103  			name = name[1:]
   104  		}
   105  		f := flags.Lookup(name[1:])
   106  		if f == nil {
   107  			continue
   108  		}
   109  
   110  		// Use flags.Set consistently (instead of f.Value.Set) so that a subsequent
   111  		// call to flags.Visit will correctly visit the flags that have been set.
   112  
   113  		if fb, ok := f.Value.(boolFlag); ok && fb.IsBoolFlag() {
   114  			if hasValue {
   115  				if err := flags.Set(f.Name, value); err != nil {
   116  					fmt.Fprintf(flags.Output(), "go: invalid boolean value %q for flag %s (from %s): %v\n", value, name, where, err)
   117  					flags.Usage()
   118  				}
   119  			} else {
   120  				if err := flags.Set(f.Name, "true"); err != nil {
   121  					fmt.Fprintf(flags.Output(), "go: invalid boolean flag %s (from %s): %v\n", name, where, err)
   122  					flags.Usage()
   123  				}
   124  			}
   125  		} else {
   126  			if !hasValue {
   127  				fmt.Fprintf(flags.Output(), "go: flag needs an argument: %s (from %s)\n", name, where)
   128  				flags.Usage()
   129  			}
   130  			if err := flags.Set(f.Name, value); err != nil {
   131  				fmt.Fprintf(flags.Output(), "go: invalid value %q for flag %s (from %s): %v\n", value, name, where, err)
   132  				flags.Usage()
   133  			}
   134  		}
   135  	}
   136  }
   137  
   138  // InGOFLAGS returns whether GOFLAGS contains the given flag, such as "-mod".
   139  func InGOFLAGS(flag string) bool {
   140  	for _, goflag := range GOFLAGS() {
   141  		name := goflag
   142  		if strings.HasPrefix(name, "--") {
   143  			name = name[1:]
   144  		}
   145  		if i := strings.Index(name, "="); i >= 0 {
   146  			name = name[:i]
   147  		}
   148  		if name == flag {
   149  			return true
   150  		}
   151  	}
   152  	return false
   153  }
   154  

View as plain text