Sky Digging

Keep Yak shaving

30 May 2020

I created a better tool than goimports

Introduction

In this article I will share Golang checker tool I created. The tool checks import paths are sorted “strictly”.

Here’s the tool repository link.

https://github.com/momotaro98/strictgoimports

Background

There’s still an issue of goimports.

The link is here. https://github.com/golang/go/issues/20818

I created strictgoimports to resolve this issue.

Detail of the issue

goimports supports -local flag when we have local path.

When we have such an import paths.

import (
    "errors"
    "github.com/google/wire"
    "github.com/momotaro98/mixlunch-service-api/partyservice"
)

Then run goimports with -local flag

$ goimports -local "github.com/momotaro98" .

The files are sorted with whilte line like following.

import (
    "errors"

    "github.com/google/wire"
    
    "github.com/momotaro98/mixlunch-service-api/partyservice"
)

However, when we have a go file whose import paths are separate with white line in advance, goimports doesn’t support sorting for the file.

import (
    "errors"

    "github.com/momotaro98/mixlunch-service-api/partyservice"

    "github.com/google/wire"
)

When I use GoLand IDE, it sometimes makes white line separate import paths like above.

I expected “github.com/momotaro98” is at last but goimports regards it’s fine since it already has a white line.

How strictgoimports works

strictgoimports is a checker tool you can check go files whose import paths are not sorted “strictly”.

$ strictgoimports -exclude "*_mock.go,*.pb.go" -exclude-dir "testmock" -local "github.com/momotaro98" .

Command line tool supports -exclude, -exclude-dir flag and -local flag as well as goimports.

We can see instruction output when there’s such “not sorted strictly” files with file names, line number, and column number like followings.

/Users/shintaro/.ghq/github.com/momotaro98/mixlunch-service-api/partyservice/domain_test.go:8:2: import not sorted correctly. should be replace to
import (
        "errors"
        "testing"
        "time"

        "github.com/golang/mock/gomock"

        "github.com/momotaro98/mixlunch-service-api/userservice"
        "github.com/momotaro98/mixlunch-service-api/utils"
)
/Users/shintaro/.ghq/github.com/momotaro98/mixlunch-service-api/userservice/provider.go:5:2: import not sorted correctly. should be replace to
import (
        "github.com/google/wire"

        "github.com/momotaro98/mixlunch-service-api/tagservice"
)

You can modify the target files with -w option.

We can modify the target files by using -w option.

$ strictgoimports -w -exclude "*_mock.go,*.pb.go" -exclude-dir "testmock" -local "github.com/momotaro98" .

Just adding the -w option, strictgoimports modifies the target files and doesn’t show the results.