A Go tool that finds duplicated string literals in Go source files and suggests refactoring opportunities.
.
├── cmd/
│ └── gorefactor/ # Main application entry point
│ └── main.go
├── pkg/
│ └── duplicates/ # Core logic for finding duplicated literals
│ ├── duplicates.go
│ └── duplicates_test.go
├── Makefile # Build automation
└── go.mod
Build the tool:
make buildOr using go directly:
go build -o bin/gorefactor ./cmd/gorefactorRun it on a Go file:
./bin/gorefactor [flags] <path-to-go-file>--format- Output format:text(default) orjson--min-count- Minimum number of occurrences to report (default: 2)
Text output (default):
./bin/gorefactor cmd/gorefactor/main.go
./bin/gorefactor pkg/duplicates/duplicates.goJSON output (for AI agents and tooling):
./bin/gorefactor --format json cmd/gorefactor/main.goFilter by minimum occurrences:
./bin/gorefactor --min-count 3 cmd/gorefactor/main.gomake build- Build the gorefactor binary (default)make clean- Remove the bin/ directorymake test- Run testsmake vet- Run go vetmake install- Install to GOPATH/bin
Run the test suite:
make testOr using go directly:
go test -v ./...The test suite includes:
- Finding duplicates in test files
- Handling files with no duplicates
- Error handling for invalid files
- Error handling for invalid Go code
- Multiple duplicate detection
- Minimum count filtering
- JSON output round-trip testing
The tool:
- Parses the provided Go file into an AST using Go's standard library (
pkg/duplicates) - Walks the AST to collect all string literals and their line numbers
- Identifies literals that appear more than the minimum count (default: 2)
- Generates suggestions for extracting duplicates to constants
- Outputs the duplicated literals with their locations and suggestions (
cmd/gorefactor)
Duplicate string literals found:
String: "Hello, World!"
Found 3 times at lines: [7 8 15]
Suggestion: String "Hello, World!" appears 3 times. Consider extracting to a package-level constant.
String: "example"
Found 2 times at lines: [6 11]
Suggestion: String "example" appears 2 times. Consider extracting to a package-level constant.
{
"file_path": "example.go",
"duplicates": [
{
"value": "\"Hello, World!\"",
"lines": [7, 8, 15],
"suggestion": "String \"Hello, World!\" appears 3 times. Consider extracting to a package-level constant."
},
{
"value": "\"example\"",
"lines": [6, 11],
"suggestion": "String \"example\" appears 2 times. Consider extracting to a package-level constant."
}
]
}See CONTRIBUTING.md for guidelines on contributing to this project.