Skip to content

A linter which requires an import alias for all imports where the last part of the path does not match the package name #2401

Closed
@mitar

Description

@mitar

Your feature request related to a problem? Please describe.

I have code with the following imports:

import (
	"github.com/deckarep/golang-set"
	"github.com/go-git/go-git/v5"
	"github.com/whilp/git-urls"
	"github.com/xanzy/go-gitlab"
	"github.com/xmidt-org/gokeepachangelog"
)

Without reading their code or documentation it is not really possible to know how to use it and which symbol later in the code relates to which package. This is why I use the following:

import (
	mapset "github.com/deckarep/golang-set"
	git "github.com/go-git/go-git/v5"
	giturls "github.com/whilp/git-urls"
	gitlab "github.com/xanzy/go-gitlab"
	changelog "github.com/xmidt-org/gokeepachangelog"
)

Those aliases are unnecessary, because those imports already provide packages under those names, but they make code much cleaner and easier to read. If I search for "mapset" in the code I can see where it was imported.

Describe the solution you'd like.

I would suggest to have a linter which would check all imports and require an import alias when the last part of the path does not match the package name imported.

Under a configuration flag I would also suggest that one could enable strict mode: where the alias has to match the package name. For an exemption (where such mode would introduce conflicts), one could disable linting on that line, or allow it through another setting.

Describe alternatives you've considered.

I searched around but I could not find an existing solutions. There is importas but it requires one to manually specify aliases which is not what I would want here.

Additional context.

There is some discussion about cognitive load because of this and ways to address it through changes in Go language itself. But I think a linter can already help a lot.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or improvement

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions