/
env.go
172 lines (150 loc) · 4.37 KB
/
env.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmdline
import (
"fmt"
"io"
"os"
"strconv"
"v.io/x/lib/envvar"
"v.io/x/lib/lookpath"
"v.io/x/lib/textutil"
"v.io/x/lib/timing"
)
// EnvFromOS returns a new environment based on the operating system.
func EnvFromOS() *Env {
return &Env{
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Vars: envvar.SliceToMap(os.Environ()),
Timer: timing.NewTimer("root"),
}
}
// Env represents the environment for command parsing and running. Typically
// EnvFromOS is used to produce a default environment. The environment may be
// explicitly set for finer control; e.g. in tests.
type Env struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
Vars map[string]string // Environment variables
Timer *timing.Timer
// Usage is a function that prints usage information to w. Typically set by
// calls to Main or Parse to print usage of the leaf command.
Usage func(env *Env, w io.Writer)
}
func (e *Env) clone() *Env {
return &Env{
Stdin: e.Stdin,
Stdout: e.Stdout,
Stderr: e.Stderr,
Vars: envvar.CopyMap(e.Vars),
Usage: e.Usage,
Timer: e.Timer, // use the same timer for all operations
}
}
// UsageErrorf prints the error message represented by the printf-style format
// and args, followed by the output of the Usage function. Returns ErrUsage to
// make it easy to use from within the Runner.Run function.
func (e *Env) UsageErrorf(format string, args ...interface{}) error {
return usageErrorf(e, e.Usage, format, args...)
}
// TimerPush calls e.Timer.Push(name), only if the Timer is non-nil.
func (e *Env) TimerPush(name string) {
if e.Timer != nil {
e.Timer.Push(name)
}
}
// TimerPop calls e.Timer.Pop(), only if the Timer is non-nil.
func (e *Env) TimerPop() {
if e.Timer != nil {
e.Timer.Pop()
}
}
// LookPath returns the absolute path of the executable with the given name,
// based on the directories in PATH. Calls lookpath.Look.
func (e *Env) LookPath(name string) (string, error) {
e.TimerPush("lookpath " + name)
defer e.TimerPop()
return lookpath.Look(e.Vars, name)
}
// LookPathPrefix returns the absolute paths of all executables with the given
// name prefix, based on the directories in PATH. Calls lookpath.LookPrefix.
func (e *Env) LookPathPrefix(prefix string, names map[string]bool) ([]string, error) {
e.TimerPush("lookpathprefix " + prefix)
defer e.TimerPop()
return lookpath.LookPrefix(e.Vars, prefix, names)
}
func usageErrorf(env *Env, usage func(*Env, io.Writer), format string, args ...interface{}) error {
fmt.Fprint(env.Stderr, "ERROR: ")
fmt.Fprintf(env.Stderr, format, args...)
fmt.Fprint(env.Stderr, "\n\n")
if usage != nil {
usage(env, env.Stderr)
} else {
fmt.Fprint(env.Stderr, "usage error\n")
}
return ErrUsage
}
// defaultWidth is a reasonable default for the output width in runes.
const defaultWidth = 80
func (e *Env) width() int {
if width, err := strconv.Atoi(e.Vars["CMDLINE_WIDTH"]); err == nil && width != 0 {
return width
}
if _, width, err := textutil.TerminalSize(); err == nil && width != 0 {
return width
}
return defaultWidth
}
func (e *Env) style() style {
style := styleCompact
style.Set(e.Vars["CMDLINE_STYLE"])
return style
}
func (e *Env) prefix() string {
return e.Vars["CMDLINE_PREFIX"]
}
func (e *Env) firstCall() bool {
return e.Vars["CMDLINE_FIRST_CALL"] == ""
}
// style describes the formatting style for usage descriptions.
type style int
const (
styleCompact style = iota // Default style, good for compact cmdline output.
styleFull // Similar to compact but shows all global flags.
styleGoDoc // Good for godoc processing.
styleShortOnly // Only output short description.
)
func (s *style) String() string {
switch *s {
case styleCompact:
return "compact"
case styleFull:
return "full"
case styleGoDoc:
return "godoc"
case styleShortOnly:
return "shortonly"
default:
panic(fmt.Errorf("unhandled style %d", *s))
}
}
// Set implements the flag.Value interface method.
func (s *style) Set(value string) error {
switch value {
case "compact":
*s = styleCompact
case "full":
*s = styleFull
case "godoc":
*s = styleGoDoc
case "shortonly":
*s = styleShortOnly
default:
return fmt.Errorf("unknown style %q", value)
}
return nil
}