Skip to content

Commit b65a0a3

Browse files
committed
Fix signal handling when --watch flag is given
Closes #132
1 parent 687b4ec commit b65a0a3

File tree

2 files changed

+25
-10
lines changed

2 files changed

+25
-10
lines changed

cmd/task/task.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,11 @@ func main() {
8787
return
8888
}
8989

90+
ctx := context.Background()
91+
if !watch {
92+
ctx = getSignalContext()
93+
}
94+
9095
e := task.Executor{
9196
Force: force,
9297
Watch: watch,
@@ -95,7 +100,7 @@ func main() {
95100
Dir: dir,
96101
Dry: dry,
97102

98-
Context: getSignalContext(),
103+
Context: ctx,
99104

100105
Stdin: os.Stdin,
101106
Stdout: os.Stdout,

watch.go

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ package task
22

33
import (
44
"context"
5+
"os"
6+
"os/signal"
57
"strings"
8+
"syscall"
69
"time"
710

811
"github.com/go-task/task/internal/taskfile"
@@ -40,6 +43,8 @@ func (e *Executor) watchTasks(calls ...taskfile.Call) error {
4043
return err
4144
}
4245

46+
closeOnInterrupt(w)
47+
4348
go func() {
4449
for {
4550
select {
@@ -66,6 +71,7 @@ func (e *Executor) watchTasks(calls ...taskfile.Call) error {
6671
e.Logger.Errf("%v", err)
6772
}
6873
case <-w.Closed:
74+
cancel()
6975
return
7076
}
7177
}
@@ -84,6 +90,19 @@ func (e *Executor) watchTasks(calls ...taskfile.Call) error {
8490
return w.Start(time.Second)
8591
}
8692

93+
func isContextError(err error) bool {
94+
return err == context.Canceled || err == context.DeadlineExceeded
95+
}
96+
97+
func closeOnInterrupt(w *watcher.Watcher) {
98+
ch := make(chan os.Signal, 1)
99+
signal.Notify(ch, os.Interrupt, os.Kill, syscall.SIGTERM)
100+
go func() {
101+
<-ch
102+
w.Close()
103+
}()
104+
}
105+
87106
func (e *Executor) registerWatchedFiles(w *watcher.Watcher, calls ...taskfile.Call) error {
88107
oldWatchedFiles := make(map[string]struct{})
89108
for f := range w.WatchedFiles() {
@@ -140,12 +159,3 @@ func (e *Executor) registerWatchedFiles(w *watcher.Watcher, calls ...taskfile.Ca
140159
}
141160
return nil
142161
}
143-
144-
func isContextError(err error) bool {
145-
switch err {
146-
case context.Canceled, context.DeadlineExceeded:
147-
return true
148-
default:
149-
return false
150-
}
151-
}

0 commit comments

Comments
 (0)