Skip to content

Commit 71e7cd5

Browse files
committed
listening for SIGINT and SIGTERM
closes #75
1 parent 57e42af commit 71e7cd5

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

cmd/task/task.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package main
22

33
import (
4-
"fmt"
4+
"context"
55
"log"
66
"os"
7+
"os/signal"
8+
"syscall"
79

810
"github.com/go-task/task"
911
"github.com/go-task/task/internal/args"
@@ -37,9 +39,10 @@ Options:
3739

3840
func main() {
3941
log.SetFlags(0)
42+
log.SetOutput(os.Stderr)
4043

4144
pflag.Usage = func() {
42-
fmt.Print(usage)
45+
log.Print(usage)
4346
pflag.PrintDefaults()
4447
}
4548

@@ -87,6 +90,8 @@ func main() {
8790
Silent: silent,
8891
Dir: dir,
8992

93+
Context: getSignalContext(),
94+
9095
Stdin: os.Stdin,
9196
Stdout: os.Stdout,
9297
Stderr: os.Stderr,
@@ -115,3 +120,15 @@ func main() {
115120
log.Fatal(err)
116121
}
117122
}
123+
124+
func getSignalContext() context.Context {
125+
ch := make(chan os.Signal, 1)
126+
signal.Notify(ch, os.Interrupt, os.Kill, syscall.SIGTERM)
127+
ctx, cancel := context.WithCancel(context.Background())
128+
go func() {
129+
sig := <-ch
130+
log.Printf("task: signal received: %s", sig)
131+
cancel()
132+
}()
133+
return ctx
134+
}

task.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ type Executor struct {
3030
Verbose bool
3131
Silent bool
3232

33+
Context context.Context
34+
3335
Stdin io.Reader
3436
Stdout io.Writer
3537
Stderr io.Writer
@@ -63,6 +65,9 @@ type Task struct {
6365

6466
// Run runs Task
6567
func (e *Executor) Run(calls ...Call) error {
68+
if e.Context == nil {
69+
e.Context = context.Background()
70+
}
6671
if e.Stdin == nil {
6772
e.Stdin = os.Stdin
6873
}
@@ -96,7 +101,7 @@ func (e *Executor) Run(calls ...Call) error {
96101
}
97102

98103
for _, c := range calls {
99-
if err := e.RunTask(context.TODO(), c); err != nil {
104+
if err := e.RunTask(e.Context, c); err != nil {
100105
return err
101106
}
102107
}

0 commit comments

Comments
 (0)