Back to Opa

sprintf-arguments-mismatch

docs/projects/regal/rules/bugs/sprintf-arguments-mismatch.md

1.16.11.8 KB
Original Source

sprintf-arguments-mismatch

Summary: Mismatch in sprintf arguments count

Category: Bugs

Avoid

rego
package policy

max_issues := 1

report contains warning if {
    count(issues) > max_issues

    # two placeholders found in the string, but only one value in the array
    warning := sprintf("number of issues (%d) must not be higher than %d", [count(issues)])
}

Prefer

rego
package policy

max_issues := 1

report contains warning if {
    count(issues) > max_issues

    # two placeholders found in the string, and two values in the array
    warning := sprintf("number of issues (%d) must not be higher than %d", [count(issues), max_issues])
}

Rationale

While the built-in sprintf function itself reports argument mismatches, it'll do so by returning a string containing the error message rather than actually failing.

shell
> opa eval -f pretty 'sprintf("%v %d", [1])'
"1 %!d(MISSING)"

While this is normally caught in development and testing, having this issue reported at "compile time", which ideally is directly in your editor as you work on your policy. This means less time spent chasing down issues later, and a happier development experience.

Configuration Options

This linter rule provides the following configuration options:

yaml
rules:
  bugs:
    sprintf-arguments-mismatch:
      # one of "error", "warning", "ignore"
      level: error