-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
70 lines (60 loc) · 1.73 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
package script
import (
"io"
"os"
isatty "github.com/mattn/go-isatty"
"github.com/spf13/afero"
)
// Context for script operations. A Context includes the working directory and provides
// access the buffers and results of commands run in the Context.
// Using different Contexts it is possible to handle multiple separate environments.
type Context struct {
workingDir string
env map[string]string
fs afero.Fs
stdout io.Writer
stderr io.Writer
stdin io.Reader
isTTY bool
}
// NewContext returns a pointer to a new Context.
func NewContext() (context *Context) {
// initialize Context
context = &Context{
env: make(map[string]string, 0),
fs: afero.NewOsFs(),
stdout: os.Stdout,
stderr: os.Stderr,
stdin: os.Stdin,
}
cwd, err := os.Getwd()
if err == nil {
context.SetWorkingDir(cwd)
}
return
}
// SetWorkingDir changes the current working dir
func (c *Context) SetWorkingDir(workingDir string) {
c.workingDir = workingDir
}
// WorkingDir retrieves the current working dir
func (c *Context) WorkingDir() string {
return c.workingDir
}
// SetWorkingDirTemp changes the current working dir to a temporary directory, returning an error in case something went wrong
func (c *Context) SetWorkingDirTemp() error {
dir, err := c.TempDir()
if err != nil {
return err
}
c.SetWorkingDir(dir)
return nil
}
// IsUserRoot checks if a user is root priviledged (Linux and Mac only? Windows?)
func (c *Context) IsUserRoot() bool {
return os.Geteuid() == 0
}
// IsTerminal returns if this program is run inside an interactive terminal
func (c Context) IsTerminal() bool {
return !(os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())))
}