Skip to content

Commit

Permalink
trim trailing newlines
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 523324423
  • Loading branch information
vapier authored and txtpbfmt-copybara-robot committed Apr 11, 2023
1 parent 3462fbc commit 7962e19
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 6 deletions.
16 changes: 14 additions & 2 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -1337,13 +1337,25 @@ func DebugFormat(nodes []*ast.Node, depth int) string {
func Pretty(nodes []*ast.Node, depth int) string {
var result strings.Builder
formatter{&result}.writeNodes(removeDeleted(nodes), depth, false /* isSameLine */, false /* asListItems */)
return result.String()

// Trim excess trailing newlines.
res := result.String()
if strings.HasSuffix(res, "\n\n") {
return res[:len(res)-1]
}
return res
}

func out(nodes []*ast.Node) []byte {
var result bytes.Buffer
formatter{&result}.writeNodes(removeDeleted(nodes), 0, false /* isSameLine */, false /* asListItems */)
return result.Bytes()

// Trim excess trailing newlines.
res := result.Bytes()
if bytes.HasSuffix(res, []byte("\n\n")) {
return res[:len(res)-1]
}
return res
}

// UnsortedFieldCollector collects UnsortedFields during parsing.
Expand Down
35 changes: 31 additions & 4 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,6 @@ presubmit: {
review_notify: "address" # review same line comment 2
}
`}, {
name: "empty children",
in: `
Expand All @@ -359,7 +358,6 @@ presubmit: {
# presubmit comment 2
presubmit: {
}
`}, {
name: "list notation with []",
in: `
Expand Down Expand Up @@ -605,7 +603,6 @@ tricorder: {
options:
"first line" # first comment
"second line" # second comment
`}, {
name: "all kinds of inline comments",
in: `# presubmit pre comment 1
Expand Down Expand Up @@ -826,7 +823,6 @@ check_tests: {
`,
out: `presubmit {
}
`}, {
name: "template directive",
in: `[ext]: {
Expand Down Expand Up @@ -2355,6 +2351,37 @@ foo {
foo: "\"bar\""`,
out: `# txtpbfmt: smartquotes
foo: '"bar"'
`,
}, {
name: "blank lines",
in: `
# comment 0
# comment 1
# comment 2
# comment 3
blah {
}
`,
out: `# comment 0
# comment 1
# comment 2
# comment 3
blah {
}
`,
},
}
Expand Down

0 comments on commit 7962e19

Please sign in to comment.