forked from getsops/sops
-
Notifications
You must be signed in to change notification settings - Fork 1
/
exec.go
115 lines (92 loc) · 2 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
package exec
import (
"fmt"
"io/ioutil"
"os"
"runtime"
"strings"
"go.mozilla.org/sops/v3/logging"
"go.mozilla.org/sops/v3/stores/dotenv"
"github.com/sirupsen/logrus"
)
var log *logrus.Logger
func init() {
log = logging.NewLogger("EXEC")
}
type ExecOpts struct {
Command string
Plaintext []byte
Background bool
Fifo bool
User string
Filename string
}
func GetFile(dir, filename string) *os.File {
handle, err := ioutil.TempFile(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 := ioutil.TempDir("", ".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)
}
env := os.Environ()
store := dotenv.Store{}
branches, err := store.LoadPlainFile(opts.Plaintext)
if err != nil {
log.Fatal(err)
}
for _, item := range branches[0] {
if item.Value == nil {
continue
}
env = append(env, fmt.Sprintf("%s=%s", item.Key, item.Value))
}
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()
}