-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_parse.go
110 lines (86 loc) · 2.47 KB
/
app_parse.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
package warg
import (
"context"
"os"
"go.bbkane.com/warg/command"
)
// ParseResult holds the result of parsing the command line.
type ParseResult struct {
Context command.Context
// Action holds the passed command's action to execute.
Action command.Action
}
type ParseOptHolder struct {
Args []string
Context context.Context
LookupFunc LookupFunc
// Stderr will be passed to command.Context for user commands to print to.
// This file is never closed by warg, so if setting to something other than stderr/stdout,
// remember to close the file after running the command.
// Useful for saving output for tests. Defaults to os.Stderr if not passed
Stderr *os.File
// Stdout will be passed to command.Context for user commands to print to.
// This file is never closed by warg, so if setting to something other than stderr/stdout,
// remember to close the file after running the command.
// Useful for saving output for tests. Defaults to os.Stdout if not passed
Stdout *os.File
}
type ParseOpt func(*ParseOptHolder)
func AddContext(ctx context.Context) ParseOpt {
return func(poh *ParseOptHolder) {
poh.Context = ctx
}
}
func OverrideArgs(args []string) ParseOpt {
return func(poh *ParseOptHolder) {
poh.Args = args
}
}
func OverrideLookupFunc(lookup LookupFunc) ParseOpt {
return func(poh *ParseOptHolder) {
poh.LookupFunc = lookup
}
}
func OverrideStderr(stderr *os.File) ParseOpt {
return func(poh *ParseOptHolder) {
poh.Stderr = stderr
}
}
func OverrideStdout(stdout *os.File) ParseOpt {
return func(poh *ParseOptHolder) {
poh.Stdout = stdout
}
}
func NewParseOptHolder(opts ...ParseOpt) ParseOptHolder {
parseOptHolder := ParseOptHolder{
Context: nil,
Args: nil,
LookupFunc: nil,
Stderr: nil,
Stdout: nil,
}
for _, opt := range opts {
opt(&parseOptHolder)
}
if parseOptHolder.Args == nil {
OverrideArgs(os.Args)(&parseOptHolder)
}
if parseOptHolder.Context == nil {
AddContext(context.Background())(&parseOptHolder)
}
if parseOptHolder.LookupFunc == nil {
OverrideLookupFunc(os.LookupEnv)(&parseOptHolder)
}
if parseOptHolder.Stderr == nil {
OverrideStderr(os.Stderr)(&parseOptHolder)
}
if parseOptHolder.Stdout == nil {
OverrideStdout(os.Stdout)(&parseOptHolder)
}
return parseOptHolder
}
// Parse parses the args, but does not execute anything.
func (app *App) Parse(opts ...ParseOpt) (*ParseResult, error) {
parseOptHolder := NewParseOptHolder(opts...)
return app.parseWithOptHolder2(parseOptHolder)
}