From ce9a486a0e0e3288ffa2b874cad5f34954585048 Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Tue, 27 Feb 2024 17:30:51 -0800 Subject: [PATCH] commands: handle ctrl-c on active prompt Signed-off-by: Tonis Tiigi --- commands/prune.go | 8 ++++++-- commands/rm.go | 8 ++++++-- commands/util.go | 23 +++++++++++++++++++++++ 3 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 commands/util.go diff --git a/commands/prune.go b/commands/prune.go index 1a2a5220..e2821721 100644 --- a/commands/prune.go +++ b/commands/prune.go @@ -49,8 +49,12 @@ func runPrune(ctx context.Context, dockerCli command.Cli, opts pruneOptions) err warning = allCacheWarning } - if !opts.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) { - return nil + if !opts.force { + if ok, err := prompt(ctx, dockerCli.In(), dockerCli.Out(), warning); err != nil { + return err + } else if !ok { + return nil + } } b, err := builder.New(dockerCli, builder.WithName(opts.builder)) diff --git a/commands/rm.go b/commands/rm.go index 081cdb78..6987cc42 100644 --- a/commands/rm.go +++ b/commands/rm.go @@ -28,8 +28,12 @@ const ( ) func runRm(ctx context.Context, dockerCli command.Cli, in rmOptions) error { - if in.allInactive && !in.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), rmInactiveWarning) { - return nil + if in.allInactive && !in.force { + if ok, err := prompt(ctx, dockerCli.In(), dockerCli.Out(), rmInactiveWarning); err != nil { + return err + } else if !ok { + return nil + } } txn, release, err := storeutil.GetStore(dockerCli) diff --git a/commands/util.go b/commands/util.go new file mode 100644 index 00000000..d7e44f50 --- /dev/null +++ b/commands/util.go @@ -0,0 +1,23 @@ +package commands + +import ( + "context" + "io" + + "github.com/docker/cli/cli/command" +) + +func prompt(ctx context.Context, ins io.Reader, out io.Writer, msg string) (bool, error) { + done := make(chan struct{}) + var ok bool + go func() { + ok = command.PromptForConfirmation(ins, out, msg) + close(done) + }() + select { + case <-ctx.Done(): + return false, context.Cause(ctx) + case <-done: + return ok, nil + } +}