-
Notifications
You must be signed in to change notification settings - Fork 1
/
program.go
104 lines (92 loc) · 1.84 KB
/
program.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
package commander
import (
"fmt"
"os"
)
type GoCommander interface {
Commander
Context
}
var Program GoCommander = newProgram()
type _Program struct {
_Command
_Context
Format Formatter
Exec Execute
initial bool
version string // version if root command
errFunc func(error)
}
func newProgram() *_Program {
return &_Program{
_Command: *newCommand(true),
Format: Format,
Exec: Exec,
errFunc: func(err error) {
fmt.Println(err.Error())
},
}
}
func (p *_Program) init() *_Program {
if p.initial {
return p
}
p.initial = true
p._Command.init()
p.Command("-h --help", "output usage information", func() _Result {
p.ShowHelpMessage()
return resultBreak()
})
p.Command("-v --version", "output the version number", func() _Result {
p.ShowVersion()
return resultBreak()
})
return p
}
func (p *_Program) Version(ver string) Commander {
p._Command.Version(ver)
p.version = ver
return p
}
func (p _Program) ShowVersion() string {
fmt.Println(p.version)
return p.version
}
func (p *_Program) HelpMessage() string {
return p.init()._Command.HelpMessage()
}
func (p _Program) ShowHelpMessage() string {
s := p.HelpMessage()
fmt.Println(s)
return s
}
func (p *_Program) Parse(args ...[]string) (Context, error) {
var argv []string = nil
if len(args) != 0 {
argv = args[0]
}
if argv == nil && len(os.Args) > 1 {
argv = os.Args
}
if argv == nil || len(argv) == 0 {
argv = []string{"", "-h"}
}
d, err := Parse(p.HelpMessage(), argv, false, "", false, false)
if err != nil {
return nil, err
}
p._Context = *newContext(argv, d)
if r := p.run(&p._Context); r != nil {
if r.Break() {
if p.errFunc != nil && r.Error() != nil {
p.errFunc(r.Error())
}
return &p._Context, r.Error()
}
}
return &p._Context, nil
}
func (p *_Program) ErrorHandling(f func(error)) Commander {
p.errFunc = f
return p
}