-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmd.go
70 lines (59 loc) · 1.05 KB
/
cmd.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
package cmd
import (
"fmt"
"os"
"path/filepath"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/x-mod/errors"
)
//default root command
var rootCmd *Command
var exitCode bool
func _program() string {
return filepath.Base(os.Args[0])
}
//Add for default root command
func Add(opts ...CommandOpt) *Command {
c := newCommand(opts...)
c.build()
if c.parent == nil {
return rootCmd
}
return c
}
//PersistentFlags
func PersistentFlags() *pflag.FlagSet {
return rootCmd.PersistentFlags()
}
//Flags
func Flags() *pflag.FlagSet {
return rootCmd.Flags()
}
//Version root command
func Version(v string) {
rootCmd.Version = v
}
//ExitCode
func ExitCode(enable bool) {
exitCode = enable
}
//Execute for default root command
func Execute() {
viper.AutomaticEnv()
exit(rootCmd.Execute())
}
func exit(err error) {
if err != nil {
fmt.Println("failed:", err)
if exitCode {
os.Exit(int(errors.ValueFrom(err)))
}
}
os.Exit(0)
}
func init() {
rootCmd = newCommand(Name(_program()))
rootCmd.TraverseChildren = true
exitCode = false
}