Skip to content

Commit

Permalink
add an indentation estimation to printLength
Browse files Browse the repository at this point in the history
  • Loading branch information
mvdan committed Apr 12, 2019
1 parent 1cd8171 commit 047ce8d
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
16 changes: 13 additions & 3 deletions internal/gofumpt.go
Expand Up @@ -20,9 +20,7 @@ import (

// Multiline nodes which could fit on a single line under this many
// bytes may be collapsed onto a single line.
// TODO: Increase this to 60 once we take indentation into account. For now,
// subtract two tabs.
const shortLineLimit = 44
const shortLineLimit = 60

func GofumptBytes(src []byte) ([]byte, error) {
fset := token.NewFileSet()
Expand Down Expand Up @@ -150,9 +148,21 @@ func (f *fumpter) printLength(node ast.Node) int {
if err := format.Node(&count, f.fset, node); err != nil {
panic(fmt.Sprintf("unexpected print error: %v", err))
}

// Add the space taken by an inline comment.
if c := f.inlineComment(node.End()); c != nil {
fmt.Fprintf(&count, " %s", c.Text)
}

// Add an approximation of the indentation level. We can't know the
// number of tabs go/printer will add ahead of time. Trying to print the
// entire top-level declaration would tell us that, but then it's near
// impossible to reliably find our node again.
for _, parent := range f.stack {
if _, ok := parent.(*ast.BlockStmt); ok {
count += 8
}
}
return int(count)
}

Expand Down
28 changes: 28 additions & 0 deletions testdata/scripts/short-case.txt
Expand Up @@ -32,6 +32,20 @@ func f(r rune) {
case 'a', 'b', 'c',
'd': // short comment
}
{
{
{
{
{
switch r {
case 'i', 'n', 'd', 'e',
'n', 't', 'e', 'd':
}
}
}
}
}
}
}
-- foo.go.golden --
package p
Expand Down Expand Up @@ -59,4 +73,18 @@ func f(r rune) {

case 'a', 'b', 'c', 'd': // short comment
}
{
{
{
{
{
switch r {
case 'i', 'n', 'd', 'e',
'n', 't', 'e', 'd':
}
}
}
}
}
}
}

0 comments on commit 047ce8d

Please sign in to comment.