Skip to content

Commit

Permalink
remove empty lines surrounding lone comments in field lists
Browse files Browse the repository at this point in the history
  • Loading branch information
ebati authored Feb 20, 2022
1 parent d74ca43 commit 9827b59
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 1 deletion.
23 changes: 22 additions & 1 deletion format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -562,13 +562,34 @@ func (f *fumpter) applyPre(c *astutil.Cursor) {
f.stmts(node.Body)

case *ast.FieldList:
if node.NumFields() == 0 && len(f.commentsBetween(node.Pos(), node.End())) == 0 {
numFields := node.NumFields()
comments := f.commentsBetween(node.Pos(), node.End())

if numFields == 0 && len(comments) == 0 {
// Empty field lists should not contain a newline.
// Do not join the two lines if the first has an inline
// comment, as that can result in broken formatting.
openLine := f.Line(node.Pos())
closeLine := f.Line(node.End())
f.removeLines(openLine, closeLine)
} else {
// Remove lines before first comment/field and lines after last
// comment/field
var bodyPos, bodyEnd token.Pos
if numFields > 0 {
bodyPos = node.List[0].Pos()
bodyEnd = node.List[len(node.List)-1].End()
}
if len(comments) > 0 {
if pos := comments[0].Pos(); !bodyPos.IsValid() || pos < bodyPos {
bodyPos = pos
}
if pos := comments[len(comments)-1].End(); !bodyPos.IsValid() || pos > bodyEnd {
bodyEnd = pos
}
}
f.removeLinesBetween(node.Pos(), bodyPos)
f.removeLinesBetween(bodyEnd, node.End())
}

// Merging adjacent fields (e.g. parameters) is disabled by default.
Expand Down
51 changes: 51 additions & 0 deletions testdata/scripts/block-empty.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,42 @@ func f() {
// lone comment

}

type S struct {


// lone comment


}

type I interface {


// lone comment


}


}

type SOut struct {

// lone comment

}

type IOut interface {


// lone comment


}



-- foo.go.golden --
package p

Expand All @@ -34,4 +69,20 @@ func f() {
{
// lone comment
}

type S struct {
// lone comment
}

type I interface {
// lone comment
}
}

type SOut struct {
// lone comment
}

type IOut interface {
// lone comment
}

0 comments on commit 9827b59

Please sign in to comment.