-
Notifications
You must be signed in to change notification settings - Fork 409
Expand file tree
/
Copy pathrun.go
More file actions
372 lines (317 loc) · 10.9 KB
/
run.go
File metadata and controls
372 lines (317 loc) · 10.9 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package cmd
import (
"context"
"fmt"
"io"
"os"
"strings"
"github.com/loft-sh/devspace/pkg/devspace/kubectl"
"github.com/loft-sh/devspace/pkg/devspace/pipeline/env"
"mvdan.cc/sh/v3/expand"
"github.com/loft-sh/devspace/pkg/devspace/config"
"github.com/loft-sh/devspace/pkg/devspace/config/versions/latest"
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context"
"github.com/loft-sh/devspace/pkg/devspace/hook"
"github.com/loft-sh/devspace/pkg/devspace/pipeline/engine"
"github.com/loft-sh/devspace/pkg/devspace/plugin"
"github.com/loft-sh/devspace/pkg/util/exit"
"github.com/loft-sh/devspace/pkg/util/interrupt"
"github.com/loft-sh/devspace/pkg/util/log"
"github.com/loft-sh/utils/pkg/command"
"mvdan.cc/sh/v3/interp"
"github.com/loft-sh/devspace/cmd/flags"
"github.com/loft-sh/devspace/pkg/devspace/config/loader"
"github.com/loft-sh/devspace/pkg/devspace/dependency"
"github.com/loft-sh/devspace/pkg/util/factory"
flagspkg "github.com/loft-sh/devspace/pkg/util/flags"
"github.com/loft-sh/devspace/pkg/util/message"
"github.com/sirupsen/logrus"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
// RunCmd holds the run cmd flags
type RunCmd struct {
*flags.GlobalFlags
Dependency string
Stdout io.Writer
Stderr io.Writer
}
// NewRunCmd creates a new run command
func NewRunCmd(f factory.Factory, globalFlags *flags.GlobalFlags, rawConfig *RawConfig) *cobra.Command {
cmd := &RunCmd{
GlobalFlags: globalFlags,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
runCmd := &cobra.Command{
Use: "run",
DisableFlagParsing: true,
Short: "Executes a predefined command",
Long: `
#######################################################
##################### devspace run ####################
#######################################################
Executes a predefined command from the devspace.yaml
Examples:
devspace run mycommand --myarg 123
devspace run mycommand2 1 2 3
devspace --dependency my-dependency run any-command --any-command-flag
#######################################################
`,
Args: cobra.MinimumNArgs(1),
}
runCmd.RunE = func(cobraCmd *cobra.Command, _ []string) error {
args, err := ParseArgs(runCmd, cmd.GlobalFlags, f.GetLog())
if err != nil {
return err
}
plugin.SetPluginCommand(cobraCmd, args)
return cmd.RunRun(f, args)
}
if rawConfig != nil && rawConfig.Config != nil {
for _, cmd := range rawConfig.Config.Commands {
runCmd.AddCommand(NewSpecificRunCommand(cmd))
}
}
runCmd.Flags().StringVar(&cmd.Dependency, "dependency", "", "Run a command from a specific dependency")
return runCmd
}
// RunRun executes the functionality "devspace run"
func (cmd *RunCmd) RunRun(f factory.Factory, args []string) error {
if len(args) == 0 {
return fmt.Errorf("run requires at least one argument")
}
// check if dependency command
commandSplitted := strings.Split(args[0], ".")
if len(commandSplitted) > 1 {
cmd.Dependency = strings.Join(commandSplitted[:len(commandSplitted)-1], ".")
args[0] = commandSplitted[len(commandSplitted)-1]
}
// Execute plugin hook
err := hook.ExecuteHooks(nil, nil, "run")
if err != nil {
return err
}
// Set config root
configOptions := cmd.ToConfigOptions()
configLoader, err := f.NewConfigLoader(cmd.ConfigPath)
if err != nil {
return err
}
configExists, err := configLoader.SetDevSpaceRoot(f.GetLog())
if err != nil {
return err
} else if !configExists {
return errors.New(message.ConfigNotFound)
}
// load the config
ctx, err := cmd.LoadCommandsConfig(f, configLoader, configOptions, f.GetLog())
if err != nil {
return err
}
// check if we should execute a dependency command
if cmd.Dependency != "" {
config, err := configLoader.LoadWithCache(context.Background(), ctx.Config().LocalCache(), nil, configOptions, f.GetLog())
if err != nil {
return err
}
ctx = ctx.WithConfig(config)
dependencies, err := f.NewDependencyManager(ctx, configOptions).ResolveAll(ctx, dependency.ResolveOptions{})
if err != nil {
return err
}
dep := dependency.GetDependencyByPath(dependencies, cmd.Dependency)
if dep == nil {
return fmt.Errorf("couldn't find dependency %s", cmd.Dependency)
}
ctx = ctx.AsDependency(dep)
commandConfig, err := findCommand(ctx.Config(), args[0])
if err != nil {
return err
}
return executeCommandWithAfter(ctx.Context(), commandConfig, args[1:], ctx.Config().Variables(), ctx.WorkingDir(), cmd.Stdout, cmd.Stderr, os.Stdin, ctx.Log())
}
commandConfig, err := findCommand(ctx.Config(), args[0])
if err != nil {
return err
}
return executeCommandWithAfter(ctx.Context(), commandConfig, args[1:], ctx.Config().Variables(), ctx.WorkingDir(), cmd.Stdout, cmd.Stderr, os.Stdin, ctx.Log())
}
func findCommand(config config.Config, name string) (*latest.CommandConfig, error) {
// Find command
if config.Config().Commands == nil || config.Config().Commands[name] == nil {
return nil, errors.Errorf("couldn't find command '%s' in devspace config", name)
}
return config.Config().Commands[name], nil
}
func executeCommandWithAfter(ctx context.Context, command *latest.CommandConfig, args []string, variables map[string]interface{}, dir string, stdout io.Writer, stderr io.Writer, stdin io.Reader, log log.Logger) error {
originalErr := interrupt.Global.Run(func() error {
return ExecuteCommand(ctx, command, variables, args, dir, stdout, stderr, stdin)
}, func() {
if command.After != "" {
vars := variables
vars["COMMAND_INTERRUPT"] = "true"
err := executeShellCommand(ctx, command.After, vars, args, dir, stdout, stderr, stdin)
if err != nil {
log.Errorf("error executing after command: %v", err)
}
}
})
if command.After != "" {
vars := variables
if originalErr != nil {
vars["COMMAND_ERROR"] = originalErr.Error()
}
err := executeShellCommand(ctx, command.After, vars, args, dir, stdout, stderr, stdin)
if err != nil {
return errors.Wrap(err, "error executing after command")
}
}
return originalErr
}
func ParseArgs(cobraCmd *cobra.Command, globalFlags *flags.GlobalFlags, log log.Logger) ([]string, error) {
index := -1
for i, v := range os.Args {
if v == cobraCmd.Use {
index = i + 1
break
}
}
if index == -1 {
return nil, fmt.Errorf("error parsing command: couldn't find %s in command: %v", cobraCmd.Use, os.Args)
}
// check if is help command
osArgs := os.Args[:index]
if len(os.Args) == index+1 && (os.Args[index] == "-h" || os.Args[index] == "--help") {
return nil, cobraCmd.Help()
}
// enable flag parsing
cobraCmd.DisableFlagParsing = false
// apply extra flags
_, err := flagspkg.ApplyExtraFlags(cobraCmd, osArgs, true)
if err != nil {
return nil, err
}
if globalFlags.Silent {
log.SetLevel(logrus.FatalLevel)
} else if globalFlags.Debug {
log.SetLevel(logrus.DebugLevel)
}
args := os.Args[index:]
return args, nil
}
// LoadCommandsConfig loads the commands config
func (cmd *RunCmd) LoadCommandsConfig(f factory.Factory, configLoader loader.ConfigLoader, configOptions *loader.ConfigOptions, log log.Logger) (devspacecontext.Context, error) {
// load generated
localCache, err := configLoader.LoadLocalCache()
if err != nil {
return nil, err
}
// try to load client
client, err := f.NewKubeClientFromContext(cmd.KubeContext, cmd.Namespace)
if err != nil {
log.Debugf("Unable to create new kubectl client: %v", err)
client = nil
}
// verify client connectivity / authn / authz
if client != nil {
// If the current kube context or namespace is different than old,
// show warnings and reset kube client if necessary
client, err = kubectl.CheckKubeContext(client, localCache, cmd.NoWarn, cmd.SwitchContext, false, log)
if err != nil {
log.Debugf("Unable to verify kube context %v", err)
client = nil
}
}
// Parse commands
commandsInterface, err := configLoader.LoadWithParser(context.Background(), localCache, client, loader.NewCommandsParser(), configOptions, log)
if err != nil {
return nil, err
}
// create context
return devspacecontext.NewContext(context.Background(), commandsInterface.Variables(), log).
WithKubeClient(client).
WithConfig(commandsInterface), nil
}
func executeShellCommand(ctx context.Context, shellCommand string, variables map[string]interface{}, args []string, dir string, stdout io.Writer, stderr io.Writer, stdin io.Reader) error {
extraEnv := map[string]string{}
for k, v := range variables {
extraEnv[k] = fmt.Sprintf("%v", v)
}
// execute the command in a shell
err := engine.ExecuteSimpleShellCommand(ctx, dir, env.NewVariableEnvProvider(expand.ListEnviron(os.Environ()...), extraEnv), stdout, stderr, stdin, shellCommand, args...)
if err != nil {
if status, ok := interp.IsExitStatus(err); ok {
return &exit.ReturnCodeError{
ExitCode: int(status),
}
}
return errors.Wrap(err, "execute command")
}
return nil
}
// ExecuteCommand executes a command from the config
func ExecuteCommand(ctx context.Context, cmd *latest.CommandConfig, variables map[string]interface{}, args []string, dir string, stdout io.Writer, stderr io.Writer, stdin io.Reader) error {
shellCommand := strings.TrimSpace(cmd.Command)
shellArgs := cmd.Args
appendArgs := cmd.AppendArgs
extraEnv := map[string]string{}
for k, v := range variables {
extraEnv[k] = fmt.Sprintf("%v", v)
}
if shellArgs == nil {
if appendArgs {
// Append args to shell command
for _, arg := range args {
arg = strings.ReplaceAll(arg, "'", "'\"'\"'")
shellCommand += " '" + arg + "'"
}
}
// execute the command in a shell
err := engine.ExecuteSimpleShellCommand(ctx, dir, env.NewVariableEnvProvider(expand.ListEnviron(os.Environ()...), extraEnv), stdout, stderr, stdin, shellCommand, args...)
if err != nil {
if status, ok := interp.IsExitStatus(err); ok {
return &exit.ReturnCodeError{
ExitCode: int(status),
}
}
return errors.Wrap(err, "execute command")
}
return nil
}
shellArgs = append(shellArgs, args...)
return command.Command(ctx, dir, env.NewVariableEnvProvider(expand.ListEnviron(os.Environ()...), extraEnv), stdout, stderr, stdin, shellCommand, shellArgs...)
}
// RunCommandCmd holds the cmd flags of a run command
type RunCommandCmd struct {
*flags.GlobalFlags
Command *latest.CommandConfig
Variables map[string]interface{}
Stdout io.Writer
Stderr io.Writer
}
// NewSpecificRunCommand creates a new run command
func NewSpecificRunCommand(command *latest.CommandConfig) *cobra.Command {
description := command.Description
longDescription := command.Description
if description == "" {
description = "Runs command: " + command.Name
longDescription = description
}
if len(description) > 64 {
if len(description) > 64 {
description = description[:61] + "..."
}
}
runCmd := &cobra.Command{
Use: command.Name,
Short: description,
Long: longDescription,
Args: cobra.ArbitraryArgs,
RunE: func(cobraCmd *cobra.Command, originalArgs []string) error {
return cobraCmd.Parent().RunE(cobraCmd, originalArgs)
},
}
runCmd.DisableFlagParsing = true
return runCmd
}