Skip to content

Commit 73b8c65

Browse files
authored
Improve pointless-reassignment to cover nested cases (#1727)
Previously this rule would only check expressions at the topmost level of rule bodies. Now it checks expressions anywhere in the policy. Signed-off-by: Anders Eknert <anders@eknert.com>
1 parent f3722ea commit 73b8c65

2 files changed

Lines changed: 40 additions & 7 deletions

File tree

bundle/regal/rules/style/pointless-reassignment/pointless_reassignment.rego

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,15 @@ report contains violation if {
1717
violation := result.fail(rego.metadata.chain(), result.location(rule))
1818
}
1919

20-
# pointless reassignment in rule body
20+
# pointless reassignment in expressions
2121
report contains violation if {
22-
expr := input.rules[_].body[_]
22+
some expr
23+
ast.found.expressions[_][expr].terms[0].value[0].value == "assign"
2324

2425
not expr.with
25-
26-
[lhs, rhs] := ast.assignment_terms(expr.terms)
27-
28-
lhs.type == "var"
29-
rhs.type == "var"
26+
expr.terms[0].type == "ref"
27+
expr.terms[1].type == "var"
28+
expr.terms[2].type == "var"
3029

3130
violation := result.fail(rego.metadata.chain(), result.infix_expr_location(expr.terms))
3231
}

bundle/regal/rules/style/pointless-reassignment/pointless_reassignment_test.rego

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,40 @@ test_fail_pointless_reassignment_in_rule_body if {
6767
}}
6868
}
6969

70+
test_fail_pointless_reassignment_in_rule_body_nested if {
71+
module := ast.with_rego_v1(`
72+
rule if {
73+
foo := "foo"
74+
75+
comp := [bar |
76+
bar := foo
77+
]
78+
}
79+
`)
80+
r := rule.report with input as module
81+
82+
r == {{
83+
"category": "style",
84+
"description": "Pointless reassignment of variable",
85+
"level": "error",
86+
"location": {
87+
"col": 4,
88+
"row": 10,
89+
"end": {
90+
"col": 10,
91+
"row": 10,
92+
},
93+
"file": "policy.rego",
94+
"text": "\t\t\tbar := foo",
95+
},
96+
"related_resources": [{
97+
"description": "documentation",
98+
"ref": config.docs.resolve_url("$baseUrl/$category/pointless-reassignment", "style"),
99+
}],
100+
"title": "pointless-reassignment",
101+
}}
102+
}
103+
70104
test_success_pointless_reassignment_in_rule_body_using_with if {
71105
module := ast.with_rego_v1(`
72106
foo := input

0 commit comments

Comments
 (0)