~juju-qa/ubuntu/yakkety/juju/2.0-rc3-again

« back to all changes in this revision

Viewing changes to src/launchpad.net/gnuflag/flag.go

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2013-04-24 22:34:47 UTC
  • Revision ID: package-import@ubuntu.com-20130424223447-f0qdji7ubnyo0s71
Tags: upstream-1.10.0.1
ImportĀ upstreamĀ versionĀ 1.10.0.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
        Package flag implements command-line flag parsing in the GNU style.
 
7
        It is almost exactly the same as the standard flag package,
 
8
        the only difference being the extra argument to Parse.
 
9
 
 
10
        Command line flag syntax:
 
11
                -f              // single letter flag
 
12
                -fg             // two single letter flags together
 
13
                --flag  // multiple letter flag
 
14
                --flag x  // non-boolean flags only
 
15
                -f x            // non-boolean flags only
 
16
                -fx             // if f is a non-boolean flag, x is its argument.
 
17
 
 
18
        The last three forms are not permitted for boolean flags because the
 
19
        meaning of the command
 
20
                cmd -f *
 
21
        will change if there is a file called 0, false, etc.  There is currently
 
22
        no way to turn off a boolean flag.
 
23
 
 
24
        Flag parsing stops after the terminator "--", or just before the first
 
25
        non-flag argument ("-" is a non-flag argument) if the interspersed
 
26
        argument to Parse is false. 
 
27
*/
 
28
package gnuflag
 
29
 
 
30
import (
 
31
        "bytes"
 
32
        "errors"
 
33
        "fmt"
 
34
        "io"
 
35
        "os"
 
36
        "sort"
 
37
        "strconv"
 
38
        "strings"
 
39
        "time"
 
40
        "unicode/utf8"
 
41
)
 
42
 
 
43
// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
 
44
var ErrHelp = errors.New("flag: help requested")
 
45
 
 
46
// -- bool Value
 
47
type boolValue bool
 
48
 
 
49
func newBoolValue(val bool, p *bool) *boolValue {
 
50
        *p = val
 
51
        return (*boolValue)(p)
 
52
}
 
53
 
 
54
func (b *boolValue) Set(s string) error {
 
55
        v, err := strconv.ParseBool(s)
 
56
        *b = boolValue(v)
 
57
        return err
 
58
}
 
59
 
 
60
func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
 
61
 
 
62
// -- int Value
 
63
type intValue int
 
64
 
 
65
func newIntValue(val int, p *int) *intValue {
 
66
        *p = val
 
67
        return (*intValue)(p)
 
68
}
 
69
 
 
70
func (i *intValue) Set(s string) error {
 
71
        v, err := strconv.ParseInt(s, 0, 64)
 
72
        *i = intValue(v)
 
73
        return err
 
74
}
 
75
 
 
76
func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
 
77
 
 
78
// -- int64 Value
 
79
type int64Value int64
 
80
 
 
81
func newInt64Value(val int64, p *int64) *int64Value {
 
82
        *p = val
 
83
        return (*int64Value)(p)
 
84
}
 
85
 
 
86
func (i *int64Value) Set(s string) error {
 
87
        v, err := strconv.ParseInt(s, 0, 64)
 
88
        *i = int64Value(v)
 
89
        return err
 
90
}
 
91
 
 
92
func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
 
93
 
 
94
// -- uint Value
 
95
type uintValue uint
 
96
 
 
97
func newUintValue(val uint, p *uint) *uintValue {
 
98
        *p = val
 
99
        return (*uintValue)(p)
 
100
}
 
101
 
 
102
func (i *uintValue) Set(s string) error {
 
103
        v, err := strconv.ParseUint(s, 0, 64)
 
104
        *i = uintValue(v)
 
105
        return err
 
106
}
 
107
 
 
108
func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
 
109
 
 
110
// -- uint64 Value
 
111
type uint64Value uint64
 
112
 
 
113
func newUint64Value(val uint64, p *uint64) *uint64Value {
 
114
        *p = val
 
115
        return (*uint64Value)(p)
 
116
}
 
117
 
 
118
func (i *uint64Value) Set(s string) error {
 
119
        v, err := strconv.ParseUint(s, 0, 64)
 
120
        *i = uint64Value(v)
 
121
        return err
 
122
}
 
123
 
 
124
func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
 
125
 
 
126
// -- string Value
 
127
type stringValue string
 
