proposal: x/tools/cmd/goimports: add flag to remove blank lines in import for regrouping during formatting #64271
Open
Description
current
The goimports will retain blank lines and multiple groups will exist after formatting.
testdata in.go:
import (
"fmt"
"github.com/foo/a"
"github.com/foo/b"
"go.pkg.com/bar/x"
"go.pkg.com/bar/y"
"context"
"github.com/foo/c"
"go.pkg.com/bar/z"
)
goimports -local go.pkg.com in.go
output:
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"
)
expect
Would like a tool to automate the removal of blank lines and regrouping.
Add a -r
flag, goimports -r -local go.pkg.com in.go
output:
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"
)
implement
It's easy to implement, here's the pseudo-code:
// add flag
regroup = flag.Bool("r", false, "remove blank line and regroup imports")
func processFile() {
if *regroup {
src = removeBlankLineInImport(src)
}
// origin imports.Process
res, err := imports.Process(target, src, opt)
}
func removeBlankLineInImport(src []byte) []byte {
// 1. parset AST
// 2. find first import block start and end line
// 3. rewrite src, remove blank line in import block
}
No breaking changes, and even regrouping keeps compatibility with the original goimports rules.
We forked goimports in our internal project and added this feature so that if the proposal is accepted, I can submit a PR.
Metadata
Assignees
Type
Projects
Status
Incoming