-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmdline_tool_template.go
113 lines (104 loc) · 1.89 KB
/
cmdline_tool_template.go
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
package main
import (
"flag"
"fmt"
"os"
)
const (
BOOL_OPT = 1 + iota
STRING_OPT
INT_OPT
)
// TODO: LOW_PRIO: Support LISENCE Identifier
const (
PG_NAME = "Please input program name"
USAGE = "Please input usage"
VERSION = "0.0.1"
)
// prepare cmdline opt vars
var (
is_help bool
is_version bool
is_verbose bool
)
func show_help() {
flag.Usage()
os.Exit(-1)
}
func show_version() {
fmt.Println(VERSION)
}
func verbose_info(fmt_str string, args []interface{}) {
if is_verbose {
fmt.Println(fmt_str, args)
}
}
/*
* @flags: type, ptr, opt, default, usage
* @return: ret bool: is process success
* err int: error code
*/
func initializeFlag(flags [][]interface{}) (ret bool, err int) {
ret = true
err = 0
// set usage
flag.Usage = func() {
show_version()
print("usage: ", PG_NAME, USAGE, "\n")
flag.PrintDefaults()
}
for i := 0; i < len(flags); i++ {
typename := flags[i][0].(int)
opt := flags[i][2].(string)
usage := flags[i][4].(string)
switch typename {
case BOOL_OPT:
ptr := flags[i][1].(*bool)
defval := flags[i][3].(bool)
flag.BoolVar(ptr, opt, defval, usage)
break
case STRING_OPT:
ptr := flags[i][1].(*string)
defval := flags[i][3].(string)
flag.StringVar(ptr, opt, defval, usage)
break
case INT_OPT:
ptr := flags[i][1].(*int)
defval := flags[i][3].(int)
flag.IntVar(ptr, opt, defval, usage)
break
default:
ret = false
err = -1
break
}
}
flag.Parse()
return
}
func main() {
flags := [][]interface{}{
{
BOOL_OPT, &is_verbose, "-verbose",
false, "show verbose info message",
},
{
BOOL_OPT, &is_help, "-help", false,
"show usage",
},
{
BOOL_OPT, &is_version, "-version", false,
"show version",
},
}
ret, err := initializeFlag(flags)
if is_help {
show_help()
}
if is_version {
show_version()
os.Exit(-1)
}
fmt.Println("ret:", ret)
fmt.Println("err:", err)
}