128
 
 
129
func newStringValue(val string, p *string) *stringValue {
 
130
        *p = val
 
131
        return (*stringValue)(p)
 
132
}
 
133
 
 
134
func (s *stringValue) Set(val string) error {
 
135
        *s = stringValue(val)
 
136
        return nil
 
137
}
 
138
 
 
139
func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
 
140
 
 
141
// -- float64 Value
 
142
type float64Value float64
 
143
 
 
144
func newFloat64Value(val float64, p *float64) *float64Value {
 
145
        *p = val
 
146
        return (*float64Value)(p)
 
147
}
 
148
 
 
149
func (f *float64Value) Set(s string) error {
 
150
        v, err := strconv.ParseFloat(s, 64)
 
151
        *f = float64Value(v)
 
152
        return err
 
153
}
 
154
 
 
155
func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
 
156
 
 
157
// -- time.Duration Value
 
158
type durationValue time.Duration
 
159
 
 
160
func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
 
161
        *p = val
 
162
        return (*durationValue)(p)
 
163
}
 
164
 
 
165
func (d *durationValue) Set(s string) error {
 
166
        v, err := time.ParseDuration(s)
 
167
        *d = durationValue(v)
 
168
        return err
 
169
}
 
170
 
 
171
func (d *durationValue) String() string { return (*time.Duration)(d).String() }
 
172
 
 
173
// Value is the interface to the dynamic value stored in a flag.
 
174
// (The default value is represented as a string.)
 
175
type Value interface {
 
176
        String() string
 
177
        Set(string) error
 
178
}
 
179
 
 
180
// ErrorHandling defines how to handle flag parsing errors.
 
181
type ErrorHandling int
 
182
 
 
183
const (
 
184
        ContinueOnError ErrorHandling = iota
 
185
        ExitOnError
 
186
        PanicOnError
 
187
)
 
188
 
 
189
// A FlagSet represents a set of defined flags.
 
190
type FlagSet struct {
 
191
        // Usage is the function called when an error occurs while parsing flags.
 
192
        // The field is a function (not a method) that may be changed to point to
 
193
        // a custom error handler.
 
194
        Usage func()
 
195
 
 
196
        name             string
 
197
        parsed           bool
 
198
        actual           map[string]*Flag
 
199
        formal           map[string]*Flag
 
200
        args             []string // arguments after flags
 
201
        procArgs         []string // arguments being processed (gnu only)
 
202
        procFlag         string   // flag being processed (gnu only)
 
203
        allowIntersperse bool     // (gnu only)
 
204
        exitOnError      bool     // does the program exit if there's an error?
 
205
        errorHandling    ErrorHandling
 
206
        output           io.Writer // nil means stderr; use out() accessor
 
207
}
 
208
 
 
209
// A Flag represents the state of a flag.
 
210
type Flag struct {
 
211
        Name     string // name as it appears on command line
 
212
        Usage    string // help message
 
213
        Value    Value  // value as set
 
214
        DefValue string // default value (as text); for usage message
 
215
}
 
216
 
 
217
// sortFlags returns the flags as a slice in lexicographical sorted order.
 
218
func sortFlags(flags map[string]*Flag) []*Flag {
 
219
        list := make(sort.StringSlice, len(flags))
 
220
        i := 0
 
221
        for _, f := range flags {
 
222
                list[i] = f.Name
 
223
                i++
 
224
        }
 
225
        list.Sort()
 
226
        result := make([]*Flag, len(list))
 
227
        for i, name := range list {
 
228
                result[i] = flags[name]
 
229
        }
 
230
        return result
 
231
}
 
232
 
 
233
func (f *FlagSet) out() io.Writer {
 
234
        if f.output == nil {
 
235
                return os.Stderr
 
236
        }
 
237
        return f.output
 
238
}
 
239
 
 
240
// SetOutput sets the destination for usage and error messages.
 
241
// If output is nil, os.Stderr is used.
 
242
func (f *FlagSet) SetOutput(output io.Writer) {
 
243
        f.output = output
 
244
}
 
245
 
 
246
// VisitAll visits the flags in lexicographical order, calling fn for each.
 
247
// It visits all flags, even those not set.
 
248
func (f *FlagSet) VisitAll(fn func(*Flag)) {
 
249
        for _, flag := range sortFlags(f.formal) {
 
250
                fn(flag)
 
251
        }
 
252
}
 
253
 
 
254
// VisitAll visits the command-line flags in lexicographical order, calling
 
