/
options.go
58 lines (51 loc) 路 1.16 KB
/
options.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
package excmd
import (
"os"
"path/filepath"
"strings"
)
// BuildCommand create a new Command object from given options.
func BuildCommand(name string, opts []Option) *Command {
c := &Command{Name: name, Env: os.Environ()}
for _, f := range opts {
f(c)
}
return c
}
// WithArgs sets arguments for a command.
func WithArgs(args ...string) Option {
return func(c *Command) {
c.Args = append(c.Args, args...)
}
}
// WithDir sets a working directory for a command.
func WithDir(dir string) Option {
return func(c *Command) {
c.Dir = dir
}
}
// WithPATH sets a PATH for a command.
func WithPATH(value string) Option {
return func(c *Command) {
for i := 0; i < len(c.Env); i++ {
kv := strings.Split(c.Env[i], "=")
if kv[0] == "PATH" {
c.Env[i] = "PATH=" + value + string(filepath.ListSeparator) + kv[1]
return
}
}
WithEnv("PATH", value)(c)
}
}
// WithEnv append a environment variable for a command.
func WithEnv(key, value string) Option {
return func(c *Command) {
c.Env = append(c.Env, key+"="+value)
}
}
// WithIOConnected connects i/o with a command.
func WithIOConnected() Option {
return func(c *Command) {
c.IOConnected = true
}
}