Repository navigation
ci: Detect duplicate code with jscpd #3133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| name: jscpd - Duplicate Code Analysis | ||
| on: | ||
| pull_request: | ||
| branches: [main] | ||
| concurrency: | ||
| group: ${{ github.workflow }}-${{ github.ref }} | ||
| cancel-in-progress: true | ||
| jobs: | ||
| jscpd: | ||
| timeout-minutes: 10 | ||
| runs-on: ubuntu-24.04 | ||
| permissions: | ||
| contents: read | ||
| pull-requests: write | ||
| steps: | ||
| - name: Checkout PR branch | ||
| uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 | ||
| with: | ||
| # --baseline-from-ref scans the base branch's tree, so the whole | ||
| # history has to be present. Blobless, not treeless: jscpd needs the | ||
| # trees to materialise the base ref's files. | ||
| fetch-depth: 0 | ||
| filter: blob:none | ||
|
|
||
| - name: Setup node | ||
| uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 | ||
| with: | ||
| node-version-file: '.nvmrc' | ||
| cache-dependency-path: 'yarn.lock' | ||
| cache: 'yarn' | ||
|
|
||
| - name: Install dependencies | ||
| run: yarn install --immutable | ||
|
|
||
| # Advisory check. dupes.mjs always exits 0; continue-on-error covers the | ||
| # case where it cannot run at all, so a tool failure can never block a PR. | ||
| - name: Build duplication report | ||
| continue-on-error: true | ||
| env: | ||
| BASE_REF: ${{ github.base_ref }} | ||
| run: | ||
| node scripts/ci/dupes.mjs --base "origin/$BASE_REF" --markdown > | ||
| /tmp/jscpd-comment.md | ||
|
|
||
| - name: Read report | ||
| id: report | ||
| uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 | ||
| with: | ||
| result-encoding: string | ||
| script: | | ||
| const fs = require('fs'); | ||
| const path = '/tmp/jscpd-comment.md'; | ||
| const body = fs.existsSync(path) | ||
| ? fs.readFileSync(path, 'utf8').trim() | ||
| : ''; | ||
| if (body === '') { | ||
| core.error('No duplication report was produced; skipping the PR comment.'); | ||
| return ''; | ||
| } | ||
| // Logged as well as commented so fork PRs, which cannot be | ||
| // commented on, still surface the result somewhere. | ||
| core.info(body); | ||
| return body; | ||
|
|
||
| - name: Comment PR with duplication report | ||
| # Skip for fork PRs: GITHUB_TOKEN cannot write to the base repo | ||
| if: | ||
| steps.report.outputs.result != '' && | ||
| github.event.pull_request.head.repo.fork != true | ||
| uses: mshick/add-pr-comment@ec328af66588ab8f77cdeb2c264f14aba45bbf59 # v3.12.0 | ||
| with: | ||
| message: ${{ steps.report.outputs.result }} | ||
| message-id: jscpd-duplication | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| { | ||
| "minLines": 5, | ||
| "minTokens": 70, | ||
| "format": ["typescript", "tsx"], | ||
| "ignore": [ | ||
|
pulpdrew marked this conversation as resolved.
Resolved
|
||
| "**/__tests__/**", | ||
| "**/__mocks__/**", | ||
| "**/__snapshots__/**", | ||
| "**/__fixtures__/**", | ||
| "**/*.test.ts", | ||
| "**/*.test.tsx", | ||
| "**/*.spec.ts", | ||
| "**/*.spec.tsx", | ||
| "**/*.stories.tsx", | ||
| "**/*.d.ts", | ||
| "packages/app/tests/e2e/**", | ||
| "packages/api/migrations/**" | ||
| ] | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| #!/usr/bin/env node | ||
|
pulpdrew marked this conversation as resolved.
Resolved
|
||
| // Duplicate-code report. Advisory: always exits 0. | ||
| // | ||
| // jscpd's console reporter ignores --baseline-from-ref and prints every clone, | ||
| // so "what did this branch add" is only available as an `isNew` flag in the | ||
| // JSON report. This wraps the JSON run and renders the new clones. | ||
|
|
||
| import { execFileSync } from 'node:child_process'; | ||
| import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; | ||
| import { tmpdir } from 'node:os'; | ||
| import { dirname, join, resolve } from 'node:path'; | ||
| import { fileURLToPath } from 'node:url'; | ||
|
|
||
| const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); | ||
| const PACKAGES = ['packages/app', 'packages/api', 'packages/common-utils']; | ||
|
pulpdrew marked this conversation as resolved.
Resolved
|
||
| const CONFIG = join(ROOT, '.jscpd.json'); | ||
|
|
||
| // Cap the number of duplicates listed in the PR comment | ||
| const MAX_LISTED_IN_COMMENT = 20; | ||
|
|
||
| const argv = process.argv.slice(2); | ||
| const all = argv.includes('--all'); | ||
| const markdown = argv.includes('--markdown'); | ||
| const baseIdx = argv.indexOf('--base'); | ||
| const baseArg = argv[baseIdx + 1]; | ||
| if (baseIdx !== -1 && (!baseArg || baseArg.startsWith('--'))) { | ||
| console.error('--base requires a git ref, e.g. --base origin/main'); | ||
| process.exit(0); | ||
| } | ||
| const base = baseIdx === -1 ? 'origin/main' : baseArg; | ||
|
|
||
| // A malformed .jscpd.json makes jscpd log one line to stderr and carry on with | ||
| // its defaults, which scans markdown, tests and CHANGELOG.md. Fail loudly here | ||
| // instead of silently reporting noise. | ||
| try { | ||
| JSON.parse(readFileSync(CONFIG, 'utf8')); | ||
| } catch (e) { | ||
| console.error(`Cannot parse ${CONFIG}: ${e.message}`); | ||
| process.exit(0); | ||
| } | ||
|
|
||
| const out = mkdtempSync(join(tmpdir(), 'jscpd-')); | ||
| // process.exit skips finally blocks, so every exit path clears the temp dir | ||
| // through here instead. | ||
| const bail = message => { | ||
| console.error(message); | ||
| rmSync(out, { recursive: true, force: true }); | ||
| process.exit(0); | ||
| }; | ||
|
|
||
| const args = [ | ||
| ...PACKAGES, | ||
| '--absolute', | ||
| '--no-tips', | ||
| '--reporters', | ||
| 'json', | ||
| '--output', | ||
| out, | ||
| ]; | ||
| if (!all) args.push('--baseline-from-ref', base); | ||
|
|
||
| try { | ||
| execFileSync(join(ROOT, 'node_modules', '.bin', 'jscpd'), args, { | ||
| cwd: ROOT, | ||
| stdio: ['ignore', 'ignore', 'inherit'], | ||
| }); | ||
| } catch (e) { | ||
| bail(`jscpd failed to run: ${e.message}`); | ||
| } | ||
|
|
||
| const report = join(out, 'jscpd-report.json'); | ||
| if (!existsSync(report)) bail('jscpd produced no report.'); | ||
|
|
||
| const data = JSON.parse(readFileSync(report, 'utf8')); | ||
|
pulpdrew marked this conversation as resolved.
Resolved
|
||
| rmSync(out, { recursive: true, force: true }); | ||
| const total = data.statistics?.total ?? {}; | ||
| const rel = p => (p.startsWith(`${ROOT}/`) ? p.slice(ROOT.length + 1) : p); | ||
| const at = f => `${rel(f.name)}:${f.start}-${f.end}`; | ||
| const duplicates = all | ||
| ? (data.duplicates ?? []) | ||
| : (data.duplicates ?? []).filter(c => c.isNew); | ||
| const plural = duplicates.length === 1 ? '' : 's'; | ||
|
|
||
| if (markdown) { | ||
| const lines = ['## Duplicate code analysis', '']; | ||
| if (duplicates.length === 0) { | ||
| lines.push('No new duplicate code introduced by this PR.'); | ||
| } else { | ||
| lines.push( | ||
| `**${duplicates.length} new clone${plural}** introduced by this PR.`, | ||
| '', | ||
| ); | ||
| for (const c of duplicates.slice(0, MAX_LISTED_IN_COMMENT)) { | ||
| lines.push( | ||
| `- \`${at(c.firstFile)}\` ↔ \`${at(c.secondFile)}\` — ${c.lines} lines`, | ||
| ); | ||
| } | ||
| if (duplicates.length > MAX_LISTED_IN_COMMENT) { | ||
| lines.push(`- …and ${duplicates.length - MAX_LISTED_IN_COMMENT} more`); | ||
| } | ||
| lines.push( | ||
| '', | ||
| 'If one of these duplicates a helper that already exists, import it instead', | ||
| 'of redefining it. If the duplication is deliberate, ignore this comment —', | ||
| 'the check is advisory and never fails the build.', | ||
| ); | ||
| } | ||
| lines.push( | ||
| '', | ||
| '---', | ||
| `[jscpd](https://github.com/kucherenko/jscpd) compared this branch against \`${base}\``, | ||
| 'across app, api and common-utils. Only new clones are listed; the codebase', | ||
| `currently holds ${total.clones ?? 0} in total (${(total.percentage ?? 0).toFixed(2)}%).`, | ||
| 'Run `yarn dupes` locally to reproduce, or `yarn dupes:all` for the full picture.', | ||
| ); | ||
| console.log(lines.join('\n')); | ||
| process.exit(0); | ||
| } | ||
|
|
||
| if (duplicates.length === 0) { | ||
| console.log( | ||
| all ? 'No duplicate code found.' : `No new duplicate code vs ${base}.`, | ||
| ); | ||
| } else { | ||
| const scope = all ? 'in app, api and common-utils' : `vs ${base}`; | ||
| console.log(`${duplicates.length} clone${plural} ${scope}:\n`); | ||
| for (const c of duplicates) { | ||
| console.log(` ${at(c.firstFile)}`); | ||
| console.log(` ${at(c.secondFile)} (${c.lines} lines)\n`); | ||
| } | ||
| } | ||
| if (!all) { | ||
| console.log( | ||
| `Total duplication: ${total.clones ?? 0} clones (${(total.percentage ?? 0).toFixed(2)}%). ` + | ||
| 'Run `yarn dupes:all` to list them.', | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔵 minor — Clean PRs still get a bot comment
Every non-fork PR gets a jscpd comment, even when it adds no duplicates, because
dupes.mjs --markdownalways prints a body ('No new duplicate code introduced by this PR.')..github/workflows/knip.yml:98-119handles the same case by skipping the comment and deleting any stale one. Do the same here: emit empty output when there are no new clones (or add adelete-on-status/cleanup step) so the comment only appears when there is something to act on.Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond