polydup 0.8.1

Cross-language duplicate code detector - find copy-pasted code across JavaScript, TypeScript, Python, and Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# PolyDup CLI

Command-line interface for **PolyDup**, the cross-language duplicate code detector.

## Installation

### From Source

```bash
cd crates/polydup-cli
cargo build --release

# Binary will be at: target/release/polydup
```

### System-wide Installation

```bash
cargo install --path crates/polydup-cli

# Or from the workspace root:
cargo install --path .
```

## Usage

### Basic Scan

```bash
polydup ./src
```

### Scan Multiple Paths

```bash
polydup ./src ./lib ./tests
```

### Adjust Detection Parameters

```bash
# Set minimum block size (default: 50 tokens)
polydup ./src --threshold 30

# Set similarity threshold (default: 0.85 = 85%)
polydup ./src --similarity 0.9

# Combine both
polydup ./src --threshold 30 --similarity 0.9
```

### Exclude Files (e.g., Tests)

By default, PolyDup excludes common test file patterns:
- `**/*.test.{ts,js,tsx,jsx}`
- `**/*.spec.{ts,js,tsx,jsx}`
- `**/__tests__/**`
- `**/*.test.py`

To use **custom exclusions** (replaces defaults):

```bash
# Exclude specific patterns
polydup ./src --exclude "**/*.generated.ts" --exclude "**/*.mock.js"

# Exclude multiple patterns
polydup ./src -e "**/*.test.ts" -e "**/*.spec.js" -e "**/fixtures/**"

# No exclusions (scan everything including tests)
polydup ./src --exclude ""
```

### Output Formats

**Text output (default):**
```bash
polydup ./src
```

Output:
```
Scan Results
═══════════════════════════════════════════════════════════
Files scanned:      4
Functions analyzed: 45
Duplicates found:   0

No duplicates found!
```

**JSON output (for scripting):**
```bash
polydup ./src --format json
```

Output:
```json
{
  "files_scanned": 4,
  "functions_analyzed": 45,
  "duplicates": [],
  "stats": {
    "total_lines": 0,
    "total_tokens": 3665,
    "unique_hashes": 2666,
    "duration_ms": 8
  }
}
```

### Verbose Mode

Show additional performance metrics:

```bash
polydup ./src --verbose
```

Output includes:
- Total tokens processed
- Number of unique hashes
- Scan duration

## Command-Line Options

```
polydup [OPTIONS] <PATHS>...

Arguments:
  <PATHS>...  Paths to scan (files or directories)

Options:
  -f, --format <FORMAT>
          Output format [default: text] [possible values: text, json]

  -t, --threshold <MIN_BLOCK_SIZE>
          Minimum code block size in tokens [default: 50]

  -s, --similarity <SIMILARITY>
          Similarity threshold (0.0-1.0) [default: 0.85]

  -v, --verbose
          Show verbose output

  -h, --help
          Print help

  -V, --version
          Print version
```

## Managing False Positives

PolyDup provides an ignore system to suppress false positives while keeping them documented.

### Adding Ignore Entries

Add a duplicate to the ignore list:

```bash
# Add by ID (from scan output)
polydup ignore add abc123def --files "src/utils.rs:10-30,src/helpers.rs:45-65" --reason "Intentional code reuse"

# Interactive mode
polydup ignore add
# You'll be prompted for files and reason
```

### Listing Ignored Duplicates

```bash
# List all ignored duplicates
polydup ignore list

# Verbose output (shows file paths)
polydup ignore list --verbose

# JSON output for scripting
polydup ignore list --format json
```

Example output:
```
Ignored Duplicates (2)

1. abc123def456
   Reason: Boilerplate initialization code
   Added by: alice
   Added at: 2025-12-26 10:30:15 UTC
   Files: 2 file(s)

2. xyz789abc123
   Reason: Required by framework convention
   Added by: bob
   Added at: 2025-12-26 11:45:30 UTC
   Files: 3 file(s)
```

### Removing Ignore Entries

```bash
# Remove by ID
polydup ignore remove abc123def456
```

### Ignore File Format

Ignored duplicates are stored in `.polydup-ignore` (TOML format):

```toml
version = 1

[[ignores]]
id = "abc123def456"
reason = "Intentional code reuse"
added_by = "alice"
added_at = "2025-12-26T10:30:15Z"

[[ignores.files]]
file = "src/utils.rs"
start_line = 10
end_line = 30

[[ignores.files]]
file = "src/helpers.rs"
start_line = 45
end_line = 65
```

**Tip**: Commit `.polydup-ignore` to version control to share ignore decisions with your team!

## Git-Diff Mode (PR Review)

Scan only files changed in a git diff range - perfect for PR checks:

```bash
# Scan files changed in current branch vs main
polydup scan . --git-diff origin/main..HEAD

# Scan files changed in last commit
polydup scan . --git-diff HEAD~1..HEAD

# Scan with custom similarity threshold
polydup scan . --git-diff main..feature-branch --similarity 0.9
```

### How It Works

1. **Fast**: Only scans files in your diff (10-100x faster for large repos)
2. **Smart**: Scans entire codebase but reports only duplicates involving changed files
3. **Accurate**: Detects when changed code duplicates with unchanged code

**Example Output:**
```bash
ℹ Git-Diff Mode: Only scanning files changed in origin/main..HEAD
  Git diff filter: Added 3 file(s) -> Modified/Renamed 2 file(s)
  Changed files (2):
    • src/handler.rs
    • src/utils.rs

  Git-diff filter: 4 duplicate(s) involve changed files
```

### Combined with Ignore Rules and Directives

Git-diff mode works seamlessly with ignore management:

```bash
# PR check with directives
polydup scan . --git-diff origin/main..HEAD --enable-directives

# PR check with ignore rules loaded from .polydup-ignore
polydup scan . --git-diff HEAD~1..HEAD --verbose
```

**CI/CD Example:**
```yaml
# .github/workflows/pr-check.yml
- name: Check for duplicates in PR
  run: polydup scan . --git-diff origin/${{ github.base_ref }}..HEAD
  # Only fails if new duplicates introduced in this PR
```

**Benefits:**
- ✅ Focuses review on relevant changes
- ✅ Respects existing ignore rules
- ✅ Works with inline directives
- ✅ No baseline files to manage

## Exit Codes

- **0**: No duplicates found
- **1**: Duplicates found (or error occurred)

This allows usage in CI/CD pipelines:

```bash
#!/bin/bash
if ! polydup ./src --threshold 100; then
    echo "❌ Duplicates detected!"
    exit 1
fi
echo "No duplicates!"
```

## Examples

### CI/CD Integration

**GitHub Actions:**

```yaml
name: Check Duplicates

on: [push, pull_request]

jobs:
  check-dupes:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable

      - name: Install PolyDup
        run: cargo install --path crates/polydup-cli

      - name: Check for duplicates
        run: |
          polydup ./src --threshold 50 --similarity 0.85 --format json > duplicates.json

      - name: Upload results
        uses: actions/upload-artifact@v3
        if: failure()
        with:
          name: duplicate-report
          path: duplicates.json
```

### Pre-commit Hook

```bash
#!/bin/bash
# .git/hooks/pre-commit

echo "Checking for duplicate code..."
if ! polydup ./src --threshold 100 --similarity 0.9; then
    echo "❌ Large code duplicates detected!"
    echo "Review the duplicates above and consider refactoring."
    exit 1
fi
```

### Makefile Integration

```makefile
.PHONY: check-dupes
check-dupes:
	@echo "Scanning for duplicates..."
	@polydup ./src ./lib --threshold 50 --similarity 0.85

.PHONY: dupes-json
dupes-json:
	@polydup ./src --format json > duplicates.json
	@echo "Report saved to duplicates.json"
```

### Shell Script for Multiple Projects

```bash
#!/bin/bash
# scan-all-projects.sh

projects=(
    "project1/src"
    "project2/lib"
    "project3/backend"
)

for project in "${projects[@]}"; do
    echo "Scanning $project..."
    polydup "$project" --format json > "${project//\//-}-report.json"
done

echo "All scans complete!"
```

## Performance Tuning

### Fast Scan (Lower Accuracy)

```bash
# Large block size = fewer comparisons = faster
polydup ./src --threshold 100 --similarity 0.7
```

### Thorough Scan (Higher Accuracy)

```bash
# Small block size = more comparisons = slower but catches smaller duplicates
polydup ./src --threshold 20 --similarity 0.95
```

### Recommended Settings

| Use Case | Threshold | Similarity |
|----------|-----------|------------|
| **Quick check** | 100 | 0.85 |
| **Standard scan** | 50 | 0.85 |
| **Thorough analysis** | 30 | 0.90 |
| **Refactoring prep** | 20 | 0.95 |

## Troubleshooting

### No Duplicates Found (But You Expected Some)

- **Lower the threshold**: Try `--threshold 20` to catch smaller duplicates
- **Lower similarity**: Try `--similarity 0.7` for looser matching
- **Check file types**: Only Rust, Python, and JavaScript/TypeScript are supported

### Too Many False Positives

- **Raise the threshold**: Try `--threshold 100` to only catch large duplicates
- **Raise similarity**: Try `--similarity 0.95` for stricter matching

### Slow Performance

- **Increase threshold**: Larger blocks = fewer comparisons
- **Scan fewer files**: Be more specific with paths
- **Use release build**: `cargo build --release` (already done if installed)

## Supported Languages

- **Rust**: `.rs` files
- **Python**: `.py` files
- **JavaScript/TypeScript**: `.js`, `.jsx`, `.ts`, `.tsx` files

More languages coming soon!

## Algorithm

PolyDup uses:
1. **Tree-sitter** for AST-based parsing
2. **Token normalization** (identifiers → `$$ID`, strings → `$$STR`, numbers → `$$NUM`)
3. **Rabin-Karp rolling hash** with window size 50
4. **Parallel processing** via Rayon for multi-core performance

See [architecture-research.md](../../docs/architecture-research.md) for details.

## License

MIT OR Apache-2.0

## Links

- **Core Library**: [polydup-core]../polydup-core
- **Node.js Bindings**: [polydup-node]../polydup-node
- **Python Bindings**: [polydup-py]../polydup-py
- **GitHub**: https://github.com/wiesnerbernard/polydup