Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,15 @@ Dependencies used only by tests are treated as used when tests are included. Loc

### Duplication entropy

Gallow reports repeated Go code windows with all related locations. Its remediation order is:
Gallow reports substantial repeated Go code with all related locations. By default it requires a larger repeated block (12 meaningful lines or 100 normalized tokens across at least 12 token-bearing lines) and at least three substantive statements. Repeated single-return guard clauses—common Go error handling boilerplate—are not clone evidence.

Projects can tune the duplicate thresholds in `.gallowrc.json` when they deliberately want tighter reporting. The thresholds never accept values below the conservative safety floor: six lines, 50 tokens, eight token-lines, and one substantive statement.

Its remediation order is:

1. remove an obsolete or redundant copy;
2. extract shared logic when both copies are required and should evolve together;
3. narrowly suppress intentional local duplication.
3. narrowly suppress intentional local duplication with a `gallow-ignore` comment that explains why the duplication is intentional.

## Removal-first remediation

Expand Down Expand Up @@ -116,6 +120,12 @@ Gallow reads `.gallowrc.json` from the selected root unless `--config` specifies
"rules": {
"duplicate-code": "warn"
},
"duplicateCode": {
"minLines": 12,
"minTokens": 100,
"minTokenLines": 12,
"minStatements": 3
},
"ignorePatterns": ["internal/generated/**"],
"ignoreFindings": [
{
Expand Down
4 changes: 4 additions & 0 deletions cmd/gallow/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,10 @@ func analyzerOptions(opts cliOptions, cfg settings.Config) analyzer.Options {
WorkspacePatterns: splitCSV(opts.workspaceCSV),
BuildTags: splitCSV(opts.tagsCSV),
CheckModuleHygiene: true,
DuplicateCode: analyzer.DuplicateOptions{
MinLines: cfg.DuplicateCode.MinLines, MinTokens: cfg.DuplicateCode.MinTokens,
MinTokenLines: cfg.DuplicateCode.MinTokenLines, MinStatements: cfg.DuplicateCode.MinStatements,
},
}
}

Expand Down
6 changes: 5 additions & 1 deletion internal/analyzer/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ type Options struct {
WorkspacePatterns []string
BuildTags []string
CheckModuleHygiene bool
DuplicateCode DuplicateOptions
}

type FindingMatcher struct {
Expand Down Expand Up @@ -159,6 +160,9 @@ type moduleState struct {
}

func Analyze(opts Options) (*Report, error) {
if err := opts.DuplicateCode.Validate(); err != nil {
return nil, err
}
root := opts.Root
if root == "" {
root = "."
Expand Down Expand Up @@ -391,7 +395,7 @@ func analyzeModule(root string, modules []moduleState, moduleIndex int, opts Opt
}
}
findings = append(findings, deadCodeFindings(module)...)
findings = append(findings, duplicateFindings(module)...)
findings = append(findings, duplicateFindings(module, opts.DuplicateCode)...)
assignFingerprints(findings)
findings, suppressedByComment := applyCommentSuppressions(findings, module)
findings = filterFindings(findings, opts)
Expand Down
19 changes: 16 additions & 3 deletions internal/analyzer/analyzer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,11 @@ func a() {
total += 3
total += 4
total += 5
total += 6
total += 7
total += 8
total += 9
total += 10
_ = total
}
`)
Expand All @@ -814,6 +819,11 @@ func b() {
total += 3
total += 4
total += 5
total += 6
total += 7
total += 8
total += 9
total += 10
_ = total
}
`)
Expand All @@ -825,8 +835,8 @@ func b() {
if got := report.Summary.DuplicateGroups; got != 1 {
t.Fatalf("duplicate groups = %d; want 1", got)
}
if got := report.Modules[0].Findings[0].Lines; got != 8 {
t.Fatalf("duplicated lines = %d; want 8", got)
if got := report.Modules[0].Findings[0].Lines; got != 13 {
t.Fatalf("duplicated lines = %d; want 13", got)
}
}

Expand Down Expand Up @@ -875,7 +885,10 @@ func two(value int) int { return value }
func three(value int) int { return value }
`)

report, err := Analyze(Options{Root: root, IncludeTests: true, IncludeGenerated: true})
report, err := Analyze(Options{
Root: root, IncludeTests: true, IncludeGenerated: true,
DuplicateCode: DuplicateOptions{MinLines: 100, MinTokens: 50, MinTokenLines: 8, MinStatements: 3},
})
if err != nil {
t.Fatalf("Analyze() error = %v", err)
}
Expand Down
195 changes: 174 additions & 21 deletions internal/analyzer/duplicate.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,59 @@ import (
)

const (
duplicateWindowLines = 6
duplicateWindowTokens = 50
duplicateTokenMinLines = 8
duplicateHashLength = 12
defaultDuplicateWindowLines = 12
defaultDuplicateWindowTokens = 100
defaultDuplicateTokenMinLines = 12
defaultDuplicateMinStatements = 3

minimumDuplicateWindowLines = 6
minimumDuplicateWindowTokens = 50
minimumDuplicateTokenMinLines = 8
minimumDuplicateMinStatements = 1
duplicateHashLength = 12
)

type DuplicateOptions struct {
MinLines int
MinTokens int
MinTokenLines int
MinStatements int
}

func (o DuplicateOptions) Validate() error {
for _, threshold := range []struct {
name, minimum string
value int
minimumValue int
}{
{name: "duplicate minimum lines", minimum: "6", value: o.MinLines, minimumValue: minimumDuplicateWindowLines},
{name: "duplicate minimum tokens", minimum: "50", value: o.MinTokens, minimumValue: minimumDuplicateWindowTokens},
{name: "duplicate minimum token lines", minimum: "8", value: o.MinTokenLines, minimumValue: minimumDuplicateTokenMinLines},
{name: "duplicate minimum statements", minimum: "1", value: o.MinStatements, minimumValue: minimumDuplicateMinStatements},
} {
if threshold.value != 0 && threshold.value < threshold.minimumValue {
return fmt.Errorf("%s must be zero or at least %s", threshold.name, threshold.minimum)
}
}
return nil
}

func (o DuplicateOptions) normalized() DuplicateOptions {
if o.MinLines == 0 {
o.MinLines = defaultDuplicateWindowLines
}
if o.MinTokens == 0 {
o.MinTokens = defaultDuplicateWindowTokens
}
if o.MinTokenLines == 0 {
o.MinTokenLines = defaultDuplicateTokenMinLines
}
if o.MinStatements == 0 {
o.MinStatements = defaultDuplicateMinStatements
}
return o
}

const (
duplicateLineKeyPrefix = "line:"
duplicateTokenKeyPrefix = "token:"
Expand All @@ -35,16 +82,18 @@ type duplicateGroup struct {
locations []duplicateWindow
}

func duplicateFindings(module moduleState) []Finding {
func duplicateFindings(module moduleState, options DuplicateOptions) []Finding {
options = options.normalized()
windows := make(map[string][]duplicateWindow)
for _, pkg := range module.packages {
for _, source := range pkg.files {
data, err := os.ReadFile(source.absPath)
if err != nil {
continue
}
collectDuplicateWindows(windows, source.relPath, string(data))
collectTokenDuplicateWindows(windows, source.relPath, data, source.file, source.fset)
statements := meaningfulStatementSpans(source.file, source.fset)
collectDuplicateWindows(windows, source.relPath, string(data), statements, options)
collectTokenDuplicateWindows(windows, source.relPath, data, source.file, source.fset, statements, options)
}
}

Expand Down Expand Up @@ -191,7 +240,7 @@ func duplicatedLineCount(locations []duplicateWindow) int {
return (locations[0].endLine - locations[0].startLine + 1) * (len(locations) - 1)
}

func collectDuplicateWindows(windows map[string][]duplicateWindow, file string, content string) {
func collectDuplicateWindows(windows map[string][]duplicateWindow, file string, content string, statements []meaningfulStatement, options DuplicateOptions) {
lines := strings.Split(content, "\n")
normalized := make([]string, 0, len(lines))
lineNumbers := make([]int, 0, len(lines))
Expand All @@ -203,17 +252,22 @@ func collectDuplicateWindows(windows map[string][]duplicateWindow, file string,
normalized = append(normalized, line)
lineNumbers = append(lineNumbers, i+1)
}
if len(normalized) < duplicateWindowLines {
if len(normalized) < options.MinLines {
return
}

for i := 0; i <= len(normalized)-duplicateWindowLines; i++ {
chunk := strings.Join(normalized[i:i+duplicateWindowLines], "\n")
for i := 0; i <= len(normalized)-options.MinLines; i++ {
startLine := lineNumbers[i]
endLine := lineNumbers[i+options.MinLines-1]
if !duplicateWindowHasMeaningfulStatements(statements, startLine, endLine, options.MinStatements) {
continue
}
chunk := strings.Join(normalized[i:i+options.MinLines], "\n")
key := duplicateKey(duplicateLineKeyPrefix + chunk)
windows[key] = append(windows[key], duplicateWindow{
file: file,
startLine: lineNumbers[i],
endLine: lineNumbers[i+duplicateWindowLines-1],
startLine: startLine,
endLine: endLine,
})
}
}
Expand All @@ -223,10 +277,10 @@ type duplicateToken struct {
line int
}

func collectTokenDuplicateWindows(windows map[string][]duplicateWindow, file string, content []byte, syntax *ast.File, fset *token.FileSet) {
func collectTokenDuplicateWindows(windows map[string][]duplicateWindow, file string, content []byte, syntax *ast.File, fset *token.FileSet, statements []meaningfulStatement, options DuplicateOptions) {
tokens := duplicateTokens(file, content)
for _, body := range functionBodyLineRanges(syntax, fset) {
collectTokenSequenceDuplicateWindows(windows, file, tokensInLineRange(tokens, body))
collectTokenSequenceDuplicateWindows(windows, file, tokensInLineRange(tokens, body), statements, options)
}
}

Expand Down Expand Up @@ -292,20 +346,20 @@ func tokensInLineRange(tokens []duplicateToken, lines duplicateWindow) []duplica
return filtered
}

func collectTokenSequenceDuplicateWindows(windows map[string][]duplicateWindow, file string, tokens []duplicateToken) {
if len(tokens) < duplicateWindowTokens {
func collectTokenSequenceDuplicateWindows(windows map[string][]duplicateWindow, file string, tokens []duplicateToken, statements []meaningfulStatement, options DuplicateOptions) {
if len(tokens) < options.MinTokens {
return
}

for i := 0; i <= len(tokens)-duplicateWindowTokens; i++ {
end := i + duplicateWindowTokens - 1
for i := 0; i <= len(tokens)-options.MinTokens; i++ {
end := i + options.MinTokens - 1
startLine := tokens[i].line
endLine := tokens[end].line
if endLine-startLine+1 < duplicateTokenMinLines {
if duplicateTokenLineCount(tokens[i:i+options.MinTokens]) < options.MinTokenLines || !duplicateWindowHasMeaningfulStatements(statements, startLine, endLine, options.MinStatements) {
continue
}

key := duplicateKey(duplicateTokenKeyPrefix + duplicateTokenChunk(tokens[i:i+duplicateWindowTokens]))
key := duplicateKey(duplicateTokenKeyPrefix + duplicateTokenChunk(tokens[i:i+options.MinTokens]))
windows[key] = append(windows[key], duplicateWindow{
file: file,
startLine: startLine,
Expand All @@ -314,6 +368,105 @@ func collectTokenSequenceDuplicateWindows(windows map[string][]duplicateWindow,
}
}

func duplicateTokenLineCount(tokens []duplicateToken) int {
previousLine := -1
count := 0
for _, token := range tokens {
if token.line == previousLine {
continue
}
previousLine = token.line
count++
}
return count
}

type meaningfulStatement struct {
startLine int
endLine int
}

func meaningfulStatementSpans(syntax *ast.File, fset *token.FileSet) []meaningfulStatement {
if syntax == nil || fset == nil {
return nil
}

spans := make([]meaningfulStatement, 0)
ast.Inspect(syntax, func(node ast.Node) bool {
statement, ok := node.(ast.Stmt)
if !ok {
return true
}
if guard, ok := statement.(*ast.IfStmt); ok && isSingleReturnGuard(guard) {
return false
}
if !isMeaningfulStatement(statement) {
return true
}
spans = append(spans, meaningfulStatement{
startLine: fset.Position(statement.Pos()).Line,
endLine: fset.Position(statement.End()).Line,
})
return true
})

sort.Slice(spans, func(i, j int) bool {
if spans[i].startLine == spans[j].startLine {
return spans[i].endLine < spans[j].endLine
}
return spans[i].startLine < spans[j].startLine
})
return spans
}

func isMeaningfulStatement(statement ast.Stmt) bool {
if guard, ok := statement.(*ast.IfStmt); ok && isSingleReturnGuard(guard) {
return false
}

switch statement := statement.(type) {
case *ast.AssignStmt, *ast.IncDecStmt, *ast.SendStmt, *ast.GoStmt, *ast.RangeStmt, *ast.ForStmt, *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt, *ast.IfStmt:
return true
case *ast.ExprStmt:
_, ok := statement.X.(*ast.CallExpr)
return ok
default:
return false
}
}

func duplicateWindowHasMeaningfulStatements(statements []meaningfulStatement, startLine, endLine, minimum int) bool {
if minimum < 1 {
return false
}

first := sort.Search(len(statements), func(index int) bool {
return statements[index].startLine >= startLine
})
count := 0
for _, statement := range statements[first:] {
if statement.startLine > endLine {
break
}
if statement.endLine > endLine {
continue
}
count++
if count >= minimum {
return true
}
}
return false
}

func isSingleReturnGuard(statement *ast.IfStmt) bool {
if statement.Else != nil || statement.Body == nil || len(statement.Body.List) != 1 {
return false
}
_, ok := statement.Body.List[0].(*ast.ReturnStmt)
return ok
}

func normalizeDuplicateToken(tok token.Token, previous token.Token) (string, bool) {
switch {
case tok == token.IDENT:
Expand Down
Loading
Loading