|
| 1 | +package pkgstutter |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + |
| 6 | + "github.com/golangci/plugin-module-register/register" |
| 7 | + "golang.org/x/tools/go/analysis" |
| 8 | +) |
| 9 | + |
| 10 | +var Analyzer = &analysis.Analyzer{ |
| 11 | + Name: "pkgstutter", |
| 12 | + Doc: "Prevents stuttering package names, e.g. github.com/foo/bar/wait/wait", |
| 13 | + Run: run, |
| 14 | +} |
| 15 | + |
| 16 | +func run(pass *analysis.Pass) (any, error) { |
| 17 | + pkgPath := pass.Pkg.Path() |
| 18 | + parts := strings.Split(pkgPath, "/") |
| 19 | + |
| 20 | + // Check for adjacent identical parts in the path |
| 21 | + for i := 1; i < len(parts); i++ { |
| 22 | + if parts[i] == parts[i-1] { |
| 23 | + // If a stutter is found, report it at the package declaration |
| 24 | + // of the first file in the package to pinpoint the error. |
| 25 | + if len(pass.Files) > 0 { |
| 26 | + pass.Reportf( |
| 27 | + pass.Files[0].Package, |
| 28 | + "package path %q contains stuttering (%s/%s)", |
| 29 | + pkgPath, parts[i-1], parts[i], |
| 30 | + ) |
| 31 | + } |
| 32 | + // Break after the first finding to avoid spamming multiple errors for the same package |
| 33 | + break |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return nil, nil |
| 38 | +} |
| 39 | + |
| 40 | +func init() { |
| 41 | + register.Plugin("pkgstutter", New) |
| 42 | +} |
| 43 | + |
| 44 | +func New(settings any) (register.LinterPlugin, error) { |
| 45 | + return &plugin{}, nil |
| 46 | +} |
| 47 | + |
| 48 | +type plugin struct{} |
| 49 | + |
| 50 | +func (p *plugin) BuildAnalyzers() ([]*analysis.Analyzer, error) { |
| 51 | + return []*analysis.Analyzer{Analyzer}, nil |
| 52 | +} |
| 53 | + |
| 54 | +func (p *plugin) GetLoadMode() string { |
| 55 | + return register.LoadModeTypesInfo |
| 56 | +} |
0 commit comments