255
// fn for each.  It visits all flags, even those not set.
 
256
func VisitAll(fn func(*Flag)) {
 
257
        commandLine.VisitAll(fn)
 
258
}
 
259
 
 
260
// Visit visits the flags in lexicographical order, calling fn for each.
 
261
// It visits only those flags that have been set.
 
262
func (f *FlagSet) Visit(fn func(*Flag)) {
 
263
        for _, flag := range sortFlags(f.actual) {
 
264
                fn(flag)
 
265
        }
 
266
}
 
267
 
 
268
// Visit visits the command-line flags in lexicographical order, calling fn
 
269
// for each.  It visits only those flags that have been set.
 
270
func Visit(fn func(*Flag)) {
 
271
        commandLine.Visit(fn)
 
272
}
 
273
 
 
274
// Lookup returns the Flag structure of the named flag, returning nil if none exists.
 
275
func (f *FlagSet) Lookup(name string) *Flag {
 
276
        return f.formal[name]
 
277
}
 
278
 
 
279
// Lookup returns the Flag structure of the named command-line flag,
 
280
// returning nil if none exists.
 
281
func Lookup(name string) *Flag {
 
282
        return commandLine.formal[name]
 
283
}
 
284
 
 
285
// Set sets the value of the named flag.
 
286
func (f *FlagSet) Set(name, value string) error {
 
287
        flag, ok := f.formal[name]
 
288
        if !ok {
 
289
                return fmt.Errorf("no such flag -%v", name)
 
290
        }
 
291
        err := flag.Value.Set(value)
 
292
        if err != nil {
 
293
                return err
 
294
        }
 
295
        if f.actual == nil {
 
296
                f.actual = make(map[string]*Flag)
 
297
        }
 
298
        f.actual[name] = flag
 
299
        return nil
 
300
}
 
301
 
 
302
// Set sets the value of the named command-line flag.
 
303
func Set(name, value string) error {
 
304
        return commandLine.Set(name, value)
 
305
}
 
306
 
 
307
// flagsByLength is a slice of flags implementing sort.Interface,
 
308
// sorting primarily by the length of the flag, and secondarily
 
309
// alphabetically.
 
310
type flagsByLength []*Flag
 
311
 
 
312
func (f flagsByLength) Less(i, j int) bool {
 
313
        s1, s2 := f[i].Name, f[j].Name
 
314
        if len(s1) != len(s2) {
 
315
                return len(s1) < len(s2)
 
316
        }
 
317
        return s1 < s2
 
318
}
 
319
func (f flagsByLength) Swap(i, j int) {
 
320
        f[i], f[j] = f[j], f[i]
 
321
}
 
322
func (f flagsByLength) Len() int {
 
323
        return len(f)
 
324
}
 
325
 
 
326
// flagsByName is a slice of slices of flags implementing sort.Interface,
 
327
// alphabetically sorting by the name of the first flag in each slice.
 
328
type flagsByName [][]*Flag
 
329
 
 
330
func (f flagsByName) Less(i, j int) bool {
 
331
        return f[i][0].Name < f[j][0].Name
 
332
}
 
333
func (f flagsByName) Swap(i, j int) {
 
334
        f[i], f[j] = f[j], f[i]
 
335
}
 
336
func (f flagsByName) Len() int {
 
337
        return len(f)
 
338
}
 
339
 
 
340
// PrintDefaults prints, to standard error unless configured
 
341
// otherwise, the default values of all defined flags in the set.
 
342
// If there is more than one name for a given flag, the usage information and
 
343
// default value from the shortest will be printed (or the least alphabetically
 
344
// if there are several equally short flag names).
 
345
func (f *FlagSet) PrintDefaults() {
 
346
        // group together all flags for a given value
 
347
        flags := make(map[interface{}]flagsByLength)
 
348
        f.VisitAll(func(f *Flag) {
 
349
                flags[f.Value] = append(flags[f.Value], f)
 
350
        })
 
351
 
 
352
        // sort the output flags by shortest name for each group.
 
353
        var byName flagsByName
 
354
        for _, f := range flags {
 
355
                sort.Sort(f)
 
356
                byName = append(byName, f)
 
357
        }
 
358
        sort.Sort(byName)
 
359
 
 
360
        var line bytes.Buffer
 
361
        for _, fs := range byName {
 
362
                line.Reset()
 
363
                for i, f := range fs {
 
364
                        if i > 0 {
 
365
                                line.WriteString(", ")
 
366
                        }
 
367
                        line.WriteString(flagWithMinus(f.Name))
 
368
                }
 
369
                format := "%s  (= %s)\n    %s\n"
 
370
                if _, ok := fs[0].Value.(*stringValue); ok {
 
371
                        // put quotes on the value
 
372
                        format = "%s (= %q)\n    %s\n"
 
373
                }
 
374
                fmt.Fprintf(f.out(), format, line.Bytes(), fs[0].DefValue, fs[0].Usage)
 
375
        }
 
376
}
 
