Debian Codegraph @

project.go

raw symbols SCIP
1 package godo
2
3 import (
4 "fmt"
5 "io"
6 "path/filepath"
7 "sort"
8 "strconv"
9 "strings"
10 "sync"
11 "time"
12
13 "github.com/mgutz/minimist"
14 "gopkg.in/godo.v2/glob"
15 "gopkg.in/godo.v2/util"
16 "gopkg.in/godo.v2/watcher"
17 )
18
19 // softPanic is used to check for errors within a task handler.
20 type softPanic struct {
21 // msg is the original error that caused the panic
22 err error
23 }
24
25 func (sp *softPanic) Error() string {
26 return sp.err.Error()
27 }
28
29 // Halt is a soft panic and stops a task.
30 func Halt(v interface{}) {
31 if v == nil {
32 panic("No reason provided")
33 } else if err, ok := v.(error); ok {
34 panic(&softPanic{err})
35 }
36
37 panic(&softPanic{fmt.Errorf("%v", v)})
38 }
39
40 // M is generic string to interface alias
41 type M map[string]interface{}
42
43 // Project is a container for tasks.
44 type Project struct {
45 sync.Mutex
46 Tasks map[string]*Task
47 Namespace map[string]*Project
48 lastRun map[string]time.Time
49 exitFn func(code int)
50 ns string
51 contextArgm minimist.ArgMap
52 cwatchTasks map[chan bool]bool
53
54 parent *Project
55 }
56
57 // NewProject creates am empty project ready for tasks.
58 func NewProject(tasksFunc func(*Project), exitFn func(code int), argm minimist.ArgMap) *Project {
59 project := &Project{Tasks: map[string]*Task{}, lastRun: map[string]time.Time{}}
60 project.Namespace = map[string]*Project{}
61 project.Namespace[""] = project
62 project.ns = "root"
63 project.exitFn = exitFn
64 project.contextArgm = argm
65 project.Define(tasksFunc)
66 project.cwatchTasks = map[chan bool]bool{}
67 return project
68 }
69
70 // reset resets project state
71 func (project *Project) reset() {
72 for _, task := range project.Tasks {
73 task.Complete = false
74 }
75 project.lastRun = map[string]time.Time{}
76 }
77
78 func (project *Project) mustTask(name string) (*Project, *Task, string) {
79 if name == "" {
80 panic("Cannot get task for empty string")
81 }
82
83 proj := project
84
85 // use root
86 if strings.HasPrefix(name, "/") {
87 name = name[1:]
88 for true {
89 if proj.parent != nil {
90 proj = proj.parent
91 } else {
92 break
93 }
94 }
95 } else {
96 proj = project
97 }
98
99 taskName := "default"
100 parts := strings.Split(name, ":")
101
102 if len(parts) == 1 {
103 taskName = parts[0]
104 } else {
105 namespace := ""
106
107 for i := 0; i < len(parts)-1; i++ {
108
109 if namespace != "" {
110 namespace += ":"
111 }
112 ns := parts[i]
113 namespace += ns
114
115 proj = proj.Namespace[ns]
116 if proj == nil {
117 util.Panic("ERR", "Could not find project having namespace \"%s\"\n", namespace)
118 }
119 }
120 taskName = parts[len(parts)-1]
121 }
122
123 task := proj.Tasks[taskName]
124 if task == nil {
125 util.Panic("ERR", `"%s" task is not defined`+"\n", name)
126 }
127 return proj, task, taskName
128 }
129
130 func (project *Project) debounce(task *Task) bool {
131 if task.Name == "" {
132 panic("task name should not be empty")
133 }
134 debounce := task.debounce
135 if debounce == 0 {
136 debounce = Debounce
137 }
138
139 now := time.Now()
140 project.Lock()
141 defer project.Unlock()
142
143 oldRun := project.lastRun[task.Name]
144 if oldRun.IsZero() {
145 project.lastRun[task.Name] = now
146 return false
147 }
148
149 if oldRun.Add(debounce).After(now) {
150 project.lastRun[task.Name] = now
151 return true
152 }
153 return false
154 }
155
156 // Run runs a task by name.
157 func (project *Project) Run(name string) error {
158 return project.run(name, name, nil)
159 }
160
161 // RunWithEvent runs a task by name and adds FileEvent e to the context.
162 func (project *Project) runWithEvent(name string, logName string, e *watcher.FileEvent) error {
163 return project.run(name, logName, e)
164 }
165
166 func (project *Project) runTask(depName string, parentName string, e *watcher.FileEvent) error {
167 proj, _, taskName := project.mustTask(depName)
168
169 if proj == nil {
170 return fmt.Errorf("Project was not loaded for \"%s\" task", parentName)
171 }
172 return proj.runWithEvent(taskName, parentName+">"+depName, e)
173 }
174
175 func (project *Project) runParallel(steps []interface{}, parentName string, e *watcher.FileEvent) error {
176 var funcs = []func() error{}
177 for _, step := range steps {
178 switch t := step.(type) {
179 default:
180 panic(parentName + ": Parallel flow can only have types: (string | Series | Parallel)")
181 case string:
182 funcs = append(funcs, func() error {
183 return project.runTask(t, parentName, e)
184 })
185 case S:
186 funcs = append(funcs, func() error {
187 return project.runSeries(t, parentName, e)
188 })
189 case Series:
190 funcs = append(funcs, func() error {
191 return project.runSeries(t, parentName, e)
192 })
193 case P:
194 funcs = append(funcs, func() error {
195 return project.runParallel(t, parentName, e)
196 })
197 case Parallel:
198 funcs = append(funcs, func() error {
199 return project.runParallel(t, parentName, e)
200 })
201 }
202 }
203 err := GoThrottle(3, funcs...)
204 return err
205 }
206
207 func (project *Project) runSeries(steps []interface{}, parentName string, e *watcher.FileEvent) error {
208 var err error
209 for _, step := range steps {
210 switch t := step.(type) {
211 default:
212 panic(parentName + ": Series can only have types: (string | Series | Parallel)")
213 case string:
214 err = project.runTask(t, parentName, e)
215 case S:
216 err = project.runSeries(t, parentName, e)
217 case Series:
218 err = project.runSeries(t, parentName, e)
219 case P:
220 err = project.runParallel(t, parentName, e)
221 case Parallel:
222 err = project.runParallel(t, parentName, e)
223 }
224 if err != nil {
225 return err
226 }
227 }
228 return nil
229 }
230
231 // run runs the project, executing any tasks named on the command line.
232 func (project *Project) run(name string, logName string, e *watcher.FileEvent) error {
233 proj, task, _ := project.mustTask(name)
234
235 if !task.shouldRun(e) {
236 return nil
237 }
238
239 // debounce needs to be separate from shouldRun, so we can enqueue
240 // a file event that arrives between debounce intervals
241 if proj.debounce(task) {
242 if task.shouldRun(e) {
243 task.Lock()
244 if !task.ignoreEvents {
245 task.ignoreEvents = true
246 // fmt.Printf("DBG: ENQUEUE fileevent in between debounce\n")
247 time.AfterFunc(task.debounceValue(), func() {
248 // fmt.Printf("DBG: Running ENQUEUED\n")
249 task.Lock()
250 task.ignoreEvents = false
251 task.Unlock()
252 project.run(name, logName, e)
253 })
254 }
255 task.Unlock()
256 }
257
258 return nil
259 }
260
261 // run dependencies first
262 err := proj.runSeries(task.dependencies, name, e)
263 if err != nil {
264 return err
265 }
266
267 // then run the task itself
268 return task.RunWithEvent(logName, e)
269 }
270
271 // usage returns a string for usage screen
272 func (project *Project) usage() string {
273 tasks := "Tasks:\n"
274 names := []string{}
275 m := map[string]*Task{}
276 for ns, proj := range project.Namespace {
277 if ns != "" {
278 ns += ":"
279 }
280 for _, task := range proj.Tasks {
281 names = append(names, ns+task.Name)
282 m[ns+task.Name] = task
283 }
284 }
285 sort.Strings(names)
286 longest := 0
287 for _, name := range names {
288 l := len(name)
289 if l > longest {
290 longest = l
291 }
292 }
293
294 for _, name := range names {
295 task := m[name]
296 description := task.description
297 if description == "" {
298 if len(task.dependencies) > 0 {
299 description = fmt.Sprintf("Runs %v %s", task.DependencyNames(), name)
300 } else {
301 description = "Runs " + name
302 }
303 }
304 tasks += fmt.Sprintf(" %-"+strconv.Itoa(longest)+"s %s\n", name, description)
305 }
306
307 return tasks
308 }
309
310 // Use uses another project's task within a namespace.
311 func (project *Project) Use(namespace string, tasksFunc func(*Project)) {
312 namespace = strings.Trim(namespace, ":")
313 proj := NewProject(tasksFunc, project.exitFn, project.contextArgm)
314 proj.ns = project.ns + ":" + namespace
315 project.Namespace[namespace] = proj
316 proj.parent = project
317 }
318
319 // Task adds a task to the project with dependencies and handler.
320 func (project *Project) Task(name string, dependencies Dependency, handler func(*Context)) *Task {
321 task := NewTask(name, project.contextArgm)
322
323 if handler == nil && dependencies == nil {
324 util.Panic("godo", "Task %s requires a dependency or handler\n", name)
325 }
326
327 if handler != nil {
328 task.Handler = HandlerFunc(handler)
329 }
330 if dependencies != nil {
331 task.dependencies = append(task.dependencies, dependencies)
332 }
333
334 project.Tasks[task.Name] = task
335 return task
336 }
337
338 // Task1 adds a simple task to the project.
339 func (project *Project) Task1(name string, handler func(*Context)) *Task {
340 task := NewTask(name, project.contextArgm)
341
342 if handler == nil {
343 util.Panic("godo", "Task %s requires a dependency or handler\n", name)
344 }
345
346 task.Handler = HandlerFunc(handler)
347
348 project.Tasks[task.Name] = task
349 return task
350 }
351
352 // TaskD adds a task which runs other dependencies with no handler.
353 func (project *Project) TaskD(name string, dependencies Dependency) *Task {
354 task := NewTask(name, project.contextArgm)
355
356 if dependencies == nil {
357 util.Panic("godo", "Task %s requires a dependency or handler\n", name)
358 }
359
360 task.dependencies = append(task.dependencies, dependencies)
361 project.Tasks[task.Name] = task
362 return task
363 }
364
365 func (project *Project) watchTask(task *Task, root string, logName string, handler func(e *watcher.FileEvent)) {
366 ignorePathFn := func(p string) bool {
367 return watcher.DefaultIgnorePathFn(p) || !task.isWatchedFile(p)
368 }
369
370 const bufferSize = 2048
371 watchr, err := watcher.NewWatcher(bufferSize)
372 if err != nil {
373 util.Panic("project", "%v\n", err)
374 }
375 watchr.IgnorePathFn = ignorePathFn
376 watchr.ErrorHandler = func(err error) {
377 util.Error("project", "Watcher error %v\n", err)
378 }
379 watchr.WatchRecursive(root)
380
381 // this function will block forever, Ctrl+C to quit app
382 abs, err := filepath.Abs(root)
383 if err != nil {
384 fmt.Println("Could not get absolute path", err)
385 return
386 }
387 util.Info(logName, "watching %s\n", abs)
388
389 // not sure why this need to be unbuffered, but it was blocking
390 // on cquit <- true
391 cquit := make(chan bool, 1)
392 project.Lock()
393 project.cwatchTasks[cquit] = true
394 project.Unlock()
395 watchr.Start()
396 forloop:
397 for {
398 select {
399 case event := <-watchr.Event:
400 if event.Path != "" {
401 util.InfoColorful("godo", "%s changed\n", event.Path)
402 }
403 handler(event)
404 case <-cquit:
405 watchr.Stop()
406 break forloop
407 }
408 }
409 }
410
411 // Define defines tasks
412 func (project *Project) Define(fn func(*Project)) {
413 fn(project)
414 }
415
416 func calculateWatchPaths(patterns []string) []string {
417 //fmt.Println("DBG:calculateWatchPaths patterns", patterns)
418 paths := map[string]bool{}
419 for _, pat := range patterns {
420 if pat == "" {
421 continue
422 }
423 path := glob.PatternRoot(pat)
424 abs, err := filepath.Abs(path)
425 if err != nil {
426 fmt.Println("Error calculating watch paths", err)
427 }
428 paths[abs] = true
429 }
430
431 var keys []string
432 for key := range paths {
433 keys = append(keys, key)
434 }
435 sort.Strings(keys)
436 //fmt.Println("DBG:calculateWatchPaths keys", keys)
437
438 // skip any directories that overlap each other, eg test/sub should be
439 // ignored if test/ is in paths
440 var skip = map[string]bool{}
441 for i, dir := range keys {
442 dirSlash := dir + "/"
443 for _, dirj := range keys[i+1:] {
444 if strings.HasPrefix(dirj, dirSlash) {
445 skip[dirj] = true
446 }
447 }
448 }
449
450 var keep = []string{}
451 for _, dir := range keys {
452 if skip[dir] {
453 continue
454 }
455 rel, err := filepath.Rel(wd, dir)
456 if err != nil {
457 fmt.Println("Error calculating relative path", err)
458 continue
459 }
460 keep = append(keep, rel)
461 }
462
463 //fmt.Println("DBG:calculateWatchPaths keep", keep)
464 return keep
465 }
466
467 // gatherWatchInfo updates globs and regexps for the task based on its dependencies
468 func (project *Project) gatherWatchInfo(task *Task) (globs []string, regexps []*glob.RegexpInfo) {
469 globs = task.SrcGlobs
470 regexps = task.SrcRegexps
471
472 if len(task.dependencies) > 0 {
473 names := task.DependencyNames()
474
475 proj := project
476 for _, depname := range names {
477 var task *Task
478 proj, task, _ = project.mustTask(depname)
479 tglobs, tregexps := proj.gatherWatchInfo(task)
480 task.EffectiveWatchRegexps = tregexps
481 globs = append(globs, tglobs...)
482 regexps = append(regexps, tregexps...)
483 }
484 }
485 task.EffectiveWatchRegexps = regexps
486 task.EffectiveWatchGlobs = globs
487 return
488 }
489
490 // Watch watches the Files of a task and reruns the task on a watch event. Any
491 // direct dependency is also watched. Returns true if watching.
492 //
493 //
494 // TODO:
495 // 1. Only the parent task watches, but it gathers wath info from all dependencies.
496 //
497 // 2. Anything without src files always run when a dependency is triggered by a glob match.
498 //
499 // build [generate{*.go} compile] => go file changes => build, generate and compile
500 //
501 // 3. Tasks with src only run if it matches a src
502 //
503 // build [generate{*.go} css{*.scss} compile] => go file changes => build, generate and compile
504 // css does not need to run since no SCSS files ran
505 //
506 // X depends on [A:txt, B] => txt changes A runs, X runs without deps
507 // X:txt on [A, B] => txt changes A, B, X runs
508 //
509 func (project *Project) Watch(names []string, isParent bool) bool {
510 // fixes a bug where the first debounce prevents the task from running because
511 // all tasks are run once before Watch() is called
512 project.reset()
513
514 funcs := []func(){}
515
516 taskClosure := func(project *Project, task *Task, taskname string, logName string) func() {
517 paths := calculateWatchPaths(task.EffectiveWatchGlobs)
518 return func() {
519 if len(paths) == 0 {
520 return
521 }
522 for _, pth := range paths {
523 go func(path string) {
524 project.watchTask(task, path, logName, func(e *watcher.FileEvent) {
525 err := project.run(taskname, taskname, e)
526 if err != nil {
527 util.Error("ERR", "%s\n", err.Error())
528 }
529 })
530 }(pth)
531 }
532 }
533 }
534
535 for _, taskname := range names {
536 proj, task, _ := project.mustTask(taskname)
537 // updates effectiveWatchGlobs
538 proj.gatherWatchInfo(task)
539 if len(task.EffectiveWatchGlobs) > 0 {
540 funcs = append(funcs, taskClosure(project, task, taskname, taskname))
541 }
542 }
543
544 if len(funcs) > 0 {
545 <-all(funcs)
546 return true
547 }
548 return false
549 }
550
551 // Dumps information about the project to the console
552 func (project *Project) dump(buf io.Writer, prefix string, indent string) {
553 fmt.Fprintln(buf, "")
554 fmt.Fprintln(buf, prefix, project.ns, " =>")
555 fmt.Fprintln(buf, indent, "Tasks:")
556 for _, task := range project.Tasks {
557 task.dump(buf, indent+indent)
558 }
559
560 for key, proj := range project.Namespace {
561 if key == "" {
562 continue
563 }
564 proj.dump(buf, prefix, indent)
565 }
566 }
567
568 func (project *Project) quit(isParent bool) {
569 for ns, proj := range project.Namespace {
570 if ns != "" {
571 proj.quit(false)
572 }
573 }
574 // kill all watchTasks
575 for cquit := range project.cwatchTasks {
576 cquit <- true
577 }
578 if isParent {
579 runnerWaitGroup.Stop()
580 for _, process := range Processes {
581 if process != nil {
582 process.Kill()
583 }
584 }
585 }
586 //fmt.Printf("DBG: QUITTED\n")
587 }
588
589 // Exit quits the project.
590 func (project *Project) Exit(code int) {
591 project.quit(true)
592 }
593
594 // all runs the functions in fns concurrently.
595 func all(fns []func()) (done <-chan bool) {
596 var wg sync.WaitGroup
597 wg.Add(len(fns))
598
599 ch := make(chan bool, 1)
600 for _, fn := range fns {
601 go func(f func()) {
602 f()
603 wg.Done()
604 }(fn)
605 }
606 go func() {
607 wg.Wait()
608 doneSig(ch, true)
609 }()
610 return ch
611 }
612
613 func doneSig(ch chan bool, val bool) {
614 ch <- val
615 close(ch)
616 }