Debian Codegraph @

v2/var.go

raw symbols SCIP
1 // Copyright 2017 Google Inc. 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 package getopt
6
7 import (
8 "fmt"
9 "runtime"
10 "strings"
11 )
12
13 // Value is the interface to the dynamic value stored in a flag. Flags of type
14 // Value are declared using the Flag and FlagLong functions.
15 type Value interface {
16 // Set converts value into the appropriate type and assigns it to the
17 // receiver value. Option details are provided via opt (such as the
18 // flags name).
19 //
20 // Set is used to reset the value of an option to its default value
21 // (which is stored in string form internally).
22 Set(value string, opt Option) error
23
24 // String returns the value of the flag as a string.
25 String() string
26 }
27
28 var thisPackage string
29
30 // init initializes thisPackage to our full package with the trailing .
31 // included.
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 // thisPackage includes the trailing . after the package name.
51 thisPackage = thisPackage[:x+y+1]
52 }
53
54 // calledFrom returns a string containing the file and linenumber of the first
55 // stack frame above us that is not part of this package and is not a test.
56 // This is used to determine where a flag was initialized.
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 }