pruneplan 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **Find dead code and unused packages. Review the cleanup before applying it.**
4
4
 
5
- `pruneplan` gives you one reviewable cleanup flow for unused dependencies, files, exports, and types. It uses [Knip](https://knip.dev/) to analyze the project, removes dependencies through the package manager already in use, and updates the lockfile as part of that removal.
5
+ `pruneplan` gives you a reviewable cleanup flow for unused dependencies, files, exports, and types. It uses [Knip](https://knip.dev/) to analyze a JavaScript or TypeScript project, and leaves changes in your working tree for review.
6
6
 
7
7
  ## Quick start
8
8
 
@@ -12,41 +12,42 @@ From the root of a JavaScript or TypeScript project:
12
12
  npx pruneplan
13
13
  ```
14
14
 
15
- This only prints a plan. After reviewing it, apply the cleanup interactively:
15
+ This only prints a plan. Apply selected candidates interactively:
16
16
 
17
17
  ```sh
18
18
  npx pruneplan --apply
19
19
  ```
20
20
 
21
- To scan a different project, pass its directory:
21
+ Choose candidate numbers separated by commas, or `all`. Configuration-like files are highlighted and require explicit selection. To scan another project, pass its directory:
22
22
 
23
23
  ```sh
24
24
  npx pruneplan ../my-app
25
25
  ```
26
26
 
27
- ## What happens when you apply
27
+ For CI or other non-interactive use, `--yes` applies all safely actionable findings without prompting. It excludes configuration-like files and aborts if the Knip findings changed since preview:
28
28
 
29
- 1. `pruneplan` asks Knip to scan the project and displays the cleanup candidates.
30
- 2. After you confirm, it removes unused dependencies with npm, pnpm, Yarn, or Bun, updating the package manager's lockfile.
31
- 3. It asks Knip to remove reported unused files, exports, and types.
32
- 4. It runs any `typecheck`, `lint`, `test`, and `build` scripts defined in the project's `package.json`.
33
- 5. It leaves the changes in your working tree for review with `git diff`.
29
+ ```sh
30
+ npx pruneplan --yes
31
+ ```
34
32
 
35
- For CI or other non-interactive use, `--yes` explicitly skips the prompt:
33
+ Use `--json` to print a machine-readable report, including warnings and Knip version/source:
36
34
 
37
35
  ```sh
38
- npx pruneplan --yes
36
+ npx pruneplan --json
39
37
  ```
40
38
 
41
- ## Safety
39
+ ## Review and safety
42
40
 
43
- - The default command only reports findings. It does not modify files.
44
- - Applying requires `--apply` plus an interactive confirmation, or the explicit `--yes` flag.
45
- - Package removals use your detected package manager so its lockfile is updated too.
46
- - npm and pnpm package removals skip install scripts.
47
- - Validation runs only scripts that already exist in your project. These are ordinary project commands and may have their own side effects.
48
- - Static analysis can miss runtime-loaded packages and exports used through reflection, plugins, or external consumers. Review the plan and final diff before committing.
49
- - If validation fails, the changes remain in your working tree so you can inspect and fix them; `pruneplan` does not discard project changes.
41
+ - The default command is preview-only and does not modify files.
42
+ - Interactive apply is item-selective; only selected files are removed and only selected dependencies are passed to your package manager.
43
+ - Knip's auto-fixer operates across findings rather than an individual selected export. To ensure pruneplan never changes unselected exports or types, those candidates are displayed for manual review but are not automatically fixed.
44
+ - Unlisted dependencies, duplicate exports, and other Knip issue categories are surfaced as warnings and are never interpreted as install suggestions or automatic cleanup.
45
+ - Configuration-like files are marked for extra review. Use Knip configuration (entries, workspaces, project patterns, or ignore settings) to correct analysis scope instead of assuming a flagged config file is dead.
46
+ - Immediately before applying, pruneplan scans again. If findings changed, interactive users review/select against the updated plan; `--yes` aborts rather than applying a stale plan.
47
+ - A dirty Git worktree is reported before changes. Existing changes are never automatically discarded.
48
+ - Available `typecheck`, `lint`, `test`, and `build` scripts are listed before apply and run afterwards. Passing checks does not guarantee every runtime path is covered.
49
+ - If validation fails, changes remain in the working tree. Review with `git diff` and recover manually as needed.
50
+ - Static analysis can miss runtime-loaded dependencies and exports used through reflection, plugins, dynamic routes, or external consumers. Findings are candidates, not proof they are safe to remove.
50
51
 
51
52
  ## Requirements
52
53
 
@@ -54,7 +55,7 @@ npx pruneplan --yes
54
55
  - A JavaScript or TypeScript project with a `package.json`
55
56
  - npm, pnpm, Yarn, or Bun, identified from a lockfile or the `packageManager` field
56
57
 
57
- Knip is installed as a dependency of `pruneplan`; you do not need to add it to the project being scanned.
58
+ Knip is bundled with pruneplan; a project-local Knip installation is preferred when present.
58
59
 
59
60
  ## License
60
61
 
@@ -0,0 +1,21 @@
1
+ import spawn from 'cross-spawn';
2
+
3
+ export function run(command, args, cwd, { capture = false } = {}) {
4
+ const result = spawn.sync(command, args, {
5
+ cwd, encoding: 'utf8',
6
+ stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',
7
+ shell: false,
8
+ windowsHide: true,
9
+ });
10
+ if (result.error) throw new Error(`${command} could not be started: ${result.error.message}`);
11
+ return result;
12
+ }
13
+
14
+ export function runWindowsShim(command, args, cwd, { capture = false } = {}) {
15
+ return run(command, args, cwd, { capture });
16
+ }
17
+
18
+ export function runPackageManager(manager, args, cwd, options) {
19
+ if (process.platform === 'win32') return runWindowsShim(`${manager}.cmd`, args, cwd, options);
20
+ return run(manager, args, cwd, options);
21
+ }
package/bin/pruneplan.js CHANGED
@@ -1,107 +1,65 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { spawnSync } from 'node:child_process';
4
3
  import { createInterface } from 'node:readline/promises';
5
4
  import { stdin, stdout } from 'node:process';
6
- import { access, readFile } from 'node:fs/promises';
5
+ import { access, lstat, readFile, rm } from 'node:fs/promises';
7
6
  import path from 'node:path';
8
7
  import { fileURLToPath } from 'node:url';
8
+ import { run, runPackageManager, runWindowsShim } from './process-runner.js';
9
9
 
10
- const KNIP_JSON_FLAG = '--reporter';
11
- const APPLY_FIX_TYPES = ['files', 'exports', 'types'];
12
10
  const CHECK_SCRIPTS = ['typecheck', 'lint', 'test', 'build'];
11
+ const AUTO_CATEGORIES = new Set(['files', 'exports', 'types', 'enumMembers', 'namespaceMembers', 'dependencies', 'devDependencies']);
12
+ const REVIEW_FIRST = /(^|[/\\])(?:eslint|prettier|vite|webpack|rollup|jest|vitest|knip|babel|postcss|tailwind|tsconfig|commitlint|lint-staged|stylelint|next|nuxt|svelte|astro|playwright|cypress)[^/\\]*\.(?:[cm]?[jt]sx?|json)$/i;
13
13
 
14
14
  function parseArgs(argv) {
15
- const options = { apply: false, yes: false, directory: process.cwd() };
15
+ const options = { apply: false, yes: false, json: false, directory: process.cwd() };
16
16
  let hasDirectory = false;
17
-
18
17
  for (const arg of argv) {
19
18
  if (arg === '--apply') options.apply = true;
20
- else if (arg === '--yes' || arg === '-y') {
21
- options.apply = true;
22
- options.yes = true;
23
- } else if (arg === '--help' || arg === '-h') options.help = true;
19
+ else if (arg === '--yes' || arg === '-y') { options.apply = true; options.yes = true; }
20
+ else if (arg === '--json') options.json = true;
21
+ else if (arg === '--help' || arg === '-h') options.help = true;
24
22
  else if (arg.startsWith('-')) throw new Error(`Unknown option: ${arg}`);
25
23
  else if (hasDirectory) throw new Error('Only one project path can be supplied.');
26
- else {
27
- options.directory = path.resolve(arg);
28
- hasDirectory = true;
29
- }
24
+ else { options.directory = path.resolve(arg); hasDirectory = true; }
30
25
  }
31
-
32
26
  return options;
33
27
  }
34
28
 
35
29
  function printHelp() {
36
30
  stdout.write(`pruneplan — review unused dependencies and dead code\n\n`);
37
- stdout.write(`Usage:\n pruneplan [project-directory] [--apply] [--yes]\n\n`);
38
- stdout.write(`Options:\n`);
39
- stdout.write(` --apply Apply the displayed cleanup plan after confirmation\n`);
40
- stdout.write(` --yes Apply without an interactive confirmation (for automation)\n`);
41
- stdout.write(` -h, --help Show this help\n\n`);
42
- stdout.write(`Knip is included with pruneplan; no project setup is required.\n`);
31
+ stdout.write(`Usage:\n pruneplan [project-directory] [--apply] [--yes] [--json]\n\n`);
32
+ stdout.write(`Options:\n --apply Review and select individual cleanup candidates\n --yes Apply all safely actionable candidates without prompts\n --json Print the Knip findings as a JSON report\n -h, --help Show this help\n\n`);
43
33
  }
44
34
 
45
35
  async function readProject(directory) {
46
- const packagePath = path.join(directory, 'package.json');
47
- const packageJson = JSON.parse(await readFile(packagePath, 'utf8'));
48
- return { packagePath, packageJson };
36
+ const packageJson = JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8'));
37
+ return { packageJson };
49
38
  }
50
39
 
51
40
  async function detectPackageManager(directory, packageJson) {
52
- const lockfiles = [
53
- ['pnpm-lock.yaml', 'pnpm'],
54
- ['yarn.lock', 'yarn'],
55
- ['bun.lock', 'bun'],
56
- ['bun.lockb', 'bun'],
57
- ['package-lock.json', 'npm'],
58
- ['npm-shrinkwrap.json', 'npm'],
59
- ];
60
-
61
- for (const [file, manager] of lockfiles) {
62
- try {
63
- await access(path.join(directory, file));
64
- return manager;
65
- } catch {}
41
+ for (const [file, manager] of [['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn'], ['bun.lock', 'bun'], ['bun.lockb', 'bun'], ['package-lock.json', 'npm'], ['npm-shrinkwrap.json', 'npm']]) {
42
+ try { await access(path.join(directory, file)); return manager; } catch {}
66
43
  }
67
-
68
44
  const declared = packageJson.packageManager?.split('@')[0];
69
45
  if (['npm', 'pnpm', 'yarn', 'bun'].includes(declared)) return declared;
70
46
  throw new Error('Could not detect the package manager. Add a lockfile or packageManager field to package.json.');
71
47
  }
72
48
 
73
- function run(command, args, cwd, { capture = false } = {}) {
74
- const result = spawnSync(command, args, {
75
- cwd,
76
- encoding: 'utf8',
77
- stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',
78
- shell: process.platform === 'win32',
79
- });
80
-
81
- if (result.error) throw new Error(`${command} could not be started: ${result.error.message}`);
82
- return result;
83
- }
84
-
85
49
  async function findKnip(directory) {
86
50
  let current = directory;
87
51
  while (true) {
88
- const localBin = path.join(current, 'node_modules', '.bin', process.platform === 'win32' ? 'knip.cmd' : 'knip');
89
- try {
90
- await access(localBin);
91
- return { command: localBin, prefixArgs: [] };
92
- } catch {}
93
-
52
+ const script = path.join(current, 'node_modules', 'knip', 'bin', 'knip.js');
53
+ try { await access(script); return { command: process.execPath, prefixArgs: [script], source: 'project-local' }; } catch {}
94
54
  const parent = path.dirname(current);
95
55
  if (parent === current) break;
96
56
  current = parent;
97
57
  }
98
- const bundledKnip = fileURLToPath(new URL('../node_modules/knip/bin/knip.js', import.meta.url));
99
- try {
100
- await access(bundledKnip);
101
- return { command: process.execPath, prefixArgs: [bundledKnip] };
102
- } catch {}
103
-
104
- return { command: 'knip', prefixArgs: [] };
58
+ const bundled = fileURLToPath(new URL('../node_modules/knip/bin/knip.js', import.meta.url));
59
+ try { await access(bundled); return { command: process.execPath, prefixArgs: [bundled], source: 'bundled' }; } catch {}
60
+ return process.platform === 'win32'
61
+ ? { command: 'knip.cmd', prefixArgs: [], source: 'PATH', windowsShim: true }
62
+ : { command: 'knip', prefixArgs: [], source: 'PATH' };
105
63
  }
106
64
 
107
65
  function extractIssues(output) {
@@ -110,62 +68,72 @@ function extractIssues(output) {
110
68
  if (start < 0 || end < start) throw new Error('Knip did not return JSON. Run `knip --reporter json` to inspect its output.');
111
69
  const parsed = JSON.parse(output.slice(start, end + 1));
112
70
  if (!Array.isArray(parsed.issues)) throw new Error('Knip JSON output did not include an issues array.');
113
- return parsed.issues;
71
+ return parsed;
114
72
  }
115
73
 
116
- function collectPlan(issues) {
74
+ function collectPlan(report) {
117
75
  const files = [];
118
76
  const exports = [];
119
77
  const dependencies = new Map();
120
-
121
- for (const issue of issues) {
122
- for (const item of issue.files ?? []) files.push({ file: issue.file, name: item.name });
78
+ const warnings = [];
79
+ for (const issue of report.issues) {
80
+ const file = issue.file ?? '(project)';
81
+ for (const item of issue.files ?? []) files.push({ kind: 'file', file, name: item.name, reason: 'Knip reported an unused file' });
123
82
  for (const category of ['exports', 'types', 'enumMembers', 'namespaceMembers']) {
124
- for (const item of issue[category] ?? []) exports.push({ file: issue.file, category, name: item.name });
83
+ for (const item of issue[category] ?? []) exports.push({ kind: 'export', file, category, name: item.name, reason: `Knip reported an unused ${category === 'exports' ? 'export' : category}` });
125
84
  }
126
85
  for (const category of ['dependencies', 'devDependencies']) {
127
86
  for (const item of issue[category] ?? []) {
128
- dependencies.set(item.name, { name: item.name, category, file: issue.file });
87
+ dependencies.set(`${category}:${item.name}`, { kind: 'dependency', name: item.name, category, file, reason: `Knip reported an unused ${category === 'dependencies' ? 'dependency' : 'dev dependency'}` });
129
88
  }
130
89
  }
90
+ for (const [category, items] of Object.entries(issue)) {
91
+ if (category === 'file' || AUTO_CATEGORIES.has(category) || !Array.isArray(items) || !items.length) continue;
92
+ for (const item of items) warnings.push({ category, file, name: item.name ?? item.dependency ?? JSON.stringify(item) });
93
+ }
131
94
  }
132
-
133
- return { files, exports, dependencies: [...dependencies.values()] };
95
+ const candidates = [...dependencies.values(), ...files, ...exports];
96
+ candidates.forEach((item, index) => { item.id = index + 1; item.reviewFirst = item.kind === 'file' && REVIEW_FIRST.test(item.file); });
97
+ return { files, exports, dependencies: [...dependencies.values()], warnings, candidates };
134
98
  }
135
99
 
136
- function displayPlan(plan, manager) {
137
- const total = plan.files.length + plan.exports.length + plan.dependencies.length;
138
- stdout.write(`\nPruneplan found ${total} cleanup candidate${total === 1 ? '' : 's'}.\n`);
139
- if (total === 0) {
140
- stdout.write('Your project looks tidy.\n');
141
- return;
142
- }
100
+ function planSummary(plan) {
101
+ return JSON.stringify(plan.candidates.map(({ kind, file, name, category }) => [kind, file, name, category]).sort());
102
+ }
143
103
 
144
- if (plan.dependencies.length) {
145
- stdout.write(`\nUnused packages (${plan.dependencies.length}) — will be removed with ${manager}:\n`);
146
- for (const item of plan.dependencies) stdout.write(` • ${item.name} (${item.category})\n`);
147
- }
148
- if (plan.files.length) {
149
- stdout.write(`\nUnused files (${plan.files.length}) — Knip can delete these:\n`);
150
- for (const item of plan.files) stdout.write(` • ${item.file}\n`);
104
+ function displayPlan(plan, manager, knip) {
105
+ stdout.write(`\nKnip ${knip.version ?? 'version unavailable'} (${knip.source}) found ${plan.candidates.length} cleanup candidate${plan.candidates.length === 1 ? '' : 's'}.\n`);
106
+ if (!plan.candidates.length) stdout.write('No supported cleanup candidates found.\n');
107
+ for (const item of plan.candidates) {
108
+ const target = item.kind === 'dependency' ? `${item.name} (${item.category}, ${manager})` : item.kind === 'file' ? item.file : `${item.name} in ${item.file} (${item.category})`;
109
+ const action = item.kind === 'export' ? 'manual review only' : 'selectable';
110
+ stdout.write(` ${item.id}. [${item.kind}; ${action}] ${target}${item.reviewFirst ? ' — configuration-like file: review carefully' : ''}\n`);
151
111
  }
152
- if (plan.exports.length) {
153
- stdout.write(`\nUnused exports and types (${plan.exports.length}) — Knip can remove these:\n`);
154
- for (const item of plan.exports) stdout.write(` • ${item.name} in ${item.file}\n`);
112
+ if (plan.warnings.length) {
113
+ stdout.write(`\nKnip warnings (${plan.warnings.length}) — review manually; pruneplan will not change these:\n`);
114
+ for (const warning of plan.warnings) stdout.write(` • ${warning.category}${warning.name ? `: ${warning.name}` : ''}${warning.file !== '(project)' ? ` in ${warning.file}` : ''}\n`);
155
115
  }
156
116
  }
157
117
 
158
- async function confirmApply() {
159
- if (!stdin.isTTY || !stdout.isTTY) {
160
- throw new Error('Applying in a non-interactive terminal requires the explicit `--yes` flag.');
161
- }
118
+ async function promptLine(question) {
119
+ if (!stdin.isTTY || !stdout.isTTY) throw new Error('Applying in a non-interactive terminal requires `--yes`.');
162
120
  const prompt = createInterface({ input: stdin, output: stdout });
163
- try {
164
- const answer = await prompt.question('\nApply this cleanup plan? [y/N] ');
165
- return answer.trim().toLowerCase() === 'y';
166
- } finally {
167
- prompt.close();
168
- }
121
+ try { return await prompt.question(question); } finally { prompt.close(); }
122
+ }
123
+
124
+ async function selectCandidates(plan, yes) {
125
+ const selectable = plan.candidates.filter((item) => item.kind !== 'export');
126
+ if (yes) return selectable.filter((item) => !item.reviewFirst);
127
+ if (!selectable.length) return [];
128
+ stdout.write('\nChoose item numbers to apply, separated by commas (or press Enter for none). Configuration-like files require explicit selection.\n');
129
+ const answer = (await promptLine('Apply: ')).trim();
130
+ if (!answer) return [];
131
+ if (answer.toLowerCase() === 'all') return selectable.filter((item) => !item.reviewFirst);
132
+ const numbers = answer.split(',').map((part) => part.trim());
133
+ if (numbers.some((part) => !/^\d+$/.test(part))) throw new Error('Enter comma-separated item numbers or `all`.');
134
+ const ids = new Set(numbers.map(Number));
135
+ if (ids.size !== numbers.length || [...ids].some((id) => !selectable.some((item) => item.id === id))) throw new Error('Selection includes an invalid or duplicate item number.');
136
+ return selectable.filter((item) => ids.has(item.id));
169
137
  }
170
138
 
171
139
  function managerRemoveArgs(manager, packages) {
@@ -178,73 +146,136 @@ function managerRemoveArgs(manager, packages) {
178
146
  }
179
147
  }
180
148
 
181
- async function runChecks(directory, packageJson) {
182
- const scripts = packageJson.scripts ?? {};
183
- const available = CHECK_SCRIPTS.filter((name) => typeof scripts[name] === 'string');
184
- if (!available.length) {
185
- stdout.write('\nNo typecheck, lint, test, or build scripts found; skipped validation.\n');
186
- return true;
149
+ async function getDirtyStatus(directory) {
150
+ const result = run('git', ['status', '--porcelain'], directory, { capture: true });
151
+ if (result.status !== 0) return null;
152
+ return result.stdout.trim().length > 0;
153
+ }
154
+
155
+ function safeProjectPath(directory, file) {
156
+ const absolute = path.resolve(directory, file);
157
+ const relative = path.relative(directory, absolute);
158
+ if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) throw new Error(`Refusing to remove a path outside the project: ${file}`);
159
+ return absolute;
160
+ }
161
+
162
+ async function assertNoSymlinkParent(directory, target) {
163
+ const relative = path.relative(directory, path.dirname(target));
164
+ let current = directory;
165
+ for (const part of relative.split(path.sep).filter(Boolean)) {
166
+ current = path.join(current, part);
167
+ try {
168
+ if ((await lstat(current)).isSymbolicLink()) {
169
+ throw new Error(`Refusing to remove a file through a symlinked directory: ${path.relative(directory, current)}`);
170
+ }
171
+ } catch (error) {
172
+ if (error.code === 'ENOENT') throw new Error(`Parent directory no longer exists; no changes applied: ${path.relative(directory, current)}`);
173
+ throw error;
174
+ }
187
175
  }
176
+ }
188
177
 
178
+ async function removeSelectedFiles(directory, selected) {
179
+ for (const item of selected.filter((candidate) => candidate.kind === 'file')) {
180
+ const target = safeProjectPath(directory, item.file);
181
+ await assertNoSymlinkParent(directory, target);
182
+ try { await lstat(target); } catch (error) {
183
+ if (error.code === 'ENOENT') throw new Error(`File no longer exists; no further changes applied: ${item.file}`);
184
+ throw error;
185
+ }
186
+ await rm(target, { force: false });
187
+ stdout.write(`Removed ${item.file}\n`);
188
+ }
189
+ }
190
+
191
+ async function runChecks(directory, packageJson) {
192
+ const available = CHECK_SCRIPTS.filter((name) => typeof packageJson.scripts?.[name] === 'string');
193
+ if (!available.length) { stdout.write('\nNo typecheck, lint, test, or build scripts found; skipped validation.\n'); return true; }
189
194
  const manager = await detectPackageManager(directory, packageJson);
190
- stdout.write(`\nRunning project checks with ${manager}: ${available.join(', ')}\n`);
195
+ stdout.write(`\nRunning checks with ${manager}: ${available.join(', ')}\n`);
191
196
  for (const name of available) {
192
- const args = manager === 'npm' ? ['run', name] : ['run', name];
193
- const result = run(manager, args, directory);
194
- if (result.status !== 0) {
195
- stdout.write(`\nValidation failed at \`${name}\`. Review the changes with git diff.\n`);
196
- return false;
197
- }
197
+ const result = runPackageManager(manager, ['run', name], directory);
198
+ if (result.status !== 0) { stdout.write(`\nValidation failed at \`${name}\`. Changes remain in the working tree; inspect with git diff.\n`); return false; }
198
199
  }