377
 
 
378
// PrintDefaults prints to standard error the default values of all defined command-line flags.
 
379
func PrintDefaults() {
 
380
        commandLine.PrintDefaults()
 
381
}
 
382
 
 
383
// defaultUsage is the default function to print a usage message.
 
384
func defaultUsage(f *FlagSet) {
 
385
        fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
 
386
        f.PrintDefaults()
 
387
}
 
388
 
 
389
// NOTE: Usage is not just defaultUsage(commandLine)
 
390
// because it serves (via godoc flag Usage) as the example
 
391
// for how to write your own usage function.
 
392
 
 
393
// Usage prints to standard error a usage message documenting all defined command-line flags.
 
394
// The function is a variable that may be changed to point to a custom function.
 
395
var Usage = func() {
 
396
        fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
 
397
        PrintDefaults()
 
398
}
 
399
 
 
400
// NFlag returns the number of flags that have been set.
 
401
func (f *FlagSet) NFlag() int { return len(f.actual) }
 
402
 
 
403
// NFlag returns the number of command-line flags that have been set.
 
404
func NFlag() int { return len(commandLine.actual) }
 
405
 
 
406
// Arg returns the i'th argument.  Arg(0) is the first remaining argument
 
407
// after flags have been processed.
 
408
func (f *FlagSet) Arg(i int) string {
 
409
        if i < 0 || i >= len(f.args) {
 
410
                return ""
 
411
        }
 
412
        return f.args[i]
 
413
}
 
414
 
 
415
// Arg returns the i'th command-line argument.  Arg(0) is the first remaining argument
 
416
// after flags have been processed.
 
417
func Arg(i int) string {
 
418
        return commandLine.Arg(i)
 
419
}
 
420
 
 
421
// NArg is the number of arguments remaining after flags have been processed.
 
422
func (f *FlagSet) NArg() int { return len(f.args) }
 
423
 
 
424
// NArg is the number of arguments remaining after flags have been processed.
 
425
func NArg() int { return len(commandLine.args) }
 
426
 
 
427
// Args returns the non-flag arguments.
 
428
func (f *FlagSet) Args() []string { return f.args }
 
429
 
 
430
// Args returns the non-flag command-line arguments.
 
431
func Args() []string { return commandLine.args }
 
432
 
 
433
// BoolVar defines a bool flag with specified name, default value, and usage string.
 
434
// The argument p points to a bool variable in which to store the value of the flag.
 
435
func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
 
436
        f.Var(newBoolValue(value, p), name, usage)
 
437
}
 
438
 
 
439
// BoolVar defines a bool flag with specified name, default value, and usage string.
 
440
// The argument p points to a bool variable in which to store the value of the flag.
 
441
func BoolVar(p *bool, name string, value bool, usage string) {
 
442
        commandLine.Var(newBoolValue(value, p), name, usage)
 
443
}
 
444
 
 
445
// Bool defines a bool flag with specified name, default value, and usage string.
 
446
// The return value is the address of a bool variable that stores the value of the flag.
 
447
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
 
448
        p := new(bool)
 
449
        f.BoolVar(p, name, value, usage)
 
450
        return p
 
451
}
 
452
 
 
453
// Bool defines a bool flag with specified name, default value, and usage string.
 
454
// The return value is the address of a bool variable that stores the value of the flag.
 
455
func Bool(name string, value bool, usage string) *bool {
 
456
        return commandLine.Bool(name, value, usage)
 
457
}
 
458
 
 
459
// IntVar defines an int flag with specified name, default value, and usage string.
 
460
// The argument p points to an int variable in which to store the value of the flag.
 
461
func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
 
462
        f.Var(newIntValue(value, p), name, usage)
 
463
}
 
464
 
 
465
// IntVar defines an int flag with specified name, default value, and usage string.
 
466
// The argument p points to an int variable in which to store the value of the flag.
 
