Skip to content

Commit

Permalink
cmd/goimports: add regroup flag support regroup imports
Browse files Browse the repository at this point in the history
  • Loading branch information
win5do committed Jan 11, 2025
1 parent 1b796a9 commit 6902c24
Show file tree
Hide file tree
Showing 3 changed files with 123 additions and 1 deletion.
1 change: 1 addition & 0 deletions cmd/goimports/goimports.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func init() {
flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)")
flag.StringVar(&options.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
flag.BoolVar(&options.FormatOnly, "format-only", false, "if true, don't fix imports and only format. In this mode, goimports is effectively gofmt, with the addition that imports are grouped into sections.")
flag.BoolVar(&options.RegroupImports, "regroup", false, "remove blank line and regroup imports")
}

func report(err error) {
Expand Down
67 changes: 67 additions & 0 deletions internal/imports/fix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3085,3 +3085,70 @@ func BenchmarkMatchesPath(b *testing.B) {
})
}
}

func TestRegroupImports(t *testing.T) {
const input = `package foo
import (
"fmt"
"github.com/foo/a"
"github.com/foo/b"
"context"
"go.pkg.com/bar/x"
"go.pkg.com/bar/y"
"github.com/foo/c"
"go.pkg.com/bar/z"
)
var (
ctx context.Context
fmt1 fmt.Formatter
a1 a.A
b1 b.A
c1 c.A
x1 x.A
y1 y.A
z1 z.A
)
`

const want = `package foo
import (
"context"
"fmt"
"github.com/foo/a"
"github.com/foo/b"
"github.com/foo/c"
"go.pkg.com/bar/x"
"go.pkg.com/bar/y"
"go.pkg.com/bar/z"
)
var (
ctx context.Context
fmt1 fmt.Formatter
a1 a.A
b1 b.A
c1 c.A
x1 x.A
y1 y.A
z1 z.A
)
`

testConfig{
module: packagestest.Module{
Name: "foo.com",
Files: fm{
"p/test.go": input,
},
},
}.processTest(t, "foo.com", "p/test.go", nil, &Options{
RegroupImports: true,
}, want)
}
56 changes: 55 additions & 1 deletion internal/imports/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,19 @@ type Options struct {
TabIndent bool // Use tabs for indent (true if nil *Options provided)
TabWidth int // Tab width (8 if nil *Options provided)

FormatOnly bool // Disable the insertion and deletion of imports
FormatOnly bool // Disable the insertion and deletion of imports
RegroupImports bool // Remove blank line in imports.
}

// Process implements golang.org/x/tools/imports.Process with explicit context in opt.Env.
func Process(filename string, src []byte, opt *Options) (formatted []byte, err error) {
if opt.RegroupImports {
src, err = removeBlankLineInImport(filename, src)
if err != nil {
return nil, err
}
}

fileSet := token.NewFileSet()
var parserMode parser.Mode
if opt.Comments {
Expand Down Expand Up @@ -357,3 +365,49 @@ func addImportSpaces(r io.Reader, breaks []string) ([]byte, error) {
}
return out.Bytes(), nil
}

// removeBlankLineInImport remove blank line in import block.
func removeBlankLineInImport(filename string, src []byte) (out []byte, rerr error) {
tokenSet := token.NewFileSet()
astFile, err := parser.ParseFile(tokenSet, filename, src, parser.ParseComments)
if err != nil {
return src, err
}

if len(astFile.Decls) <= 1 {
return src, nil
}
tokenFile := tokenSet.File(astFile.Pos())

for i := 0; i < len(astFile.Decls); i++ {
decl := astFile.Decls[i]
gen, ok := decl.(*ast.GenDecl)
if !ok || gen.Tok != token.IMPORT || declImports(gen, "C") {
continue
}

if !gen.Lparen.IsValid() {
// Not a block: sorted by default.
continue
}

lpLine := tokenFile.Line(gen.Lparen)
rpLine := tokenFile.Line(gen.Rparen)
src = removeEmptyLine(src, lpLine, rpLine)
}

return src, nil
}

func removeEmptyLine(src []byte, l, r int) []byte {
lines := bytes.Split(src, []byte("\n"))
for i := l; i < r; i++ {
if i < len(lines) && len(bytes.TrimSpace(lines[i])) == 0 {
lines = append(lines[:i], lines[i+1:]...)
i--
r--
}
}

return bytes.Join(lines, []byte("\n"))
}

0 comments on commit 6902c24

Please sign in to comment.