Skip to content

Commit 0c605cc

Browse files
authored
fix: consider padding pattern in sprintf-arguments-mismatch (#1575)
Fixes #1574 Signed-off-by: Anders Eknert <anders@styra.com>
1 parent be86c30 commit 0c605cc

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

bundle/regal/rules/bugs/sprintf-arguments-mismatch/sprintf_arguments_mismatch.rego

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ report contains violation if {
3737

3838
values_in_arr := count(fn.args[1].value)
3939
str_no_escape := replace(format_term.value, "%%", "") # don't include '%%' as it's used to "escape" %
40-
values_in_str := strings.count(str_no_escape, "%") - _repeated_explicit_argument_indexes(str_no_escape)
40+
num_patterns := strings.count(str_no_escape, "%")
41+
num_paddings := strings.count(str_no_escape, "%-*s") # these require 2 arguments to be provided
42+
values_in_str := (num_patterns + num_paddings) - _repeated_explicit_argument_indexes(str_no_escape)
4143

4244
values_in_str != values_in_arr
4345

bundle/regal/rules/bugs/sprintf-arguments-mismatch/sprintf_arguments_mismatch_test.rego

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,3 +157,36 @@ test_success_escaped_verbs_are_ignored if {
157157

158158
r == set()
159159
}
160+
161+
# verify fix for https://github.com/styrainc/regal/issues/1574
162+
test_fail_padding_not_accounted_for if {
163+
r := rule.report with input as ast.policy(`x := sprintf("%-*s", ["foo"])`)
164+
165+
r == {{
166+
"category": "bugs",
167+
"description": "Mismatch in `sprintf` arguments count",
168+
"level": "error",
169+
"location": {
170+
"col": 14,
171+
"end": {
172+
"col": 29,
173+
"row": 3,
174+
},
175+
"file": "policy.rego",
176+
"row": 3,
177+
"text": "x := sprintf(\"%-*s\", [\"foo\"])",
178+
},
179+
"related_resources": [{
180+
"description": "documentation",
181+
"ref": config.docs.resolve_url("$baseUrl/$category/sprintf-arguments-mismatch", "bugs"),
182+
}],
183+
"title": "sprintf-arguments-mismatch",
184+
}}
185+
}
186+
187+
# verify fix for https://github.com/styrainc/regal/issues/1574
188+
test_success_padding_accounted_for if {
189+
r := rule.report with input as ast.policy(`x := sprintf("%-*s", [2, "foo"])`)
190+
191+
r == set()
192+
}

0 commit comments

Comments
 (0)