-
Notifications
You must be signed in to change notification settings - Fork 198
/
context.go
277 lines (236 loc) · 7.39 KB
/
context.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package context
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/carolynvs/aferox"
"github.com/pkg/errors"
"github.com/spf13/afero"
)
const (
// MixinOutputsDir represents the directory where mixin output files are written/read
MixinOutputsDir = "/cnab/app/porter/outputs"
)
type CommandBuilder func(name string, arg ...string) *exec.Cmd
type Context struct {
Debug bool
DebugPlugins bool
verbose bool
environ map[string]string
FileSystem aferox.Aferox
In io.Reader
Out io.Writer
Err io.Writer
NewCommand CommandBuilder
PlugInDebugContext *PluginDebugContext
}
// New creates a new context in the specified directory.
func New() *Context {
// Ignore any error getting the working directory and report errors
// when we attempt to access files in the current directory. This
// allows us to use the current directory as a default, and allow
// tests to override it.
pwd, _ := os.Getwd()
c := &Context{
environ: getEnviron(),
FileSystem: aferox.NewAferox(pwd, afero.NewOsFs()),
In: os.Stdin,
Out: NewCensoredWriter(os.Stdout),
Err: NewCensoredWriter(os.Stderr),
}
c.defaultNewCommand()
c.PlugInDebugContext = NewPluginDebugContext(c)
return c
}
func (c *Context) defaultNewCommand() {
c.NewCommand = func(name string, arg ...string) *exec.Cmd {
return c.Command(name, arg...)
}
}
// Command creates a new exec.Cmd using the context's current directory.
func (c *Context) Command(name string, arg ...string) *exec.Cmd {
cmd := &exec.Cmd{
Dir: c.Getwd(),
Path: name,
Args: append([]string{name}, arg...),
}
if filepath.Base(name) == name {
if lp, ok := c.LookPath(name); ok {
cmd.Path = lp
}
}
return cmd
}
func getEnviron() map[string]string {
environ := map[string]string{}
for _, env := range os.Environ() {
envParts := strings.SplitN(env, "=", 2)
key := envParts[0]
value := ""
if len(envParts) > 1 {
value = envParts[1]
}
environ[key] = value
}
return environ
}
func (c *Context) SetVerbose(value bool) {
c.verbose = value
}
func (c *Context) IsVerbose() bool {
return c.Debug || c.verbose
}
// Environ returns a copy of strings representing the environment,
// in the form "key=value".
func (c *Context) Environ() []string {
e := make([]string, 0, len(c.environ))
for k, v := range c.environ {
e = append(e, fmt.Sprintf("%s=%s", k, v))
}
return e
}
// EnvironMap returns a map of the current environment variables.
func (c *Context) EnvironMap() map[string]string {
env := make(map[string]string, len(c.environ))
for k, v := range c.environ {
env[k] = v
}
return env
}
// ExpandEnv replaces ${var} or $var in the string according to the values
// of the current environment variables. References to undefined
// variables are replaced by the empty string.
func (c *Context) ExpandEnv(s string) string {
return os.Expand(s, func(key string) string { return c.Getenv(key) })
}
// Getenv retrieves the value of the environment variable named by the key.
// It returns the value, which will be empty if the variable is not present.
// To distinguish between an empty value and an unset value, use LookupEnv.
func (c *Context) Getenv(key string) string {
return c.environ[key]
}
// This is a simplified exec.LookPath that checks if command is accessible given
// a PATH environment variable.
func (c *Context) LookPath(file string) (string, bool) {
return c.FileSystem.LookPath(file, c.Getenv("PATH"), c.Getenv("PATHEXT"))
}
// LookupEnv retrieves the value of the environment variable named
// by the key. If the variable is present in the environment the
// value (which may be empty) is returned and the boolean is true.
// Otherwise the returned value will be empty and the boolean will
// be false.
func (c *Context) LookupEnv(key string) (string, bool) {
value, ok := c.environ[key]
return value, ok
}
// Setenv sets the value of the environment variable named by the key.
// It returns an error, if any.
func (c *Context) Setenv(key string, value string) {
if c.environ == nil {
c.environ = make(map[string]string, 1)
}
c.environ[key] = value
}
// Unsetenv unsets a single environment variable.
func (c *Context) Unsetenv(key string) {
delete(c.environ, key)
}
// Clearenv deletes all environment variables.
func (c *Context) Clearenv() {
c.environ = make(map[string]string, 0)
}
// Getwd returns a rooted path name corresponding to the current directory.
func (c *Context) Getwd() string {
return c.FileSystem.Getwd()
}
// Chdir changes the current working directory to the named directory.
func (c *Context) Chdir(dir string) {
c.FileSystem.Chdir(dir)
}
// CensoredWriter is a writer wrapping the provided io.Writer with logic to censor certain values
type CensoredWriter struct {
writer io.Writer
sensitiveValues []string
}
// NewCensoredWriter returns a new CensoredWriter
func NewCensoredWriter(writer io.Writer) *CensoredWriter {
return &CensoredWriter{writer: writer, sensitiveValues: []string{}}
}
// SetSensitiveValues sets values needing masking for an CensoredWriter
func (cw *CensoredWriter) SetSensitiveValues(vals []string) {
cw.sensitiveValues = vals
}
// Write implements io.Writer's Write method, performing necessary auditing while doing so
func (cw *CensoredWriter) Write(b []byte) (int, error) {
auditedBytes := b
for _, val := range cw.sensitiveValues {
if strings.TrimSpace(val) != "" {
auditedBytes = bytes.Replace(auditedBytes, []byte(val), []byte("*******"), -1)
}
}
_, err := cw.writer.Write(auditedBytes)
return len(b), err
}
func (c *Context) CopyDirectory(srcDir, destDir string, includeBaseDir bool) error {
var stripPrefix string
if includeBaseDir {
stripPrefix = filepath.Dir(srcDir)
} else {
stripPrefix = srcDir
}
return c.FileSystem.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return errors.WithStack(err)
}
// Translate the path from the src to the final destination
dest := filepath.Join(destDir, strings.TrimPrefix(path, stripPrefix))
if dest == "" {
return nil
}
if info.IsDir() {
return errors.WithStack(c.FileSystem.MkdirAll(dest, info.Mode()))
}
return c.CopyFile(path, dest)
})
}
func (c *Context) CopyFile(src, dest string) error {
info, err := c.FileSystem.Stat(src)
if err != nil {
return errors.WithStack(err)
}
data, err := c.FileSystem.ReadFile(src)
if err != nil {
return errors.WithStack(err)
}
err = c.FileSystem.WriteFile(dest, data, info.Mode())
return errors.WithStack(err)
}
// WriteMixinOutputToFile writes the provided bytes (representing a mixin output)
// to a file named by the provided filename in Porter's mixin outputs directory
func (c *Context) WriteMixinOutputToFile(filename string, bytes []byte) error {
exists, err := c.FileSystem.DirExists(MixinOutputsDir)
if err != nil {
return err
}
if !exists {
if err := c.FileSystem.MkdirAll(MixinOutputsDir, os.ModePerm); err != nil {
return errors.Wrap(err, "couldn't make output directory")
}
}
return c.FileSystem.WriteFile(filepath.Join(MixinOutputsDir, filename), bytes, os.ModePerm)
}
// SetSensitiveValues sets the sensitive values needing masking on output/err streams
func (c *Context) SetSensitiveValues(vals []string) {
if len(vals) > 0 {
out := NewCensoredWriter(c.Out)
out.SetSensitiveValues(vals)
c.Out = out
err := NewCensoredWriter(c.Err)
err.SetSensitiveValues(vals)
c.Err = err
}
}