forked from rhysd/actionlint
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrule_if_cond.go
More file actions
70 lines (62 loc) · 1.75 KB
/
rule_if_cond.go
File metadata and controls
70 lines (62 loc) · 1.75 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
package actionlint
import (
"strings"
)
// RuleIfCond is a rule to check if: conditions.
type RuleIfCond struct {
RuleBase
}
// NewRuleIfCond creates new RuleIfCond instance.
func NewRuleIfCond() *RuleIfCond {
return &RuleIfCond{
RuleBase: RuleBase{
name: "if-cond",
desc: "Checks for if: conditions which are always true/false",
},
}
}
// VisitStep is callback when visiting Step node.
func (rule *RuleIfCond) VisitStep(n *Step) error {
rule.checkIfCond(n.If)
return nil
}
// VisitJobPre is callback when visiting Job node before visiting its children.
func (rule *RuleIfCond) VisitJobPre(n *Job) error {
rule.checkIfCond(n.If)
if n.Snapshot != nil {
rule.checkIfCond(n.Snapshot.If)
}
return nil
}
func (rule *RuleIfCond) checkIfCond(n *String) {
if n == nil {
return
}
s, e := strings.Index(n.Value, "${{"), strings.Index(n.Value, "}}")
if s >= 0 && e >= 0 {
rule.checkPlaceholder(n, s, e)
} else {
rule.checkExpression(n.Pos, n.Value)
}
}
func (rule *RuleIfCond) checkPlaceholder(n *String, start, end int) {
// Check number of ${{ }} for conditions like `${{ false }} || ${{ true }}` which are always evaluated to true
if start > 0 || end+len("}}") < len(n.Value) || strings.Count(n.Value, "${{") > 1 {
rule.Errorf(
n.Pos,
"if: condition %q is always evaluated to true because extra characters are around ${{ }}",
n.Value,
)
return
}
rule.checkExpression(n.Pos, n.Value[start+len("${{"):end])
}
func (rule *RuleIfCond) checkExpression(pos *Pos, input string) {
i := strings.TrimSpace(input)
l := NewExprLexer(i + "}}")
if e, err := NewExprParser().Parse(l); err == nil {
if NewExprSemanticsChecker(false, nil).IsConstant(e) {
rule.Errorf(pos, "constant expression %q in condition. remove the if: section", i)
}
}
}