Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/goimports: add regroup flag support regroup imports #554

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
cmd/goimports: add regroup flag support regroup imports
win5do committed Jan 11, 2025
commit 6902c24fa18bfc9328421ca85a2774afbaff7dbb
1 change: 1 addition & 0 deletions cmd/goimports/goimports.go
Original file line number Diff line number Diff line change
@@ -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) {
67 changes: 67 additions & 0 deletions internal/imports/fix_test.go
Original file line number Diff line number Diff line change
@@ -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
@@ -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 {
@@ -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"))
}