-
Notifications
You must be signed in to change notification settings - Fork 3
/
func_task.go
48 lines (39 loc) · 857 Bytes
/
func_task.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package run
import (
"context"
"io"
)
// FuncTask produces a runnable Task from a go function. metadata.Dir is ignored.
func FuncTask(fn func(ctx context.Context, w io.Writer) error, metadata TaskMetadata) Task {
return &funcTask{
fn: fn,
metadata: metadata,
}
}
type funcTask struct {
fn func(ctx context.Context, w io.Writer) error
// read-only
metadata TaskMetadata
}
// *funcTask implements Task
var _ Task = &funcTask{}
func (t *funcTask) Metadata() TaskMetadata {
meta := t.metadata
return meta
}
func (t *funcTask) Start(ctx context.Context, stdout io.Writer) error {
ctx, cancel := context.WithCancel(context.Background())
exit := make(chan error)
// Run the func!
go func() {
exit <- t.fn(ctx, stdout)
}()
select {
case err := <-exit:
cancel()
return err
case <-ctx.Done():
cancel()
return <-exit
}
}