diff --git a/format/format.go b/format/format.go index 22cabd9605b..144bb3527bf 100644 --- a/format/format.go +++ b/format/format.go @@ -11,6 +11,7 @@ import ( "regexp" "sort" "strings" + "unicode" "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/future" @@ -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 @@ -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) diff --git a/format/testfiles/test_issue_6161.rego b/format/testfiles/test_issue_6161.rego new file mode 100644 index 00000000000..8f2839b42c7 --- /dev/null +++ b/format/testfiles/test_issue_6161.rego @@ -0,0 +1,8 @@ +package p + +# this is a comment with trailing whitespace + +allow { + # another comment with trailing whitespace + 1 == 1 +} diff --git a/format/testfiles/test_issue_6161.rego.formatted b/format/testfiles/test_issue_6161.rego.formatted new file mode 100644 index 00000000000..9f78be7b051 --- /dev/null +++ b/format/testfiles/test_issue_6161.rego.formatted @@ -0,0 +1,8 @@ +package p + +# this is a comment with trailing whitespace + +allow { + # another comment with trailing whitespace + 1 == 1 +}