Source file src/cmd/go/internal/test/genflags.go

     1  // Copyright 2019 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  //go:build ignore
     6  
     7  package main
     8  
     9  import (
    10  	"bytes"
    11  	"flag"
    12  	exec "internal/execabs"
    13  	"log"
    14  	"os"
    15  	"strings"
    16  	"testing"
    17  	"text/template"
    18  
    19  	"cmd/go/internal/test/internal/genflags"
    20  )
    21  
    22  func main() {
    23  	if err := regenerate(); err != nil {
    24  		log.Fatal(err)
    25  	}
    26  }
    27  
    28  func regenerate() error {
    29  	vetAnalyzers, err := genflags.VetAnalyzers()
    30  	if err != nil {
    31  		return err
    32  	}
    33  
    34  	t := template.Must(template.New("fileTemplate").Parse(fileTemplate))
    35  	tData := map[string][]string{
    36  		"testFlags":    testFlags(),
    37  		"vetAnalyzers": vetAnalyzers,
    38  	}
    39  	buf := bytes.NewBuffer(nil)
    40  	if err := t.Execute(buf, tData); err != nil {
    41  		return err
    42  	}
    43  
    44  	f, err := os.Create("flagdefs.go")
    45  	if err != nil {
    46  		return err
    47  	}
    48  
    49  	cmd := exec.Command("gofmt")
    50  	cmd.Stdin = buf
    51  	cmd.Stdout = f
    52  	cmd.Stderr = os.Stderr
    53  	cmdErr := cmd.Run()
    54  
    55  	if err := f.Close(); err != nil {
    56  		return err
    57  	}
    58  	if cmdErr != nil {
    59  		os.Remove(f.Name())
    60  		return cmdErr
    61  	}
    62  
    63  	return nil
    64  }
    65  
    66  func testFlags() []string {
    67  	testing.Init()
    68  
    69  	var names []string
    70  	flag.VisitAll(func(f *flag.Flag) {
    71  		if !strings.HasPrefix(f.Name, "test.") {
    72  			return
    73  		}
    74  		name := strings.TrimPrefix(f.Name, "test.")
    75  
    76  		switch name {
    77  		case "testlogfile", "paniconexit0", "fuzzcachedir", "fuzzworker":
    78  			// These flags are only for use by cmd/go.
    79  		default:
    80  			names = append(names, name)
    81  		}
    82  	})
    83  
    84  	return names
    85  }
    86  
    87  const fileTemplate = `// Copyright 2019 The Go Authors. All rights reserved.
    88  // Use of this source code is governed by a BSD-style
    89  // license that can be found in the LICENSE file.
    90  
    91  // Code generated by genflags.go — DO NOT EDIT.
    92  
    93  package test
    94  
    95  // passFlagToTest contains the flags that should be forwarded to
    96  // the test binary with the prefix "test.".
    97  var passFlagToTest = map[string]bool {
    98  {{- range .testFlags}}
    99  	"{{.}}": true,
   100  {{- end }}
   101  }
   102  
   103  var passAnalyzersToVet = map[string]bool {
   104  {{- range .vetAnalyzers}}
   105  	"{{.}}": true,
   106  {{- end }}
   107  }
   108  `
   109  

View as plain text