github.com/rohankumardubey/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/src/cmd/go/testflag.go (about)

     1  // Copyright 2011 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 main
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  	"strconv"
    11  	"strings"
    12  )
    13  
    14  // The flag handling part of go test is large and distracting.
    15  // We can't use the flag package because some of the flags from
    16  // our command line are for us, and some are for 6.out, and
    17  // some are for both.
    18  
    19  var usageMessage = `Usage of go test:
    20    -c=false: compile but do not run the test binary
    21    -file=file_test.go: specify file to use for tests;
    22        use multiple times for multiple files
    23    -p=n: build and test up to n packages in parallel
    24    -x=false: print command lines as they are executed
    25  
    26    // These flags can be passed with or without a "test." prefix: -v or -test.v.
    27    -bench="": passes -test.bench to test
    28    -benchmem=false: print memory allocation statistics for benchmarks
    29    -benchtime=1s: passes -test.benchtime to test
    30    -cover=false: enable coverage analysis
    31    -covermode="set": specifies mode for coverage analysis
    32    -coverpkg="": comma-separated list of packages for coverage analysis
    33    -coverprofile="": passes -test.coverprofile to test if -cover
    34    -cpu="": passes -test.cpu to test
    35    -cpuprofile="": passes -test.cpuprofile to test
    36    -memprofile="": passes -test.memprofile to test
    37    -memprofilerate=0: passes -test.memprofilerate to test
    38    -blockprofile="": pases -test.blockprofile to test
    39    -blockprofilerate=0: passes -test.blockprofilerate to test
    40    -outputdir=$PWD: passes -test.outputdir to test
    41    -parallel=0: passes -test.parallel to test
    42    -run="": passes -test.run to test
    43    -short=false: passes -test.short to test
    44    -timeout=0: passes -test.timeout to test
    45    -v=false: passes -test.v to test
    46  `
    47  
    48  // usage prints a usage message and exits.
    49  func testUsage() {
    50  	fmt.Fprint(os.Stderr, usageMessage)
    51  	setExitStatus(2)
    52  	exit()
    53  }
    54  
    55  // testFlagSpec defines a flag we know about.
    56  type testFlagSpec struct {
    57  	name       string
    58  	boolVar    *bool
    59  	passToTest bool // pass to Test
    60  	multiOK    bool // OK to have multiple instances
    61  	present    bool // flag has been seen
    62  }
    63  
    64  // testFlagDefn is the set of flags we process.
    65  var testFlagDefn = []*testFlagSpec{
    66  	// local.
    67  	{name: "c", boolVar: &testC},
    68  	{name: "file", multiOK: true},
    69  	{name: "i", boolVar: &testI},
    70  	{name: "cover", boolVar: &testCover},
    71  	{name: "coverpkg"},
    72  
    73  	// build flags.
    74  	{name: "a", boolVar: &buildA},
    75  	{name: "n", boolVar: &buildN},
    76  	{name: "p"},
    77  	{name: "x", boolVar: &buildX},
    78  	{name: "work", boolVar: &buildWork},
    79  	{name: "gcflags"},
    80  	{name: "ldflags"},
    81  	{name: "gccgoflags"},
    82  	{name: "tags"},
    83  	{name: "compiler"},
    84  	{name: "race", boolVar: &buildRace},
    85  	{name: "installsuffix"},
    86  
    87  	// passed to 6.out, adding a "test." prefix to the name if necessary: -v becomes -test.v.
    88  	{name: "bench", passToTest: true},
    89  	{name: "benchmem", boolVar: new(bool), passToTest: true},
    90  	{name: "benchtime", passToTest: true},
    91  	{name: "covermode"},
    92  	{name: "coverprofile", passToTest: true},
    93  	{name: "cpu", passToTest: true},
    94  	{name: "cpuprofile", passToTest: true},
    95  	{name: "memprofile", passToTest: true},
    96  	{name: "memprofilerate", passToTest: true},
    97  	{name: "blockprofile", passToTest: true},
    98  	{name: "blockprofilerate", passToTest: true},
    99  	{name: "outputdir", passToTest: true},
   100  	{name: "parallel", passToTest: true},
   101  	{name: "run", passToTest: true},
   102  	{name: "short", boolVar: new(bool), passToTest: true},
   103  	{name: "timeout", passToTest: true},
   104  	{name: "v", boolVar: &testV, passToTest: true},
   105  }
   106  
   107  // testFlags processes the command line, grabbing -x and -c, rewriting known flags
   108  // to have "test" before them, and reading the command line for the 6.out.
   109  // Unfortunately for us, we need to do our own flag processing because go test
   110  // grabs some flags but otherwise its command line is just a holding place for
   111  // pkg.test's arguments.
   112  // We allow known flags both before and after the package name list,
   113  // to allow both
   114  //	go test fmt -custom-flag-for-fmt-test
   115  //	go test -x math
   116  func testFlags(args []string) (packageNames, passToTest []string) {
   117  	inPkg := false
   118  	outputDir := ""
   119  	testCoverMode = "set"
   120  	for i := 0; i < len(args); i++ {
   121  		if !strings.HasPrefix(args[i], "-") {
   122  			if !inPkg && packageNames == nil {
   123  				// First package name we've seen.
   124  				inPkg = true
   125  			}
   126  			if inPkg {
   127  				packageNames = append(packageNames, args[i])
   128  				continue
   129  			}
   130  		}
   131  
   132  		if inPkg {
   133  			// Found an argument beginning with "-"; end of package list.
   134  			inPkg = false
   135  		}
   136  
   137  		f, value, extraWord := testFlag(args, i)
   138  		if f == nil {
   139  			// This is a flag we do not know; we must assume
   140  			// that any args we see after this might be flag
   141  			// arguments, not package names.
   142  			inPkg = false
   143  			if packageNames == nil {
   144  				// make non-nil: we have seen the empty package list
   145  				packageNames = []string{}
   146  			}
   147  			passToTest = append(passToTest, args[i])
   148  			continue
   149  		}
   150  		var err error
   151  		switch f.name {
   152  		// bool flags.
   153  		case "a", "c", "i", "n", "x", "v", "race", "cover", "work":
   154  			setBoolFlag(f.boolVar, value)
   155  		case "p":
   156  			setIntFlag(&buildP, value)
   157  		case "gcflags":
   158  			buildGcflags, err = splitQuotedFields(value)
   159  			if err != nil {
   160  				fatalf("invalid flag argument for -%s: %v", f.name, err)
   161  			}
   162  		case "ldflags":
   163  			buildLdflags, err = splitQuotedFields(value)
   164  			if err != nil {
   165  				fatalf("invalid flag argument for -%s: %v", f.name, err)
   166  			}
   167  		case "gccgoflags":
   168  			buildGccgoflags, err = splitQuotedFields(value)
   169  			if err != nil {
   170  				fatalf("invalid flag argument for -%s: %v", f.name, err)
   171  			}
   172  		case "tags":
   173  			buildContext.BuildTags = strings.Fields(value)
   174  		case "compiler":
   175  			buildCompiler{}.Set(value)
   176  		case "file":
   177  			testFiles = append(testFiles, value)
   178  		case "bench":
   179  			// record that we saw the flag; don't care about the value
   180  			testBench = true
   181  		case "timeout":
   182  			testTimeout = value
   183  		case "blockprofile", "cpuprofile", "memprofile":
   184  			testProfile = true
   185  			testNeedBinary = true
   186  		case "coverpkg":
   187  			testCover = true
   188  			if value == "" {
   189  				testCoverPaths = nil
   190  			} else {
   191  				testCoverPaths = strings.Split(value, ",")
   192  			}
   193  		case "coverprofile":
   194  			testCover = true
   195  			testProfile = true
   196  		case "covermode":
   197  			switch value {
   198  			case "set", "count", "atomic":
   199  				testCoverMode = value
   200  			default:
   201  				fatalf("invalid flag argument for -cover: %q", value)
   202  			}
   203  			testCover = true
   204  		case "outputdir":
   205  			outputDir = value
   206  		}
   207  		if extraWord {
   208  			i++
   209  		}
   210  		if f.passToTest {
   211  			passToTest = append(passToTest, "-test."+f.name+"="+value)
   212  		}
   213  	}
   214  
   215  	// Tell the test what directory we're running in, so it can write the profiles there.
   216  	if testProfile && outputDir == "" {
   217  		dir, err := os.Getwd()
   218  		if err != nil {
   219  			fatalf("error from os.Getwd: %s", err)
   220  		}
   221  		passToTest = append(passToTest, "-test.outputdir", dir)
   222  	}
   223  	return
   224  }
   225  
   226  // testFlag sees if argument i is a known flag and returns its definition, value, and whether it consumed an extra word.
   227  func testFlag(args []string, i int) (f *testFlagSpec, value string, extra bool) {
   228  	arg := args[i]
   229  	if strings.HasPrefix(arg, "--") { // reduce two minuses to one
   230  		arg = arg[1:]
   231  	}
   232  	switch arg {
   233  	case "-?", "-h", "-help":
   234  		usage()
   235  	}
   236  	if arg == "" || arg[0] != '-' {
   237  		return
   238  	}
   239  	name := arg[1:]
   240  	// If there's already "test.", drop it for now.
   241  	name = strings.TrimPrefix(name, "test.")
   242  	equals := strings.Index(name, "=")
   243  	if equals >= 0 {
   244  		value = name[equals+1:]
   245  		name = name[:equals]
   246  	}
   247  	for _, f = range testFlagDefn {
   248  		if name == f.name {
   249  			// Booleans are special because they have modes -x, -x=true, -x=false.
   250  			if f.boolVar != nil {
   251  				if equals < 0 { // otherwise, it's been set and will be verified in setBoolFlag
   252  					value = "true"
   253  				} else {
   254  					// verify it parses
   255  					setBoolFlag(new(bool), value)
   256  				}
   257  			} else { // Non-booleans must have a value.
   258  				extra = equals < 0
   259  				if extra {
   260  					if i+1 >= len(args) {
   261  						testSyntaxError("missing argument for flag " + f.name)
   262  					}
   263  					value = args[i+1]
   264  				}
   265  			}
   266  			if f.present && !f.multiOK {
   267  				testSyntaxError(f.name + " flag may be set only once")
   268  			}
   269  			f.present = true
   270  			return
   271  		}
   272  	}
   273  	f = nil
   274  	return
   275  }
   276  
   277  // setBoolFlag sets the addressed boolean to the value.
   278  func setBoolFlag(flag *bool, value string) {
   279  	x, err := strconv.ParseBool(value)
   280  	if err != nil {
   281  		testSyntaxError("illegal bool flag value " + value)
   282  	}
   283  	*flag = x
   284  }
   285  
   286  // setIntFlag sets the addressed integer to the value.
   287  func setIntFlag(flag *int, value string) {
   288  	x, err := strconv.Atoi(value)
   289  	if err != nil {
   290  		testSyntaxError("illegal int flag value " + value)
   291  	}
   292  	*flag = x
   293  }
   294  
   295  func testSyntaxError(msg string) {
   296  	fmt.Fprintf(os.Stderr, "go test: %s\n", msg)
   297  	fmt.Fprintf(os.Stderr, `run "go help test" or "go help testflag" for more information`+"\n")
   298  	os.Exit(2)
   299  }