-
Notifications
You must be signed in to change notification settings - Fork 833
/
exec.go
116 lines (93 loc) · 1.94 KB
/
exec.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
package exec
import (
"bytes"
"os"
"runtime"
"strings"
"github.com/getsops/sops/v3/logging"
"github.com/sirupsen/logrus"
)
var log *logrus.Logger
func init() {
log = logging.NewLogger("EXEC")
}
type ExecOpts struct {
Command string
Plaintext []byte
Background bool
Pristine bool
Fifo bool
User string
Filename string
}
func GetFile(dir, filename string) *os.File {
handle, err := os.CreateTemp(dir, filename)
if err != nil {
log.Fatal(err)
}
return handle
}
func ExecWithFile(opts ExecOpts) error {
if opts.User != "" {
SwitchUser(opts.User)
}
if runtime.GOOS == "windows" && opts.Fifo {
log.Warn("no fifos on windows, use --no-fifo next time")
opts.Fifo = false
}
dir, err := os.MkdirTemp("", ".sops")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
var filename string
if opts.Fifo {
// fifo handling needs to be async, even opening to write
// will block if there is no reader present
filename = GetPipe(dir, opts.Filename)
go WritePipe(filename, opts.Plaintext)
} else {
handle := GetFile(dir, opts.Filename)
handle.Write(opts.Plaintext)
handle.Close()
filename = handle.Name()
}
placeholdered := strings.Replace(opts.Command, "{}", filename, -1)
cmd := BuildCommand(placeholdered)
cmd.Env = os.Environ()
if opts.Background {
return cmd.Start()
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func ExecWithEnv(opts ExecOpts) error {
if opts.User != "" {
SwitchUser(opts.User)
}
var env []string
if !opts.Pristine {
env = os.Environ()
}
lines := bytes.Split(opts.Plaintext, []byte("\n"))
for _, line := range lines {
if len(line) == 0 {
continue
}
if line[0] == '#' {
continue
}
env = append(env, string(line))
}
cmd := BuildCommand(opts.Command)
cmd.Env = env
if opts.Background {
return cmd.Start()
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}