diff --git a/cmd/compose/bridge.go b/cmd/compose/bridge.go index be93f3923d7..5879a104832 100644 --- a/cmd/compose/bridge.go +++ b/cmd/compose/bridge.go @@ -83,7 +83,7 @@ func convertCommand(p *ProjectOptions, dockerCli command.Cli) *cobra.Command { PreRunE: rejectDryRun, RunE: Adapt(func(ctx context.Context, args []string) error { if assumeYes { - convertOpts.Confirm = func(string, bool) (bool, error) { return true, nil } + convertOpts.Confirm = func(context.Context, string, bool) (bool, error) { return true, nil } } else { convertOpts.Confirm = prompt.NewPrompt(dockerCli.In(), dockerCli.Out()).Confirm } diff --git a/cmd/compose/options.go b/cmd/compose/options.go index 2d31cd4556c..b17613ca841 100644 --- a/cmd/compose/options.go +++ b/cmd/compose/options.go @@ -126,7 +126,7 @@ func checksForRemoteStack(ctx context.Context, dockerCli command.Cli, project *t return nil } if metrics, ok := ctx.Value(tracing.MetricsKey{}).(tracing.Metrics); ok && metrics.CountIncludesRemote > 0 { - if err := confirmRemoteIncludes(dockerCli, options, assumeYes); err != nil { + if err := confirmRemoteIncludes(ctx, dockerCli, options, assumeYes); err != nil { return err } } @@ -164,7 +164,7 @@ func promptForInterpolatedVariables(ctx context.Context, dockerCli command.Cli, // Prompt for confirmation userInput := prompt.NewPrompt(dockerCli.In(), dockerCli.Out()) msg := "\nDo you want to proceed with these variables?" - confirmed, err := userInput.Confirm(msg, true) + confirmed, err := userInput.Confirm(ctx, msg, true) if err != nil { return err } @@ -261,7 +261,7 @@ func displayLocationRemoteStack(dockerCli command.Cli, project *types.Project, o } } -func confirmRemoteIncludes(dockerCli command.Cli, options buildOptions, assumeYes bool) error { +func confirmRemoteIncludes(ctx context.Context, dockerCli command.Cli, options buildOptions, assumeYes bool) error { if assumeYes { return nil } @@ -288,7 +288,7 @@ func confirmRemoteIncludes(dockerCli command.Cli, options buildOptions, assumeYe _, _ = fmt.Fprintln(dockerCli.Out(), "\nRemote includes could potentially be malicious. Make sure you trust the source.") msg := "Do you want to continue?" - confirmed, err := prompt.NewPrompt(dockerCli.In(), dockerCli.Out()).Confirm(msg, false) + confirmed, err := prompt.NewPrompt(dockerCli.In(), dockerCli.Out()).Confirm(ctx, msg, false) if err != nil { return err } diff --git a/cmd/compose/options_test.go b/cmd/compose/options_test.go index 07df9128545..b193414237c 100644 --- a/cmd/compose/options_test.go +++ b/cmd/compose/options_test.go @@ -433,7 +433,7 @@ func TestConfirmRemoteIncludes(t *testing.T) { cli.EXPECT().In().Return(streams.NewIn(inbuf)).AnyTimes() } - err := confirmRemoteIncludes(cli, tt.opts, tt.assumeYes) + err := confirmRemoteIncludes(t.Context(), cli, tt.opts, tt.assumeYes) if tt.wantErr { assert.Error(t, err, tt.errMessage) diff --git a/cmd/prompt/prompt.go b/cmd/prompt/prompt.go index e7d75cc7946..b58f80c717f 100644 --- a/cmd/prompt/prompt.go +++ b/cmd/prompt/prompt.go @@ -18,7 +18,7 @@ package prompt import ( "bufio" - "errors" + "context" "fmt" "io" "strings" @@ -26,16 +26,19 @@ import ( "github.com/docker/cli/cli/streams" + "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) //go:generate mockgen -destination=./prompt_mock.go -self_package "github.com/docker/compose/v5/pkg/prompt" -package=prompt . UI -var errInterrupt = errors.New("interrupt") +// errInterrupt is a Ctrl+C typed at the prompt. It is a cancellation, like the +// SIGINT it replaces while the terminal is in raw mode. +var errInterrupt = fmt.Errorf("interrupt: %w", api.ErrCanceled) // UI - prompt user input type UI interface { - Confirm(message string, defaultValue bool) (bool, error) + Confirm(ctx context.Context, message string, defaultValue bool) (bool, error) } func NewPrompt(stdin *streams.In, stdout *streams.Out) UI { @@ -52,8 +55,9 @@ type User struct { reader *bufio.Reader } -// Confirm asks for yes or no input -func (u User) Confirm(message string, defaultValue bool) (bool, error) { +// Confirm asks for yes or no input. It returns ctx.Err() as soon as ctx is +// canceled, restoring the terminal on the way out. +func (u User) Confirm(ctx context.Context, message string, defaultValue bool) (bool, error) { if err := u.stdin.SetRawTerminal(); err != nil { return false, err } @@ -67,7 +71,9 @@ func (u User) Confirm(message string, defaultValue bool) (bool, error) { for { _, _ = fmt.Fprint(u.stdout, message+prompt) - answer, err := readLine(u.reader, u.stdout) + answer, err := readOrCancel(ctx, u.stdout, "\r\n", func() (string, error) { + return readLine(u.reader, u.stdout) + }) if err != nil { return false, err } @@ -126,10 +132,40 @@ type Pipe struct { stdin io.Reader } -// Confirm asks for yes or no input -func (u Pipe) Confirm(message string, defaultValue bool) (bool, error) { +// Confirm asks for yes or no input. It returns ctx.Err() as soon as ctx is canceled. +func (u Pipe) Confirm(ctx context.Context, message string, defaultValue bool) (bool, error) { _, _ = fmt.Fprint(u.stdout, message) - var answer string - _, _ = fmt.Fscanln(u.stdin, &answer) + answer, err := readOrCancel(ctx, u.stdout, "\n", func() (string, error) { + var answer string + _, _ = fmt.Fscanln(u.stdin, &answer) + return answer, nil + }) + if err != nil { + return false, err + } return utils.StringToBool(answer), nil } + +// readOrCancel runs read, which blocks on stdin and cannot be interrupted, and +// stops waiting for it as soon as ctx is canceled, ending the prompt line with +// newline. The abandoned read keeps running until stdin delivers something or +// the process exits. +func readOrCancel(ctx context.Context, out io.Writer, newline string, read func() (string, error)) (string, error) { + type result struct { + answer string + err error + } + done := make(chan result, 1) + go func() { + answer, err := read() + done <- result{answer, err} + }() + + select { + case <-ctx.Done(): + _, _ = fmt.Fprint(out, newline) + return "", ctx.Err() + case r := <-done: + return r.answer, r.err + } +} diff --git a/cmd/prompt/prompt_mock.go b/cmd/prompt/prompt_mock.go index 83b0ff1189b..3fcc3afe018 100644 --- a/cmd/prompt/prompt_mock.go +++ b/cmd/prompt/prompt_mock.go @@ -5,6 +5,7 @@ package prompt import ( + context "context" reflect "reflect" gomock "go.uber.org/mock/gomock" @@ -34,18 +35,18 @@ func (m *MockUI) EXPECT() *MockUIMockRecorder { } // Confirm mocks base method -func (m *MockUI) Confirm(arg0 string, arg1 bool) (bool, error) { +func (m *MockUI) Confirm(arg0 context.Context, arg1 string, arg2 bool) (bool, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Confirm", arg0, arg1) + ret := m.ctrl.Call(m, "Confirm", arg0, arg1, arg2) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(error) return ret0, ret1 } // Confirm indicates an expected call of Confirm -func (mr *MockUIMockRecorder) Confirm(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockUIMockRecorder) Confirm(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Confirm", reflect.TypeOf((*MockUI)(nil).Confirm), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Confirm", reflect.TypeOf((*MockUI)(nil).Confirm), arg0, arg1, arg2) } // Input mocks base method diff --git a/cmd/prompt/prompt_test.go b/cmd/prompt/prompt_test.go index 1072d5e9613..b94acefbb72 100644 --- a/cmd/prompt/prompt_test.go +++ b/cmd/prompt/prompt_test.go @@ -19,6 +19,7 @@ package prompt import ( "bufio" "bytes" + "context" "io" "os" "strings" @@ -28,6 +29,8 @@ import ( "github.com/creack/pty" "github.com/docker/cli/cli/streams" "gotest.tools/v3/assert" + + "github.com/docker/compose/v5/pkg/api" ) // TestPipeConfirmSequential verifies consecutive piped confirmations consume @@ -39,15 +42,68 @@ func TestPipeConfirmSequential(t *testing.T) { stdout: &stdout, } - got, err := pipe.Confirm("first? ", false) + got, err := pipe.Confirm(t.Context(), "first? ", false) assert.NilError(t, err) assert.Assert(t, got) - got, err = pipe.Confirm("second? ", true) + got, err = pipe.Confirm(t.Context(), "second? ", true) assert.NilError(t, err) assert.Assert(t, !got) } +// TestPipeConfirmCancel verifies that a piped confirmation stops waiting for +// input as soon as its context is canceled. +func TestPipeConfirmCancel(t *testing.T) { + stdin, writer := io.Pipe() // never written to: Confirm would block forever + t.Cleanup(func() { _ = writer.Close() }) + pipe := Pipe{stdin: stdin, stdout: io.Discard} + + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan error, 1) + go func() { + _, err := pipe.Confirm(ctx, "continue? ", false) + done <- err + }() + + cancel() + + select { + case err := <-done: + assert.ErrorIs(t, err, context.Canceled) + case <-time.After(time.Second): + t.Fatal("timed out waiting for the prompt to return after cancellation") + } +} + +// TestUserConfirmCancel verifies that an interactive confirmation stops +// waiting for input when its context is canceled, and gives the terminal back +// in cooked mode. +func TestUserConfirmCancel(t *testing.T) { + ptmx, user := newTestUser(t) + + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan error, 1) + go func() { + _, err := user.Confirm(ctx, "Continue?", false) + done <- err + }() + + readUntil(t, ptmx, "Continue? [y/N]: ") + cancel() + + select { + case err := <-done: + assert.ErrorIs(t, err, context.Canceled) + case <-time.After(time.Second): + t.Fatal("timed out waiting for the prompt to return after cancellation") + } + + // A terminal back in cooked mode echoes what it receives; in raw mode it doesn't. + _, err := ptmx.Write([]byte("z")) + assert.NilError(t, err) + readUntil(t, ptmx, "z") +} + // TestUserConfirm verifies that an interactive terminal confirmation returns // the expected answer and retries invalid input. func TestUserConfirm(t *testing.T) { @@ -59,7 +115,7 @@ func TestUserConfirm(t *testing.T) { }, 1) go func() { - answer, err := user.Confirm("Continue?", false) + answer, err := user.Confirm(t.Context(), "Continue?", false) done <- struct { answer bool err error @@ -96,7 +152,7 @@ func TestUserConfirmDefault(t *testing.T) { }, 1) go func() { - answer, err := user.Confirm("Continue?", true) + answer, err := user.Confirm(t.Context(), "Continue?", true) done <- struct { answer bool err error @@ -127,7 +183,7 @@ func TestUserConfirmSequential(t *testing.T) { err error }, 1) go func() { - first, err := user.Confirm("first?", false) + first, err := user.Confirm(t.Context(), "first?", false) if err != nil { done <- struct { first, second bool @@ -135,7 +191,7 @@ func TestUserConfirmSequential(t *testing.T) { }{err: err} return } - second, err := user.Confirm("second?", true) + second, err := user.Confirm(t.Context(), "second?", true) done <- struct { first, second bool err error @@ -169,6 +225,8 @@ func TestReadLineInterrupt(t *testing.T) { ) assert.ErrorIs(t, err, errInterrupt) + // AdaptCmd turns a canceled command into exit code 130, as for SIGINT. + assert.Assert(t, api.IsErrCanceled(err)) assert.Equal(t, stdout.String(), "\r\n") } diff --git a/internal/e2e/prompt_cancel_test.go b/internal/e2e/prompt_cancel_test.go new file mode 100644 index 00000000000..2afcad534c0 --- /dev/null +++ b/internal/e2e/prompt_cancel_test.go @@ -0,0 +1,56 @@ +//go:build e2e + +/* + Copyright 2026 Docker Compose CLI authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package e2e + +import ( + "syscall" + "testing" + "time" +) + +// Regression tests for a captain-reported bug: a command waiting at a +// confirmation prompt ignored SIGTERM until its standard input closed, so +// `timeout 5 docker compose rm` returned after 30s in the report, while the +// engine CLI's own prompts stopped at once. + +func TestRmPromptTerminated(t *testing.T) { + NewScenario(t, "rm must stop waiting for its confirmation when terminated, and remove nothing"). + Step("up leaves a stopped container for rm to propose", + ComposeCmd("up", "-d"), + Eventually(ServiceState("app", "exited"), 10*time.Second)). + Step("rm terminated at its prompt exits as a canceled command", + ComposeCmd("rm").SignaledOnOutput(syscall.SIGTERM, "Going to remove").Within(10*time.Second).MayFail(), + ExitCode(130), + NotRecreated("app"), + ServiceState("app", "exited")) +} + +func TestUpVolumeRecreatePromptTerminated(t *testing.T) { + s := NewScenario(t, "up must stop waiting for the confirmation to recreate a volume when terminated, and recreate nothing") + + s.Step("up creates the volume and the service", + ComposeCmd("up", "-d"), + Eventually(ServiceState("app", "running"), 10*time.Second)). + FromFile("diverged.yaml"). + Step("up with a diverged volume, terminated at its prompt, exits as a canceled command", + ComposeCmd("up", "-d").SignaledOnOutput(syscall.SIGTERM, "data will be lost").Within(10*time.Second).MayFail(), + ExitCode(130), + NotRecreated("app"), + VolumeExists(s.Project()+"_data")) +} diff --git a/internal/e2e/scenario.go b/internal/e2e/scenario.go index af57adc0c94..7ba770300fa 100644 --- a/internal/e2e/scenario.go +++ b/internal/e2e/scenario.go @@ -31,6 +31,7 @@ import ( "github.com/moby/moby/client" "github.com/moby/moby/client/pkg/versions" "gotest.tools/v3/icmd" + "gotest.tools/v3/poll" ) // Scenario is a thin declarative layer over the e2e CLI helpers: a test reads @@ -329,7 +330,7 @@ func (s *Scenario) Step(name string, action Action, checks ...Check) *Scenario { t.Logf("step: %s — %s", name, strings.Join(cmd.Command, " ")) begin := time.Now() - res := icmd.RunCmd(cmd) + res := s.run(action, cmd) rec := stepRecord{name: name, command: strings.Join(cmd.Command, " "), result: res, duration: time.Since(begin)} s.steps = append(s.steps, rec) @@ -352,6 +353,45 @@ func (s *Scenario) Step(name string, action Action, checks ...Check) *Scenario { return s } +// run executes the command and waits for it. An action signaled on output +// gets an open standard input — a prompt waiting on it never sees EOF — and +// its signal as soon as the output shows the expected text. +func (s *Scenario) run(action Action, cmd icmd.Cmd) *icmd.Result { + s.t.Helper() + if action.signalOn == "" { + return icmd.RunCmd(cmd) + } + if action.timeout == 0 { + s.t.Fatal("SignaledOnOutput requires Within: a command that never prints the expected text would hang") + } + // held is the write end, kept open so the command never sees EOF on stdin. + stdin, held, err := os.Pipe() + if err != nil { + s.t.Fatal(err) + } + defer func() { + _ = stdin.Close() + _ = held.Close() + }() + cmd.Stdin = stdin + + res := icmd.StartCmd(cmd) + if res.Error != nil { + return res + } + // poll.WaitOn fails the test without returning: signal the command then + // too, as the docker CLI relays it to the compose plugin it runs. + s.t.Cleanup(func() { _ = res.Cmd.Process.Signal(action.signal) }) + poll.WaitOn(s.t, func(poll.LogT) poll.Result { + if strings.Contains(res.Combined(), action.signalOn) { + return poll.Success() + } + return poll.Continue("waiting for %q in the output", action.signalOn) + }, poll.WithDelay(20*time.Millisecond), poll.WithTimeout(action.timeout)) + _ = res.Cmd.Process.Signal(action.signal) + return icmd.WaitOnCmd(action.timeout, res) +} + // command materializes an action into a runnable command, layering scenario // env then action env on top of the CLI environment. func (s *Scenario) command(action Action) icmd.Cmd { @@ -608,6 +648,9 @@ type Action struct { stdin string mayFail bool timeout time.Duration + + signal os.Signal + signalOn string } // ComposeCmd runs `docker compose ` against the scenario's compose @@ -659,6 +702,16 @@ func (a Action) Within(timeout time.Duration) Action { return a } +// SignaledOnOutput holds the command's standard input open and sends it sig as +// soon as its output contains text, e.g. to terminate an interactive prompt the +// way `timeout` does. It requires Within, which bounds a command that ignores +// the signal. +func (a Action) SignaledOnOutput(sig os.Signal, text string) Action { + a.signal = sig + a.signalOn = text + return a +} + // ---------- Requirements ---------- // Requirement checks an environment prerequisite; it returns a non-empty diff --git a/internal/e2e/testdata/TestRmPromptTerminated/compose.yaml b/internal/e2e/testdata/TestRmPromptTerminated/compose.yaml new file mode 100644 index 00000000000..eabf41c8a15 --- /dev/null +++ b/internal/e2e/testdata/TestRmPromptTerminated/compose.yaml @@ -0,0 +1,4 @@ +services: + app: + image: alpine + command: "true" diff --git a/internal/e2e/testdata/TestUpVolumeRecreatePromptTerminated/compose.yaml b/internal/e2e/testdata/TestUpVolumeRecreatePromptTerminated/compose.yaml new file mode 100644 index 00000000000..0e6afd9d356 --- /dev/null +++ b/internal/e2e/testdata/TestUpVolumeRecreatePromptTerminated/compose.yaml @@ -0,0 +1,11 @@ +services: + app: + image: alpine + command: sleep infinity + volumes: + - data:/data + +volumes: + data: + labels: + version: "1" diff --git a/internal/e2e/testdata/TestUpVolumeRecreatePromptTerminated/diverged.yaml b/internal/e2e/testdata/TestUpVolumeRecreatePromptTerminated/diverged.yaml new file mode 100644 index 00000000000..9640d4016f7 --- /dev/null +++ b/internal/e2e/testdata/TestUpVolumeRecreatePromptTerminated/diverged.yaml @@ -0,0 +1,11 @@ +services: + app: + image: alpine + command: sleep infinity + volumes: + - data:/data + +volumes: + data: + labels: + version: "2" diff --git a/internal/publish/publish.go b/internal/publish/publish.go index 113eced36aa..5468cf12421 100644 --- a/internal/publish/publish.go +++ b/internal/publish/publish.go @@ -65,7 +65,7 @@ type Backend interface { // DryRun tells whether the operation only reports what it would do. DryRun() bool // Prompt asks the user a yes/no question. - Prompt(message string, defaultValue bool) (bool, error) + Prompt(ctx context.Context, message string, defaultValue bool) (bool, error) // Push pushes the images built for the project, as part of the operation // already running: it opens no progress bracket of its own. Push(ctx context.Context, project *types.Project, options api.PushOptions) error @@ -401,7 +401,7 @@ func (s *Service) preChecks(ctx context.Context, project *types.Project, options } } b.WriteString("Are you ok to publish these bind mount declarations?") - confirm, err := s.backend.Prompt(b.String(), false) + confirm, err := s.backend.Prompt(ctx, b.String(), false) if err != nil || !confirm { return false, err } @@ -420,7 +420,7 @@ func (s *Service) preChecks(ctx context.Context, project *types.Project, options fmt.Fprintf(&b, "%q: %s\n", val.Key, val.Value) } b.WriteString("Are you ok to publish these sensitive data?") - confirm, err := s.backend.Prompt(b.String(), false) + confirm, err := s.backend.Prompt(ctx, b.String(), false) if err != nil || !confirm { return false, err } @@ -495,13 +495,13 @@ func (s *Service) checkEnvironmentVariables(ctx context.Context, project *types. } if !options.WithEnvironment && findings.hasEnvFinding() { - if err := s.confirmOrCancel(buildEnvPromptMessage(findings.services)); err != nil { + if err := s.confirmOrCancel(ctx, buildEnvPromptMessage(findings.services)); err != nil { return err } } if len(findings.configsLiteralContent) > 0 { - if err := s.confirmOrCancel(buildConfigContentPromptMessage(findings.configsLiteralContent)); err != nil { + if err := s.confirmOrCancel(ctx, buildConfigContentPromptMessage(findings.configsLiteralContent)); err != nil { return err } } @@ -513,8 +513,8 @@ func (s *Service) checkEnvironmentVariables(ctx context.Context, project *types. // - the prompt's error verbatim, if it failed; // - api.ErrCanceled if the user declined; // - nil if the user accepted. -func (s *Service) confirmOrCancel(message string) error { - confirm, err := s.backend.Prompt(message, false) +func (s *Service) confirmOrCancel(ctx context.Context, message string) error { + confirm, err := s.backend.Prompt(ctx, message, false) if err != nil { return err } diff --git a/internal/publish/publish_test.go b/internal/publish/publish_test.go index 246a6d88264..e9cbf32e851 100644 --- a/internal/publish/publish_test.go +++ b/internal/publish/publish_test.go @@ -49,7 +49,7 @@ import ( // the given function, serves its API client and auth, and ignores the events. type fakeBackend struct { apiClient client.APIClient - prompt func(message string, defaultValue bool) (bool, error) + prompt func(ctx context.Context, message string, defaultValue bool) (bool, error) auth registry.AuthProvider } @@ -59,8 +59,8 @@ func (f *fakeBackend) AuthProvider() registry.AuthProvider { return f. func (f *fakeBackend) Events() api.EventProcessor { return progress.Noop{} } func (f *fakeBackend) DryRun() bool { return false } -func (f *fakeBackend) Prompt(message string, defaultValue bool) (bool, error) { - return f.prompt(message, defaultValue) +func (f *fakeBackend) Prompt(ctx context.Context, message string, defaultValue bool) (bool, error) { + return f.prompt(ctx, message, defaultValue) } func (f *fakeBackend) Push(context.Context, *types.Project, api.PushOptions) error { @@ -158,7 +158,7 @@ func Test_preChecks_sensitive_data_detected_decline(t *testing.T) { }, } - declined := func(message string, defaultValue bool) (bool, error) { + declined := func(_ context.Context, message string, defaultValue bool) (bool, error) { return false, nil } svc := &Service{backend: &fakeBackend{prompt: declined}} @@ -630,7 +630,7 @@ type fakePrompt struct { prompts []string // captured prompt messages } -func (p *fakePrompt) handler(message string, _ bool) (bool, error) { +func (p *fakePrompt) handler(_ context.Context, message string, _ bool) (bool, error) { p.prompts = append(p.prompts, message) if len(p.answers) == 0 { return true, nil @@ -772,7 +772,7 @@ func Test_publish_decline_returns_ErrCanceled(t *testing.T) { }, } - declined := func(message string, defaultValue bool) (bool, error) { + declined := func(_ context.Context, message string, defaultValue bool) (bool, error) { return false, nil } svc := &Service{backend: &fakeBackend{prompt: declined}} diff --git a/pkg/bridge/convert.go b/pkg/bridge/convert.go index 79594dc4fc4..89e7ed6a9bc 100644 --- a/pkg/bridge/convert.go +++ b/pkg/bridge/convert.go @@ -44,7 +44,7 @@ import ( // Confirm asks the user to confirm a destructive action described by // message, returning defaultValue when no explicit answer can be read. -type Confirm func(message string, defaultValue bool) (bool, error) +type Confirm func(ctx context.Context, message string, defaultValue bool) (bool, error) type ConvertOptions struct { Output string @@ -77,7 +77,7 @@ func Convert(ctx context.Context, dockerCli command.Cli, project *types.Project, } if opts.Output != "" { - if err := prepareOutputDir(opts); err != nil { + if err := prepareOutputDir(ctx, opts); err != nil { return err } } @@ -88,7 +88,7 @@ func Convert(ctx context.Context, dockerCli command.Cli, project *types.Project, // prepareOutputDir makes sure output exists and is empty. If it already // contains files, it asks for confirmation before deleting them, so a typo // or misuse (e.g. -o . or -o $HOME) doesn't silently destroy user data. -func prepareOutputDir(opts ConvertOptions) error { +func prepareOutputDir(ctx context.Context, opts ConvertOptions) error { empty, err := isEmptyOrMissingDir(opts.Output) if err != nil { return err @@ -100,6 +100,7 @@ func prepareOutputDir(opts ConvertOptions) error { confirmed := false if opts.Confirm != nil { confirmed, err = opts.Confirm( + ctx, fmt.Sprintf("Output directory '%s' is not empty, all its content will be permanently deleted. Continue?", opts.Output), false) if err != nil { diff --git a/pkg/bridge/convert_test.go b/pkg/bridge/convert_test.go index de0e5cdaa38..c10781f1a1c 100644 --- a/pkg/bridge/convert_test.go +++ b/pkg/bridge/convert_test.go @@ -17,6 +17,7 @@ package bridge import ( + "context" "os" "path/filepath" "testing" @@ -76,7 +77,7 @@ func TestIsEmptyOrMissingDir(t *testing.T) { func failIfCalled(t *testing.T) Confirm { t.Helper() - return func(string, bool) (bool, error) { + return func(context.Context, string, bool) (bool, error) { t.Fatal("Confirm should not be called") return false, nil } @@ -88,7 +89,7 @@ func TestPrepareOutputDir_EmptyOrMissingDirNeedsNoConfirmation(t *testing.T) { "empty": t.TempDir(), } { t.Run(name, func(t *testing.T) { - assert.NilError(t, prepareOutputDir(ConvertOptions{Output: dir, Confirm: failIfCalled(t)})) + assert.NilError(t, prepareOutputDir(t.Context(), ConvertOptions{Output: dir, Confirm: failIfCalled(t)})) info, err := os.Stat(dir) assert.NilError(t, err) @@ -101,7 +102,7 @@ func TestPrepareOutputDir_NilConfirmRefusesNonEmptyDir(t *testing.T) { dir := t.TempDir() assert.NilError(t, os.WriteFile(filepath.Join(dir, "README.md"), []byte("do not delete me"), 0o600)) - err := prepareOutputDir(ConvertOptions{Output: dir}) + err := prepareOutputDir(t.Context(), ConvertOptions{Output: dir}) assert.ErrorContains(t, err, "not confirmed") _, statErr := os.Stat(filepath.Join(dir, "README.md")) @@ -111,9 +112,9 @@ func TestPrepareOutputDir_NilConfirmRefusesNonEmptyDir(t *testing.T) { func TestPrepareOutputDir_ConfirmedWipesNonEmptyDir(t *testing.T) { dir := t.TempDir() assert.NilError(t, os.WriteFile(filepath.Join(dir, "stale.yaml"), []byte("stale"), 0o600)) - confirm := func(string, bool) (bool, error) { return true, nil } + confirm := func(context.Context, string, bool) (bool, error) { return true, nil } - assert.NilError(t, prepareOutputDir(ConvertOptions{Output: dir, Confirm: confirm})) + assert.NilError(t, prepareOutputDir(t.Context(), ConvertOptions{Output: dir, Confirm: confirm})) _, err := os.Stat(filepath.Join(dir, "stale.yaml")) assert.Assert(t, os.IsNotExist(err)) @@ -122,9 +123,9 @@ func TestPrepareOutputDir_ConfirmedWipesNonEmptyDir(t *testing.T) { func TestPrepareOutputDir_DeclinedPreservesFiles(t *testing.T) { dir := t.TempDir() assert.NilError(t, os.WriteFile(filepath.Join(dir, "README.md"), []byte("do not delete me"), 0o600)) - confirm := func(string, bool) (bool, error) { return false, nil } + confirm := func(context.Context, string, bool) (bool, error) { return false, nil } - err := prepareOutputDir(ConvertOptions{Output: dir, Confirm: confirm}) + err := prepareOutputDir(t.Context(), ConvertOptions{Output: dir, Confirm: confirm}) assert.ErrorContains(t, err, "not confirmed") _, statErr := os.Stat(filepath.Join(dir, "README.md")) diff --git a/pkg/compose/compose.go b/pkg/compose/compose.go index 630eee40ccd..43ad293ee20 100644 --- a/pkg/compose/compose.go +++ b/pkg/compose/compose.go @@ -84,7 +84,7 @@ func NewComposeService(dockerCli command.Cli, options ...Option) (api.Compose, e } } if s.prompt == nil { - s.prompt = func(message string, defaultValue bool) (bool, error) { + s.prompt = func(_ context.Context, message string, defaultValue bool) (bool, error) { fmt.Println(message) logrus.Warning("Compose is running without a 'prompt' component to interact with user") return defaultValue, nil @@ -197,11 +197,13 @@ func WithDryRun(s *composeService) error { return nil } -type Prompt func(message string, defaultValue bool) (bool, error) +// Prompt asks the user to confirm an action. An implementation that blocks on +// user input must return ctx.Err() as soon as ctx is canceled. +type Prompt func(ctx context.Context, message string, defaultValue bool) (bool, error) // AlwaysOkPrompt returns a Prompt implementation that always returns true without user interaction. func AlwaysOkPrompt() Prompt { - return func(message string, defaultValue bool) (bool, error) { + return func(context.Context, string, bool) (bool, error) { return true, nil } } diff --git a/pkg/compose/publish.go b/pkg/compose/publish.go index 00900f498e8..fcb7eefd337 100644 --- a/pkg/compose/publish.go +++ b/pkg/compose/publish.go @@ -64,8 +64,8 @@ func (b publishBackend) DryRun() bool { return b.s.dryRun } -func (b publishBackend) Prompt(message string, defaultValue bool) (bool, error) { - return b.s.prompt(message, defaultValue) +func (b publishBackend) Prompt(ctx context.Context, message string, defaultValue bool) (bool, error) { + return b.s.prompt(ctx, message, defaultValue) } // Push must stay the unexported push: Publish already runs inside the "publish" diff --git a/pkg/compose/publish_test.go b/pkg/compose/publish_test.go index ecb91886f19..d68ebfd8eec 100644 --- a/pkg/compose/publish_test.go +++ b/pkg/compose/publish_test.go @@ -17,6 +17,7 @@ package compose import ( + "context" "testing" "github.com/compose-spec/compose-go/v2/types" @@ -57,11 +58,11 @@ func TestPublishBackendWiring(t *testing.T) { t.Run("a refused prompt stays refused", func(t *testing.T) { var asked string var asDefault bool - s.prompt = func(message string, defaultValue bool) (bool, error) { + s.prompt = func(_ context.Context, message string, defaultValue bool) (bool, error) { asked, asDefault = message, defaultValue return false, nil } - answer, err := b.Prompt("publish?", true) + answer, err := b.Prompt(t.Context(), "publish?", true) assert.NilError(t, err) assert.Assert(t, !answer) assert.Equal(t, asked, "publish?") diff --git a/pkg/compose/reconcile.go b/pkg/compose/reconcile.go index 138335db0a5..d9a9ec62865 100644 --- a/pkg/compose/reconcile.go +++ b/pkg/compose/reconcile.go @@ -171,7 +171,7 @@ type reconciler struct { // reconcile is the main entry point: it builds a Plan from desired vs observed state. // The prompt function is consulted while planning to confirm destructive // decisions (see the reconciler.prompt field). -func reconcile(_ context.Context, project *types.Project, observed *ObservedState, options ReconcileOptions, prompt Prompt) (*planning.Plan, error) { +func reconcile(ctx context.Context, project *types.Project, observed *ObservedState, options ReconcileOptions, prompt Prompt) (*planning.Plan, error) { r := &reconciler{ project: project, observed: observed, @@ -199,7 +199,7 @@ func reconcile(_ context.Context, project *types.Project, observed *ObservedStat return nil, err } - if err := r.reconcileVolumes(); err != nil { + if err := r.reconcileVolumes(ctx); err != nil { return nil, err } @@ -431,7 +431,7 @@ func (r *reconciler) planRecreateNetworks(keys []string) { // hash (e.g. created by an older Compose) is left untouched: without a // recorded hash there is no reliable way to tell configuration drift apart // from deliberate manual setup, and volumes carry data. -func (r *reconciler) reconcileVolumes() error { +func (r *reconciler) reconcileVolumes(ctx context.Context) error { var diverged []string for _, key := range slices.Sorted(maps.Keys(r.project.Volumes)) { desired := r.project.Volumes[key] @@ -474,6 +474,7 @@ func (r *reconciler) reconcileVolumes() error { continue } confirmed, err := r.prompt( + ctx, fmt.Sprintf("Volume %q exists but doesn't match configuration in compose file. Recreate (data will be lost)?", desired.Name), false) if err != nil { diff --git a/pkg/compose/reconcile_test.go b/pkg/compose/reconcile_test.go index 57244231bc5..539642404a4 100644 --- a/pkg/compose/reconcile_test.go +++ b/pkg/compose/reconcile_test.go @@ -17,6 +17,7 @@ package compose import ( + "context" "errors" "fmt" "strconv" @@ -35,18 +36,18 @@ import ( ) // noPrompt is a Prompt that should never be called in tests that don't expect it. -func noPrompt(msg string, _ bool) (bool, error) { +func noPrompt(_ context.Context, msg string, _ bool) (bool, error) { panic("unexpected prompt call: " + msg) } // yesPrompt confirms every prompt (equivalent to `--yes`). -func yesPrompt(_ string, _ bool) (bool, error) { +func yesPrompt(_ context.Context, _ string, _ bool) (bool, error) { return true, nil } // declinePrompt rejects every prompt (the default answer for a non-interactive // session with no input). -func declinePrompt(_ string, _ bool) (bool, error) { +func declinePrompt(_ context.Context, _ string, _ bool) (bool, error) { return false, nil } @@ -55,7 +56,7 @@ type recordingPrompt struct { messages []string } -func (p *recordingPrompt) confirm(msg string, _ bool) (bool, error) { +func (p *recordingPrompt) confirm(_ context.Context, msg string, _ bool) (bool, error) { p.messages = append(p.messages, msg) return true, nil } @@ -615,7 +616,7 @@ func TestReconcileVolumes_DivergedPromptMessage(t *testing.T) { func TestReconcileVolumes_DivergedPromptError(t *testing.T) { project, observed := divergedVolumeProject(t, 1, 1) - boom := func(_ string, _ bool) (bool, error) { return false, errors.New("boom") } + boom := func(_ context.Context, _ string, _ bool) (bool, error) { return false, errors.New("boom") } _, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), boom) assert.ErrorContains(t, err, "boom") } @@ -755,7 +756,7 @@ func TestReconcileVolumes_DivergedPartialConfirm(t *testing.T) { // Confirm data1 only (sorted order: data1 prompted first). first := true - prompt := func(_ string, _ bool) (bool, error) { + prompt := func(_ context.Context, _ string, _ bool) (bool, error) { if first { first = false return true, nil diff --git a/pkg/compose/remove.go b/pkg/compose/remove.go index 49c7fbb74f4..d4125167a7a 100644 --- a/pkg/compose/remove.go +++ b/pkg/compose/remove.go @@ -86,7 +86,7 @@ func (s *composeService) Remove(ctx context.Context, projectName string, options if options.Force { _, _ = fmt.Fprintln(s.stdout(), msg) } else { - confirm, err := s.prompt(msg, false) + confirm, err := s.prompt(ctx, msg, false) if err != nil { return err }