You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[linter-miner] Add index-compare-to-contains linter for Go static analysis #65911
This PR introduces a new static analysis linter that detects strings.Index() and bytes.Index() comparisons that should be replaced with the more readable strings.Contains() or bytes.Contains() variants.
Motivation
Code patterns like strings.Index(s, sub) != -1 are valid but less idiomatic than strings.Contains(s, sub). This linter catches these patterns and suggests the more readable alternatives.
Keeping this issue open: PR #67544 fixes existing analyzer blind spots, but does not add the proposed indexcomparetocontains analyzer or integrate its strings/bytes/LastIndex coverage. This pending implementation proposal is not resolved by that merge.
Tip
Your pull request is ready to create! 🎉 ✅
Everything is OK—the changes have been pushed to a branch. Please review the protected files, then create the pull request when you are ready.
Create the pull request
The original pull request description is below.
Add
index-compare-to-containsLinterSummary
This PR introduces a new static analysis linter that detects
strings.Index()andbytes.Index()comparisons that should be replaced with the more readablestrings.Contains()orbytes.Contains()variants.Motivation
Code patterns like
strings.Index(s, sub) != -1are valid but less idiomatic thanstrings.Contains(s, sub). This linter catches these patterns and suggests the more readable alternatives.Patterns Detected
The linter reports the following patterns:
Positive Containment Checks
strings.Index(s, sub) != -1→strings.Contains(s, sub)strings.Index(s, sub) >= 0→strings.Contains(s, sub)strings.Index(s, sub) > -1→strings.Contains(s, sub)Negative Containment Checks
strings.Index(s, sub) == -1→!strings.Contains(s, sub)strings.Index(s, sub) < 0→!strings.Contains(s, sub)strings.Index(s, sub) <= -1→!strings.Contains(s, sub)Also Handles
strings.LastIndex()/bytes.LastIndex()comparisonsstrings.IndexByte()/bytes.IndexByte()comparisons-1 != strings.Index(...))Test Coverage
The linter includes comprehensive test cases covering:
All tests pass:
Files Changed
pkg/linters/indexcomparetocontains/ - New linter package
indexcomparetocontains.go- Main linter implementationindexcomparetocontains_test.go- Test suitetestdata/- Test fixturespkg/linters/README.md - Added linter documentation
pkg/linters/registry.go - Registered the new analyzer
Note
Protected files
This patch modifies protected files, which may affect project dependencies, CI/CD pipelines, or agent behaviour.
Protected files
README.mdTo route changes like this to a review issue instead of blocking, configure
protected-files: fallback-to-issuein your workflow configuration.