-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
121 lines (100 loc) · 2 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package task
import (
"fmt"
"os"
"os/exec"
"sync"
"github.com/charmbracelet/lipgloss"
)
var notifStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#99ff99"))
var cmdStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#9999ff"))
type Task struct {
Name string
Ready chan struct{}
workingDir string
runCmd string
depsCount int
children []*Task
touch []*sync.Mutex
}
func (t *Task) Run() error {
readyCount := 0
for {
select {
case <-t.Ready:
readyCount++
if readyCount == t.depsCount {
return t.run()
}
default:
if readyCount == t.depsCount {
return t.run()
}
}
}
}
func (t *Task) AddChildren(children ...*Task) {
t.children = append(t.children, children...)
}
func (t *Task) run() error {
for _, touch := range t.touch {
touch.Lock()
defer touch.Unlock()
}
fmt.Println(notifStyle.Render("Running task:"), cmdStyle.Render(t.Name))
c := exec.Command("/bin/sh", "-c", t.runCmd)
c.Stdout = os.Stdout
c.Stderr = c.Stdout
c.Env = os.Environ()
err := c.Run()
for _, child := range t.children {
child.Ready <- struct{}{}
}
return err
}
type Opt func(*Task) error
func NewWithOpts(opts ...Opt) (*Task, error) {
task := &Task{Ready: make(chan struct{})}
for _, opt := range opts {
if err := opt(task); err != nil {
return nil, err
}
}
return task, nil
}
func WithChildren(children ...*Task) Opt {
return func(task *Task) error {
task.children = children
return nil
}
}
func WithDeps(deps ...string) Opt {
return func(task *Task) error {
task.depsCount = len(deps)
return nil
}
}
func WithName(name string) Opt {
return func(task *Task) error {
task.Name = name
return nil
}
}
func WithRun(run string) Opt {
return func(task *Task) error {
task.runCmd = run
return nil
}
}
func WithTouch(touch ...*sync.Mutex) Opt {
return func(task *Task) error {
task.touch = touch
return nil
}
}
func WithWorkingDir(workingDir string) Opt {
return func(task *Task) error {
task.workingDir = workingDir
return nil
}
}