github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/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  
    86  	// passed to 6.out, adding a "test." prefix to the name if necessary: -v becomes -test.v.
    87  	{name: "bench", passToTest: true},
    88  	{name: "benchmem", boolVar: new(bool), passToTest: true},
    89  	{name: "benchtime", passToTest: true},
    90  	{name: "covermode"},
    91  	{name: "coverprofile", passToTest: true},
    92  	{name: "cpu", passToTest: true},
    93  	{name: "cpuprofile", passToTest: true},
    94  	{name: "memprofile", passToTest: true},
    95  	{name: "memprofilerate", passToTest: true},
    96  	{name: "blockprofile", passToTest: true},
    97  	{name: "blockprofilerate", passToTest: true},
    98  	{name: "outputdir", passToTest: true},
    99  	{name: "parallel", passToTest: true},
   100  	{name: "run", passToTest: true},
   101  	{name: "short", boolVar: new(bool), passToTest: true},
   102  	{name: "timeout", passToTest: true},
   103  	{name: "v", boolVar: &testV, passToTest: true},
   104  }
   105  
   106  // testFlags processes the command line, grabbing -x and -c, rewriting known flags
   107  // to have "test" before them, and reading the command line for the 6.out.
   108  // Unfortunately for us, we need to do our own flag processing because go test
   109  // grabs some flags but otherwise its command line is just a holding place for
   110  // pkg.test's arguments.
   111  // We allow known flags both before and after the package name list,
   112  // to allow both
   113  //	go test fmt -custom-flag-for-fmt-test
   114  //	go test -x math
   115  func testFlags(args []string) (packageNames, passToTest []string) {
   116  	inPkg := false
   117  	outputDir := ""
   118  	testCoverMode = "set"
   119  	for i := 0; i < len(args); i++ {
   120  		if !strings.HasPrefix(args[i], "-") {
   121  			if !inPkg && packageNames == nil {
   122  				// First package name we've seen.
   123  				inPkg = true
   124  			}
   125  			if inPkg {
   126  				packageNames = append(packageNames, args[i])
   127  				continue
   128  			}
   129  		}
   130  
   131  		if inPkg {
   132  			// Found an argument beginning with "-"; end of package list.
   133  			inPkg = false
   134  		}
   135  
   136  		f, value, extraWord := testFlag(args, i)
   137  		if f == nil {
   138  			// This is a flag we do not know; we must assume
   139  			// that any args we see after this might be flag
   140  			// arguments, not package names.
   141  			inPkg = false
   142  			if packageNames == nil {
   143  				// make non-nil: we have seen the empty package list
   144  				packageNames = []string{}
   145  			}
   146  			passToTest = append(passToTest, args[i])
   147  			continue
   148  		}
   149  		var err error
   150  		switch f.name {
   151  		// bool flags.
   152  		case "a", "c", "i", "n", "x", "v", "race", "cover", "work":
   153  			setBoolFlag(f.boolVar, value)
   154  		case "p":
   155  			setIntFlag(&buildP, value)
   156  		case "gcflags":
   157  			buildGcflags, err = splitQuotedFields(value)
   158  			if err != nil {
   159  				fatalf("invalid flag argument for -%s: %v", f.name, err)
   160  			}
   161  		case "ldflags":
   162  			buildLdflags, err = splitQuotedFields(value)
   163  			if err != nil {
   164  				fatalf("invalid flag argument for -%s: %v", f.name, err)
   165  			}
   166  		case "gccgoflags":
   167  			buildGccgoflags, err = splitQuotedFields(value)
   168  			if err != nil {
   169  				fatalf("invalid flag argument for -%s: %v", f.name, err)
   170  			}
   171  		case "tags":
   172  			buildContext.BuildTags = strings.Fields(value)
   173  		case "compiler":
   174  			buildCompiler{}.Set(value)
   175  		case "file":
   176  			testFiles = append(testFiles, value)
   177  		case "bench":
   178  			// record that we saw the flag; don't care about the value
   179  			testBench = true
   180  		case "timeout":
   181  			testTimeout = value
   182  		case "blockprofile", "cpuprofile", "memprofile":
   183  			testProfile = true
   184  		case "coverpkg":
   185  			testCover = true
   186  			if value == "" {
   187  				testCoverPaths = nil
   188  			} else {
   189  				testCoverPaths = strings.Split(value, ",")
   190  			}
   191  		case "coverprofile":
   192  			testCover = true
   193  			testProfile = true
   194  		case "covermode":
   195  			switch value {
   196  			case "set", "count", "atomic":
   197  				testCoverMode = value
   198  			default:
   199  				fatalf("invalid flag argument for -cover: %q", value)
   200  			}
   201  			testCover = true
   202  		case "outputdir":
   203  			outputDir = value
   204  		}
   205  		if extraWord {
   206  			i++
   207  		}
   208  		if f.passToTest {
   209  			passToTest = append(passToTest, "-test."+f.name+"="+value)
   210  		}
   211  	}
   212  
   213  	// Tell the test what directory we're running in, so it can write the profiles there.
   214  	if testProfile && outputDir == "" {
   215  		dir, err := os.Getwd()
   216  		if err != nil {
   217  			fatalf("error from os.Getwd: %s", err)
   218  		}
   219  		passToTest = append(passToTest, "-test.outputdir", dir)
   220  	}
   221  	return
   222  }
   223  
   224  // testFlag sees if argument i is a known flag and returns its definition, value, and whether it consumed an extra word.
   225  func testFlag(args []string, i int) (f *testFlagSpec, value string, extra bool) {
   226  	arg := args[i]
   227  	if strings.HasPrefix(arg, "--") { // reduce two minuses to one
   228  		arg = arg[1:]
   229  	}
   230  	switch arg {
   231  	case "-?", "-h", "-help":
   232  		usage()
   233  	}
   234  	if arg == "" || arg[0] != '-' {
   235  		return
   236  	}
   237  	name := arg[1:]
   238  	// If there's already "test.", drop it for now.
   239  	name = strings.TrimPrefix(name, "test.")
   240  	equals := strings.Index(name, "=")
   241  	if equals >= 0 {
   242  		value = name[equals+1:]
   243  		name = name[:equals]
   244  	}
   245  	for _, f = range testFlagDefn {
   246  		if name == f.name {
   247  			// Booleans are special because they have modes -x, -x=true, -x=false.
   248  			if f.boolVar != nil {
   249  				if equals < 0 { // otherwise, it's been set and will be verified in setBoolFlag
   250  					value = "true"
   251  				} else {
   252  					// verify it parses
   253  					setBoolFlag(new(bool), value)
   254  				}
   255  			} else { // Non-booleans must have a value.
   256  				extra = equals < 0
   257  				if extra {
   258  					if i+1 >= len(args) {
   259  						testSyntaxError("missing argument for flag " + f.name)
   260  					}
   261  					value = args[i+1]
   262  				}
   263  			}
   264  			if f.present && !f.multiOK {
   265  				testSyntaxError(f.name + " flag may be set only once")
   266  			}
   267  			f.present = true
   268  			return
   269  		}
   270  	}
   271  	f = nil
   272  	return
   273  }
   274  
   275  // setBoolFlag sets the addressed boolean to the value.
   276  func setBoolFlag(flag *bool, value string) {
   277  	x, err := strconv.ParseBool(value)
   278  	if err != nil {
   279  		testSyntaxError("illegal bool flag value " + value)
   280  	}
   281  	*flag = x
   282  }
   283  
   284  // setIntFlag sets the addressed integer to the value.
   285  func setIntFlag(flag *int, value string) {
   286  	x, err := strconv.Atoi(value)
   287  	if err != nil {
   288  		testSyntaxError("illegal int flag value " + value)
   289  	}
   290  	*flag = x
   291  }
   292  
   293  func testSyntaxError(msg string) {
   294  	fmt.Fprintf(os.Stderr, "go test: %s\n", msg)
   295  	fmt.Fprintf(os.Stderr, `run "go help test" or "go help testflag" for more information`+"\n")
   296  	os.Exit(2)
   297  }