1
2
3
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
17
18
19
20
21 func GOFLAGS() []string {
22 InitGOFLAGS()
23 return goflags
24 }
25
26
27
28 func InitGOFLAGS() {
29 if goflags != nil {
30 return
31 }
32
33 goflags = strings.Fields(cfg.Getenv("GOFLAGS"))
34 if len(goflags) == 0 {
35
36 goflags = []string{}
37 return
38 }
39
40
41
42
43
44 hideErrors := cfg.CmdName == "env" || cfg.CmdName == "bug"
45
46
47
48
49 for _, f := range goflags {
50
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
75
76 type boolFlag interface {
77 flag.Value
78 IsBoolFlag() bool
79 }
80
81
82 func SetFromGOFLAGS(flags *flag.FlagSet) {
83 InitGOFLAGS()
84
85
86
87
88
89 where := "$GOFLAGS"
90 if runtime.GOOS == "windows" {
91 where = "%GOFLAGS%"
92 }
93 for _, goflag := range goflags {
94 name, value, hasValue := goflag, "", false
95
96
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
111
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
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