-
Notifications
You must be signed in to change notification settings - Fork 18
/
taskfilter.go
88 lines (67 loc) · 2.02 KB
/
taskfilter.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
package taskfilter
import (
"errors"
"fmt"
"github.com/cirruslabs/cirrus-ci-agent/api"
"strings"
)
var ErrNoMatch = errors.New("task filter yielded no matches")
type TaskFilter func([]*api.Task) ([]*api.Task, error)
func MatchAnyTask() TaskFilter {
return func(tasks []*api.Task) ([]*api.Task, error) {
return tasks, nil
}
}
func MatchExactTask(desiredTaskName string) TaskFilter {
return func(tasks []*api.Task) ([]*api.Task, error) {
var filteredTasks []*api.Task
for _, task := range tasks {
// Ensure that this task's name matches with the name we're looking for
desiredTaskNameLower := strings.ToLower(desiredTaskName)
taskNameLower := strings.ToLower(task.Name)
if !strings.HasPrefix(desiredTaskNameLower, taskNameLower) {
continue
}
// In case we're looking for a task with specific labels — extract them and ensure they all match
desiredLabels := extractLabels(strings.TrimPrefix(desiredTaskNameLower, taskNameLower))
var actualLabels []string
if task.Metadata != nil {
actualLabels = task.Metadata.UniqueLabels
}
if !containsAll(actualLabels, desiredLabels) {
continue
}
// Clear task's dependencies
task.RequiredGroups = task.RequiredGroups[:0]
filteredTasks = append(filteredTasks, task)
}
if len(filteredTasks) == 0 {
return nil, fmt.Errorf("%w: none of the %d task(s) were matched using a %q filter",
ErrNoMatch, len(tasks), desiredTaskName)
}
return filteredTasks, nil
}
}
func extractLabels(s string) (result []string) {
labels := strings.Split(s, " ")
// Filter out empty labels
for _, label := range labels {
if strings.TrimSpace(label) == "" {
continue
}
result = append(result, label)
}
return
}
func containsAll(actualLabels []string, desiredLabels []string) bool {
var numMatchedLabels int
for _, desiredLabel := range desiredLabels {
for _, actualLabel := range actualLabels {
if strings.EqualFold(desiredLabel, actualLabel) {
numMatchedLabels++
break
}
}
}
return numMatchedLabels == len(desiredLabels)
}