-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexec.go
More file actions
71 lines (65 loc) · 1.92 KB
/
Copy pathexec.go
File metadata and controls
71 lines (65 loc) · 1.92 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
package cli
import (
"context"
"errors"
"fmt"
"io"
"os"
"github.com/spf13/cobra"
"codebox/internal/app"
)
func newExecCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "exec INSTANCE -- COMMAND [ARGS...]",
Short: "Execute a command inside a sandbox instance",
Long: "Execute a command inside a sandbox instance and exit with its\n" +
"status code. Place '--' before COMMAND so flags meant for the\n" +
"inner command are not consumed by codebox.",
Args: execArgs,
ValidArgsFunction: completeInstances,
RunE: func(cmd *cobra.Command, args []string) error {
return runExec(cmd.Context(),
cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr(),
args[0], args[1], args[2:], readCommonOpts(cmd))
},
}
cmd.Flags().SortFlags = false
return cmd
}
// execArgs enforces the "exec INSTANCE -- COMMAND [ARGS...]" shape. The
// '--' separator is required: it tells codebox where its own flags end
// and the inner command begins, so flags like `-la` are forwarded to
// COMMAND instead of being interpreted by codebox.
func execArgs(cmd *cobra.Command, args []string) error {
dash := cmd.ArgsLenAtDash()
switch {
case dash < 0:
return errors.New("missing '--' before COMMAND (use: exec INSTANCE -- COMMAND [ARGS...])")
case dash != 1:
return errors.New("expected exactly one INSTANCE before '--'")
case len(args) == dash:
return errors.New("missing COMMAND after '--'")
}
return nil
}
func runExec(
ctx context.Context,
stdin io.Reader,
stdout, stderr io.Writer,
instance, command string,
innerArgs []string,
opts commonOpts,
) error {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("locate home directory: %w", err)
}
return app.New(home).Exec(ctx, stdin, stdout, stderr, app.ExecRequest{
Instance: instance,
Orchestrator: opts.orchestrator,
Remote: opts.remote,
InstanceKeys: opts.instanceKeys,
Command: command,
Args: innerArgs,
})
}