-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflag.go
More file actions
115 lines (97 loc) · 2.15 KB
/
flag.go
File metadata and controls
115 lines (97 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package sctx
import (
"flag"
"fmt"
"os"
"reflect"
"strings"
"github.com/taimaifika/service-context/flagenv"
)
func isZeroValue(f *flag.Flag, value string) bool {
typ := reflect.TypeOf(f.Value)
var z reflect.Value
if typ.Kind() == reflect.Ptr {
z = reflect.New(typ.Elem())
} else {
z = reflect.Zero(typ)
}
if value == z.Interface().(flag.Value).String() {
return true
}
switch value {
case "false":
return true
case "":
return true
case "0":
return true
}
return false
}
func getEnvName(name string) string {
name = strings.Replace(name, ".", "_", -1)
name = strings.Replace(name, "-", "_", -1)
if flagenv.Prefix != "" {
name = flagenv.Prefix + name
}
return strings.ToUpper(name)
}
type AppFlagSet struct {
*flag.FlagSet
}
func newFlagSet(name string, fs *flag.FlagSet) *AppFlagSet {
fSet := &AppFlagSet{fs}
fSet.Usage = flagCustomUsage(name, fSet)
return fSet
}
func (f *AppFlagSet) GetSampleEnvs() {
f.VisitAll(func(f *flag.Flag) {
if f.Name == "outenv" {
return
}
s := fmt.Sprintf("## %s (-%s)\n", f.Usage, f.Name)
s += fmt.Sprintf("#%s=", getEnvName(f.Name))
if !isZeroValue(f, f.DefValue) {
t := fmt.Sprintf("%T", f.Value)
if t == "*flag.stringValue" {
// put quotes on the value
s += fmt.Sprintf("%q", f.DefValue)
} else {
s += fmt.Sprintf("%v", f.DefValue)
}
}
fmt.Print(s, "\n\n")
})
}
func (f *AppFlagSet) Parse(args []string) {
flagenv.Parse()
_ = f.FlagSet.Parse(args)
}
func flagCustomUsage(name string, fSet *AppFlagSet) func() {
return func() {
_, _ = fmt.Fprintf(os.Stderr, "Usage of %s:\n", name)
fSet.VisitAll(func(f *flag.Flag) {
s := fmt.Sprintf(" -%s", f.Name)
name, usage := flag.UnquoteUsage(f)
if len(name) > 0 {
s += " " + name
}
if len(s) <= 4 {
s += "\t"
} else {
s += "\n \t"
}
s += usage
if !isZeroValue(f, f.DefValue) {
t := fmt.Sprintf("%T", f.Value)
if t == "*flag.stringValue" {
s += fmt.Sprintf(" (default %q)", f.DefValue)
} else {
s += fmt.Sprintf(" (default %v)", f.DefValue)
}
}
s += fmt.Sprintf(" [$%s]", getEnvName(f.Name))
_, _ = fmt.Fprint(os.Stderr, s, "\n")
})
}
}