OSDN Git Service

Update to current Go library.
[pf3gnuchains/gcc-fork.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.Arg(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         "sort"
72         "strconv"
73 )
74
75 // -- Bool Value
76 type boolValue bool
77
78 func newBoolValue(val bool, p *bool) *boolValue {
79         *p = val
80         return (*boolValue)(p)
81 }
82
83 func (b *boolValue) Set(s string) bool {
84         v, err := strconv.Atob(s)
85         *b = boolValue(v)
86         return err == nil
87 }
88
89 func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
90
91 // -- Int Value
92 type intValue int
93
94 func newIntValue(val int, p *int) *intValue {
95         *p = val
96         return (*intValue)(p)
97 }
98
99 func (i *intValue) Set(s string) bool {
100         v, err := strconv.Btoi64(s, 0)
101         *i = intValue(v)
102         return err == nil
103 }
104
105 func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
106
107 // -- Int64 Value
108 type int64Value int64
109
110 func newInt64Value(val int64, p *int64) *int64Value {
111         *p = val
112         return (*int64Value)(p)
113 }
114
115 func (i *int64Value) Set(s string) bool {
116         v, err := strconv.Btoi64(s, 0)
117         *i = int64Value(v)
118         return err == nil
119 }
120
121 func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
122
123 // -- Uint Value
124 type uintValue uint
125
126 func newUintValue(val uint, p *uint) *uintValue {
127         *p = val
128         return (*uintValue)(p)
129 }
130
131 func (i *uintValue) Set(s string) bool {
132         v, err := strconv.Btoui64(s, 0)
133         *i = uintValue(v)
134         return err == nil
135 }
136
137 func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
138
139 // -- uint64 Value
140 type uint64Value uint64
141
142 func newUint64Value(val uint64, p *uint64) *uint64Value {
143         *p = val
144         return (*uint64Value)(p)
145 }
146
147 func (i *uint64Value) Set(s string) bool {
148         v, err := strconv.Btoui64(s, 0)
149         *i = uint64Value(v)
150         return err == nil
151 }
152
153 func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
154
155 // -- string Value
156 type stringValue string
157
158 func newStringValue(val string, p *string) *stringValue {
159         *p = val
160         return (*stringValue)(p)
161 }
162
163 func (s *stringValue) Set(val string) bool {
164         *s = stringValue(val)
165         return true
166 }
167
168 func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
169
170 // -- Float64 Value
171 type float64Value float64
172
173 func newFloat64Value(val float64, p *float64) *float64Value {
174         *p = val
175         return (*float64Value)(p)
176 }
177
178 func (f *float64Value) Set(s string) bool {
179         v, err := strconv.Atof64(s)
180         *f = float64Value(v)
181         return err == nil
182 }
183
184 func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
185
186 // Value is the interface to the dynamic value stored in a flag.
187 // (The default value is represented as a string.)
188 type Value interface {
189         String() string
190         Set(string) bool
191 }
192
193 // A Flag represents the state of a flag.
194 type Flag struct {
195         Name     string // name as it appears on command line
196         Usage    string // help message
197         Value    Value  // value as set
198         DefValue string // default value (as text); for usage message
199 }
200
201 type allFlags struct {
202         actual map[string]*Flag
203         formal map[string]*Flag
204         args   []string // arguments after flags
205 }
206
207 var flags *allFlags
208
209 // sortFlags returns the flags as a slice in lexicographical sorted order.
210 func sortFlags(flags map[string]*Flag) []*Flag {
211         list := make(sort.StringArray, len(flags))
212         i := 0
213         for _, f := range flags {
214                 list[i] = f.Name
215                 i++
216         }
217         list.Sort()
218         result := make([]*Flag, len(list))
219         for i, name := range list {
220                 result[i] = flags[name]
221         }
222         return result
223 }
224
225 // VisitAll visits the flags in lexicographical order, calling fn for each.
226 // It visits all flags, even those not set.
227 func VisitAll(fn func(*Flag)) {
228         for _, f := range sortFlags(flags.formal) {
229                 fn(f)
230         }
231 }
232
233 // Visit visits the flags in lexicographical order, calling fn for each.
234 // It visits only those flags that have been set.
235 func Visit(fn func(*Flag)) {
236         for _, f := range sortFlags(flags.actual) {
237                 fn(f)
238         }
239 }
240
241 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
242 func Lookup(name string) *Flag {
243         return flags.formal[name]
244 }
245
246 // Set sets the value of the named flag.  It returns true if the set succeeded; false if
247 // there is no such flag defined.
248 func Set(name, value string) bool {
249         f, ok := flags.formal[name]
250         if !ok {
251                 return false
252         }
253         ok = f.Value.Set(value)
254         if !ok {
255                 return false
256         }
257         flags.actual[name] = f
258         return true
259 }
260
261 // PrintDefaults prints to standard error the default values of all defined flags.
262 func PrintDefaults() {
263         VisitAll(func(f *Flag) {
264                 format := "  -%s=%s: %s\n"
265                 if _, ok := f.Value.(*stringValue); ok {
266                         // put quotes on the value
267                         format = "  -%s=%q: %s\n"
268                 }
269                 fmt.Fprintf(os.Stderr, format, f.Name, f.DefValue, f.Usage)
270         })
271 }
272
273 // Usage prints to standard error a default usage message documenting all defined flags.
274 // The function is a variable that may be changed to point to a custom function.
275 var Usage = func() {
276         fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
277         PrintDefaults()
278 }
279
280 var panicOnError = false
281
282 // failf prints to standard error a formatted error and Usage, and then exits the program.
283 func failf(format string, a ...interface{}) {
284         fmt.Fprintf(os.Stderr, format, a...)
285         Usage()
286         if panicOnError {
287                 panic("flag parse error")
288         }
289         os.Exit(2)
290 }
291
292 // NFlag returns the number of flags that have been set.
293 func NFlag() int { return len(flags.actual) }
294
295 // Arg returns the i'th command-line argument.  Arg(0) is the first remaining argument
296 // after flags have been processed.
297 func Arg(i int) string {
298         if i < 0 || i >= len(flags.args) {
299                 return ""
300         }
301         return flags.args[i]
302 }
303
304 // NArg is the number of arguments remaining after flags have been processed.
305 func NArg() int { return len(flags.args) }
306
307 // Args returns the non-flag command-line arguments.
308 func Args() []string { return flags.args }
309
310 // BoolVar defines a bool flag with specified name, default value, and usage string.
311 // The argument p points to a bool variable in which to store the value of the flag.
312 func BoolVar(p *bool, name string, value bool, usage string) {
313         Var(newBoolValue(value, p), name, usage)
314 }
315
316 // Bool defines a bool flag with specified name, default value, and usage string.
317 // The return value is the address of a bool variable that stores the value of the flag.
318 func Bool(name string, value bool, usage string) *bool {
319         p := new(bool)
320         BoolVar(p, name, value, usage)
321         return p
322 }
323
324 // IntVar defines an int flag with specified name, default value, and usage string.
325 // The argument p points to an int variable in which to store the value of the flag.
326 func IntVar(p *int, name string, value int, usage string) {
327         Var(newIntValue(value, p), name, usage)
328 }
329
330 // Int defines an int flag with specified name, default value, and usage string.
331 // The return value is the address of an int variable that stores the value of the flag.
332 func Int(name string, value int, usage string) *int {
333         p := new(int)
334         IntVar(p, name, value, usage)
335         return p
336 }
337
338 // Int64Var defines an int64 flag with specified name, default value, and usage string.
339 // The argument p points to an int64 variable in which to store the value of the flag.
340 func Int64Var(p *int64, name string, value int64, usage string) {
341         Var(newInt64Value(value, p), name, usage)
342 }
343
344 // Int64 defines an int64 flag with specified name, default value, and usage string.
345 // The return value is the address of an int64 variable that stores the value of the flag.
346 func Int64(name string, value int64, usage string) *int64 {
347         p := new(int64)
348         Int64Var(p, name, value, usage)
349         return p
350 }
351
352 // UintVar defines a uint flag with specified name, default value, and usage string.
353 // The argument p points to a uint variable in which to store the value of the flag.
354 func UintVar(p *uint, name string, value uint, usage string) {
355         Var(newUintValue(value, p), name, usage)
356 }
357
358 // Uint defines a uint flag with specified name, default value, and usage string.
359 // The return value is the address of a uint variable that stores the value of the flag.
360 func Uint(name string, value uint, usage string) *uint {
361         p := new(uint)
362         UintVar(p, name, value, usage)
363         return p
364 }
365
366 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
367 // The argument p points to a uint64 variable in which to store the value of the flag.
368 func Uint64Var(p *uint64, name string, value uint64, usage string) {
369         Var(newUint64Value(value, p), name, usage)
370 }
371
372 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
373 // The return value is the address of a uint64 variable that stores the value of the flag.
374 func Uint64(name string, value uint64, usage string) *uint64 {
375         p := new(uint64)
376         Uint64Var(p, name, value, usage)
377         return p
378 }
379
380 // StringVar defines a string flag with specified name, default value, and usage string.
381 // The argument p points to a string variable in which to store the value of the flag.
382 func StringVar(p *string, name, value string, usage string) {
383         Var(newStringValue(value, p), name, usage)
384 }
385
386 // String defines a string flag with specified name, default value, and usage string.
387 // The return value is the address of a string variable that stores the value of the flag.
388 func String(name, value string, usage string) *string {
389         p := new(string)
390         StringVar(p, name, value, usage)
391         return p
392 }
393
394 // Float64Var defines a float64 flag with specified name, default value, and usage string.
395 // The argument p points to a float64 variable in which to store the value of the flag.
396 func Float64Var(p *float64, name string, value float64, usage string) {
397         Var(newFloat64Value(value, p), name, usage)
398 }
399
400 // Float64 defines a float64 flag with specified name, default value, and usage string.
401 // The return value is the address of a float64 variable that stores the value of the flag.
402 func Float64(name string, value float64, usage string) *float64 {
403         p := new(float64)
404         Float64Var(p, name, value, usage)
405         return p
406 }
407
408 // Var defines a user-typed flag with specified name, default value, and usage string.
409 // The argument p points to a Value variable in which to store the value of the flag.
410 func Var(value Value, name string, usage string) {
411         // Remember the default value as a string; it won't change.
412         f := &Flag{name, usage, value, value.String()}
413         _, alreadythere := flags.formal[name]
414         if alreadythere {
415                 fmt.Fprintln(os.Stderr, "flag redefined:", name)
416                 panic("flag redefinition") // Happens only if flags are declared with identical names
417         }
418         flags.formal[name] = f
419 }
420
421
422 func (f *allFlags) parseOne() (ok bool) {
423         if len(f.args) == 0 {
424                 return false
425         }
426         s := f.args[0]
427         if len(s) == 0 || s[0] != '-' || len(s) == 1 {
428                 return false
429         }
430         num_minuses := 1
431         if s[1] == '-' {
432                 num_minuses++
433                 if len(s) == 2 { // "--" terminates the flags
434                         f.args = f.args[1:]
435                         return false
436                 }
437         }
438         name := s[num_minuses:]
439         if len(name) == 0 || name[0] == '-' || name[0] == '=' {
440                 failf("bad flag syntax: %s\n", s)
441         }
442
443         // it's a flag. does it have an argument?
444         f.args = f.args[1:]
445         has_value := false
446         value := ""
447         for i := 1; i < len(name); i++ { // equals cannot be first
448                 if name[i] == '=' {
449                         value = name[i+1:]
450                         has_value = true
451                         name = name[0:i]
452                         break
453                 }
454         }
455         m := flags.formal
456         flag, alreadythere := m[name] // BUG
457         if !alreadythere {
458                 failf("flag provided but not defined: -%s\n", name)
459         }
460         if fv, ok := flag.Value.(*boolValue); ok { // special case: doesn't need an arg
461                 if has_value {
462                         if !fv.Set(value) {
463                                 failf("invalid boolean value %q for flag: -%s\n", value, name)
464                         }
465                 } else {
466                         fv.Set("true")
467                 }
468         } else {
469                 // It must have a value, which might be the next argument.
470                 if !has_value && len(f.args) > 0 {
471                         // value is the next arg
472                         has_value = true
473                         value, f.args = f.args[0], f.args[1:]
474                 }
475                 if !has_value {
476                         failf("flag needs an argument: -%s\n", name)
477                 }
478                 ok = flag.Value.Set(value)
479                 if !ok {
480                         failf("invalid value %q for flag: -%s\n", value, name)
481                 }
482         }
483         flags.actual[name] = flag
484         return true
485 }
486
487 // Parse parses the command-line flags.  Must be called after all flags are defined
488 // and before any are accessed by the program.
489 func Parse() {
490         flags.args = os.Args[1:]
491         for flags.parseOne() {
492         }
493 }
494
495 func init() {
496         flags = &allFlags{make(map[string]*Flag), make(map[string]*Flag), os.Args[1:]}
497 }