Fix opa fmt location for non-key rules (#4695)

Running the following through `opa fmt`:

    package foo

    bar {
    	# before
    	input.bar
    	# after
    }

Causes the `after` comment to be moved outside of the rule:

    package foo

    bar {
    	# before
    	input.bar
    }

    # after

This was caused by `skipPast` in `closingLoc` being called even when there is no
`[key]` part in the rule head.  Adding a third clause fixed this; it seems
like `closingLoc` is designed to take `0` in this case because of the
`skipOpen > 0`.

This did affect one other test case, where I had to add an extra newline
to separate the comment from the rule head.  Without that, `insertComments`
(correctly, I guess) inserts:

    } # some special case

Signed-off-by: Jasper Van der Jeugt <m@jaspervdj.be>
This commit is contained in:
Jasper Van der Jeugt
2022-05-16 17:38:30 +02:00
committed by GitHub
parent 2a1ef47110
commit 07227f6a38
4 changed files with 19 additions and 2 deletions
+3 -1
View File
@@ -300,8 +300,10 @@ func (w *writer) writeRule(rule *ast.Rule, isElse bool, comments []*ast.Comment)
if len(rule.Head.Args) > 0 {
closeLoc = closingLoc('(', ')', '{', '}', rule.Location)
} else {
} else if rule.Head.Key != nil {
closeLoc = closingLoc('[', ']', '{', '}', rule.Location)
} else {
closeLoc = closingLoc(0, 0, '{', '}', rule.Location)
}
comments = w.insertComments(comments, closeLoc)
@@ -0,0 +1,7 @@
package foo
bar {
# before
input.bar
# after
}
@@ -0,0 +1,7 @@
package foo
bar {
# before
input.bar
# after
}
+2 -1
View File
@@ -25,7 +25,8 @@ else = z {
# Mixed compact and newline separated
p = x {
foo == "bar"
} # some special case
}
# some special case
# with lots of comments
# describing it
else = y {