199
200
  return true;
200
201
  }
201
202
 
203
+ async function scanProject(directory, knip) {
204
+ const args = [...knip.prefixArgs, '--reporter', 'json', '--no-exit-code'];
205
+ const result = knip.windowsShim
206
+ ? runWindowsShim(knip.command, args, directory, { capture: true })
207
+ : run(knip.command, args, directory, { capture: true });
208
+ if (result.status !== 0) throw new Error(result.stderr.trim() || 'Knip scan failed. Check its configuration and try again.');
209
+ return extractIssues(result.stdout);
210
+ }
211
+
212
+ async function getKnipVersion(directory) {
213
+ for (const location of [directory, path.dirname(fileURLToPath(new URL('../package.json', import.meta.url)))]) {
214
+ try {
215
+ const pkg = JSON.parse(await readFile(path.join(location, 'node_modules/knip/package.json'), 'utf8'));
216
+ return pkg.version;
217
+ } catch {}
218
+ }
219
+ return null;
220
+ }
221
+
202
222
  async function main() {
203
223
  const options = parseArgs(process.argv.slice(2));
204
224
  if (options.help) return printHelp();
205
-
206
225
  const directory = path.resolve(options.directory);
207
226
  const { packageJson } = await readProject(directory);
208
227
  const manager = await detectPackageManager(directory, packageJson);
209
228
  const knip = await findKnip(directory);
229
+ knip.version = await getKnipVersion(directory);
210
230
 
211
231
  stdout.write(`Scanning ${path.relative(process.cwd(), directory) || '.'} with Knip…\n`);
212
- const scan = run(knip.command, [...knip.prefixArgs, KNIP_JSON_FLAG, 'json', '--no-exit-code'], directory, { capture: true });
213
- if (scan.status !== 0) {
214
- const details = scan.stderr.trim();
215
- throw new Error(details || 'Knip failed. Check its configuration and try again.');
232
+ const report = await scanProject(directory, knip);
233
+ const plan = collectPlan(report);
234
+ if (options.json) {
235
+ stdout.write(`${JSON.stringify({ knip: { version: knip.version, source: knip.source }, ...plan }, null, 2)}\n`);
236
+ return;
216
237
  }
217
-
218
- const plan = collectPlan(extractIssues(scan.stdout));
219
- displayPlan(plan, manager);
220
- const total = plan.files.length + plan.exports.length + plan.dependencies.length;
221
- if (!total || !options.apply) {
222
- if (total && !options.apply) stdout.write('\nPreview only. Run with --apply to make these changes.\n');
238
+ displayPlan(plan, manager, knip);
239
+ if (!options.apply || !plan.candidates.length) {
240
+ if (plan.candidates.length) stdout.write('\nPreview only. Run with --apply to select candidates.\n');
223
241
  return;
224
242
  }
225
243
 
226
- if (!options.yes && !(await confirmApply())) {
244
+ const dirty = await getDirtyStatus(directory);
245
+ if (dirty === true) stdout.write('\nWarning: the project worktree is dirty. Existing changes will not be discarded. Review the final diff carefully.\n');
246
+ else if (dirty === null) stdout.write('\nWarning: git status is unavailable; worktree cleanliness could not be checked.\n');
247
+ const checks = CHECK_SCRIPTS.filter((name) => typeof packageJson.scripts?.[name] === 'string');
248
+ stdout.write(`Available validation scripts: ${checks.length ? checks.join(', ') : 'none'}\n`);
249
+
250
+ let selected = await selectCandidates(plan, options.yes);
251
+ if (!selected.length) { stdout.write('No automatically applicable items selected. Exports and types are shown for manual review and will not be auto-fixed.\n'); return; }
252
+
253
+ // Re-scan immediately before changes. If Knip's result changed, interactive users must select again;
254
+ // --yes aborts rather than silently applying a plan different from the one it approved.
255
+ const currentPlan = collectPlan(await scanProject(directory, knip));
256
+ if (planSummary(currentPlan) !== planSummary(plan)) {
257
+ if (options.yes) throw new Error('Knip findings changed since the preview. Re-run pruneplan and review the updated plan.');
258
+ displayPlan(currentPlan, manager, knip);
259
+ selected = await selectCandidates(currentPlan, false);
260
+ if (!selected.length) { stdout.write('No changes made.\n'); return; }
261
+ const verifiedPlan = collectPlan(await scanProject(directory, knip));
262
+ if (planSummary(verifiedPlan) !== planSummary(currentPlan)) throw new Error('Knip findings changed again. Re-run pruneplan before applying; no changes made.');
263
+ } else if (!options.yes && (await promptLine('\nApply only the selected items? [y/N] ')).trim().toLowerCase() !== 'y') {
227
264
  stdout.write('No files changed.\n');
228
265
  return;
229
266
  }
230
267
 
231
- if (plan.dependencies.length) {
232
- const names = [...new Set(plan.dependencies.map(({ name }) => name))];
233
- stdout.write(`\nRemoving ${names.length} unused package${names.length === 1 ? '' : 's'}…\n`);
234
- const result = run(manager, managerRemoveArgs(manager, names), directory);
268
+ // Knip's fixer applies fixes globally, so export/type candidates are intentionally never passed to it.
269
+ // File removals and package removals are scoped to explicit selection only.
270
+ await removeSelectedFiles(directory, selected);
271
+ const packages = [...new Set(selected.filter((item) => item.kind === 'dependency').map((item) => item.name))];
272
+ if (packages.length) {
273
+ stdout.write(`\nRemoving selected packages with ${manager}: ${packages.join(', ')}\n`);
274
+ const result = runPackageManager(manager, managerRemoveArgs(manager, packages), directory);
235
275
  if (result.status !== 0) throw new Error('Package manager removal failed. Review the current working tree before continuing.');
236
276
  }
237
-
238
- if (plan.files.length || plan.exports.length) {
239
- stdout.write('\nRemoving dead files and exports with Knip…\n');
240
- const args = ['--fix', '--no-exit-code', '--fix-type', APPLY_FIX_TYPES.join(',')];
241
- if (plan.files.length) args.push('--allow-remove-files');
242
- const result = run(knip.command, [...knip.prefixArgs, ...args], directory);
243
- if (result.status !== 0) throw new Error('Knip could not apply all code fixes. Review the current working tree before continuing.');
244
- }
245
-
246
277
  const checksPassed = await runChecks(directory, packageJson);
247
- stdout.write('\nCleanup applied. Review the result with `git diff` before committing.\n');
278
+ stdout.write('\nSelected cleanup applied. Review the result with `git diff` before committing.\n');
248
279
  if (!checksPassed) process.exitCode = 1;
249
280
  }
250
281
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pruneplan",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Review and safely apply unused dependency and dead code cleanup plans.",
5
5
  "type": "module",
6
6
  "author": "Lakshmi Udbhav Regadamilli",
@@ -29,12 +29,16 @@
29
29
  "cli"
30
30
  ],
31
31
  "license": "MIT",
32
+ "scripts": {
33
+ "test": "node --test"
34
+ },
32
35
  "files": [
33
36
  "bin/",
34
37
  "README.md",
35
38
  "LICENSE"
36
39
  ],
37
40
  "dependencies": {
41
+ "cross-spawn": "^7.0.6",
38
42
  "knip": "^6.47.0"
39
43
  }
40
44
  }