-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.go
105 lines (93 loc) · 2.33 KB
/
filter.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
package factory
import (
"github.com/hashicorp/hcl/v2"
"github.com/zclconf/go-cty/cty"
)
type Include struct {
Paths []string
Branches []string
}
type Exclude struct {
Paths []string
Branches []string
}
type Filter struct {
Include Include
Exclude Exclude
}
var filterBlockSchema = &hcl.BodySchema{
Attributes: []hcl.AttributeSchema{
{Name: "stages"},
},
Blocks: []hcl.BlockHeaderSchema{
{Type: "include"},
{Type: "exclude"},
},
}
func decodeFilterBlock(block *hcl.Block) (*Filter, hcl.Diagnostics) {
content, diags := block.Body.Content(filterBlockSchema)
filter := &Filter{}
// Decode blocks
for _, block := range content.Blocks {
switch block.Type {
case "include":
include, incDiags := decodeIncludeOrExcludeBlock(block)
diags = append(diags, incDiags...)
filter.Include = *include.(*Include)
case "exclude":
exclude, exDiags := decodeIncludeOrExcludeBlock(block)
diags = append(diags, exDiags...)
filter.Exclude = *exclude.(*Exclude)
}
}
return filter, diags
}
func decodeIncludeOrExcludeBlock(block *hcl.Block) (interface{}, hcl.Diagnostics) {
attributes, diags := block.Body.JustAttributes()
var result interface{}
switch block.Type {
case "include":
include := Include{}
result = &include
case "exclude":
exclude := Exclude{}
result = &exclude
}
for _, attr := range attributes {
switch attr.Name {
case "paths":
paths := decodeStringSliceAttribute(attr, &diags)
if block.Type == "include" {
result.(*Include).Paths = paths
} else {
result.(*Exclude).Paths = paths
}
case "branches":
branches := decodeStringSliceAttribute(attr, &diags)
if block.Type == "include" {
result.(*Include).Branches = branches
} else {
result.(*Exclude).Branches = branches
}
}
}
return result, diags
}
func decodeStringSliceAttribute(attr *hcl.Attribute, diags *hcl.Diagnostics) []string {
var result []string
p, d := attr.Expr.Value(nil)
*diags = append(*diags, d...)
for _, val := range p.AsValueSlice() {
if val.Type() != cty.String {
*diags = append(*diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Value within paths or branches must be of string type",
Detail: "Invalid type for branch or path",
Expression: attr.Expr,
})
return []string{}
}
result = append(result, val.AsString())
}
return result
}