Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang import grouping by package

Tags:

go

I see that Go has goimports to help with import grouping, but I'm wondering if anyone has created a package to group imports in groupings by some pattern?

Go imports does this a little by enforcing at least two groupings stdlib and everything else; however, my company has a policy of grouping imports in 4 groups

import (
    stdlib

    current_project

    company

    all others 
)

is there a tool that can automatically do this?

like image 612
Josh Wilson Avatar asked Aug 01 '16 17:08

Josh Wilson


People also ask

How do I import a package into go?

To import a package, we use import syntax followed by the package name. 💡 Unlike other programming languages, a package name can also be a subpath like some-dir/greet and Go will automatically resolve the path to the greet package for us as you will see in the nested package topic ahead.

How do I sort imports in Goland?

Open settings by pressing Ctrl+Alt+S and navigate to Editor | Code Style | Go. Click the Imports tab. From the Sorting type list, select goimports.

How do you use Goimports?

goimports If your project does not have goimports, click the go get goimports link in the Goimports file notification window. Otherwise, open the Terminal tool window (View | Tool Windows | Terminal), and type the following command to install goimports: go get golang.org/x/tools/cmd/goimports . Press Enter .


2 Answers

If one is using GoLand, it's possible to adjust sorting in the settings:

enter image description here

Note “Group stdimports” and “Move all stdimports in a single group” checkboxes.

like image 153
Dmytro Titov Avatar answered Sep 20 '22 08:09

Dmytro Titov


The latest version of goimports support -local flag. Quoting this commit message:

For example, running goimports -local example.com/ might produce

import (
    "database/sql"
    "io"
    "strconv"

    "golang.org/x/net/context"

    "example.com/foo/bar"
    "example.com/foo/baz"
)
like image 23
kostya Avatar answered Sep 22 '22 08:09

kostya