|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "os/exec" |
| 8 | + "path/filepath" |
| 9 | + "sort" |
| 10 | + |
| 11 | + "github.com/spf13/cobra" |
| 12 | + |
| 13 | + "github.com/open-source-cloud/devstack/internal/config" |
| 14 | + "github.com/open-source-cloud/devstack/internal/docker" |
| 15 | + "github.com/open-source-cloud/devstack/internal/generate" |
| 16 | +) |
| 17 | + |
| 18 | +// newShellCmd wires `devstack shell <service> [--project P] [-- cmd...]` (spec 26): |
| 19 | +// an interactive exec into a running service container of the current (or |
| 20 | +// --project) project stack. It shells `docker compose exec` with all three std |
| 21 | +// streams inherited (a real -it TTY) via the InteractiveRunner and propagates the |
| 22 | +// container's exit code verbatim. With no `-- cmd` it opens a login shell |
| 23 | +// (bash→sh). A non-TTY invocation errors clearly rather than hanging. |
| 24 | +func newShellCmd(g *GlobalOpts) *cobra.Command { |
| 25 | + var project string |
| 26 | + cmd := &cobra.Command{ |
| 27 | + Use: "shell [service] [-- cmd...]", |
| 28 | + Short: "Open an interactive shell (or run a command) in a service container", |
| 29 | + Long: "shell execs into a running service container of this workspace. With one\n" + |
| 30 | + "service it defaults to it; with many, name the service (completion helps).\n" + |
| 31 | + "With no `-- cmd` it opens a login shell (bash, falling back to sh); pass\n" + |
| 32 | + "`shell <service> -- <cmd...>` to run a one-off command instead. Requires an\n" + |
| 33 | + "interactive terminal.", |
| 34 | + // Args are the service name and, after `--`, the command. Cobra puts args |
| 35 | + // after `--` in ArgsLenAtDash; we split them ourselves below. |
| 36 | + ValidArgsFunction: shellServiceCompletion(&project), |
| 37 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 38 | + // Split the positional service arg from the post-`--` command. |
| 39 | + service, command := splitShellArgs(cmd, args) |
| 40 | + |
| 41 | + cwd, err := os.Getwd() |
| 42 | + if err != nil { |
| 43 | + return err |
| 44 | + } |
| 45 | + model, err := config.Load(cwd) |
| 46 | + if err != nil { |
| 47 | + return err |
| 48 | + } |
| 49 | + proj, svc, err := resolveShellTarget(model, project, service) |
| 50 | + if err != nil { |
| 51 | + return err |
| 52 | + } |
| 53 | + |
| 54 | + // An interactive `compose exec -it` needs a real terminal on stdin; a |
| 55 | + // pipe/CI would otherwise hang or fail opaquely. Fail clearly first. |
| 56 | + if !isTerminal(os.Stdin) { |
| 57 | + return fmt.Errorf("shell needs an interactive terminal (stdin is not a TTY); " + |
| 58 | + "run it from a real terminal, or use a lifecycle hook / `docker compose exec -T` for scripted commands") |
| 59 | + } |
| 60 | + |
| 61 | + outDir := filepath.Join(model.ProjectDir(proj), generate.GenDir) |
| 62 | + composeFile := filepath.Join(outDir, generate.ComposeFile) |
| 63 | + if _, err := os.Stat(composeFile); err != nil { |
| 64 | + composeFile = "" // fall back to label-driven `compose -p <proj> exec` |
| 65 | + } |
| 66 | + run := command |
| 67 | + if len(run) == 0 { |
| 68 | + run = defaultShellCmd() |
| 69 | + } |
| 70 | + cp := docker.Compose{ |
| 71 | + Project: "devstack-" + proj, |
| 72 | + File: composeFile, |
| 73 | + Dir: outDir, |
| 74 | + Runner: docker.InteractiveRunner{}, |
| 75 | + } |
| 76 | + err = cp.Exec(cmd.Context(), svc, true, run...) |
| 77 | + if err != nil { |
| 78 | + // Propagate the container's exit code verbatim (spec 26): a non-zero |
| 79 | + // shell exit is the shell's outcome, not a devstack failure. |
| 80 | + var ee *exec.ExitError |
| 81 | + if errors.As(err, &ee) { |
| 82 | + os.Exit(ee.ExitCode()) |
| 83 | + } |
| 84 | + return err |
| 85 | + } |
| 86 | + return nil |
| 87 | + }, |
| 88 | + } |
| 89 | + cmd.Flags().StringVar(&project, "project", "", "project whose stack to exec into (default: the only project, else required)") |
| 90 | + return cmd |
| 91 | +} |
| 92 | + |
| 93 | +// splitShellArgs separates the positional service name (before `--`) from the |
| 94 | +// command to run (after `--`). Cobra records the `--` position in ArgsLenAtDash. |
| 95 | +func splitShellArgs(cmd *cobra.Command, args []string) (service string, command []string) { |
| 96 | + dash := cmd.ArgsLenAtDash() |
| 97 | + if dash < 0 { |
| 98 | + // No `--`: the first arg (if any) is the service; anything else is ignored. |
| 99 | + if len(args) > 0 { |
| 100 | + return args[0], nil |
| 101 | + } |
| 102 | + return "", nil |
| 103 | + } |
| 104 | + if dash > 0 { |
| 105 | + service = args[0] |
| 106 | + } |
| 107 | + command = args[dash:] |
| 108 | + return service, command |
| 109 | +} |
| 110 | + |
| 111 | +// resolveShellTarget resolves the project + service to exec into. project defaults |
| 112 | +// to the workspace's only project (else it is required); service defaults to the |
| 113 | +// project's only service (else it is required). Errors list the choices. |
| 114 | +func resolveShellTarget(m *config.Model, project, service string) (proj, svc string, err error) { |
| 115 | + proj = project |
| 116 | + if proj == "" { |
| 117 | + names := sortedProjectNames(m) |
| 118 | + switch len(names) { |
| 119 | + case 0: |
| 120 | + return "", "", fmt.Errorf("this workspace has no projects") |
| 121 | + case 1: |
| 122 | + proj = names[0] |
| 123 | + default: |
| 124 | + return "", "", fmt.Errorf("workspace has multiple projects (%v); pass --project", names) |
| 125 | + } |
| 126 | + } |
| 127 | + p, ok := m.Projects[proj] |
| 128 | + if !ok { |
| 129 | + return "", "", fmt.Errorf("project %q is not in this workspace", proj) |
| 130 | + } |
| 131 | + svc = service |
| 132 | + if svc == "" { |
| 133 | + names := sortedServiceNames(p.Services) |
| 134 | + switch len(names) { |
| 135 | + case 0: |
| 136 | + return "", "", fmt.Errorf("project %q has no services", proj) |
| 137 | + case 1: |
| 138 | + svc = names[0] |
| 139 | + default: |
| 140 | + return "", "", fmt.Errorf("project %q has multiple services (%v); name one", proj, names) |
| 141 | + } |
| 142 | + return proj, svc, nil |
| 143 | + } |
| 144 | + if _, ok := p.Services[svc]; !ok { |
| 145 | + return "", "", fmt.Errorf("service %q is not in project %q (have %v)", svc, proj, sortedServiceNames(p.Services)) |
| 146 | + } |
| 147 | + return proj, svc, nil |
| 148 | +} |
| 149 | + |
| 150 | +// defaultShellCmd is the login-shell command when no `-- cmd` is given: prefer |
| 151 | +// bash, fall back to sh, probed inside the container in a single exec |
| 152 | +// (Q-SHELL-DEFAULT-CMD). |
| 153 | +func defaultShellCmd() []string { |
| 154 | + return []string{"sh", "-c", "command -v bash >/dev/null 2>&1 && exec bash || exec sh"} |
| 155 | +} |
| 156 | + |
| 157 | +// shellServiceCompletion completes the service argument with the workspace's |
| 158 | +// service names (of --project, or all projects), per spec 07's ValidArgsFunction. |
| 159 | +func shellServiceCompletion(project *string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { |
| 160 | + return func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) { |
| 161 | + if len(args) > 0 { |
| 162 | + return nil, cobra.ShellCompDirectiveNoFileComp |
| 163 | + } |
| 164 | + cwd, err := os.Getwd() |
| 165 | + if err != nil { |
| 166 | + return nil, cobra.ShellCompDirectiveNoFileComp |
| 167 | + } |
| 168 | + m, err := config.Load(cwd) |
| 169 | + if err != nil { |
| 170 | + return nil, cobra.ShellCompDirectiveNoFileComp |
| 171 | + } |
| 172 | + set := map[string]bool{} |
| 173 | + for pname, p := range m.Projects { |
| 174 | + if *project != "" && pname != *project { |
| 175 | + continue |
| 176 | + } |
| 177 | + for sname := range p.Services { |
| 178 | + set[sname] = true |
| 179 | + } |
| 180 | + } |
| 181 | + out := make([]string, 0, len(set)) |
| 182 | + for s := range set { |
| 183 | + out = append(out, s) |
| 184 | + } |
| 185 | + sort.Strings(out) |
| 186 | + return out, cobra.ShellCompDirectiveNoFileComp |
| 187 | + } |
| 188 | +} |
| 189 | + |
| 190 | +// isTerminal reports whether f is a character device (a TTY), using only stdlib. |
| 191 | +func isTerminal(f *os.File) bool { |
| 192 | + if f == nil { |
| 193 | + return false |
| 194 | + } |
| 195 | + fi, err := f.Stat() |
| 196 | + if err != nil { |
| 197 | + return false |
| 198 | + } |
| 199 | + return fi.Mode()&os.ModeCharDevice != 0 |
| 200 | +} |
0 commit comments