-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathpipeline.go
More file actions
349 lines (288 loc) · 7.7 KB
/
pipeline.go
File metadata and controls
349 lines (288 loc) · 7.7 KB
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"fmt"
"os"
"reflect"
"strconv"
"strings"
"github.com/bmatcuk/doublestar/v4"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
// WaitStep represents a Buildkite Wait Step
// https://buildkite.com/docs/pipelines/wait-step
// We can't use Step here since the value for Wait is always nil
// regardless of whether or not we want to include the key.
type WaitStep struct{}
func (WaitStep) MarshalYAML() (interface{}, error) {
return map[string]interface{}{
"wait": nil,
}, nil
}
func (s Step) MarshalYAML() (interface{}, error) {
if s.Group == "" {
type Alias Step
return (Alias)(s), nil
}
label := s.Group
key := s.Key
s.Group = ""
s.Key = ""
stps := []Step{s}
if s.Steps != nil {
stps = s.Steps
}
return Group{Label: label, Key: key, Steps: stps}, nil
}
func (n PluginNotify) MarshalYAML() (interface{}, error) {
type Alias PluginNotify
return (Alias)(n), nil
}
// PipelineGenerator generates pipeline file
type PipelineGenerator func(steps []Step, plugin Plugin) (*os.File, bool, error)
func uploadPipeline(plugin Plugin, generatePipeline PipelineGenerator) (string, []string, error) {
diffOutput, err := diff(plugin.Diff)
if err != nil {
log.Fatal(err)
return "", []string{}, err
}
if len(diffOutput) < 1 {
log.Info("No changes detected. Skipping pipeline upload.")
return "", []string{}, nil
}
log.Debug("Output from diff: \n" + strings.Join(diffOutput, "\n"))
steps, err := stepsToTrigger(diffOutput, plugin.Watch)
if err != nil {
return "", []string{}, err
}
pipeline, hasSteps, err := generatePipeline(steps, plugin)
if err != nil {
return "", []string{}, err
}
defer func() {
if removeErr := os.Remove(pipeline.Name()); removeErr != nil {
log.Errorf("Failed to remove temporary pipeline file: %v", removeErr)
}
}()
if !hasSteps {
log.Info("No steps generated. Skipping pipeline upload.")
return "", []string{}, nil
}
cmd := "buildkite-agent"
args := []string{"pipeline", "upload", pipeline.Name()}
if !plugin.Interpolation {
args = append(args, "--no-interpolation")
}
_, err = executeCommand("buildkite-agent", args)
return cmd, args, err
}
func diff(command string) ([]string, error) {
log.Infof("Running diff command: %s", command)
output, err := executeCommand(
env("SHELL", "bash"),
[]string{"-c", strings.ReplaceAll(command, "\n", " ")},
)
if err != nil {
return nil, fmt.Errorf("diff command failed: %v", err)
}
hasNewlines := strings.ContainsRune(output, '\n')
output = strings.TrimRight(output, "\n")
if output == "" {
return []string{}, nil
}
var fields []string
if hasNewlines {
for _, line := range strings.Split(output, "\n") {
line = strings.TrimSpace(line)
if line != "" {
fields = append(fields, line)
}
}
} else {
// Single line without newline — legacy compat for custom diff commands
fields = strings.Fields(output)
}
paths := make([]string, 0, len(fields))
for _, field := range fields {
// Git quotes paths with special characters using C-style quoting
if strings.HasPrefix(field, "\"") && strings.HasSuffix(field, "\"") {
// Unquote to decode escape sequences (e.g., \360\237\252\201 -> 🪁)
if unquoted, err := strconv.Unquote(field); err == nil {
paths = append(paths, unquoted)
} else {
// If unquoting fails, fall back to removing quotes
paths = append(paths, strings.Trim(field, "\""))
}
} else {
paths = append(paths, field)
}
}
return paths, nil
}
// filterValidSteps splits steps into valid and invalid
func filterValidSteps(steps []Step) (valid []Step, invalid []Step) {
valid = []Step{}
invalid = []Step{}
for _, step := range steps {
if step.isValid() {
valid = append(valid, step)
} else {
invalid = append(invalid, step)
}
}
return valid, invalid
}
// logInvalidStep logs why a step is invalid
func logInvalidStep(step Step) {
context := "empty step configuration"
if step.Group != "" {
if len(step.Steps) == 0 {
context = fmt.Sprintf("group '%s' has no valid nested steps", step.Group)
} else {
context = fmt.Sprintf("group '%s' has invalid nested steps", step.Group)
}
} else if step.Label != "" {
context = fmt.Sprintf("step with label '%s' has no command, trigger, or group", step.Label)
}
log.Warnf("Skipping invalid step: %s. Steps must have at least one of: command, commands, trigger, or group with nested steps.", context)
}
func stepsToTrigger(files []string, watch []WatchConfig) ([]Step, error) {
steps := []Step{}
var defaultStep *Step
for _, w := range watch {
if w.Default != nil {
defaultStep = &w.Step
continue
}
except := false
for _, ex := range w.ExceptPaths {
if except {
break
}
for _, f := range files {
exceptMatch, errExcept := matchPath(ex, f)
if errExcept != nil {
return nil, errExcept
}
if exceptMatch {
log.Printf("excepted: %s\n", f)
except = true
break
}
}
}
if except {
continue
}
for _, p := range w.Paths {
for _, f := range files {
match, err := matchPath(p, f)
skip := false
for _, sp := range w.SkipPaths {
skipMatch, errSkip := matchPath(sp, f)
if errSkip != nil {
return nil, errSkip
}
if skipMatch {
skip = true
}
}
if err != nil {
return nil, err
}
if match && !skip {
steps = append(steps, w.Step)
break
}
}
}
}
if len(steps) == 0 && defaultStep != nil {
steps = append(steps, *defaultStep)
}
deduped := dedupSteps(steps)
valid, invalid := filterValidSteps(deduped)
// Log all invalid steps with helpful context
for _, step := range invalid {
logInvalidStep(step)
}
return valid, nil
}
// matchPath checks if the file f matches the path p.
func matchPath(p string, f string) (bool, error) {
// If the path contains a glob, the `doublestar.Match`
// method is used to determine the match,
// otherwise `strings.HasPrefix` is used.
if strings.Contains(p, "*") {
match, err := doublestar.Match(p, f)
if err != nil {
return false, fmt.Errorf("path matching failed: %v", err)
}
if match {
return true, nil
}
}
if strings.HasPrefix(f, p) {
return true, nil
}
return false, nil
}
func dedupSteps(steps []Step) []Step {
unique := []Step{}
for _, p := range steps {
duplicate := false
for _, t := range unique {
if reflect.DeepEqual(p, t) {
duplicate = true
break
}
}
if !duplicate {
unique = append(unique, p)
}
}
return unique
}
func generatePipeline(steps []Step, plugin Plugin) (*os.File, bool, error) {
tmp, err := os.CreateTemp(os.TempDir(), "bmrd-")
if err != nil {
return nil, false, fmt.Errorf("could not create temporary pipeline file: %v", err)
}
yamlSteps := make([]yaml.Marshaler, len(steps))
for i, step := range steps {
yamlSteps[i] = step
}
if plugin.Wait {
yamlSteps = append(yamlSteps, WaitStep{})
}
for _, cmd := range plugin.Hooks {
yamlSteps = append(yamlSteps, Step{Command: cmd.Command})
}
yamlNotify := make([]yaml.Marshaler, len(plugin.Notify))
for i, n := range plugin.Notify {
yamlNotify[i] = n
}
pipeline := map[string][]yaml.Marshaler{
"steps": yamlSteps,
}
if len(yamlNotify) > 0 {
pipeline["notify"] = yamlNotify
}
data, err := yaml.Marshal(&pipeline)
if err != nil {
return nil, false, fmt.Errorf("could not serialize the pipeline: %v", err)
}
// Disable logging in context of go tests.
if env("TEST_MODE", "") != "true" {
fmt.Printf("Generated Pipeline:\n%s\n", string(data))
}
if err = os.WriteFile(tmp.Name(), data, 0o644); err != nil {
return nil, false, fmt.Errorf("could not write step to temporary file: %v", err)
}
// Returns the temporary file and a boolean indicating whether or not the pipeline has steps
if len(yamlSteps) == 0 {
return tmp, false, nil
} else {
return tmp, true, nil
}
}