-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontext.go
More file actions
112 lines (92 loc) · 2.4 KB
/
context.go
File metadata and controls
112 lines (92 loc) · 2.4 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
package clip
import (
"errors"
"fmt"
"io"
"os"
)
// Context is a command context with runtime metadata.
type Context struct {
command *Command
parent *Context
}
// Name is the name of the command.
func (ctx *Context) Name() string {
return ctx.command.Name()
}
// Summary is a one-line description of the command.
func (ctx *Context) Summary() string {
return ctx.command.Summary()
}
// Description is a multi-line description of the command.
func (ctx *Context) Description() string {
return ctx.command.Description()
}
// Stdout is the writer for the command output.
func (ctx *Context) Stdout() io.Writer {
for cur := ctx; cur != nil; cur = cur.parent {
if cur.command.stdout != nil {
return cur.command.stdout
}
}
return os.Stdout
}
// Stderr is the writer for the command error output.
func (ctx *Context) Stderr() io.Writer {
for cur := ctx; cur != nil; cur = cur.parent {
if cur.command.stderr != nil {
return cur.command.stderr
}
}
return os.Stderr
}
// Parent is the context's parent context.
func (ctx *Context) Parent() *Context { return ctx.parent }
// Root is the context's root context.
func (ctx *Context) Root() *Context {
cur := ctx
for cur.parent != nil {
cur = cur.parent
}
return cur
}
// Args returns the list of arguments.
func (ctx *Context) args() []string {
return ctx.command.flagSet.Args()
}
// run runs the command with a given context.
func (ctx *Context) run(args []string) error {
if len(args) == 0 {
return errors.New("no arguments were provided; this is a developer error")
}
if err := ctx.command.flagSet.Parse(args[1:]); err != nil {
return newUsageError(ctx, err)
}
// Flag actions
if wasSet, err := ctx.command.flagAction(ctx); wasSet {
return err
}
// No sub commands or command action
if len(ctx.command.subCommandMap) == 0 || len(ctx.args()) == 0 {
return ctx.command.action(ctx)
}
// Sub commands, something passed
subCmdName := ctx.args()[0]
if subCmd, ok := ctx.command.subCommandMap[subCmdName]; ok {
subCtx := Context{
command: subCmd,
parent: ctx,
}
return subCtx.run(ctx.args())
}
return newUsageError(ctx, fmt.Errorf("undefined sub-command: %s", subCmdName))
}
// printError prints an error with contextual information.
func (ctx *Context) printError(err error) {
w := ctx.Stderr()
fmt.Fprintf(w, "Error: %s\n", err)
if ectx, ok := err.(errorContext); ok {
fmt.Fprintln(w)
fmt.Fprint(w, ectx.ErrorContext())
}
}