From 791a5f1e649827da20129f1cb161f2c58e415f79 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Sun, 29 Nov 2026 05:23:32 +0100 Subject: [PATCH 1/3] chore(tooling): make the dead-code job blocking (#1356) The surplus exports are gone; what knip still reported were exports read through CommonJS namespace access, a spread re-export in a test fixture, a module loaded as source by its test, or module.exports read back by the module itself. Silence those per file and for unused exports only, and drop continue-on-error so a new finding fails the workflow. --- .ai/contexts/build-release.md | 17 +++++++----- .github/workflows/test.yml | 3 +-- docs/development.md | 30 +++++++++++++++------ knip.json | 49 ++++++++++++++++++++++++++++++++++- test/deadcode-report.test.js | 25 +++++++++++++++--- 5 files changed, 103 insertions(+), 21 deletions(-) diff --git a/.ai/contexts/build-release.md b/.ai/contexts/build-release.md index b059039cc..69e01f798 100644 --- a/.ai/contexts/build-release.md +++ b/.ai/contexts/build-release.md @@ -349,18 +349,21 @@ The rule is in [changelog.md](../../docs/changelog.md#documentation-in-the-same- Review still assesses the prose. Adding the label or editing the reason needs a rerun. Required-check settings and label creation remain separate actions. -The `deadcode` job reports and never blocks (#1356, first step). It runs one +The `deadcode` job blocks on any finding (#1356). It runs one cell, Node 22 on `ubuntu-latest`, installs locked dependencies with `npm ci --ignore-scripts` (knip needs no native rebuild and no Electron download), then runs the locked knip with `npx --no-install`, so the version is the one pinned in `package.json`. The markdown report goes to the log and to the job summary through `tee`. The step sets `shell: bash` for pipefail, so -knip's non-zero exit still marks the step, and `continue-on-error: true`, so -the job and the workflow stay green whatever knip finds. Nothing `needs` it and -it is not a required check. Making it blocking is a later step of #1356, once -the report is clean. `test/deadcode-report.test.js` checks the pin, the job's -shape and that no gate task or job depends on it. What knip analyses and its -known false positives are in +knip's non-zero exit fails the step through `tee`; neither the step nor the +job sets `continue-on-error`, so a finding fails the workflow. Nothing `needs` +it. Whether it is a required status check is a repository ruleset setting, not +part of the workflow. False positives are silenced in `knip.json` by +`ignoreIssues`, one file per key with `["exports"]` only. +`test/deadcode-report.test.js` checks the pin, the job's shape, the absence +of `continue-on-error`, that every ignore names one existing file for unused +exports only, and that no gate task or job depends on it. What knip analyses, +its known false positives and how to add one are in [development.md](../../docs/development.md#dead-code-report). Linux runs the full Node suite with coverage. Every non-Linux runner runs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2beb62b71..932dbbb66 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -53,8 +53,7 @@ jobs: - name: Install dependencies without lifecycle scripts run: npm ci --ignore-scripts - - name: Report unused files, exports and dependencies - continue-on-error: true + - name: Check for unused files, exports and dependencies shell: bash run: npx --no-install knip --no-progress --reporter markdown | tee -a "$GITHUB_STEP_SUMMARY" diff --git a/docs/development.md b/docs/development.md index 75949ad80..0892f7270 100644 --- a/docs/development.md +++ b/docs/development.md @@ -117,9 +117,8 @@ modifies must be 80 % covered (`diff-cover`), `main.js`, `preload.js`, the MCP bridge, `claude-auth.js`, `public/app.js`, `public/terminal-manager.js`, the CodeMirror and Mermaid files, workers, scripts, tests and `e2e/` excepted. The same workflow runs the [changelog check](changelog.md#the-ci-check) on pull -requests and the [end-to-end journeys](e2e.md). Its `deadcode` job prints the -[dead-code report](#dead-code-report); knip's findings and errors never fail it, -though a failed install does. +requests and the [end-to-end journeys](e2e.md). Its `deadcode` job runs the +[dead-code check](#dead-code-report) and fails on any finding knip reports. ### Dead-code report @@ -127,8 +126,10 @@ though a failed install does. `devDependencies`, with `npx --no-install`: it uses the locked copy in `node_modules` and never downloads another. Run `task install` first after pulling the change that adds it. Arguments after `--` go to knip, for example -`task deadcode -- --production`. knip exits non-zero when it reports anything; -the report is information, not a gate, and no other task depends on it. +`task deadcode -- --production`. knip exits non-zero when it reports anything. +No other task depends on it, but the CI `deadcode` job fails on the same +report, so a pull request that adds an unused file, export or dependency goes +red. `knip.json` declares what is analysed: @@ -158,10 +159,23 @@ listing them: `css-tree` through jsdom's own resolution path, and `app-builder-lib` and `builder-util` for electron-builder's macro helpers in `test/build-workflow.test.js`. -Known false positive: knip does not follow CommonJS namespace access. An export +Known false positives: knip does not follow CommonJS namespace access. An export read as `const ns = require('./x'); ns.name()`, destructured later from `ns`, or -re-exported with `module.exports = { ...ns }` is reported unused. Check every -reported export for that pattern before removing it. +re-exported with `module.exports = { ...ns }` (as `test/fixtures/trigger-watcher.cjs` +does) is reported unused. So is an export a test reaches by loading the module's +source into a VM context, and one the module reads back through +`module.exports.name`. Check every reported export for these patterns before +removing it. + +`ignoreIssues` in `knip.json` lists the files whose exports are reached only +that way, each with `["exports"]` and nothing else. knip 6 has no per-export +setting short of a JSDoc tag, and production code carries no such comment, so +the ignore covers every export of the file: a genuinely unused export added to +one of those files is not reported. To handle a new false positive, add the +one file to `ignoreIssues` with `["exports"]`, never a glob, a broader issue +type or a global switch such as `ignoreExportsUsedInFile`, and give in the pull +request the export and the line that reads it. `test/deadcode-report.test.js` +refuses a pattern, another issue type or a global switch. ## Running from source next to an installed copy diff --git a/knip.json b/knip.json index 5d0f02740..d731bde4c 100644 --- a/knip.json +++ b/knip.json @@ -28,5 +28,52 @@ "css-tree", "app-builder-lib", "builder-util" - ] + ], + "ignoreIssues": { + "archived-projects.js": [ + "exports" + ], + "jsonl-scan.js": [ + "exports" + ], + "project-remap.js": [ + "exports" + ], + "session-transitions.js": [ + "exports" + ], + "worktree-delete.js": [ + "exports" + ], + "src/main/changes/git-changes-file.js": [ + "exports" + ], + "src/main/projects/project-delete-writer.js": [ + "exports" + ], + "src/main/remote/remote-ssh-binary.js": [ + "exports" + ], + "src/main/schedules/schedule-background.js": [ + "exports" + ], + "src/main/schedules/schedule-delete-file.js": [ + "exports" + ], + "src/main/schedules/schedule-ipc.js": [ + "exports" + ], + "src/main/schedules/schedule-run-results.js": [ + "exports" + ], + "src/main/session-index/read-counters.js": [ + "exports" + ], + "src/main/triggers/trigger-name.js": [ + "exports" + ], + "src/main/triggers/trigger-watcher.js": [ + "exports" + ] + } } diff --git a/test/deadcode-report.test.js b/test/deadcode-report.test.js index 16edba8cc..f4d8e44d7 100644 --- a/test/deadcode-report.test.js +++ b/test/deadcode-report.test.js @@ -42,7 +42,7 @@ test('task deadcode runs the locked knip and no gate task depends on it', () => } }); -test('the deadcode CI job reports on Node 22 Linux without ever failing the workflow', () => { +test('the deadcode CI job runs on Node 22 Linux and fails on any finding', () => { const { jobs } = yaml.load(read('.github/workflows/test.yml')); const job = jobs.deadcode; assert.ok(job, 'test.yml has a deadcode job'); @@ -55,9 +55,28 @@ test('the deadcode CI job reports on Node 22 Linux without ever failing the work assert.match(install.run, /--ignore-scripts/, 'knip needs no native rebuild'); const report = job.steps.filter(step => knipCommand.test(step.run || '')); assert.equal(report.length, 1, 'one step runs knip'); - assert.equal(report[0]['continue-on-error'], true, 'findings never fail the job'); - assert.equal(report[0].shell, 'bash', 'bash runs with pipefail, so the step still shows knip\'s exit'); + assert.equal(job['continue-on-error'], undefined, 'a finding fails the workflow'); + for (const step of job.steps) assert.equal(step['continue-on-error'], undefined, step.name || step.uses); + assert.equal(report[0].shell, 'bash', 'bash runs with pipefail, so tee does not hide knip\'s exit'); for (const [id, other] of Object.entries(jobs)) { assert.ok(![].concat(other.needs || []).includes('deadcode'), `${id} must not wait on deadcode`); } }); + +test('knip silences its false positives file by file, never by a global switch', () => { + const config = JSON.parse(read('knip.json')); + assert.equal(config.ignoreExportsUsedInFile, undefined, 'no global export switch'); + assert.equal(config.includeEntryExports, undefined); + assert.equal(config.rules, undefined, 'no issue type turned off for the whole project'); + assert.equal(config.exclude, undefined, 'no issue type excluded for the whole project'); + assert.equal(config.include, undefined, 'no issue type selection for the whole project'); + assert.equal(config.ignoreFiles, undefined); + for (const pattern of config.ignore) assert.ok(pattern === 'public/**', `only the renderer is ignored whole: ${pattern}`); + const entries = Object.entries(config.ignoreIssues || {}); + assert.ok(entries.length > 0, 'the known false positives are declared'); + for (const [file, types] of entries) { + assert.doesNotMatch(file, /[*?{}[\]!]/, `${file}: one file, no pattern`); + assert.ok(fs.statSync(path.join(root, file)).isFile(), `${file} exists`); + assert.deepEqual(types, ['exports'], `${file}: unused exports only`); + } +}); From 84b10fce333b8dca23e1e29ed24d355633716fe0 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Sun, 29 Nov 2026 05:35:01 +0100 Subject: [PATCH 2/3] chore(tooling): allow knip's false positives export by export (#1356) A file-wide ignoreIssues entry also hid any new unused export in the same file. A knip preprocessor now drops exactly the listed (file, export) pairs, each with its reason, and lowers the counters knip derives its exit code from; a listed pair knip no longer reports fails the run so stale entries get removed. --- .ai/contexts/build-release.md | 11 ++-- Taskfile.yaml | 2 +- docs/development.md | 29 ++++++---- knip.json | 48 +---------------- scripts/knip-preprocessor.js | 86 ++++++++++++++++++++++++++++++ test/deadcode-report.test.js | 19 ++++--- test/knip-preprocessor.test.js | 97 ++++++++++++++++++++++++++++++++++ 7 files changed, 224 insertions(+), 68 deletions(-) create mode 100644 scripts/knip-preprocessor.js create mode 100644 test/knip-preprocessor.test.js diff --git a/.ai/contexts/build-release.md b/.ai/contexts/build-release.md index 69e01f798..4a8dba660 100644 --- a/.ai/contexts/build-release.md +++ b/.ai/contexts/build-release.md @@ -358,11 +358,14 @@ the job summary through `tee`. The step sets `shell: bash` for pipefail, so knip's non-zero exit fails the step through `tee`; neither the step nor the job sets `continue-on-error`, so a finding fails the workflow. Nothing `needs` it. Whether it is a required status check is a repository ruleset setting, not -part of the workflow. False positives are silenced in `knip.json` by -`ignoreIssues`, one file per key with `["exports"]` only. +part of the workflow. False positives are dropped one (file, export) pair at a time by +`scripts/knip-preprocessor.js`, the `preprocessor` of `knip.json`; knip +computes its exit code from the counters the preprocessor returns, and a +listed pair knip no longer reports fails the run. `test/deadcode-report.test.js` checks the pin, the job's shape, the absence -of `continue-on-error`, that every ignore names one existing file for unused -exports only, and that no gate task or job depends on it. What knip analyses, +of `continue-on-error` and of any file-wide or global ignore, that neither the +task nor the step overrides the preprocessor, and that no gate task or job +depends on it; `test/knip-preprocessor.test.js` checks the filtering. What knip analyses, its known false positives and how to add one are in [development.md](../../docs/development.md#dead-code-report). diff --git a/Taskfile.yaml b/Taskfile.yaml index c66f82b73..7989e6298 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -101,7 +101,7 @@ tasks: - node scripts/check-docs.js --validate deadcode: - desc: "Report unused files, exports and dependencies with knip (report only; see docs/development.md)" + desc: "Check for unused files, exports and dependencies with knip (CI fails on any finding; see docs/development.md)" cmds: - npx --no-install knip {{.CLI_ARGS}} diff --git a/docs/development.md b/docs/development.md index 0892f7270..b7c73fed2 100644 --- a/docs/development.md +++ b/docs/development.md @@ -167,15 +167,26 @@ source into a VM context, and one the module reads back through `module.exports.name`. Check every reported export for these patterns before removing it. -`ignoreIssues` in `knip.json` lists the files whose exports are reached only -that way, each with `["exports"]` and nothing else. knip 6 has no per-export -setting short of a JSDoc tag, and production code carries no such comment, so -the ignore covers every export of the file: a genuinely unused export added to -one of those files is not reported. To handle a new false positive, add the -one file to `ignoreIssues` with `["exports"]`, never a glob, a broader issue -type or a global switch such as `ignoreExportsUsedInFile`, and give in the pull -request the export and the line that reads it. `test/deadcode-report.test.js` -refuses a pattern, another issue type or a global switch. +The exports reached only that way are listed one by one in +`scripts/knip-preprocessor.js`, which `knip.json` names as its `preprocessor`. +knip hands it the report before printing it and computes its exit code from +the counters it returns. Each entry of `ALLOWED_UNUSED_EXPORTS` is one file, one +export and a reason: `namespace` (namespace access in app code), +`test-namespace` (namespace access or destructuring in a test), +`fixture-spread` (re-exported by spread from a test fixture), `source-loaded` +(a test loads the module's source) or `self-read` (the module reads +`module.exports.name` itself). The preprocessor drops exactly those pairs and +decrements the counters, so any other unused export, in the same file or not, +still fails knip. An entry knip no longer reports makes it fail with that pair +named: remove the entry with the export, or when its last reader goes. + +To handle a new false positive, add one entry with its file, export and +reason, and give in the pull request the line that reads the export. Never use +a file-wide `ignoreIssues`, a glob or a global switch such as +`ignoreExportsUsedInFile`; `test/deadcode-report.test.js` refuses them, and +neither `task deadcode` nor the CI step passes `--preprocessor`, which would +replace the configured one. Arguments after `--` reach knip unchanged, so +`task deadcode -- --preprocessor …` drops the allow-list for that run. ## Running from source next to an installed copy diff --git a/knip.json b/knip.json index d731bde4c..bb5387bd8 100644 --- a/knip.json +++ b/knip.json @@ -29,51 +29,5 @@ "app-builder-lib", "builder-util" ], - "ignoreIssues": { - "archived-projects.js": [ - "exports" - ], - "jsonl-scan.js": [ - "exports" - ], - "project-remap.js": [ - "exports" - ], - "session-transitions.js": [ - "exports" - ], - "worktree-delete.js": [ - "exports" - ], - "src/main/changes/git-changes-file.js": [ - "exports" - ], - "src/main/projects/project-delete-writer.js": [ - "exports" - ], - "src/main/remote/remote-ssh-binary.js": [ - "exports" - ], - "src/main/schedules/schedule-background.js": [ - "exports" - ], - "src/main/schedules/schedule-delete-file.js": [ - "exports" - ], - "src/main/schedules/schedule-ipc.js": [ - "exports" - ], - "src/main/schedules/schedule-run-results.js": [ - "exports" - ], - "src/main/session-index/read-counters.js": [ - "exports" - ], - "src/main/triggers/trigger-name.js": [ - "exports" - ], - "src/main/triggers/trigger-watcher.js": [ - "exports" - ] - } + "preprocessor": "./scripts/knip-preprocessor.js" } diff --git a/scripts/knip-preprocessor.js b/scripts/knip-preprocessor.js new file mode 100644 index 000000000..82b884022 --- /dev/null +++ b/scripts/knip-preprocessor.js @@ -0,0 +1,86 @@ +'use strict'; + +const REASONS = ['namespace', 'test-namespace', 'fixture-spread', 'source-loaded', 'self-read']; + +const ALLOWED_UNUSED_EXPORTS = [ + { file: 'archived-projects.js', symbol: 'filterArchivedProjects', reason: 'namespace' }, + { file: 'archived-projects.js', symbol: 'relatedEntries', reason: 'namespace' }, + { file: 'archived-projects.js', symbol: 'retireArchivedEntries', reason: 'namespace' }, + { file: 'archived-projects.js', symbol: 'undoArchiveProjectFolders', reason: 'namespace' }, + { file: 'jsonl-scan.js', symbol: 'MAX_LINE_BYTES', reason: 'self-read' }, + { file: 'project-remap.js', symbol: 'rewriteJsonlAtomic', reason: 'source-loaded' }, + { file: 'session-transitions.js', symbol: 'currentSessionId', reason: 'namespace' }, + { file: 'session-transitions.js', symbol: 'detectPendingBackgroundContinuations', reason: 'namespace' }, + { file: 'session-transitions.js', symbol: 'detectSessionTransitions', reason: 'namespace' }, + { file: 'session-transitions.js', symbol: 'drainMetadataWrites', reason: 'namespace' }, + { file: 'session-transitions.js', symbol: 'hasPendingLaunches', reason: 'namespace' }, + { file: 'session-transitions.js', symbol: 'holdContinuationExit', reason: 'namespace' }, + { file: 'session-transitions.js', symbol: 'refreshDescriptorSessions', reason: 'namespace' }, + { file: 'session-transitions.js', symbol: 'resolvePendingLaunches', reason: 'namespace' }, + { file: 'session-transitions.js', symbol: 'snapshotContinuations', reason: 'test-namespace' }, + { file: 'session-transitions.js', symbol: 'snapshotContinuationsBeforeSpawn', reason: 'namespace' }, + { file: 'session-transitions.js', symbol: 'sweepPendingLaunches', reason: 'namespace' }, + { file: 'src/main/changes/git-changes-file.js', symbol: 'resolveRepoDirs', reason: 'namespace' }, + { file: 'src/main/projects/project-delete-writer.js', symbol: 'buildDeletionUnits', reason: 'test-namespace' }, + { file: 'src/main/projects/project-delete-writer.js', symbol: 'buildFinalizationUnits', reason: 'test-namespace' }, + { file: 'src/main/remote/remote-ssh-binary.js', symbol: 'createBinaryResolver', reason: 'test-namespace' }, + { file: 'src/main/schedules/schedule-background.js', symbol: 'backgroundRefusal', reason: 'namespace' }, + { file: 'src/main/schedules/schedule-background.js', symbol: 'launchBackgroundSchedule', reason: 'namespace' }, + { file: 'src/main/schedules/schedule-delete-file.js', symbol: 'deleteScheduleFile', reason: 'source-loaded' }, + { file: 'src/main/schedules/schedule-ipc.js', symbol: 'ensureScheduleCreatorCommand', reason: 'namespace' }, + { file: 'src/main/schedules/schedule-ipc.js', symbol: 'init', reason: 'namespace' }, + { file: 'src/main/schedules/schedule-ipc.js', symbol: 'reportRunExit', reason: 'namespace' }, + { file: 'src/main/schedules/schedule-ipc.js', symbol: 'SHIPPED_CREATOR_TEMPLATE_SHA256', reason: 'test-namespace' }, + { file: 'src/main/schedules/schedule-run-results.js', symbol: 'writeScheduleRunResult', reason: 'test-namespace' }, + { file: 'src/main/session-index/read-counters.js', symbol: 'readBodyFile', reason: 'test-namespace' }, + { file: 'src/main/triggers/trigger-name.js', symbol: 'hasLoneSurrogate', reason: 'namespace' }, + { file: 'src/main/triggers/trigger-name.js', symbol: 'markerNaming', reason: 'namespace' }, + { file: 'src/main/triggers/trigger-name.js', symbol: 'recoveredNaming', reason: 'namespace' }, + { file: 'src/main/triggers/trigger-name.js', symbol: 'requestedNameFields', reason: 'namespace' }, + { file: 'src/main/triggers/trigger-watcher.js', symbol: 'deliverSingle', reason: 'test-namespace' }, + { file: 'src/main/triggers/trigger-watcher.js', symbol: 'isCompactCommand', reason: 'fixture-spread' }, + { file: 'src/main/triggers/trigger-watcher.js', symbol: 'SUBMITTED_RANK', reason: 'fixture-spread' }, + { file: 'src/main/triggers/trigger-watcher.js', symbol: 'submitWithVerify', reason: 'fixture-spread' }, + { file: 'src/main/triggers/trigger-watcher.js', symbol: 'waitForBusyFall', reason: 'fixture-spread' }, + { file: 'src/main/triggers/trigger-watcher.js', symbol: 'waitForCliIdleAfter', reason: 'fixture-spread' }, + { file: 'src/main/triggers/trigger-watcher.js', symbol: 'weakestSubmitted', reason: 'fixture-spread' }, + { file: 'worktree-delete.js', symbol: 'parseWorktreeList', reason: 'namespace' }, + { file: 'worktree-delete.js', symbol: 'removeWorktree', reason: 'namespace' }, + { file: 'worktree-delete.js', symbol: 'runningSessions', reason: 'namespace' }, + { file: 'worktree-delete.js', symbol: 'streamGit', reason: 'namespace' }, +]; + +const toPosix = file => file.split('\\').join('/'); + +function createPreprocessor(allowed) { + const allowedKeys = new Set(allowed.map(entry => `${entry.file}#${entry.symbol}`)); + return async function preprocess(data) { + if (!data.report.exports) return data; + const matched = new Set(); + const exports = {}; + for (const [file, symbols] of Object.entries(data.issues.exports)) { + const kept = {}; + for (const [symbol, issue] of Object.entries(symbols)) { + const key = `${toPosix(file)}#${symbol}`; + if (allowedKeys.has(key)) matched.add(key); + else kept[symbol] = issue; + } + if (Object.keys(kept).length > 0) exports[file] = kept; + } + const stale = [...allowedKeys].filter(key => !matched.has(key)); + if (stale.length > 0) { + throw new Error(`scripts/knip-preprocessor.js allows unused exports knip no longer reports; remove them: ${stale.join(', ')}`); + } + const dropped = matched.size; + return { + ...data, + issues: { ...data.issues, exports }, + counters: { ...data.counters, exports: data.counters.exports - dropped, total: data.counters.total - dropped }, + }; + }; +} + +module.exports = createPreprocessor(ALLOWED_UNUSED_EXPORTS); +module.exports.ALLOWED_UNUSED_EXPORTS = ALLOWED_UNUSED_EXPORTS; +module.exports.REASONS = REASONS; +module.exports.createPreprocessor = createPreprocessor; diff --git a/test/deadcode-report.test.js b/test/deadcode-report.test.js index f4d8e44d7..6a62e7871 100644 --- a/test/deadcode-report.test.js +++ b/test/deadcode-report.test.js @@ -63,7 +63,7 @@ test('the deadcode CI job runs on Node 22 Linux and fails on any finding', () => } }); -test('knip silences its false positives file by file, never by a global switch', () => { +test('knip silences its false positives export by export, never by a file or global switch', () => { const config = JSON.parse(read('knip.json')); assert.equal(config.ignoreExportsUsedInFile, undefined, 'no global export switch'); assert.equal(config.includeEntryExports, undefined); @@ -71,12 +71,17 @@ test('knip silences its false positives file by file, never by a global switch', assert.equal(config.exclude, undefined, 'no issue type excluded for the whole project'); assert.equal(config.include, undefined, 'no issue type selection for the whole project'); assert.equal(config.ignoreFiles, undefined); + assert.equal(config.ignoreIssues, undefined, 'a file-wide ignore would hide a new unused export in that file'); for (const pattern of config.ignore) assert.ok(pattern === 'public/**', `only the renderer is ignored whole: ${pattern}`); - const entries = Object.entries(config.ignoreIssues || {}); - assert.ok(entries.length > 0, 'the known false positives are declared'); - for (const [file, types] of entries) { - assert.doesNotMatch(file, /[*?{}[\]!]/, `${file}: one file, no pattern`); - assert.ok(fs.statSync(path.join(root, file)).isFile(), `${file} exists`); - assert.deepEqual(types, ['exports'], `${file}: unused exports only`); + assert.equal(config.preprocessor, './scripts/knip-preprocessor.js', 'the per-export allow-list'); + assert.equal(config.preprocessorOptions, undefined); +}); + +test('neither the task nor the CI step replaces the configured preprocessor', () => { + const { tasks } = yaml.load(read('Taskfile.yaml')); + const { jobs } = yaml.load(read('.github/workflows/test.yml')); + const commands = [...tasks.deadcode.cmds, ...jobs.deadcode.steps.map(step => step.run || '')]; + for (const cmd of commands.filter(c => knipCommand.test(c))) { + assert.doesNotMatch(cmd, /--preprocessor|--no-exit-code|--max-issues|--include|--exclude/, cmd); } }); diff --git a/test/knip-preprocessor.test.js b/test/knip-preprocessor.test.js new file mode 100644 index 000000000..0a54ee9f8 --- /dev/null +++ b/test/knip-preprocessor.test.js @@ -0,0 +1,97 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); + +const preprocess = require('../scripts/knip-preprocessor'); +const { ALLOWED_UNUSED_EXPORTS, REASONS, createPreprocessor } = preprocess; + +const exportIssue = (filePath, symbol) => ({ type: 'exports', filePath: path.resolve(filePath), symbol, fixes: [] }); + +function reportOf(pairs, extra = {}) { + const exports = {}; + for (const [file, symbol] of pairs) { + exports[file] = exports[file] || {}; + exports[file][symbol] = exportIssue(file, symbol); + } + const files = extra.files || {}; + return { + report: { exports: true, files: true }, + issues: { exports, files }, + counters: { exports: pairs.length, files: Object.keys(files).length, processed: 10, total: pairs.length + Object.keys(files).length }, + }; +} + +const allPairs = ALLOWED_UNUSED_EXPORTS.map(entry => [entry.file, entry.symbol]); + +test('every allowed pair names one file, one export and a known reason', () => { + assert.ok(ALLOWED_UNUSED_EXPORTS.length > 0); + const seen = new Set(); + for (const entry of ALLOWED_UNUSED_EXPORTS) { + assert.deepEqual(Object.keys(entry).sort(), ['file', 'reason', 'symbol'], JSON.stringify(entry)); + assert.doesNotMatch(entry.file, /[*?{}[\]!\\]/, `${entry.file}: one posix path, no pattern`); + assert.match(entry.symbol, /^[A-Za-z_$][\w$]*$/, entry.symbol); + assert.ok(REASONS.includes(entry.reason), `${entry.file}#${entry.symbol}: ${entry.reason}`); + const key = `${entry.file}#${entry.symbol}`; + assert.ok(!seen.has(key), `${key} listed twice`); + seen.add(key); + } +}); + +test('GIVEN the allowed pairs and an unlisted export in the same file WHEN preprocessed THEN only the unlisted export remains and the counters match', async () => { + const [file] = allPairs[0]; + const data = reportOf([...allPairs, [file, 'genuinelyUnused']]); + const out = await preprocess(data); + assert.deepEqual(Object.keys(out.issues.exports), [file]); + assert.deepEqual(Object.keys(out.issues.exports[file]), ['genuinelyUnused']); + assert.equal(out.counters.exports, 1); + assert.equal(out.counters.total, 1); + assert.equal(out.counters.processed, 10); +}); + +test('GIVEN only the allowed pairs WHEN preprocessed THEN no export issue and no count remain', async () => { + const out = await preprocess(reportOf(allPairs)); + assert.deepEqual(out.issues.exports, {}); + assert.equal(out.counters.exports, 0); + assert.equal(out.counters.total, 0); +}); + +test('GIVEN an allowed symbol in another file WHEN preprocessed THEN it is kept', async () => { + const [, symbol] = allPairs[0]; + const out = await preprocess(reportOf([...allPairs, ['encode-project-path.js', symbol]])); + assert.deepEqual(Object.keys(out.issues.exports), ['encode-project-path.js']); + assert.equal(out.counters.exports, 1); +}); + +test('GIVEN other issue types WHEN preprocessed THEN they are left untouched', async () => { + const files = { 'orphan.js': { 'orphan.js': { type: 'files', filePath: path.resolve('orphan.js'), symbol: 'orphan.js' } } }; + const out = await preprocess(reportOf(allPairs, { files })); + assert.deepEqual(Object.keys(out.issues.files), ['orphan.js']); + assert.equal(out.counters.files, 1); + assert.equal(out.counters.total, 1); +}); + +test('GIVEN an allowed pair knip no longer reports WHEN preprocessed THEN it fails and names the stale pair', async () => { + const [file, symbol] = allPairs[allPairs.length - 1]; + await assert.rejects(preprocess(reportOf(allPairs.slice(0, -1))), error => { + assert.match(error.message, new RegExp(`${file.replace(/[.]/g, '\\.')}#${symbol}`)); + return true; + }); +}); + +test('GIVEN a run that does not report exports WHEN preprocessed THEN nothing is checked or changed', async () => { + const data = reportOf([]); + data.report.exports = false; + const out = await preprocess(data); + assert.equal(out, data); + assert.equal(out.counters.exports, 0); +}); + +test('GIVEN keys knip wrote with backslashes WHEN preprocessed THEN they match the posix allow-list', async () => { + const run = createPreprocessor([{ file: 'src/a.js', symbol: 'x', reason: REASONS[0] }]); + const data = reportOf([['src\\a.js', 'x']]); + const out = await run(data); + assert.deepEqual(out.issues.exports, {}); + assert.equal(out.counters.exports, 0); +}); From a09b3394a3e1922b40d80fa796ab10540789866e Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Sun, 29 Nov 2026 05:43:48 +0100 Subject: [PATCH 3/3] chore(tooling): leave knip's file total alone when dropping allowed exports (#1356) --- scripts/knip-preprocessor.js | 2 +- test/knip-preprocessor.test.js | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/knip-preprocessor.js b/scripts/knip-preprocessor.js index 82b884022..df7ba1cff 100644 --- a/scripts/knip-preprocessor.js +++ b/scripts/knip-preprocessor.js @@ -75,7 +75,7 @@ function createPreprocessor(allowed) { return { ...data, issues: { ...data.issues, exports }, - counters: { ...data.counters, exports: data.counters.exports - dropped, total: data.counters.total - dropped }, + counters: { ...data.counters, exports: data.counters.exports - dropped }, }; }; } diff --git a/test/knip-preprocessor.test.js b/test/knip-preprocessor.test.js index 0a54ee9f8..ea33f9699 100644 --- a/test/knip-preprocessor.test.js +++ b/test/knip-preprocessor.test.js @@ -19,7 +19,7 @@ function reportOf(pairs, extra = {}) { return { report: { exports: true, files: true }, issues: { exports, files }, - counters: { exports: pairs.length, files: Object.keys(files).length, processed: 10, total: pairs.length + Object.keys(files).length }, + counters: { exports: pairs.length, files: Object.keys(files).length, processed: 10, total: 10 + Object.keys(files).length }, }; } @@ -46,7 +46,7 @@ test('GIVEN the allowed pairs and an unlisted export in the same file WHEN prepr assert.deepEqual(Object.keys(out.issues.exports), [file]); assert.deepEqual(Object.keys(out.issues.exports[file]), ['genuinelyUnused']); assert.equal(out.counters.exports, 1); - assert.equal(out.counters.total, 1); + assert.equal(out.counters.total, 10, 'total counts files, not findings'); assert.equal(out.counters.processed, 10); }); @@ -54,7 +54,7 @@ test('GIVEN only the allowed pairs WHEN preprocessed THEN no export issue and no const out = await preprocess(reportOf(allPairs)); assert.deepEqual(out.issues.exports, {}); assert.equal(out.counters.exports, 0); - assert.equal(out.counters.total, 0); + assert.equal(out.counters.total, 10, 'total counts files, not findings'); }); test('GIVEN an allowed symbol in another file WHEN preprocessed THEN it is kept', async () => { @@ -69,7 +69,7 @@ test('GIVEN other issue types WHEN preprocessed THEN they are left untouched', a const out = await preprocess(reportOf(allPairs, { files })); assert.deepEqual(Object.keys(out.issues.files), ['orphan.js']); assert.equal(out.counters.files, 1); - assert.equal(out.counters.total, 1); + assert.equal(out.counters.total, 11, 'total counts files, not findings'); }); test('GIVEN an allowed pair knip no longer reports WHEN preprocessed THEN it fails and names the stale pair', async () => {