467
func IntVar(p *int, name string, value int, usage string) {
 
468
        commandLine.Var(newIntValue(value, p), name, usage)
 
469
}
 
470
 
 
471
// Int defines an int flag with specified name, default value, and usage string.
 
472
// The return value is the address of an int variable that stores the value of the flag.
 
473
func (f *FlagSet) Int(name string, value int, usage string) *int {
 
474
        p := new(int)
 
475
        f.IntVar(p, name, value, usage)
 
476
        return p
 
477
}
 
478
 
 
479
// Int defines an int flag with specified name, default value, and usage string.
 
480
// The return value is the address of an int variable that stores the value of the flag.
 
481
func Int(name string, value int, usage string) *int {
 
482
        return commandLine.Int(name, value, usage)
 
483
}
 
484
 
 
485
// Int64Var defines an int64 flag with specified name, default value, and usage string.
 
486
// The argument p points to an int64 variable in which to store the value of the flag.
 
487
func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
 
488
        f.Var(newInt64Value(value, p), name, usage)
 
489
}
 
490
 
 
491
// Int64Var defines an int64 flag with specified name, default value, and usage string.
 
492
// The argument p points to an int64 variable in which to store the value of the flag.
 
493
func Int64Var(p *int64, name string, value int64, usage string) {
 
494
        commandLine.Var(newInt64Value(value, p), name, usage)
 
495
}
 
496
 
 
497
// Int64 defines an int64 flag with specified name, default value, and usage string.
 
498
// The return value is the address of an int64 variable that stores the value of the flag.
 
499
func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
 
500
        p := new(int64)
 
501
        f.Int64Var(p, name, value, usage)
 
502
        return p
 
503
}
 
504
 
 
505
// Int64 defines an int64 flag with specified name, default value, and usage string.
 
506
// The return value is the address of an int64 variable that stores the value of the flag.
 
507
func Int64(name string, value int64, usage string) *int64 {
 
508
        return commandLine.Int64(name, value, usage)
 
509
}
 
510
 
 
511
// UintVar defines a uint flag with specified name, default value, and usage string.
 
512
// The argument p points to a uint variable in which to store the value of the flag.
 
513
func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
 
514
        f.Var(newUintValue(value, p), name, usage)
 
515
}
 
516
 
 
517
// UintVar defines a uint flag with specified name, default value, and usage string.
 
518
// The argument p points to a uint  variable in which to store the value of the flag.
 
519
func UintVar(p *uint, name string, value uint, usage string) {
 
520
        commandLine.Var(newUintValue(value, p), name, usage)
 
521
}
 
522
 
 
523
// Uint defines a uint flag with specified name, default value, and usage string.
 
524
// The return value is the address of a uint  variable that stores the value of the flag.
 
525
func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
 
526
        p := new(uint)
 
527
        f.UintVar(p, name, value, usage)
 
528
        return p
 
529
}
 
530
 
 
531
// Uint defines a uint flag with specified name, default value, and usage string.
 
532
// The return value is the address of a uint  variable that stores the value of the flag.
 
533
func Uint(name string, value uint, usage string) *uint {
 
534
        return commandLine.Uint(name, value, usage)
 
535
}
 
536
 
 
537
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
 
538
// The argument p points to a uint64 variable in which to store the value of the flag.
 
539
func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
 
540
        f.Var(newUint64Value(value, p), name, usage)
 
541
}
 
542
 
 
543
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
 
544
// The argument p points to a uint64 variable in which to store the value of the flag.
 
545
func Uint64Var(p *uint64, name string, value uint64, usage string) {
 
546
        commandLine.Var(newUint64Value(value, p), name, usage)
 
547
}
 
548
 
 
549
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
 
550
// The return value is the address of a uint64 variable that stores the value of the flag.
 
551
func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
 
552
        p := new(uint64)
 
553
        f.Uint64Var(p, name, value, usage)
 
554
        return p
 
555
}
 
556
 
 
557
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
 
558
// The return value is the address of a uint64 variable that stores the value of the flag.
 
559
func Uint64(name string, value uint64, usage string) *uint64 {
 
560
        return commandLine.Uint64(name, value, usage)
 
561
}
 
562
 
 
563
// StringVar defines a string flag with specified name, default value, and usage string.
 
564
// The argument p points to a string variable in which to store the value of the flag.
 
565
func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
 
566
        f.Var(newStringValue(value, p), name, usage)
 
567
}
 
