Skip to content

x/tools/cmd/goimports: make "-local" flag match exactly path without final "/" in addition to prefix #24368

@nmiyake

Description

@nmiyake

Currently, it is not possible for goimports to group imports in a manner that encapsulates the operation "group all packages from a repository into the same group" using the -local flag due to the nature of prefix matches.

If a file imports github.com/org/project, github.com/org/project/pkg and github.com/org/project2/pkg, -local github.com/org/project will match the undesired package github.com/org/project2, while -local github.com/org/project/ will not match imports for the root package github.com/org/project.

Proposal

As a special case, if a prefix provided to -local ends in a slash (/) and the import being considered is exactly the prefix without the slash, treat it as a match. Although this modifies the current behavior, I believe that it semantically captures what such a prefix match would be trying to achieve (the fix is also very small and targeted). I believe that any other fix would require adding flags or options, which I know is not desirable.

Example repros

Groups github.com/org/project2/pkg with imports from github.com/org/project:

echo 'package foo\nimport (\n_ "fmt"\n_ "gopkg.in/yaml.v2"\n_ "github.com/org/project/pkg"\n_ "github.com/org/project"\n_ "github.com/org/project2/pkg"\n)' | cat | goimports -local github.com/org/project

package foo

import (
	_ "fmt"

	_ "gopkg.in/yaml.v2"

	_ "github.com/org/project"
	_ "github.com/org/project/pkg"
	_ "github.com/org/project2/pkg"
)

Does not group import for github.com/org/project with github.com/org/project/pkg:

echo 'package foo\nimport (\n_ "fmt"\n_ "gopkg.in/yaml.v2"\n_ "github.com/org/project/pkg"\n_ "github.com/org/project"\n_ "github.com/org/project2/pkg"\n)' | cat | goimports -local github.com/org/project/

package foo

import (
	_ "fmt"

	_ "github.com/org/project"
	_ "github.com/org/project2/pkg"
	_ "gopkg.in/yaml.v2"

	_ "github.com/org/project/pkg"
)

The proposed behavior would result in:

echo 'package foo\nimport (\n_ "fmt"\n_ "gopkg.in/yaml.v2"\n_ "github.com/org/project/pkg"\n_ "github.com/org/project"\n_ "github.com/org/project2/pkg"\n)' | cat | goimports -local github.com/org/project/

package foo

import (
	_ "fmt"

	_ "github.com/org/project2/pkg"
	_ "gopkg.in/yaml.v2"

	_ "github.com/org/project"
	_ "github.com/org/project/pkg"
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureRequestIssues asking for a new feature that does not need a proposal.FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.help wanted

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions