This repository has been archived by the owner on Jan 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.go
75 lines (64 loc) · 1.6 KB
/
graph.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
package xgraph
import "fmt"
// Graph is an execution graph
type Graph struct {
generators []JobGenerator
jobs map[string]Job
}
// New creates a new Graph
func New() *Graph {
return &Graph{
generators: []JobGenerator{},
jobs: make(map[string]Job),
}
}
// AddJob adds a Job to the Graph
func (g *Graph) AddJob(job Job) *Graph {
g.jobs[job.Name()] = job
return g
}
// AddGenerator adds a JobGenerator to the Graph
func (g *Graph) AddGenerator(generator JobGenerator) *Graph {
g.generators = append(g.generators, generator)
return g
}
func (g *Graph) generateJob(name string) (Job, error) {
for _, gen := range g.generators {
j, err := gen(name)
if err != nil {
return nil, err
}
if j != nil {
g.AddJob(j)
return j, nil
}
}
return nil, nil
}
// JobNotFoundError is an error type indicating that a job was not found.
// The underlying string is the name of the job.
type JobNotFoundError string
func (err JobNotFoundError) Error() string {
return fmt.Sprintf("job not found: %q", string(err))
}
func (err JobNotFoundError) String() string {
return err.Error()
}
// GetJob searches the Graph for a Job with the specified name.
func (g *Graph) GetJob(name string) (j Job, err error) {
j = g.jobs[name]
if j == nil {
j, err = g.generateJob(name)
if err != nil {
return
}
}
if j == nil {
err = JobNotFoundError(name)
}
return
}
// JobGenerator is a type which generates Jobs dynamically.
// If a job with the given name should not be generated by this generator, a nil Job should be returned.
// Any errors will be propogated.
type JobGenerator func(name string) (Job, error)