568
 
 
569
// StringVar defines a string flag with specified name, default value, and usage string.
 
570
// The argument p points to a string variable in which to store the value of the flag.
 
571
func StringVar(p *string, name string, value string, usage string) {
 
572
        commandLine.Var(newStringValue(value, p), name, usage)
 
573
}
 
574
 
 
575
// String defines a string flag with specified name, default value, and usage string.
 
576
// The return value is the address of a string variable that stores the value of the flag.
 
577
func (f *FlagSet) String(name string, value string, usage string) *string {
 
578
        p := new(string)
 
579
        f.StringVar(p, name, value, usage)
 
580
        return p
 
581
}
 
582
 
 
583
// String defines a string flag with specified name, default value, and usage string.
 
584
// The return value is the address of a string variable that stores the value of the flag.
 
585
func String(name string, value string, usage string) *string {
 
586
        return commandLine.String(name, value, usage)
 
587
}
 
588
 
 
589
// Float64Var defines a float64 flag with specified name, default value, and usage string.
 
590
// The argument p points to a float64 variable in which to store the value of the flag.
 
591
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
 
592
        f.Var(newFloat64Value(value, p), name, usage)
 
593
}
 
594
 
 
595
// Float64Var defines a float64 flag with specified name, default value, and usage string.
 
596
// The argument p points to a float64 variable in which to store the value of the flag.
 
597
func Float64Var(p *float64, name string, value float64, usage string) {
 
598
        commandLine.Var(newFloat64Value(value, p), name, usage)
 
599
}
 
600
 
 
601
// Float64 defines a float64 flag with specified name, default value, and usage string.
 
602
// The return value is the address of a float64 variable that stores the value of the flag.
 
603
func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
 
604
        p := new(float64)
 
605
        f.Float64Var(p, name, value, usage)
 
606
        return p
 
607
}
 
608
 
 
609
// Float64 defines a float64 flag with specified name, default value, and usage string.
 
610
// The return value is the address of a float64 variable that stores the value of the flag.
 
611
func Float64(name string, value float64, usage string) *float64 {
 
612
        return commandLine.Float64(name, value, usage)
 
613
}
 
614
 
 
615
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
 
616
// The argument p points to a time.Duration variable in which to store the value of the flag.
 
617
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
 
618
        f.Var(newDurationValue(value, p), name, usage)
 
619
}
 
620
 
 
621
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
 
622
// The argument p points to a time.Duration variable in which to store the value of the flag.
 
623
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
 
624
        commandLine.Var(newDurationValue(value, p), name, usage)
 
625
}
 
626
 
 
627
// Duration defines a time.Duration flag with specified name, default value, and usage string.
 
628
// The return value is the address of a time.Duration variable that stores the value of the flag.
 
629
func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
 
630
        p := new(time.Duration)
 
631
        f.DurationVar(p, name, value, usage)
 
632
        return p
 
633
}
 
634
 
 
635
// Duration defines a time.Duration flag with specified name, default value, and usage string.
 
636
// The return value is the address of a time.Duration variable that stores the value of the flag.
 
637
func Duration(name string, value time.Duration, usage string) *time.Duration {
 
638
        return commandLine.Duration(name, value, usage)
 
639
}
 
640
 
 
641
// Var defines a flag with the specified name and usage string. The type and
 
642
// value of the flag are represented by the first argument, of type Value, which
 
643
// typically holds a user-defined implementation of Value. For instance, the
 
644
// caller could create a flag that turns a comma-separated string into a slice
 
645
// of strings by giving the slice the methods of Value; in particular, Set would
 
646
// decompose the comma-separated string into the slice.
 
647
func (f *FlagSet) Var(value Value, name string, usage string) {
 
648
        // Remember the default value as a string; it won't change.
 
649
        flag := &Flag{name, usage, value, value.String()}
 
650
        _, alreadythere := f.formal[name]
 
651
        if alreadythere {
 
652
                fmt.Fprintf(f.out(), "%s flag redefined: %s\n", f.name, name)
 
653
                panic("flag redefinition") // Happens only if flags are declared with identical names
 
654
        }
 
655
        if f.formal == nil {
 
656
                f.formal = make(map[string]*Flag)
 
657
        }
 
658
        f.formal[name] = flag
 
659
}
 
660
 
 
661
// Var defines a flag with the specified name and usage string. The type and
 
662
// value of the flag are represented by the first argument, of type Value, which
 
