-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
step.go
145 lines (130 loc) · 2.56 KB
/
step.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package genny
import (
"bytes"
"crypto/sha1"
"errors"
"fmt"
"io"
"math/rand"
"strconv"
"sync"
"time"
"github.com/gobuffalo/genny/v2/internal/safe"
)
type DeleteFn func()
type Step struct {
as *Generator
before []*Generator
after []*Generator
index int
moot *sync.RWMutex
}
func (s *Step) Before(g *Generator) DeleteFn {
df := func() {
var a []*Generator
s.moot.Lock()
for _, b := range s.before {
if g.StepName == b.StepName {
continue
}
a = append(a, b)
}
s.before = a
s.moot.Unlock()
}
s.moot.Lock()
s.before = append(s.before, g)
s.moot.Unlock()
return df
}
func (s *Step) After(g *Generator) DeleteFn {
df := func() {
var a []*Generator
s.moot.Lock()
for _, b := range s.after {
if g.StepName == b.StepName {
continue
}
a = append(a, b)
}
s.after = a
s.moot.Unlock()
}
s.moot.Lock()
s.after = append(s.after, g)
s.moot.Unlock()
return df
}
func (s *Step) Run(r *Runner) error {
for _, b := range s.before {
if err := s.runGenerator(r, b); err != nil {
return err
}
}
if err := s.runGenerator(r, s.as); err != nil {
return err
}
for _, b := range s.after {
if err := s.runGenerator(r, b); err != nil {
return err
}
}
return nil
}
func (s *Step) runGenerator(r *Runner, g *Generator) error {
r.curGen = g
// payload := events.Payload{
// "runner": r,
// "step": s,
// "generator": g,
// }
if g.Should != nil {
err := safe.RunE(func() error {
if !g.Should(r) {
return io.EOF
}
return nil
})
if err != nil {
r.Logger.Debugf("Step: %s [skipped]", g.StepName)
// events.EmitPayload(EvtStepPrefix+":skipping:"+g.StepName, payload)
return nil
}
}
r.Logger.Debugf("Step: %s", g.StepName)
// events.EmitPayload(EvtStepPrefix+":running:"+g.StepName, payload)
return r.Chdir(r.Root, func() error {
for _, fn := range g.runners {
err := safe.RunE(func() error {
return fn(r)
})
if err != nil {
// events.EmitError(EvtStepPrefix+":running:"+g.StepName+":err", err, payload)
return err
}
}
return nil
})
}
func NewStep(g *Generator, index int) (*Step, error) {
if g == nil {
return nil, errors.New("generator can not be nil")
}
return &Step{
as: g,
index: index,
moot: &sync.RWMutex{},
}, nil
}
func init() {
rand.Seed(time.Now().UnixNano())
}
func stepName() string {
bb := &bytes.Buffer{}
bb.WriteString(fmt.Sprint(time.Now().UnixNano()))
bb.WriteString(strconv.Itoa(rand.Int()))
bb.WriteString(strconv.Itoa(rand.Int()))
h := sha1.New()
h.Write(bb.Bytes())
return fmt.Sprintf("%x", h.Sum(nil))[:8]
}