Skip to content

Commit

Permalink
fmt: Trim trailing whitespace in comments
Browse files Browse the repository at this point in the history
Not sure if there's a better way to accomplish this, but
it seems to get the job done.

Fixes #6161

Signed-off-by: Anders Eknert <[email protected]>
  • Loading branch information
anderseknert committed Aug 17, 2023
1 parent abb6cf2 commit 57054bf
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
11 changes: 11 additions & 0 deletions format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"regexp"
"sort"
"strings"
"unicode"

"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/internal/future"
Expand Down Expand Up @@ -270,6 +271,8 @@ func (w *writer) writeModule(module *ast.Module, o fmtOpts) {
return locLess(others[i], others[j])
})

comments = trimTrailingWhitespaceInComments(comments)

comments = w.writePackage(pkg, comments)
var imports []*ast.Import
var rules []*ast.Rule
Expand All @@ -288,6 +291,14 @@ func (w *writer) writeModule(module *ast.Module, o fmtOpts) {
}
}

func trimTrailingWhitespaceInComments(comments []*ast.Comment) []*ast.Comment {
for _, c := range comments {
c.Text = bytes.TrimRightFunc(c.Text, unicode.IsSpace)
}

return comments
}

func (w *writer) writePackage(pkg *ast.Package, comments []*ast.Comment) []*ast.Comment {
comments = w.insertComments(comments, pkg.Location)

Expand Down
8 changes: 8 additions & 0 deletions format/testfiles/test_issue_6161.rego
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package p

# this is a comment with trailing whitespace

allow {
# another comment with trailing whitespace
1 == 1
}
8 changes: 8 additions & 0 deletions format/testfiles/test_issue_6161.rego.formatted
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package p

# this is a comment with trailing whitespace

allow {
# another comment with trailing whitespace
1 == 1
}

0 comments on commit 57054bf

Please sign in to comment.