Skip to content

Commit

Permalink
fix(spin): interrupt child process on ctrl+c
Browse files Browse the repository at this point in the history
This will send a SIGINT to the child process when ctrl+c is pressed.

closes #730
  • Loading branch information
caarlos0 committed Nov 26, 2024
1 parent 01f36b5 commit ba45187
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions spin/spin.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"io"
"os/exec"
"strings"
"syscall"
"time"

"github.com/charmbracelet/gum/internal/exit"
Expand Down Expand Up @@ -48,6 +49,8 @@ var (
bothbuf strings.Builder
outbuf strings.Builder
errbuf strings.Builder

executing *exec.Cmd
)

type finishCommandMsg struct {
Expand All @@ -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
}
Expand All @@ -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)

Check failure on line 90 in spin/spin.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `executing.Process.Signal` is not checked (errcheck)

Check failure on line 90 in spin/spin.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `executing.Process.Signal` is not checked (errcheck)
}
return nil
}

func (m model) Init() tea.Cmd {
return tea.Batch(
m.spinner.Tick,
Expand Down Expand Up @@ -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
}
}

Expand Down

0 comments on commit ba45187

Please sign in to comment.