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

proposal: x/tools/cmd/goimports: add flag to remove blank lines in import for regrouping during formatting #64271

Open
win5do opened this issue Nov 20, 2023 · 0 comments
Labels
Milestone

Comments

@win5do
Copy link

win5do commented Nov 20, 2023

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.

@gopherbot gopherbot added this to the Proposal milestone Nov 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

2 participants