Перейти к содержанию
Skillpedia
Код в целом6.5k · #14190

dry-refactoring

Что он делает

Навык даёт пошаговый метод поиска дублированного кода и объединения его в одну общую версию. Он нужен разработчикам, которые хотят иметь один источник истины для повторяющейся логики.

Когда использовать

  • ✓Когда разработчик находит один и тот же код, вставленный в несколько мест, и хочет его объединить.
  • ✓Когда команде нужно убрать дубликаты после быстрого копирования.
  • ✓Когда разработчику нужно понять, какие почти одинаковые фрагменты являются реальными дубликатами, а какие только выглядят похоже.

Ссылка на скилл

https://github.com/kucherenko/jscpd/blob/master/skills/dry-refactoring/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/kucherenko/jscpd/blob/master/skills/dry-refactoring/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Найдите скопированный код в этом проекте и объедините самые плохие повторы в общие функции.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Навык сначала запускает поиск дубликатов, затем ведёт ИИ к исправлению точных копий раньше, чем почти одинаковых. Он использует приёмы, например выделение функции или константы.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

dry-refactoring

Guided workflow to eliminate copy-paste duplication in source code. Use after running jscpd to detect clones.

Prerequisites

First, run jscpd to identify duplications:

npx jscpd --reporters ai <path>

In codebases that mix related formats (e.g. JavaScript and TypeScript), add --cross-formats so clones spanning both are detected too:

npx jscpd --reporters ai --cross-formats "js-ts" <path>

On larger codebases, add --summary to get a refactoring-hotspot overview alongside the clone list — top files and folders with a dup% column showing how much of each file is duplicated:

npx jscpd --reporters ai --summary <path>

The default scan reports only exact copies, and those are the ones to refactor first: an exact clone is almost always a real copy-paste. Two more passes find copies that were edited after pasting. They are noisier: they ignore names, values or a few statements on purpose, so they also surface blocks that merely look alike (models and DTOs, config tables, test setup, generated code, shared idioms). Run them only after the exact clones are dealt with, one family at a time, with tight settings, and treat what they report as leads to read rather than defects to fix:

# Type-2: renamed copies (other variable names, other constants), reported as "(renamed)".
# Raise --min-tokens: with identifiers ignored, a short block is mostly placeholders.
npx jscpd --reporters ai --ignore-identifiers --min-tokens 70 <path>

# Type-3: near-miss copies (one or two edited lines, or JS/TS/Python functions with the same structure),
# reported as "[~0.91 gap]" and "[~0.85 ast]". Widen only if the tight run finds nothing.
npx jscpd --reporters ai --max-gap-lines 1 --similarity <path>

See the jscpd skill for full option reference, including cross-format group syntax, the clone-kind suffixes and how to read the summary.

Workflow

  1. Run jscpd with --reporters ai on the target path (add --summary on larger codebases to pick a starting point: files with high dup% and high token counts pay off most)
  2. Parse each clone line to identify the two duplicated locations (file + line range) and its kind: no suffix is an exact copy, (renamed) differs only in names or values, [~N gap] has a few edited lines in the middle, [~N ast] is a function pair with the same structure
  3. Read both code fragments from the source files
  4. Understand what the duplicated code does, and for renamed and similar clones list exactly what differs between the two sides
  5. Triage renamed and similar clones before touching them. Skip the pair, and say so, when any of these holds: the two sides do different things despite the same shape (a switch over different enums, two reducers with unrelated semantics); the sameness is intentional boilerplate (models, DTOs, config, route tables, test fixtures); the code is generated; a shared abstraction would need a vague name like processData; or the pair is under about 10 lines. Only a pair that would let you delete code and give the extraction a precise name goes on to the next step
  6. Design a refactoring: extract a shared function, class, module, or constant; the kind decides the strategy (below)
  7. Apply the refactoring — update both locations and all other usages
  8. Re-run jscpd with the same flags to confirm the clone is eliminated and the dup% of the touched files went down; a clone that was (renamed) will not show in a default run, so check with --ignore-identifiers again
  9. Repeat for remaining clones, highest-impact first: exact clones, then renamed, then similar. Report the skipped candidates separately from the refactored ones, with the reason, so nobody mistakes a normalized run's count for real duplication

Refactoring Strategies

Extract function — when the duplicate is a block of logic:

// Before: same block in two places
// After: shared function called from both places

Extract module/utility — when the duplicate spans multiple files in different domains:

// Move shared logic to a shared utility file and import it

Extract constant or config — when the duplicate is repeated data or configuration.

Template/base class — when the duplicate is structural (e.g., repeated class shape).

Parameterize — for (renamed) clones. The two sides are the same algorithm over different names or values, so the things that

Частые вопросы

Зачем сначала исправлять точные копии?

Точная копия почти всегда является реальным дубликатом, поэтому с неё безопаснее начинать.

Почти одинаковые фрагменты всегда дубликаты?

Нет. Навык предупреждает, что почти одинаковым может быть код моделей, настройки тестов или сгенерированный код.

Какой инструмент находит дубликаты?

Он использует детектор дубликатов jscpd.

Подробности

Оригинальное описание автора

Guided workflow to eliminate copy-paste duplication detected by jscpd. Refactor exact, renamed and near-miss clones using extract function, parameterize, module, constant, or base class strategies, starting from the hotspots the summary ranks.

repo: kucherenko/jscpd

Популярность

Звёзды на GitHub
6.5k
Место в рейтинге
#14190
Лицензия
MIT
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы