Skip to content

Commit

Permalink
format: Asserting result of fmt is valid rego
Browse files Browse the repository at this point in the history
Fixes: open-policy-agent#6833
Signed-off-by: Johan Fylling <[email protected]>
  • Loading branch information
johanfylling committed Jul 9, 2024
1 parent 3209910 commit 6e596ed
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions cmd/fmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type fmtCommandParams struct {
fail bool
regoV1 bool
v1Compatible bool
checkResult bool
}

var fmtParams = fmtCommandParams{}
Expand Down Expand Up @@ -133,6 +134,13 @@ func formatFile(params *fmtCommandParams, out io.Writer, filename string, info o
return newError("failed to format Rego source file: %v", err)
}

if params.checkResult {
_, err := ast.ParseModule("formatted", string(formatted))
if err != nil {
return newError("%s was successfully formatted, but the result is invalid: %v\n\nTo inspect the formatted Rego, you can turn off this check with --check-result=false.", filename, err)
}
}

changed := !bytes.Equal(contents, formatted)

if params.fail && !params.list && !params.diff {
Expand Down Expand Up @@ -229,6 +237,7 @@ func init() {
formatCommand.Flags().BoolVar(&fmtParams.fail, "fail", false, "non zero exit code on reformat")
addRegoV1FlagWithDescription(formatCommand.Flags(), &fmtParams.regoV1, false, "format module(s) to be compatible with both Rego v1 and current OPA version)")
addV1CompatibleFlag(formatCommand.Flags(), &fmtParams.v1Compatible, false)
formatCommand.Flags().BoolVar(&fmtParams.checkResult, "check-result", true, "assert that the formatted code is valid")

RootCommand.AddCommand(formatCommand)
}

0 comments on commit 6e596ed

Please sign in to comment.