/
command.go
64 lines (54 loc) · 1.05 KB
/
command.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
package process
import (
"context"
"fmt"
"os/exec"
"strings"
)
type Command struct {
Name string
Args []string
}
func (c *Command) UnmarshalText(p []byte) error {
var quot *rune
fields := strings.FieldsFunc(string(p), func(r rune) bool {
switch r {
case '\'', '"':
if quot == nil {
quot = &r
} else {
quot = nil
}
return false
default:
return r == ' ' && quot == nil
}
})
for i, f := range fields {
if f[0] == f[len(f)-1] && (f[0] == '"' || f[0] == '\'') {
fields[i] = f[1 : len(f)-1]
}
}
switch len(fields) {
default:
c.Args = fields[1:]
fallthrough
case 1:
c.Name = fields[0]
case 0:
c.Name = string(p)
}
return nil
}
func (c Command) String() string {
return fmt.Sprintf("%s %s", c.Name, strings.Join(c.Args, " "))
}
func (c Command) MarshalText() ([]byte, error) {
return []byte(c.String()), nil
}
func (c Command) Exec() *exec.Cmd {
return exec.Command(c.Name, c.Args...)
}
func (c Command) ExecContext(ctx context.Context) *exec.Cmd {
return exec.CommandContext(ctx, c.Name, c.Args...)
}