663
// typically holds a user-defined implementation of Value. For instance, the
 
664
// caller could create a flag that turns a comma-separated string into a slice
 
665
// of strings by giving the slice the methods of Value; in particular, Set would
 
666
// decompose the comma-separated string into the slice.
 
667
func Var(value Value, name string, usage string) {
 
668
        commandLine.Var(value, name, usage)
 
669
}
 
670
 
 
671
// failf prints to standard error a formatted error and usage message and
 
672
// returns the error.
 
673
func (f *FlagSet) failf(format string, a ...interface{}) error {
 
674
        err := fmt.Errorf(format, a...)
 
675
        fmt.Fprintln(f.out(), err)
 
676
        f.usage()
 
677
        return err
 
678
}
 
679
 
 
680
// usage calls the Usage method for the flag set, or the usage function if
 
681
// the flag set is commandLine.
 
682
func (f *FlagSet) usage() {
 
683
        if f == commandLine {
 
684
                Usage()
 
685
        } else if f.Usage == nil {
 
686
                defaultUsage(f)
 
687
        } else {
 
688
                f.Usage()
 
689
        }
 
690
}
 
691
 
 
692
func (f *FlagSet) parseOneGnu() (flagName string, long, finished bool, err error) {
 
693
        if len(f.procArgs) == 0 {
 
694
                finished = true
 
695
                return
 
696
        }
 
697
 
 
698
        // processing previously encountered single-rune flag
 
699
        if flag := f.procFlag; len(flag) > 0 {
 
700
                _, n := utf8.DecodeRuneInString(flag)
 
701
                f.procFlag = flag[n:]
 
702
                flagName = flag[0:n]
 
703
                return
 
704
        }
 
705
 
 
706
        a := f.procArgs[0]
 
707
 
 
708
        // one non-flag argument
 
709
        if a == "-" || a == "" || a[0] != '-' {
 
710
                if f.allowIntersperse {
 
711
                        f.args = append(f.args, a)
 
712
                        f.procArgs = f.procArgs[1:]
 
713
                        return
 
714
                }
 
715
                f.args = append(f.args, f.procArgs...)
 
716
                f.procArgs = nil
 
717
                finished = true
 
718
                return
 
719
        }
 
720
 
 
721
        // end of flags
 
722
        if f.procArgs[0] == "--" {
 
723
                f.args = append(f.args, f.procArgs[1:]...)
 
724
                f.procArgs = nil
 
725
                finished = true
 
726
                return
 
727
        }
 
728
 
 
729
        // long flag signified with "--" prefix
 
730
        if a[1] == '-' {
 
731
                long = true
 
732
                i := strings.Index(a, "=")
 
733
                if i < 0 {
 
734
                        f.procArgs = f.procArgs[1:]
 
735
                        flagName = a[2:]
 
736
                        return
 
737
                }
 
738
                flagName = a[2:i]
 
739
                if flagName == "" {
 
740
                        err = fmt.Errorf("empty flag in argument %q", a)
 
741
                        return
 
742
                }
 
743
                f.procArgs = f.procArgs[1:]
 
744
                f.procFlag = a[i:]
 
745
                return
 
746
        }
 
747
 
 
748
        // some number of single-rune flags
 
749
        a = a[1:]
 
750
        _, n := utf8.DecodeRuneInString(a)
 
751
        flagName = a[0:n]
 
752
        f.procFlag = a[n:]
 
753
        f.procArgs = f.procArgs[1:]
 
754
        return
 
755
}
 
756
 
 
757
func flagWithMinus(name string) string {
 
758
        if len(name) > 1 {
 
759
                return "--" + name
 
760
        }
 
761
        return "-" + name
 
762
}
 
