From c3e836f0dd26dbef58dbe636088d70d23373b2c7 Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Wed, 27 Nov 2024 14:58:21 -0300 Subject: [PATCH] fix(spin): interrupt child process on ctrl+c (#732) * fix(spin): interrupt child process on ctrl+c This will send a SIGINT to the child process when ctrl+c is pressed. closes #730 * fix: lint --- spin/spin.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/spin/spin.go b/spin/spin.go index 26c933fca..cdfc24877 100644 --- a/spin/spin.go +++ b/spin/spin.go @@ -18,6 +18,7 @@ import ( "io" "os/exec" "strings" + "syscall" "time" "github.com/charmbracelet/gum/internal/exit" @@ -48,6 +49,8 @@ var ( bothbuf strings.Builder outbuf strings.Builder errbuf strings.Builder + + executing *exec.Cmd ) type finishCommandMsg struct { @@ -64,11 +67,11 @@ func commandStart(command []string) tea.Cmd { args = command[1:] } - cmd := exec.Command(command[0], args...) //nolint:gosec - cmd.Stdout = io.MultiWriter(&bothbuf, &outbuf) - cmd.Stderr = io.MultiWriter(&bothbuf, &errbuf) - _ = cmd.Run() - status := cmd.ProcessState.ExitCode() + executing = exec.Command(command[0], args...) //nolint:gosec + executing.Stdout = io.MultiWriter(&bothbuf, &outbuf) + executing.Stderr = io.MultiWriter(&bothbuf, &errbuf) + _ = executing.Run() + status := executing.ProcessState.ExitCode() if status == -1 { status = 1 } @@ -82,6 +85,13 @@ func commandStart(command []string) tea.Cmd { } } +func commandAbort() tea.Msg { + if executing != nil && executing.Process != nil { + _ = executing.Process.Signal(syscall.SIGINT) + } + return nil +} + func (m model) Init() tea.Cmd { return tea.Batch( m.spinner.Tick, @@ -135,7 +145,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg.String() { case "ctrl+c": m.aborted = true - return m, tea.Quit + return m, commandAbort } }