Skip to content

Instantly share code, notes, and snippets.

@nodirt
Last active June 23, 2016 01:29
Show Gist options
  • Save nodirt/bf02e45f341c1c83974b633a0f8968a1 to your computer and use it in GitHub Desktop.
Save nodirt/bf02e45f341c1c83974b633a0f8968a1 to your computer and use it in GitHub Desktop.

Proposal: deterministic import blocks

Abstract

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.

Background

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.

Proposal

Implement the following rules in gofmt, ordered by precedence:

  1. all stdlib packages go the first block
  2. 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"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment