/shavakan-commands:cleanup-duplicationfrom shavakan-commands
Find and refactor duplicated code - similar blocks, copy-paste functions, repeated strings
Ships in shavakan-commands. Installing the plugin adds it to Claude Code.
Find DRY (Don't Repeat Yourself) violations and refactor duplicated code into reusable abstractions.
Safety requirements:
Run prerequisite check:
PLUGIN_ROOT="$HOME/.claude/plugins/marketplaces/shavakan"
if [[ ! "$PLUGIN_ROOT" =~ ^"$HOME"/.* ]]; then
echo "ERROR: Invalid plugin root path"
exit 1
fi
PREREQ_SCRIPT="$PLUGIN_ROOT/commands/cleanup/scripts/check-prerequisites.sh"
if [[ ! -f "$PREREQ_SCRIPT" ]]; then
echo "ERROR: Prerequisites script not found"
exit 1
fi
PREREQ_OUTPUT=$(mktemp)
if "$PREREQ_SCRIPT" > "$PREREQ_OUTPUT" 2>&1; then
source "$PREREQ_OUTPUT"
rm "$PREREQ_OUTPUT"
else
cat "$PREREQ_OUTPUT"
rm "$PREREQ_OUTPUT"
exit 1
fi
This exports: TEST_CMD, BACKUP_BRANCH, LOG_FILE
$ARGUMENTS
Identify and eliminate code duplication - extract common patterns into reusable functions, constants, and abstractions.
Duplicated blocks - Similar/identical code in multiple files (>80% similarity, 5+ lines), copy-pasted logic with minor variations
Duplicated functions - Same logic with different names, utility functions reimplemented across files, helper methods duplicated in multiple classes
Magic strings/numbers - Repeated literals (strings like "admin", "error" used 3+ times), hard-coded numbers (excluding 0, 1, -1), configuration values scattered throughout code
Similar patterns - Nearly identical implementations with slight variations, common algorithms reimplemented differently, parallel code structures that could be unified
Run the tooling probe first:
"$CLAUDE_PLUGIN_ROOT/cleanup/scripts/probe-tooling.sh"
Token-similarity tools from the probe's structural array (jscpd, pmd) are the primary detection. LSP MCP (when available, from your tool inventory) is the semantic validator that prevents bad extractions:
hover / type_definition on key symbols to verify they resolve to the same types — guards against "looks identical, behaves differently" extractions (e.g., two User types in different namespaces).find_references to confirm magic-value occurrences are truly the same constant before consolidating (e.g., "admin" as a role vs. "admin" as a route segment).workspace_symbols to find existing utility functions before creating a new one — avoids extracting duplication into something that already has a canonical home.Without LSP MCP and without structural tools from the probe, lean harder on the "Rule of Three" gate before extracting — false-positive risk is high.
Scan codebase for duplicated code. Look for similar blocks, repeated functions, magic values, and patterns that could be unified.
For each duplication found, capture location, similarity percentage, and proposed extraction. Present findings grouped by type with counts and estimated impact.
Gate: User must review full audit before proceeding.
Present audit findings with risk assessment:
Refactor code duplication?
□ Safest - Extract magic strings/numbers to constants
□ Low risk - Consolidate identical functions + extract utilities
□ Medium risk - Extract duplicated blocks + parameterize variations
□ High risk - Unify similar patterns into abstractions
□ Custom - Select specific duplications
□ Cancel
Gate: Get user approval on which duplications to refactor.
For each approved duplication:
Extract duplicated blocks: Identify common functionality, create shared function with appropriate parameters, replace all occurrences, preserve exact behavior
Consolidate functions: Compare implementations to find canonical version, merge variations into single configurable function, update all call sites, remove duplicate definitions
Extract magic values: Create constants with descriptive names (ROLE_ADMIN, DEFAULT_TIMEOUT), replace all occurrences with constant reference, group related constants together
Unify patterns: Design common abstraction that handles all cases, implement generic version with configuration, migrate each usage, remove old implementations
Critical: One refactoring at a time. Test after each. Commit on success, rollback on failure.
Gate: Tests must pass before moving to next refactoring.
Summarize: duplicated blocks extracted, functions consolidated, magic values extracted to constants, patterns unified, code reduction percentage, maintainability improvement.
Delete the backup branch after successful completion:
git branch -D "$BACKUP_BRANCH"
Don't extract if:
Bad extraction example:
// Don't do this - over-abstraction for trivial code
function addOneToNumber(n: number): number {
return n + 1;
}
// Just use n + 1 directly
// Before: Duplicated in 3 files
if (user.role === 'admin' || user.role === 'owner') {
return true;
}
// After: Extract to shared utility
// utils/auth.ts
export function canManageResources(user: User): boolean {
return user.role === 'admin' || user.role === 'owner';
}
// Usage
import { canManageResources } from './utils/auth';
if (canManageResources(user)) { }
// Before: Magic strings repeated
if (user.role === 'admin') { }
// After: Extract to constants
// constants/roles.ts
export const ROLE_ADMIN = 'admin';
// Usage
import { ROLE_ADMIN } from './constants/roles';
if (user.role === ROLE_ADMIN) { }
// Before: Similar functions with variations
function fetchUsers() { return api.get('/users'); }
function fetchPosts() { return api.get('/posts'); }
// After: Single parameterized function
function fetchResource<T>(resource: string): Promise<T[]> {
return api.get(`/${resource}`);
}
// Usage
const users = await fetchResource<User>('users');
CRITICAL:
If tests fail: Rollback immediately, identify which specific extraction broke behavior, understand the difference between duplicates.
Review with code-reviewer agent before pushing:
Use shavakan-agents:code-reviewer to verify refactorings don't introduce issues.
/shavakan-commands:cleanup - Full repository audit/shavakan-commands:cleanup-architecture - Refactor god objects/shavakan-commands:cleanup-dead-code - Remove unused codeWhat the command file sets; muted values are Claude Code's defaults
7-day visitors to each command page
12 commands in this plugin
/cleanupRepository Cleanup AuditComprehensive repository audit and cleanup (dead code, comments, docs, architecture, deps)/cleanup-architectureRefactor ArchitectureRefactor structure - split god objects, break circular deps, improve separation of concerns/cleanup-commentsRemove Comment NoiseRemove obvious comments, commented code, outdated TODOs - keep 'why' explanationsnpx claudepluginhub shavakan/claude-marketplace --plugin shavakan-commands