gofmt makes a large portion of go code consistently formatted and it is great. However, one thing that keeps inconsistent is import blocks. In order to make them consistent, I am proposing to make order and contents of import blocks deterministic.
gofmt does not mind
import (
"fmt"
"github.com/user/repo"
"github.com/user/repo2"
)
and
import (
"fmt"
"github.com/user/repo"
"github.com/user/repo2"
)
at the same time. If gofmt incorporates rules for order and contents of import blocks, this problem will be solved.
Implement the following rules in gofmt, ordered by precedence:
- all stdlib packages go the first block
- for each package path component level L of current package (e.g. 0 - "github.com", 1 - "user", or 2 - "repo"), make a import block of all imported packages that have a different path prefix, where prefix is package path components up to L.
This means that for a go file that lives in package github.com/user/repo/foo/bar
the following imports are considered well-formatted:
import (
"fmt"
"text/template"
"golang.org/x/net/context"
"github.com/another-user/x"
"github.com/org1/y"
"github.com/user/repo/baz"
"github.com/user/repo/qux"
"github.com/user/repo/foo/a"
"github.com/user/repo/foo/b"
"github.com/user/repo/foo/bar/c"
"github.com/user/repo/foo/bar/d"
)