763
 
 
764
func (f *FlagSet) parseGnuFlagArg(name string, long bool) (finished bool, err error) {
 
765
        m := f.formal
 
766
        flag, alreadythere := m[name] // BUG
 
767
        if !alreadythere {
 
768
                if name == "help" || name == "h" { // special case for nice help message.
 
769
                        f.usage()
 
770
                        return false, ErrHelp
 
771
                }
 
772
                // TODO print --xxx when flag is more than one rune.
 
773
                return false, f.failf("flag provided but not defined: %s", flagWithMinus(name))
 
774
        }
 
775
        if fv, ok := flag.Value.(*boolValue); ok && !strings.HasPrefix(f.procFlag, "=") {
 
776
                // special case: doesn't need an arg, and an arg hasn't
 
777
                // been provided explicitly.
 
778
                fv.Set("true")
 
779
        } else {
 
780
                // It must have a value, which might be the next argument.
 
781
                var hasValue bool
 
782
                var value string
 
783
                if f.procFlag != "" {
 
784
                        // value directly follows flag
 
785
                        value = f.procFlag
 
786
                        if long {
 
787
                                if value[0] != '=' {
 
788
                                        panic("no leading '=' in long flag")
 
789
                                }
 
790
                                value = value[1:]
 
791
                        }
 
792
                        hasValue = true
 
793
                        f.procFlag = ""
 
794
                }
 
795
                if !hasValue && len(f.procArgs) > 0 {
 
796
                        // value is the next arg
 
797
                        hasValue = true
 
798
                        value, f.procArgs = f.procArgs[0], f.procArgs[1:]
 
799
                }
 
800
                if !hasValue {
 
801
                        return false, f.failf("flag needs an argument: %s", flagWithMinus(name))
 
802
                }
 
803
                if err := flag.Value.Set(value); err != nil {
 
804
                        return false, f.failf("invalid value %q for flag %s: %v", value, flagWithMinus(name), err)
 
805
                }
 
806
        }
 
807
        if f.actual == nil {
 
808
                f.actual = make(map[string]*Flag)
 
809
        }
 
810
        f.actual[name] = flag
 
811
        return
 
812
}
 
813
 
 
814
// Parse parses flag definitions from the argument list, which should not
 
815
// include the command name.  Must be called after all flags in the FlagSet
 
816
// are defined and before flags are accessed by the program.
 
817
// The return value will be ErrHelp if --help was set but not defined.
 
818
// If allowIntersperse is set, arguments and flags can be interspersed, that
 
819
// is flags can follow positional arguments.
 
820
func (f *FlagSet) Parse(allowIntersperse bool, arguments []string) error {
 
821
        f.parsed = true
 
822
        f.procArgs = arguments
 
823
        f.procFlag = ""
 
824
        f.args = nil
 
825
        f.allowIntersperse = allowIntersperse
 
826
        for {
 
827
                name, long, finished, err := f.parseOneGnu()
 
828
                if !finished {
 
829
                        if name != "" {
 
830
                                finished, err = f.parseGnuFlagArg(name, long)
 
831
                        }
 
832
                }
 
833
                if err != nil {
 
834
                        switch f.errorHandling {
 
835
                        case ContinueOnError:
 
836
                                return err
 
837
                        case ExitOnError:
 
838
                                os.Exit(2)
 
839
                        case PanicOnError:
 
840
                                panic(err)
 
841
                        }
 
842
                }
 
843
                if !finished {
 
844
                        continue
 
845
                }
 
846
                if err == nil {
 
847
                        break
 
848
                }
 
849
        }
 
850
        return nil
 
851
}
 
852
 
 
853
// Parsed reports whether f.Parse has been called.
 
854
func (f *FlagSet) Parsed() bool {
 
855
        return f.parsed
 
856
}
 
857
 
 
858
// Parse parses the command-line flags from os.Args[1:].  Must be called
 
859
// after all flags are defined and before flags are accessed by the program.
 
860
// If allowIntersperse is set, arguments and flags can be interspersed, that
 
861
// is flags can follow positional arguments.
 
862
func Parse(allowIntersperse bool) {
 
863
        // Ignore errors; commandLine is set for ExitOnError.
 
864
        commandLine.Parse(allowIntersperse, os.Args[1:])
 
865
}
 
866
 
 
867
// Parsed returns true if the command-line flags have been parsed.
 
868
func Parsed() bool {
 
869
        return commandLine.Parsed()
 
870
}
 
871
 
 
872
// The default set of command-line flags, parsed from os.Args.
 
873
var commandLine = NewFlagSet(os.Args[0], ExitOnError)
 
874
 
 
875
// NewFlagSet returns a new, empty flag set with the specified name and
 
876
// error handling property.
 
877
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
 
878
        f := &FlagSet{
 
879
                name:          name,
 
880
                errorHandling: errorHandling,
 
881
        }
 
882
        return f
 
883
}
 
884
 
 
885
// Init sets the name and error handling property for a flag set.
 
886
// By default, the zero FlagSet uses an empty name and the
 
887
// ContinueOnError error handling policy.
 
888
func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
 
889
        f.name = name
 
890
        f.errorHandling = errorHandling
 
891
}