diff --git a/cli/context/signal.go b/cli/context/signal.go new file mode 100644 index 0000000..cf8f620 --- /dev/null +++ b/cli/context/signal.go @@ -0,0 +1,21 @@ +package context + +import ( + "context" + "os" + "os/signal" + "syscall" +) + +func SelfCancelingCotext(ctx context.Context) (context.Context, context.CancelFunc) { + c, done := context.WithCancel(ctx) + ch := make(chan os.Signal, 1) + signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) + go func() { + for range ch { + done() + } + }() + + return c, done +} diff --git a/cli/spin/spin.go b/cli/spin/spin.go index 3d0a804..d5570fa 100644 --- a/cli/spin/spin.go +++ b/cli/spin/spin.go @@ -94,7 +94,12 @@ func (s *spin) Err() error { } func Spin(ctx context.Context, message string) Spinner { - p := tea.NewProgram(newModel(message), tea.WithContext(ctx)) + p := tea.NewProgram( + newModel(message), + tea.WithContext(ctx), + tea.WithoutSignalHandler(), + tea.WithInput(nil), + ) s := &spin{p: p, finished: make(chan struct{}, 1)} go func() { _, err := s.p.Run() diff --git a/cmd/cool-down/main.go b/cmd/cool-down/main.go index 18487b1..234a06a 100644 --- a/cmd/cool-down/main.go +++ b/cmd/cool-down/main.go @@ -4,12 +4,15 @@ import ( "context" "codeberg.org/danjones000/utils/chill" + c "codeberg.org/danjones000/utils/cli/context" e "codeberg.org/danjones000/utils/cli/err" "codeberg.org/danjones000/utils/cli/spin" ) func main() { - ctx := chill.Chill(context.Background()) + ctx, done := c.SelfCancelingCotext(context.Background()) + defer done() + ctx = chill.Chill(ctx) s := spin.Spin(ctx, "Waiting for CPU to cool...") err := s.Wait() e.HandleErr(err)