Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/compose/bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
8 changes: 4 additions & 4 deletions cmd/compose/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand All @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/compose/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
56 changes: 46 additions & 10 deletions cmd/prompt/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,27 @@ package prompt

import (
"bufio"
"errors"
"context"
"fmt"
"io"
"strings"
"unicode"

"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 {
Expand All @@ -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
}
Expand All @@ -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
}
Expand Down Expand Up @@ -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
}
}
9 changes: 5 additions & 4 deletions cmd/prompt/prompt_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

70 changes: 64 additions & 6 deletions cmd/prompt/prompt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package prompt
import (
"bufio"
"bytes"
"context"
"io"
"os"
"strings"
Expand All @@ -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
Expand All @@ -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) {
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -127,15 +183,15 @@ 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
err error
}{err: err}
return
}
second, err := user.Confirm("second?", true)
second, err := user.Confirm(t.Context(), "second?", true)
done <- struct {
first, second bool
err error
Expand Down Expand Up @@ -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")
}

Expand Down
56 changes: 56 additions & 0 deletions internal/e2e/prompt_cancel_test.go
Original file line number Diff line number Diff line change
@@ -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"))
}
Loading
Loading