on main help sign in
fix(noninteractive): cancel on signal (#1584)
3c7ee39Christian Rocha
internal/cmd/run.go+7−2
@@ -1,9 +1,11 @@
1package cmd
1package cmd
2
2
3import (
3import (
4+ "context"
4 "fmt"
5 "fmt"
5 "log/slog"
6 "log/slog"
6 "os"
7 "os"
8+ "os/signal"
7 "strings"
9 "strings"
8
10
9 "github.com/spf13/cobra"
11 "github.com/spf13/cobra"
@@ -30,6 +32,10 @@ crush run --quiet "Generate a README for this project"
30 RunE: func(cmd *cobra.Command, args []string) error {
32 RunE: func(cmd *cobra.Command, args []string) error {
31 quiet, _ := cmd.Flags().GetBool("quiet")
33 quiet, _ := cmd.Flags().GetBool("quiet")
32
34
35+ // Cancel on SIGINT or SIGTERM.
36+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
37+ defer cancel()
38+
33 app, err := setupApp(cmd)
39 app, err := setupApp(cmd)
34 if err != nil {
40 if err != nil {
35 return err
41 return err
@@ -57,8 +63,7 @@ crush run --quiet "Generate a README for this project"
57 // crush run "Do something fancy" > output.txt
63 // crush run "Do something fancy" > output.txt
58 // echo "Do something fancy" | crush run > output.txt
64 // echo "Do something fancy" | crush run > output.txt
59 //
65 //
60− // TODO: We currently need to press ^c twice to cancel. Fix that.
61− return app.RunNonInteractive(cmd.Context(), os.Stdout, prompt, quiet)
66+ return app.RunNonInteractive(ctx, os.Stdout, prompt, quiet)
62 },
67 },
63}
68}
64
69