143a106115021d7f5d313110a3f19b3c4311d3b7
[platform/upstream/gcc.git] / libgo / go / flag / flag.go
1 // Copyright 2009 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 /*
6         The flag package implements command-line flag parsing.
7
8         Usage:
9
10         Define flags using flag.String(), Bool(), Int(), etc. Example:
11                 import "flag"
12                 var ip *int = flag.Int("flagname", 1234, "help message for flagname")
13         If you like, you can bind the flag to a variable using the Var() functions.
14                 var flagvar int
15                 func init() {
16                         flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
17                 }
18         Or you can create custom flags that satisfy the Value interface (with
19         pointer receivers) and couple them to flag parsing by
20                 flag.Var(&flagVal, "name", "help message for flagname")
21         For such flags, the default value is just the initial value of the variable.
22
23         After all flags are defined, call
24                 flag.Parse()
25         to parse the command line into the defined flags.
26
27         Flags may then be used directly. If you're using the flags themselves,
28         they are all pointers; if you bind to variables, they're values.
29                 fmt.Println("ip has value ", *ip);
30                 fmt.Println("flagvar has value ", flagvar);
31
32         After parsing, the arguments after the flag are available as the
33         slice flag.Args() or individually as flag.Arg(i).
34         The arguments are indexed from 0 up to flag.NArg().
35
36         Command line flag syntax:
37                 -flag
38                 -flag=x
39                 -flag x  // non-boolean flags only
40         One or two minus signs may be used; they are equivalent.
41         The last form is not permitted for boolean flags because the
42         meaning of the command
43                 cmd -x *
44         will change if there is a file called 0, false, etc.  You must
45         use the -flag=false form to turn off a boolean flag.
46
47         Flag parsing stops just before the first non-flag argument
48         ("-" is a non-flag argument) or after the terminator "--".
49
50         Integer flags accept 1234, 0664, 0x1234 and may be negative.
51         Boolean flags may be 1, 0, t, f, true, false, TRUE, FALSE, True, False.
52
53         It is safe to call flag.Parse multiple times, possibly after changing
54         os.Args.  This makes it possible to implement command lines with
55         subcommands that enable additional flags, as in:
56
57                 flag.Bool(...)  // global options
58                 flag.Parse()  // parse leading command
59                 subcmd := flag.Args(0)
60                 switch subcmd {
61                         // add per-subcommand options
62                 }
63                 os.Args = flag.Args()
64                 flag.Parse()
65 */
66 package flag
67
68 import (
69         "fmt"
70         "os"
71         "strconv"
72 )
73
74 // -- Bool Value
75 type boolValue bool
76
77 func newBoolValue(val bool, p *bool) *boolValue {
78         *p = val
79         return (*boolValue)(p)
80 }
81
82 func (b *boolValue) Set(s string) bool {
83         v, err := strconv.Atob(s)
84         *b = boolValue(v)
85         return err == nil
86 }
87
88 func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
89
90 // -- Int Value
91 type intValue int
92
93 func newIntValue(val int, p *int) *intValue {
94         *p = val
95         return (*intValue)(p)
96 }
97
98 func (i *intValue) Set(s string) bool {
99         v, err := strconv.Atoi(s)
100         *i = intValue(v)
101         return err == nil
102 }
103
104 func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
105
106 // -- Int64 Value
107 type int64Value int64
108
109 func newInt64Value(val int64, p *int64) *int64Value {
110         *p = val
111         return (*int64Value)(p)
112 }
113
114 func (i *int64Value) Set(s string) bool {
115         v, err := strconv.Atoi64(s)
116         *i = int64Value(v)
117         return err == nil
118 }
119
120 func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
121
122 // -- Uint Value
123 type uintValue uint
124
125 func newUintValue(val uint, p *uint) *uintValue {
126         *p = val
127         return (*uintValue)(p)
128 }
129
130 func (i *uintValue) Set(s string) bool {
131         v, err := strconv.Atoui(s)
132         *i = uintValue(v)
133         return err == nil
134 }
135
136 func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
137
138 // -- uint64 Value
139 type uint64Value uint64
140
141 func newUint64Value(val uint64, p *uint64) *uint64Value {
142         *p = val
143         return (*uint64Value)(p)
144 }
145
146 func (i *uint64Value) Set(s string) bool {
147         v, err := strconv.Atoui64(s)
148         *i = uint64Value(v)
149         return err == nil
150 }
151
152 func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
153
154 // -- string Value
155 type stringValue string
156
157 func newStringValue(val string, p *string) *stringValue {
158         *p = val
159         return (*stringValue)(p)
160 }
161
162 func (s *stringValue) Set(val string) bool {
163         *s = stringValue(val)
164         return true
165 }
166
167 func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
168
169 // -- Float64 Value
170 type float64Value float64
171
172 func newFloat64Value(val float64, p *float64) *float64Value {
173         *p = val
174         return (*float64Value)(p)
175 }
176
177 func (f *float64Value) Set(s string) bool {
178         v, err := strconv.Atof64(s)
179         *f = float64Value(v)
180         return err == nil
181 }
182
183 func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
184
185 // Value is the interface to the dynamic value stored in a flag.
186 // (The default value is represented as a string.)
187 type Value interface {
188         String() string
189         Set(string) bool
190 }
191
192 // A Flag represents the state of a flag.
193 type Flag struct {
194         Name     string // name as it appears on command line
195         Usage    string // help message
196         Value    Value  // value as set
197         DefValue string // default value (as text); for usage message
198 }
199
200 type allFlags struct {
201         actual map[string]*Flag
202         formal map[string]*Flag
203         args   []string // arguments after flags
204 }
205
206 var flags *allFlags
207
208 // VisitAll visits the flags, calling fn for each. It visits all flags, even those not set.
209 func VisitAll(fn func(*Flag)) {
210         for _, f := range flags.formal {
211                 fn(f)
212         }
213 }
214
215 // Visit visits the flags, calling fn for each. It visits only those flags that have been set.
216 func Visit(fn func(*Flag)) {
217         for _, f := range flags.actual {
218                 fn(f)
219         }
220 }
221
222 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
223 func Lookup(name string) *Flag {
224         return flags.formal[name]
225 }
226
227 // Set sets the value of the named flag.  It returns true if the set succeeded; false if
228 // there is no such flag defined.
229 func Set(name, value string) bool {
230         f, ok := flags.formal[name]
231         if !ok {
232                 return false
233         }
234         ok = f.Value.Set(value)
235         if !ok {
236                 return false
237         }
238         flags.actual[name] = f
239         return true
240 }
241
242 // PrintDefaults prints to standard error the default values of all defined flags.
243 func PrintDefaults() {
244         VisitAll(func(f *Flag) {
245                 format := "  -%s=%s: %s\n"
246                 if _, ok := f.Value.(*stringValue); ok {
247                         // put quotes on the value
248                         format = "  -%s=%q: %s\n"
249                 }
250                 fmt.Fprintf(os.Stderr, format, f.Name, f.DefValue, f.Usage)
251         })
252 }
253
254 // Usage prints to standard error a default usage message documenting all defined flags.
255 // The function is a variable that may be changed to point to a custom function.
256 var Usage = func() {
257         fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
258         PrintDefaults()
259 }
260
261 var panicOnError = false
262
263 func fail() {
264         Usage()
265         if panicOnError {
266                 panic("flag parse error")
267         }
268         os.Exit(2)
269 }
270
271 func NFlag() int { return len(flags.actual) }
272
273 // Arg returns the i'th command-line argument.  Arg(0) is the first remaining argument
274 // after flags have been processed.
275 func Arg(i int) string {
276         if i < 0 || i >= len(flags.args) {
277                 return ""
278         }
279         return flags.args[i]
280 }
281
282 // NArg is the number of arguments remaining after flags have been processed.
283 func NArg() int { return len(flags.args) }
284
285 // Args returns the non-flag command-line arguments.
286 func Args() []string { return flags.args }
287
288 // BoolVar defines a bool flag with specified name, default value, and usage string.
289 // The argument p points to a bool variable in which to store the value of the flag.
290 func BoolVar(p *bool, name string, value bool, usage string) {
291         Var(newBoolValue(value, p), name, usage)
292 }
293
294 // Bool defines a bool flag with specified name, default value, and usage string.
295 // The return value is the address of a bool variable that stores the value of the flag.
296 func Bool(name string, value bool, usage string) *bool {
297         p := new(bool)
298         BoolVar(p, name, value, usage)
299         return p
300 }
301
302 // IntVar defines an int flag with specified name, default value, and usage string.
303 // The argument p points to an int variable in which to store the value of the flag.
304 func IntVar(p *int, name string, value int, usage string) {
305         Var(newIntValue(value, p), name, usage)
306 }
307
308 // Int defines an int flag with specified name, default value, and usage string.
309 // The return value is the address of an int variable that stores the value of the flag.
310 func Int(name string, value int, usage string) *int {
311         p := new(int)
312         IntVar(p, name, value, usage)
313         return p
314 }
315
316 // Int64Var defines an int64 flag with specified name, default value, and usage string.
317 // The argument p points to an int64 variable in which to store the value of the flag.
318 func Int64Var(p *int64, name string, value int64, usage string) {
319         Var(newInt64Value(value, p), name, usage)
320 }
321
322 // Int64 defines an int64 flag with specified name, default value, and usage string.
323 // The return value is the address of an int64 variable that stores the value of the flag.
324 func Int64(name string, value int64, usage string) *int64 {
325         p := new(int64)
326         Int64Var(p, name, value, usage)
327         return p
328 }
329
330 // UintVar defines a uint flag with specified name, default value, and usage string.
331 // The argument p points to a uint variable in which to store the value of the flag.
332 func UintVar(p *uint, name string, value uint, usage string) {
333         Var(newUintValue(value, p), name, usage)
334 }
335
336 // Uint defines a uint flag with specified name, default value, and usage string.
337 // The return value is the address of a uint variable that stores the value of the flag.
338 func Uint(name string, value uint, usage string) *uint {
339         p := new(uint)
340         UintVar(p, name, value, usage)
341         return p
342 }
343
344 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
345 // The argument p points to a uint64 variable in which to store the value of the flag.
346 func Uint64Var(p *uint64, name string, value uint64, usage string) {
347         Var(newUint64Value(value, p), name, usage)
348 }
349
350 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
351 // The return value is the address of a uint64 variable that stores the value of the flag.
352 func Uint64(name string, value uint64, usage string) *uint64 {
353         p := new(uint64)
354         Uint64Var(p, name, value, usage)
355         return p
356 }
357
358 // StringVar defines a string flag with specified name, default value, and usage string.
359 // The argument p points to a string variable in which to store the value of the flag.
360 func StringVar(p *string, name, value string, usage string) {
361         Var(newStringValue(value, p), name, usage)
362 }
363
364 // String defines a string flag with specified name, default value, and usage string.
365 // The return value is the address of a string variable that stores the value of the flag.
366 func String(name, value string, usage string) *string {
367         p := new(string)
368         StringVar(p, name, value, usage)
369         return p
370 }
371
372 // Float64Var defines a float64 flag with specified name, default value, and usage string.
373 // The argument p points to a float64 variable in which to store the value of the flag.
374 func Float64Var(p *float64, name string, value float64, usage string) {
375         Var(newFloat64Value(value, p), name, usage)
376 }
377
378 // Float64 defines a float64 flag with specified name, default value, and usage string.
379 // The return value is the address of a float64 variable that stores the value of the flag.
380 func Float64(name string, value float64, usage string) *float64 {
381         p := new(float64)
382         Float64Var(p, name, value, usage)
383         return p
384 }
385
386 // Var defines a user-typed flag with specified name, default value, and usage string.
387 // The argument p points to a Value variable in which to store the value of the flag.
388 func Var(value Value, name string, usage string) {
389         // Remember the default value as a string; it won't change.
390         f := &Flag{name, usage, value, value.String()}
391         _, alreadythere := flags.formal[name]
392         if alreadythere {
393                 fmt.Fprintln(os.Stderr, "flag redefined:", name)
394                 panic("flag redefinition") // Happens only if flags are declared with identical names
395         }
396         flags.formal[name] = f
397 }
398
399
400 func (f *allFlags) parseOne() (ok bool) {
401         if len(f.args) == 0 {
402                 return false
403         }
404         s := f.args[0]
405         if len(s) == 0 || s[0] != '-' || len(s) == 1 {
406                 return false
407         }
408         num_minuses := 1
409         if s[1] == '-' {
410                 num_minuses++
411                 if len(s) == 2 { // "--" terminates the flags
412                         f.args = f.args[1:]
413                         return false
414                 }
415         }
416         name := s[num_minuses:]
417         if len(name) == 0 || name[0] == '-' || name[0] == '=' {
418                 fmt.Fprintln(os.Stderr, "bad flag syntax:", s)
419                 fail()
420         }
421
422         // it's a flag. does it have an argument?
423         f.args = f.args[1:]
424         has_value := false
425         value := ""
426         for i := 1; i < len(name); i++ { // equals cannot be first
427                 if name[i] == '=' {
428                         value = name[i+1:]
429                         has_value = true
430                         name = name[0:i]
431                         break
432                 }
433         }
434         m := flags.formal
435         flag, alreadythere := m[name] // BUG
436         if !alreadythere {
437                 fmt.Fprintf(os.Stderr, "flag provided but not defined: -%s\n", name)
438                 fail()
439         }
440         if fv, ok := flag.Value.(*boolValue); ok { // special case: doesn't need an arg
441                 if has_value {
442                         if !fv.Set(value) {
443                                 fmt.Fprintf(os.Stderr, "invalid boolean value %q for flag: -%s\n", value, name)
444                                 fail()
445                         }
446                 } else {
447                         fv.Set("true")
448                 }
449         } else {
450                 // It must have a value, which might be the next argument.
451                 if !has_value && len(f.args) > 0 {
452                         // value is the next arg
453                         has_value = true
454                         value, f.args = f.args[0], f.args[1:]
455                 }
456                 if !has_value {
457                         fmt.Fprintf(os.Stderr, "flag needs an argument: -%s\n", name)
458                         fail()
459                 }
460                 ok = flag.Value.Set(value)
461                 if !ok {
462                         fmt.Fprintf(os.Stderr, "invalid value %q for flag: -%s\n", value, name)
463                         fail()
464                 }
465         }
466         flags.actual[name] = flag
467         return true
468 }
469
470 // Parse parses the command-line flags.  Must be called after all flags are defined
471 // and before any are accessed by the program.
472 func Parse() {
473         flags.args = os.Args[1:]
474         for flags.parseOne() {
475         }
476 }
477
478 func init() {
479         flags = &allFlags{make(map[string]*Flag), make(map[string]*Flag), os.Args[1:]}
480 }