-
Notifications
You must be signed in to change notification settings - Fork 466
[linter-miner] feat(linters): add stringscutprefix linter #48210
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
github-actions
wants to merge
7
commits into
main
from
linter-miner/stringscutprefix-b666afe40b10b463
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
33e25ba
feat(linters): add stringscutprefix linter
github-actions[bot] 963b89e
docs(adr): add draft ADR-48210 for stringscutprefix linter
github-actions[bot] d63b6b4
fix stringscutprefix review feedback
Copilot a15c2ba
Merge branch 'main' into linter-miner/stringscutprefix-b666afe40b10b463
github-actions[bot] 3ab8f50
plan: re-triage unresolved PR feedback
Copilot 4320336
fix: tighten stringscutprefix expression matching
Copilot a8e184f
fix: sync fallback AW file list
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # ADR-48210: Add stringscutprefix Linter for strings.CutPrefix Migration | ||
|
|
||
| **Date**: 2026-07-26 | ||
| **Status**: Draft | ||
| **Deciders**: Unknown | ||
|
|
||
| --- | ||
|
|
||
| ### Context | ||
|
|
||
| Go 1.20 introduced `strings.CutPrefix(s, prefix)` (and the analogous `strings.CutSuffix`) as a cleaner replacement for the two-call idiom `strings.HasPrefix(s, p)` + `strings.TrimPrefix(s, p)`. The two-call pattern is widespread in older Go codebases and carries a silent correctness risk: if the prefix literal or variable is updated in the `HasPrefix` guard but not in the `TrimPrefix` call (or vice versa), the function silently returns the un-trimmed string without any compile-time or runtime error. Many projects, including gh-aw, have accumulated instances of this pattern that were never migrated after `strings.CutPrefix` became available. Manual review alone is insufficient to find and prevent new occurrences across a large codebase. | ||
|
|
||
| ### Decision | ||
|
|
||
| We will implement and register a new custom Go static-analysis linter, `stringscutprefix`, that inspects every `*ast.IfStmt` whose condition is `strings.HasPrefix(s, prefix)` and flags it when the if-body contains a `strings.TrimPrefix(s, prefix)` call with the same arguments (verified by type-object identity for identifiers and by value equality for literals/selector expressions). The linter reports the finding on the `HasPrefix` call site and recommends `strings.CutPrefix`. This linter follows the same structural conventions as the rest of the gh-aw custom linter suite and is registered in `pkg/linters/registry.go`. | ||
|
|
||
| ### Alternatives Considered | ||
|
|
||
| #### Alternative 1: Rely on an Existing Community Linter (e.g., gocritic, revive, or usestdlibvars) | ||
|
|
||
| `golangci-lint` bundles several meta-linters (`gocritic`, `revive`, `staticcheck`) that cover a wide range of idioms. If one of them already detected this pattern, a custom linter would be redundant. However, none of the bundled linters enforce the `HasPrefix`+`TrimPrefix` → `CutPrefix` migration at the time of this decision. Using a community linter would eliminate maintenance burden, but the pattern would remain undetected in CI. | ||
|
|
||
| #### Alternative 2: Enforce by Coding Guideline Only (No Automated Check) | ||
|
|
||
| A written guideline in a style guide or contributing doc would inform developers about `strings.CutPrefix` without requiring tooling changes. This approach has zero implementation cost but provides no enforcement: new occurrences of the anti-pattern would only be caught during code review, inconsistently and long after the code was written. Given the volume of existing violations and the subtle silent-failure mode of the two-call idiom, a documentation-only approach is insufficient. | ||
|
|
||
| ### Consequences | ||
|
|
||
| #### Positive | ||
| - CI automatically rejects new instances of the `HasPrefix`+`TrimPrefix` idiom, preventing silent correctness bugs from argument mismatch. | ||
| - The linter's argument-identity check (by Go type object) correctly handles both literal strings and variable references, including field selectors, with no regex or text-matching fragility. | ||
| - Follows the established gh-aw custom linter pattern (AST traversal via `astutil.Root`, `nolint` directive support, `filecheck` to skip generated files), so the implementation is consistent and immediately reviewable by existing contributors. | ||
| - Fixture-based tests via `analysistest` ensure both flagged and non-flagged cases are explicitly enumerated, making the detection boundary clear. | ||
|
|
||
| #### Negative | ||
| - Adds a new linter package to the registry that the team must maintain going forward (e.g., if the `strings` package API changes or internal `astutil`/`nolint`/`filecheck` helpers are refactored). | ||
| - The linter only detects the case where `TrimPrefix` appears directly inside the `IfStmt` body; more complex patterns (e.g., `TrimPrefix` called in a nested helper, or gated on an `else` branch) are not flagged — these require manual review. | ||
| - Teams with intentional uses of the two-call idiom (e.g., where the return value of `HasPrefix` is also used for a side effect) must add a `//nolint:stringscutprefix` directive, introducing a small per-site maintenance cost. | ||
|
|
||
| #### Neutral | ||
| - The linter is appended to the `All()` slice in `registry.go` and inherits the same run-on-all-files behavior as every other registered analyzer; no separate opt-in configuration is required. | ||
| - Existing occurrences of the anti-pattern in the codebase are not auto-fixed by this PR; a separate migration sweep would be needed to address historical violations. | ||
|
|
||
| --- | ||
|
|
||
| *ADR created by [adr-writer agent]. Review and finalize before changing status from Draft to Accepted.* |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,227 @@ | ||
| // Package stringscutprefix implements a Go analysis linter that flags | ||
| // if-blocks that use strings.HasPrefix followed by strings.TrimPrefix | ||
| // and suggests strings.CutPrefix instead. | ||
| package stringscutprefix | ||
|
|
||
| import ( | ||
| "go/ast" | ||
| "go/types" | ||
|
|
||
| "golang.org/x/tools/go/analysis" | ||
| "golang.org/x/tools/go/analysis/passes/inspect" | ||
|
|
||
| "github.com/github/gh-aw/pkg/linters/internal/astutil" | ||
| "github.com/github/gh-aw/pkg/linters/internal/filecheck" | ||
| "github.com/github/gh-aw/pkg/linters/internal/nolint" | ||
| ) | ||
|
|
||
| // Analyzer is the strings-cut-prefix analysis pass. | ||
| var Analyzer = &analysis.Analyzer{ | ||
| Name: "stringscutprefix", | ||
| Doc: "reports if-blocks that check strings.HasPrefix then call strings.TrimPrefix on the same args, suggesting strings.CutPrefix", | ||
| URL: "https://github.com/github/gh-aw/tree/main/pkg/linters/stringscutprefix", | ||
| Requires: []*analysis.Analyzer{inspect.Analyzer, nolint.Analyzer, filecheck.Analyzer}, | ||
| Run: run, | ||
| } | ||
|
|
||
| func run(pass *analysis.Pass) (any, error) { | ||
| root, err := astutil.Root(pass) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| noLintIndex, err := nolint.Index(pass) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| generatedFiles, err := filecheck.Index(pass) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| for cur := range root.Preorder((*ast.IfStmt)(nil)) { | ||
| ifStmt, ok := cur.Node().(*ast.IfStmt) | ||
| if !ok { | ||
| continue | ||
| } | ||
|
|
||
| pos := pass.Fset.PositionFor(ifStmt.Pos(), false) | ||
| if filecheck.ShouldSkipFilename(pos.Filename, generatedFiles) { | ||
| continue | ||
| } | ||
| if nolint.HasDirectiveForLinter(pos, noLintIndex, "stringscutprefix") { | ||
| continue | ||
| } | ||
|
|
||
| // Condition must be strings.HasPrefix(s, prefix) | ||
| hasPrefixCall, s, prefix := extractHasPrefixCall(pass, ifStmt.Cond) | ||
| if hasPrefixCall == nil { | ||
| continue | ||
| } | ||
|
|
||
| // Body must contain strings.TrimPrefix(s, prefix) with same args | ||
| if bodyContainsTrimPrefix(pass, ifStmt.Body, s, prefix) { | ||
| pass.ReportRangef(hasPrefixCall, | ||
| "strings.HasPrefix + strings.TrimPrefix can be replaced with strings.CutPrefix") | ||
| } | ||
| } | ||
|
|
||
| return nil, nil | ||
| } | ||
|
|
||
| // extractHasPrefixCall returns the call expression, the s argument, and the | ||
| // prefix argument if the expression is strings.HasPrefix(s, prefix). | ||
| func extractHasPrefixCall(pass *analysis.Pass, expr ast.Expr) (*ast.CallExpr, ast.Expr, ast.Expr) { | ||
| call, ok := expr.(*ast.CallExpr) | ||
| if !ok || len(call.Args) != 2 { | ||
| return nil, nil, nil | ||
| } | ||
| if !isStringsFunc(pass, call, "HasPrefix") { | ||
| return nil, nil, nil | ||
| } | ||
| return call, call.Args[0], call.Args[1] | ||
| } | ||
|
|
||
| // bodyContainsTrimPrefix returns true if the block contains a direct statement | ||
| // that calls strings.TrimPrefix with the same arguments, before either argument | ||
| // is reassigned in the enclosing if body. | ||
| func bodyContainsTrimPrefix(pass *analysis.Pass, body *ast.BlockStmt, s, prefix ast.Expr) bool { | ||
| for _, stmt := range body.List { | ||
| if stmtContainsTrimPrefix(pass, stmt, s, prefix) { | ||
| return true | ||
| } | ||
| if stmtReassignsExpr(pass, stmt, s) || stmtReassignsExpr(pass, stmt, prefix) { | ||
| return false | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| func stmtContainsTrimPrefix(pass *analysis.Pass, stmt ast.Stmt, s, prefix ast.Expr) bool { | ||
| found := false | ||
| ast.Inspect(stmt, func(n ast.Node) bool { | ||
| if found || n == nil { | ||
| return false | ||
| } | ||
| if n != stmt && shouldSkipNestedFlow(n) { | ||
| return false | ||
| } | ||
| call, ok := n.(*ast.CallExpr) | ||
| if !ok || len(call.Args) != 2 { | ||
| return true | ||
|
github-actions[bot] marked this conversation as resolved.
|
||
| } | ||
| if !isStringsFunc(pass, call, "TrimPrefix") { | ||
| return true | ||
| } | ||
| if sameExpr(pass, call.Args[0], s) && sameExpr(pass, call.Args[1], prefix) { | ||
| found = true | ||
| } | ||
| return true | ||
| }) | ||
| return found | ||
| } | ||
|
|
||
| func stmtReassignsExpr(pass *analysis.Pass, stmt ast.Stmt, target ast.Expr) bool { | ||
| reassigned := false | ||
| ast.Inspect(stmt, func(n ast.Node) bool { | ||
| if reassigned || n == nil { | ||
| return false | ||
| } | ||
| if _, ok := n.(*ast.FuncLit); ok { | ||
| return false | ||
| } | ||
| switch node := n.(type) { | ||
| case *ast.AssignStmt: | ||
| for _, lhs := range node.Lhs { | ||
| if sameExpr(pass, lhs, target) { | ||
| reassigned = true | ||
| return false | ||
| } | ||
| } | ||
| case *ast.IncDecStmt: | ||
| if sameExpr(pass, node.X, target) { | ||
| reassigned = true | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| }) | ||
| return reassigned | ||
| } | ||
|
|
||
| func shouldSkipNestedFlow(n ast.Node) bool { | ||
| switch n.(type) { | ||
| case *ast.BlockStmt, *ast.FuncLit, *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt: | ||
| return true | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| // isStringsFunc reports whether call invokes strings.<name>. | ||
| func isStringsFunc(pass *analysis.Pass, call *ast.CallExpr, name string) bool { | ||
| sel, ok := call.Fun.(*ast.SelectorExpr) | ||
| if !ok || sel.Sel.Name != name { | ||
| return false | ||
| } | ||
| ident, ok := sel.X.(*ast.Ident) | ||
| if !ok { | ||
| return false | ||
| } | ||
| obj := pass.TypesInfo.ObjectOf(ident) | ||
| if obj == nil { | ||
| return false | ||
| } | ||
| pkgName, ok := obj.(*types.PkgName) | ||
| return ok && pkgName.Imported().Path() == "strings" | ||
| } | ||
|
|
||
| // sameExpr returns true when a and b are syntactically equivalent simple | ||
| // expressions (identifiers or selector expressions) referring to the same | ||
| // object, or are equal basic literals. | ||
| func sameExpr(pass *analysis.Pass, a, b ast.Expr) bool { | ||
| for { | ||
| paren, ok := a.(*ast.ParenExpr) | ||
| if !ok { | ||
| break | ||
| } | ||
| a = paren.X | ||
| } | ||
| for { | ||
| paren, ok := b.(*ast.ParenExpr) | ||
| if !ok { | ||
| break | ||
| } | ||
| b = paren.X | ||
| } | ||
|
|
||
| switch av := a.(type) { | ||
| case *ast.Ident: | ||
| bv, ok := b.(*ast.Ident) | ||
| if !ok { | ||
| return false | ||
| } | ||
| ao := pass.TypesInfo.ObjectOf(av) | ||
| bo := pass.TypesInfo.ObjectOf(bv) | ||
| return ao != nil && ao == bo | ||
| case *ast.BasicLit: | ||
| bv, ok := b.(*ast.BasicLit) | ||
| return ok && av.Kind == bv.Kind && av.Value == bv.Value | ||
| case *ast.SelectorExpr: | ||
| bv, ok := b.(*ast.SelectorExpr) | ||
| if !ok { | ||
| return false | ||
| } | ||
| ao := pass.TypesInfo.ObjectOf(av.Sel) | ||
| bo := pass.TypesInfo.ObjectOf(bv.Sel) | ||
| return ao != nil && ao == bo && sameExpr(pass, av.X, bv.X) | ||
| case *ast.IndexExpr: | ||
| bv, ok := b.(*ast.IndexExpr) | ||
| if !ok { | ||
| return false | ||
| } | ||
| return sameExpr(pass, av.X, bv.X) && sameExpr(pass, av.Index, bv.Index) | ||
| } | ||
|
github-actions[bot] marked this conversation as resolved.
|
||
| // Complex expressions are not structurally compared; treat them as unequal | ||
| // to avoid false positives. | ||
| return false | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| //go:build !integration | ||
|
|
||
| package stringscutprefix_test | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "golang.org/x/tools/go/analysis/analysistest" | ||
|
|
||
| "github.com/github/gh-aw/pkg/linters/stringscutprefix" | ||
| ) | ||
|
|
||
| func TestAnalyzer(t *testing.T) { | ||
| analysistest.Run(t, analysistest.TestData(), stringscutprefix.Analyzer, "stringscutprefix") | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Already addressed in
d63b6b4:/home/runner/work/gh-aw/gh-aw/pkg/linters/doc.go,/home/runner/work/gh-aw/gh-aw/pkg/linters/README.md, and/home/runner/work/gh-aw/gh-aw/pkg/linters/spec_test.gonow includestringscutprefix, andTestDocSurfacesMatchRegistryAndSpecListpasses locally.