Debian Codegraph @

task.go

raw symbols SCIP
1 package godo
2
3 import (
4 "fmt"
5 "io"
6 "path/filepath"
7 "strings"
8 "sync"
9 "time"
10
11 "github.com/mgutz/minimist"
12 "github.com/mgutz/str"
13 "gopkg.in/godo.v2/glob"
14 "gopkg.in/godo.v2/util"
15 "gopkg.in/godo.v2/watcher"
16 )
17
18 // TaskFunction is the signature of the function used to define a type.
19 // type TaskFunc func(string, ...interface{}) *Task
20 // type UseFunc func(string, interface{})
21
22 // A Task is an operation performed on a user's project directory.
23 type Task struct {
24 Name string
25 description string
26 Handler Handler
27 dependencies Series
28 argm minimist.ArgMap
29
30 // Watches are watches files. On change the task is rerun. For example `**/*.less`
31 // Usually Watches and Sources are the same.
32 // WatchFiles []*FileAsset
33 // WatchGlobs []string
34 // WatchRegexps []*RegexpInfo
35
36 // computed based on dependencies
37 EffectiveWatchRegexps []*glob.RegexpInfo
38 EffectiveWatchGlobs []string
39
40 // Complete indicates whether this task has already ran. This flag is
41 // ignored in watch mode.
42 Complete bool
43 debounce time.Duration
44 RunOnce bool
45
46 SrcFiles []*glob.FileAsset
47 SrcGlobs []string
48 SrcRegexps []*glob.RegexpInfo
49
50 DestFiles []*glob.FileAsset
51 DestGlobs []string
52 DestRegexps []*glob.RegexpInfo
53
54 // used when a file event is received between debounce intervals, the file event
55 // will queue itself and set this flag and force debounce to run it
56 // when time has elapsed
57 sync.Mutex
58 ignoreEvents bool
59 }
60
61 // NewTask creates a new Task.
62 func NewTask(name string, argm minimist.ArgMap) *Task {
63 runOnce := false
64 if strings.HasSuffix(name, "?") {
65 runOnce = true
66 name = str.ChompRight(name, "?")
67 }
68 return &Task{Name: name, RunOnce: runOnce, dependencies: Series{}, argm: argm}
69 }
70
71 // Expands glob patterns.
72 func (task *Task) expandGlobs() {
73
74 // runs once lazily
75 if len(task.SrcFiles) > 0 {
76 return
77 }
78
79 files, regexps, err := glob.Glob(task.SrcGlobs)
80 if err != nil {
81 util.Error(task.Name, "%v", err)
82 return
83 }
84
85 task.SrcRegexps = regexps
86 task.SrcFiles = files
87
88 if len(task.DestGlobs) > 0 {
89 files, regexps, err := glob.Glob(task.DestGlobs)
90 if err != nil {
91 util.Error(task.Name, "%v", err)
92 return
93 }
94 task.DestRegexps = regexps
95 task.DestFiles = files
96 }
97 }
98
99 // Run runs all the dependencies of this task and when they have completed,
100 // runs this task.
101 func (task *Task) Run() error {
102 if !watching && task.Complete {
103 util.Debug(task.Name, "Already ran\n")
104 return nil
105 }
106 return task.RunWithEvent(task.Name, nil)
107 }
108
109 // isWatchedFile determines if a FileEvent's file is a watched file
110 func (task *Task) isWatchedFile(path string) bool {
111 filename, err := filepath.Rel(wd, path)
112 if err != nil {
113 return false
114 }
115
116 filename = filepath.ToSlash(filename)
117 //util.Debug("task", "checking for match %s\n", filename)
118
119 matched := false
120 for _, info := range task.EffectiveWatchRegexps {
121 if info.Negate {
122 if matched {
123 matched = !info.MatchString(filename)
124 //util.Debug("task", "negated match? %s %s\n", filename, matched)
125 continue
126 }
127 } else if info.MatchString(filename) {
128 matched = true
129 //util.Debug("task", "matched %s %s\n", filename, matched)
130 continue
131 }
132 }
133 return matched
134 }
135
136 // RunWithEvent runs this task when triggered from a watch.
137 // *e* FileEvent contains information about the file/directory which changed
138 // in watch mode.
139 func (task *Task) RunWithEvent(logName string, e *watcher.FileEvent) (err error) {
140 if task.RunOnce && task.Complete {
141 util.Debug(task.Name, "Already ran\n")
142 return nil
143 }
144
145 task.expandGlobs()
146 if !task.shouldRun(e) {
147 util.Info(logName, "up-to-date 0ms\n")
148 return nil
149 }
150
151 start := time.Now()
152 if len(task.SrcGlobs) > 0 && len(task.SrcFiles) == 0 {
153 util.Error("task", "\""+task.Name+"\" '%v' did not match any files\n", task.SrcGlobs)
154 }
155
156 // Run this task only if the file matches watch Regexps
157 rebuilt := ""
158 if e != nil {
159 rebuilt = "rebuilt "
160 if !task.isWatchedFile(e.Path) && len(task.SrcGlobs) > 0 {
161 return nil
162 }
163 if verbose {
164 util.Debug(logName, "%s\n", e.String())
165 }
166 }
167
168 log := true
169 if task.Handler != nil {
170 context := Context{Task: task, Args: task.argm, FileEvent: e}
171 defer func() {
172 if p := recover(); p != nil {
173 sp, ok := p.(*softPanic)
174 if !ok {
175 panic(p)
176 }
177 err = fmt.Errorf("%q: %s", logName, sp)
178 }
179 }()
180
181 task.Handler.Handle(&context)
182 if context.Error != nil {
183 return fmt.Errorf("%q: %s", logName, context.Error.Error())
184 }
185 } else if len(task.dependencies) > 0 {
186 // no need to log if just dependency
187 log = false
188 } else {
189 util.Info(task.Name, "Ignored. Task does not have a handler or dependencies.\n")
190 return nil
191 }
192
193 if log {
194 if rebuilt != "" {
195 util.InfoColorful(logName, "%s%vms\n", rebuilt, time.Since(start).Nanoseconds()/1e6)
196 } else {
197 util.Info(logName, "%s%vms\n", rebuilt, time.Since(start).Nanoseconds()/1e6)
198 }
199 }
200
201 task.Complete = true
202
203 return nil
204 }
205
206 // DependencyNames gets the flattened dependency names.
207 func (task *Task) DependencyNames() []string {
208 if len(task.dependencies) == 0 {
209 return nil
210 }
211 deps := []string{}
212 for _, dep := range task.dependencies {
213 switch d := dep.(type) {
214 default:
215 panic("dependencies can only be Serial or Parallel")
216 case Series:
217 deps = append(deps, d.names()...)
218 case Parallel:
219 deps = append(deps, d.names()...)
220 case S:
221 deps = append(deps, Series(d).names()...)
222 case P:
223 deps = append(deps, Parallel(d).names()...)
224 }
225 }
226 return deps
227 }
228
229 func (task *Task) dump(buf io.Writer, indent string) {
230 fmt.Fprintln(buf, indent, task.Name)
231 fmt.Fprintln(buf, indent+indent, "EffectiveWatchGlobs", task.EffectiveWatchGlobs)
232 fmt.Fprintln(buf, indent+indent, "SrcFiles", task.SrcFiles)
233 fmt.Fprintln(buf, indent+indent, "SrcGlobs", task.SrcGlobs)
234
235 }
236
237 func (task *Task) shouldRun(e *watcher.FileEvent) bool {
238 if e == nil || len(task.SrcFiles) == 0 {
239 return true
240 } else if !task.isWatchedFile(e.Path) {
241 // fmt.Printf("received a file so it should return immediately\n")
242 return false
243 }
244
245 // lazily expand globs
246 task.expandGlobs()
247
248 if len(task.SrcFiles) == 0 || len(task.DestFiles) == 0 {
249 // fmt.Printf("no source files %s %#v\n", task.Name, task.SrcFiles)
250 // fmt.Printf("no source files %s %#v\n", task.Name, task.DestFiles)
251 return true
252 }
253
254 // TODO figure out intelligent way to cache this instead of stating
255 // each time
256 for _, src := range task.SrcFiles {
257 // refresh stat
258 src.Stat()
259 for _, dest := range task.DestFiles {
260 // refresh stat
261 dest.Stat()
262 if filepath.Base(src.Path) == "foo.txt" {
263 fmt.Printf("src %s %#v\n", src.Path, src.ModTime().UnixNano())
264 fmt.Printf("dest %s %#v\n", dest.Path, dest.ModTime().UnixNano())
265 }
266 if src.ModTime().After(dest.ModTime()) {
267 return true
268 }
269 }
270 }
271
272 fmt.Printf("FileEvent ignored %#v\n", e)
273
274 return false
275 }
276
277 func (task *Task) debounceValue() time.Duration {
278 if task.debounce == 0 {
279 // use default Debounce
280 return Debounce
281 }
282 return task.debounce
283 }