Skip to content

Commit

Permalink
format: Fix panic with else blocks and comments
Browse files Browse the repository at this point in the history
When an else block had a comment in between it and the rule body we
were not starting a new line, which triggers a panic in the formatter.

This corrects the issue, and also removes the panics. If the functions
are not called correctly the formatting will be off and tests will
fail. There is little benefit in them causing a panic.

Fixes: #2420
Signed-off-by: Patrick East <[email protected]>
  • Loading branch information
patrick-east committed May 21, 2020
1 parent e6ac0a0 commit 1aec554
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
12 changes: 6 additions & 6 deletions format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,12 @@ func (w *writer) writeElse(rule *ast.Rule, comments []*ast.Comment) []*ast.Comme
rule.Else.Head.Args = nil
comments = w.insertComments(comments, rule.Else.Head.Location)

if hasCommentAbove && !wasInline {
// The comments would have ended the line, be sure to start one again
// before writing the rest of the "else" rule.
w.startLine()
}

// For backwards compatibility adjust the rule head value location
// TODO: Refactor the logic for inserting comments, or special
// case comments in a rule head value so this can be removed
Expand Down Expand Up @@ -1005,9 +1011,6 @@ func dedupComments(comments []*ast.Comment) []*ast.Comment {

// startLine begins a line with the current indentation level.
func (w *writer) startLine() {
if w.inline {
panic("currently in a line")
}
w.inline = true
for i := 0; i < w.level; i++ {
w.write(w.indent)
Expand All @@ -1016,9 +1019,6 @@ func (w *writer) startLine() {

// endLine ends a line with a newline.
func (w *writer) endLine() {
if !w.inline {
panic("not in a line")
}
w.inline = false
if w.beforeEnd != nil && !w.delay {
w.write(" " + w.beforeEnd.String())
Expand Down
11 changes: 11 additions & 0 deletions format/testfiles/test_issue_2420.rego
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package example

allow {
some_condition
}

# some comments

else {
another_condition
}
11 changes: 11 additions & 0 deletions format/testfiles/test_issue_2420.rego.formatted
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package example

allow {
some_condition
}

# some comments

else {
another_condition
}

0 comments on commit 1aec554

Please sign in to comment.