| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package getopt |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
"runtime" |
| 10 |
"strings" |
| 11 |
) |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
type Value interface { |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
Set(value string, opt Option) error |
| 23 |
|
| 24 |
|
| 25 |
String() string |
| 26 |
} |
| 27 |
|
| 28 |
var thisPackage string |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
func init() { |
| 33 |
pc, _, _, ok := runtime.Caller(0) |
| 34 |
if !ok { |
| 35 |
return |
| 36 |
} |
| 37 |
f := runtime.FuncForPC(pc) |
| 38 |
if f == nil { |
| 39 |
return |
| 40 |
} |
| 41 |
thisPackage = f.Name() |
| 42 |
x := strings.LastIndex(thisPackage, "/") |
| 43 |
if x < 0 { |
| 44 |
return |
| 45 |
} |
| 46 |
y := strings.Index(thisPackage[x:], ".") |
| 47 |
if y < 0 { |
| 48 |
return |
| 49 |
} |
| 50 |
|
| 51 |
thisPackage = thisPackage[:x+y+1] |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
func calledFrom() string { |
| 58 |
for i := 2; ; i++ { |
| 59 |
pc, file, line, ok := runtime.Caller(i) |
| 60 |
if !ok { |
| 61 |
return "" |
| 62 |
} |
| 63 |
if !strings.HasSuffix(file, "_test.go") { |
| 64 |
f := runtime.FuncForPC(pc) |
| 65 |
if f != nil && strings.HasPrefix(f.Name(), thisPackage) { |
| 66 |
continue |
| 67 |
} |
| 68 |
} |
| 69 |
return fmt.Sprintf("%s:%d", file, line) |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
func (s *Set) addFlag(p Value, name string, short rune, helpvalue ...string) Option { |
| 74 |
opt := &option{ |
| 75 |
short: short, |
| 76 |
long: name, |
| 77 |
value: p, |
| 78 |
defval: p.String(), |
| 79 |
} |
| 80 |
|
| 81 |
switch len(helpvalue) { |
| 82 |
case 2: |
| 83 |
opt.name = helpvalue[1] |
| 84 |
fallthrough |
| 85 |
case 1: |
| 86 |
opt.help = helpvalue[0] |
| 87 |
case 0: |
| 88 |
default: |
| 89 |
panic("Too many strings for String helpvalue") |
| 90 |
} |
| 91 |
if where := calledFrom(); where != "" { |
| 92 |
opt.where = where |
| 93 |
} |
| 94 |
if opt.short == 0 && opt.long == "" { |
| 95 |
fmt.Fprint(stderr, opt.where+": no short or long option given") |
| 96 |
exit(1) |
| 97 |
} |
| 98 |
s.AddOption(opt) |
| 99 |
return opt |
| 100 |
} |