Description
I'm working on a tool to fix up non-conventional or incorrect imports grouping/ordering, but I'd much rather have this be part of goimports. Would it be welcome?
What goimports does now
When goimports adds or removes an import, it heuristically attempts to find a good place for it. So if I add an os.Open()
call, and my imports already look like this:
import (
"context"
"testing"
"github.com/Sirupsen/logrus"
)
Then goimports will put "os" in the proper spot, beween "context" and "testing". That's great!
What goimports does not do
If my imports are not grouped and sorted in the conventional way, goimports will not usually fix the problem. For example, if I was using the old context package, my imports might look like this:
import (
"testing"
"github.com/Sirupsen/logrus"
"golang.org/x/net/context"
)
When I edit the context import to the new package, "context", I have this:
import (
"testing"
"github.com/Sirupsen/logrus"
"context"
)
Running goimports will notice that logrus and context don't make a proper group, so it will separate them:
import (
"testing"
"context"
"github.com/Sirupsen/logrus"
)
But this isn't what we really want. Ideally, it would just re-group and re-order all the imports, to yield:
import (
"context"
"testing"
"github.com/Sirupsen/logrus"
)
Work so far
I have a tool that will globally reorder imports according to the grouping rules, including the associated doc-comments; see below. I could also develop similar funcitonality inside goimports.
My tool is not nearly perfect: It doesn't handle multiple import declarations; it doesn't know about import "C"
. It's not even clear what should happen to random non-doc-comments inside the import block, eg:
import (
"github.com/Sirupsen/logrus"
// When we re-order, what happens to this comment?
"testing"
)
Automatically grouping and ordering would also be a behavioral change for goimports, so it would have to be behind a flag for now.