-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
shell_utils.go
294 lines (252 loc) · 7.84 KB
/
shell_utils.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package exec
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"text/template"
"mvdan.cc/sh/v3/expand"
"mvdan.cc/sh/v3/interp"
"mvdan.cc/sh/v3/syntax"
"github.com/cloudposse/atmos/pkg/schema"
u "github.com/cloudposse/atmos/pkg/utils"
)
// ExecuteShellCommand prints and executes the provided command with args and flags
func ExecuteShellCommand(
cliConfig schema.CliConfiguration,
command string,
args []string,
dir string,
env []string,
dryRun bool,
redirectStdError string,
) error {
cmd := exec.Command(command, args...)
cmd.Env = append(os.Environ(), env...)
cmd.Dir = dir
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
if runtime.GOOS == "windows" && redirectStdError == "/dev/null" {
redirectStdError = "NUL"
}
if redirectStdError == "/dev/stderr" {
cmd.Stderr = os.Stderr
} else if redirectStdError == "/dev/stdout" {
cmd.Stderr = os.Stdout
} else if redirectStdError == "" {
cmd.Stderr = os.Stderr
} else {
f, err := os.OpenFile(redirectStdError, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
u.LogWarning(cliConfig, err.Error())
return err
}
defer func(f *os.File) {
err = f.Close()
if err != nil {
u.LogWarning(cliConfig, err.Error())
}
}(f)
cmd.Stderr = f
}
u.LogDebug(cliConfig, "\nExecuting command:")
u.LogDebug(cliConfig, cmd.String())
if dryRun {
return nil
}
return cmd.Run()
}
// ExecuteShell runs a shell script
func ExecuteShell(
cliConfig schema.CliConfiguration,
command string,
name string,
dir string,
env []string,
dryRun bool,
) error {
u.LogDebug(cliConfig, "\nExecuting command:")
u.LogDebug(cliConfig, command)
if dryRun {
return nil
}
return shellRunner(command, name, dir, env, os.Stdout)
}
// ExecuteShellAndReturnOutput runs a shell script and capture its standard output
func ExecuteShellAndReturnOutput(
cliConfig schema.CliConfiguration,
command string,
name string,
dir string,
env []string,
dryRun bool,
) (string, error) {
var b bytes.Buffer
u.LogDebug(cliConfig, "\nExecuting command:")
u.LogDebug(cliConfig, command)
if dryRun {
return "", nil
}
err := shellRunner(command, name, dir, env, &b)
if err != nil {
return "", err
}
return b.String(), nil
}
// shellRunner uses mvdan.cc/sh/v3's parser and interpreter to run a shell script and divert its stdout
func shellRunner(command string, name string, dir string, env []string, out io.Writer) error {
parser, err := syntax.NewParser().Parse(strings.NewReader(command), name)
if err != nil {
return err
}
environ := append(os.Environ(), env...)
listEnviron := expand.ListEnviron(environ...)
runner, err := interp.New(
interp.Dir(dir),
interp.Env(listEnviron),
interp.StdIO(os.Stdin, out, os.Stderr),
)
if err != nil {
return err
}
return runner.Run(context.TODO(), parser)
}
// execTerraformShellCommand executes `terraform shell` command by starting a new interactive shell
func execTerraformShellCommand(
cliConfig schema.CliConfiguration,
component string,
stack string,
componentEnvList []string,
varFile string,
workingDir string,
workspaceName string,
componentPath string) error {
atmosShellLvl := os.Getenv("ATMOS_SHLVL")
atmosShellVal := 1
if atmosShellLvl != "" {
val, err := strconv.Atoi(atmosShellLvl)
if err != nil {
return err
}
atmosShellVal = val + 1
}
if err := os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", atmosShellVal)); err != nil {
return err
}
// decrement the value after exiting the shell
defer func() {
atmosShellLvl := os.Getenv("ATMOS_SHLVL")
if atmosShellLvl == "" {
return
}
val, err := strconv.Atoi(atmosShellLvl)
if err != nil {
u.LogWarning(cliConfig, fmt.Sprintf("Failed to parse ATMOS_SHLVL: %v", err))
return
}
// Prevent negative values
newVal := val - 1
if newVal < 0 {
newVal = 0
}
if err := os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", newVal)); err != nil {
u.LogWarning(cliConfig, fmt.Sprintf("Failed to update ATMOS_SHLVL: %v", err))
}
}()
// Set the Terraform environment variables to reference the var file
componentEnvList = append(componentEnvList, fmt.Sprintf("TF_CLI_ARGS_plan=-var-file=%s", varFile))
componentEnvList = append(componentEnvList, fmt.Sprintf("TF_CLI_ARGS_apply=-var-file=%s", varFile))
componentEnvList = append(componentEnvList, fmt.Sprintf("TF_CLI_ARGS_refresh=-var-file=%s", varFile))
componentEnvList = append(componentEnvList, fmt.Sprintf("TF_CLI_ARGS_import=-var-file=%s", varFile))
componentEnvList = append(componentEnvList, fmt.Sprintf("TF_CLI_ARGS_destroy=-var-file=%s", varFile))
componentEnvList = append(componentEnvList, fmt.Sprintf("TF_CLI_ARGS_console=-var-file=%s", varFile))
// Set environment variables to indicate the details of the Atmos shell configuration
componentEnvList = append(componentEnvList, fmt.Sprintf("ATMOS_STACK=%s", stack))
componentEnvList = append(componentEnvList, fmt.Sprintf("ATMOS_COMPONENT=%s", component))
componentEnvList = append(componentEnvList, fmt.Sprintf("ATMOS_SHELL_WORKING_DIR=%s", workingDir))
componentEnvList = append(componentEnvList, fmt.Sprintf("ATMOS_TERRAFORM_WORKSPACE=%s", workspaceName))
hasCustomShellPrompt := cliConfig.Components.Terraform.Shell.Prompt != ""
if hasCustomShellPrompt {
// Template for the custom shell prompt
tmpl := cliConfig.Components.Terraform.Shell.Prompt
// Data for the template
data := struct {
Component string
Stack string
}{
Component: component,
Stack: stack,
}
// Parse and execute the template
var result bytes.Buffer
t := template.Must(template.New("shellPrompt").Parse(tmpl))
if err := t.Execute(&result, data); err == nil {
componentEnvList = append(componentEnvList, fmt.Sprintf("PS1=%s", result.String()))
}
}
u.LogDebug(cliConfig, "\nStarting a new interactive shell where you can execute all native Terraform commands (type 'exit' to go back)")
u.LogDebug(cliConfig, fmt.Sprintf("Component: %s\n", component))
u.LogDebug(cliConfig, fmt.Sprintf("Stack: %s\n", stack))
u.LogDebug(cliConfig, fmt.Sprintf("Working directory: %s\n", workingDir))
u.LogDebug(cliConfig, fmt.Sprintf("Terraform workspace: %s\n", workspaceName))
u.LogDebug(cliConfig, "\nSetting the ENV vars in the shell:\n")
for _, v := range componentEnvList {
u.LogDebug(cliConfig, v)
}
// Transfer stdin, stdout, and stderr to the new process and also set the target directory for the shell to start in
pa := os.ProcAttr{
Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
Dir: componentPath,
Env: append(os.Environ(), componentEnvList...),
}
// Start a new shell
var shellCommand string
if runtime.GOOS == "windows" {
shellCommand = "cmd.exe"
} else {
// If 'SHELL' ENV var is not defined, use 'bash' shell
shellCommand = os.Getenv("SHELL")
if len(shellCommand) == 0 {
bashPath, err := exec.LookPath("bash")
if err != nil {
// Try fallback to sh if bash is not available
shPath, shErr := exec.LookPath("sh")
if shErr != nil {
return fmt.Errorf("no suitable shell found: %v", shErr)
}
shellCommand = shPath
} else {
shellCommand = bashPath
}
}
shellName := filepath.Base(shellCommand)
// This means you cannot have a custom shell prompt inside Geodesic (Geodesic requires "-l").
// Perhaps we should have special detection for Geodesic?
// We could test if env var GEODESIC_SHELL is set to "true" (or set at all).
if !hasCustomShellPrompt {
shellCommand = shellCommand + " -l"
}
if shellName == "zsh" && hasCustomShellPrompt {
shellCommand = shellCommand + " -d -f -i"
}
}
u.LogDebug(cliConfig, fmt.Sprintf("Starting process: %s\n", shellCommand))
args := strings.Fields(shellCommand)
proc, err := os.StartProcess(args[0], args[1:], &pa)
if err != nil {
return err
}
// Wait until user exits the shell
state, err := proc.Wait()
if err != nil {
return err
}
u.LogDebug(cliConfig, fmt.Sprintf("Exited shell: %s\n", state.String()))
return nil
}