knip 0.4.1 → 0.5.0

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
@@ -22,12 +22,14 @@ This is where Knip comes in:
22
22
  - [x] Supports JavaScript-only projects using ESM (without a `tsconfig.json`)
23
23
 
24
24
  Knip really shines in larger projects where you have non-production files (such as `/docs`, `/tools` and `/scripts`).
25
- The `includes` setting in `tsconfig.json` is often too broad, resulting in too many false negatives. Similar projects
26
- either detect only unimported files, or only unused exports. Most of them don't work by configuring entry files, an
27
- essential feature to produce good results. This also allows to unleash knip on a specific part of your project, and work
28
- these separately.
25
+ The `includes` setting in `tsconfig.json` is often too broad, resulting in too many false negatives. To produce good
26
+ results it's essential to configure entry files. A comparison with similar toos answers the question
27
+ [Why yet another unused file/dependency/export finder?](#why-yet-another-unused-filedependencyexport-finder)
29
28
 
30
- ✂️ Knip is another fresh take on keeping your projects clean & tidy!
29
+ Knip is a fresh take on keeping your projects clean & tidy!
30
+
31
+ [![An orange cow with scissors, Van Gogh style](./assets/cow-with-orange-scissors-van-gogh-style.webp)](https://labs.openai.com/s/xZQACaLepaKya0PRUPtIN5dC)
32
+ <sup>_“An orange cow with scissors, Van Gogh style” - generated with OpenAI_</sup>
31
33
 
32
34
  ## Installation
33
35
 
@@ -91,6 +93,8 @@ Options:
91
93
  --max-issues Maximum number of issues before non-zero exit code (default: 0)
92
94
  --reporter Select reporter: symbols, compact (default: symbols)
93
95
  --jsdoc Enable JSDoc parsing, with options: public
96
+ --debug Show debug output
97
+ --debug-level Set verbosity of debug output (default: 1, max: 2)
94
98
 
95
99
  Issue groups: files, dependencies, unlisted, exports, nsExports, types, nsTypes, duplicates
96
100
 
package/dist/cli.js CHANGED
@@ -9,7 +9,8 @@ const node_util_1 = require("node:util");
9
9
  const _1 = require(".");
10
10
  const help_1 = require("./help");
11
11
  const reporters_1 = __importDefault(require("./reporters"));
12
- const { values: { help, dir, config: configFilePath = 'knip.json', tsConfig: tsConfigFilePath, include = [], exclude = [], ignore = [], 'no-gitignore': isNoGitIgnore = false, dev: isDev = false, 'no-progress': noProgress = false, reporter = 'symbols', 'max-issues': maxIssues = '0', jsdoc: jsDoc = [], }, } = (0, node_util_1.parseArgs)({
12
+ const errors_1 = require("./util/errors");
13
+ const { values: { help, dir, config: configFilePath = 'knip.json', tsConfig: tsConfigFilePath, include = [], exclude = [], ignore = [], 'no-gitignore': isNoGitIgnore = false, dev: isDev = false, 'no-progress': noProgress = false, reporter = 'symbols', 'max-issues': maxIssues = '0', jsdoc: jsDoc = [], debug: isDebug = false, 'debug-level': debugLevel = '1', }, } = (0, node_util_1.parseArgs)({
13
14
  options: {
14
15
  help: { type: 'boolean' },
15
16
  config: { type: 'string', short: 'c' },
@@ -24,6 +25,8 @@ const { values: { help, dir, config: configFilePath = 'knip.json', tsConfig: tsC
24
25
  'max-issues': { type: 'string' },
25
26
  reporter: { type: 'string' },
26
27
  jsdoc: { type: 'string', multiple: true },
28
+ debug: { type: 'boolean' },
29
+ 'debug-level': { type: 'string' },
27
30
  },
28
31
  });
29
32
  if (help) {
@@ -48,6 +51,10 @@ const run = async () => {
48
51
  isDev,
49
52
  isShowProgress,
50
53
  jsDoc,
54
+ debug: {
55
+ isEnabled: isDebug,
56
+ level: isDebug ? Number(debugLevel) : 0,
57
+ },
51
58
  });
52
59
  printReport({ report, issues, workingDir, isDev });
53
60
  const reportGroup = report.files ? 'files' : Object.keys(report).find(key => report[key]);
@@ -59,7 +66,7 @@ const run = async () => {
59
66
  }
60
67
  }
61
68
  catch (error) {
62
- if (error instanceof Error) {
69
+ if (error instanceof errors_1.ConfigurationError) {
63
70
  console.error(error.message + '\n');
64
71
  (0, help_1.printHelp)();
65
72
  process.exit(1);
package/dist/help.js CHANGED
@@ -17,6 +17,8 @@ Options:
17
17
  --max-issues Maximum number of issues before non-zero exit code (default: 0)
18
18
  --reporter Select reporter: symbols, compact (default: symbols)
19
19
  --jsdoc Enable JSDoc parsing, with options: public
20
+ --debug Show debug output
21
+ --debug-level Set verbosity of debug output (default: 1, max: 2)
20
22
 
21
23
  Issue groups: files, dependencies, unlisted, exports, nsExports, types, nsTypes, duplicates
22
24
 
package/dist/index.js CHANGED
@@ -11,26 +11,30 @@ const fs_1 = require("./util/fs");
11
11
  const path_1 = require("./util/path");
12
12
  const project_1 = require("./util/project");
13
13
  const runner_1 = require("./runner");
14
+ const errors_1 = require("./util/errors");
15
+ const debug_1 = require("./util/debug");
14
16
  const main = async (options) => {
15
- const { cwd, workingDir, configFilePath = 'knip.json', tsConfigFilePath, include, exclude, ignore, gitignore, isDev, isShowProgress, jsDoc, } = options;
17
+ const { cwd, workingDir, configFilePath = 'knip.json', tsConfigFilePath, include, exclude, ignore, gitignore, isDev, isShowProgress, jsDoc, debug, } = options;
18
+ (0, debug_1.debugLogObject)(options, 1, 'Unresolved onfiguration', options);
16
19
  const localConfigurationPath = configFilePath && (await (0, fs_1.findFile)(workingDir, configFilePath));
17
20
  const manifestPath = await (0, fs_1.findFile)(workingDir, 'package.json');
18
21
  const localConfiguration = localConfigurationPath && require(localConfigurationPath);
19
22
  const manifest = manifestPath && require(manifestPath);
20
23
  if (!localConfigurationPath && !manifest.knip) {
21
24
  const location = workingDir === cwd ? 'current directory' : `${node_path_1.default.relative(cwd, workingDir)} or up.`;
22
- throw new Error(`Unable to find ${configFilePath} or package.json#knip in ${location}`);
25
+ throw new errors_1.ConfigurationError(`Unable to find ${configFilePath} or package.json#knip in ${location}`);
23
26
  }
24
27
  const dir = node_path_1.default.relative(cwd, workingDir);
25
28
  const resolvedConfig = (0, config_1.resolveConfig)(manifest.knip ?? localConfiguration, { workingDir: dir, isDev });
29
+ (0, debug_1.debugLogObject)(options, 1, 'Resolved onfiguration', resolvedConfig);
26
30
  if (!resolvedConfig) {
27
- throw new Error('Unable to find `entryFiles` and/or `projectFiles` in configuration.');
31
+ throw new errors_1.ConfigurationError('Unable to find `entryFiles` and/or `projectFiles` in configuration.');
28
32
  }
29
33
  const report = (0, config_1.resolveIncludedIssueGroups)(include, exclude, resolvedConfig);
30
34
  let tsConfigPaths = [];
31
35
  const tsConfigPath = await (0, fs_1.findFile)(workingDir, tsConfigFilePath ?? 'tsconfig.json');
32
36
  if (tsConfigFilePath && !tsConfigPath) {
33
- throw new Error(`Unable to find ${tsConfigFilePath}`);
37
+ throw new errors_1.ConfigurationError(`Unable to find ${tsConfigFilePath}`);
34
38
  }
35
39
  if (tsConfigPath) {
36
40
  const tsConfig = typescript_1.default.readConfigFile(tsConfigPath, typescript_1.default.sys.readFile);
@@ -38,10 +42,10 @@ const main = async (options) => {
38
42
  ? Object.keys(tsConfig.config.compilerOptions.paths).map(p => p.replace(/\*/g, '**'))
39
43
  : [];
40
44
  if (tsConfig.error) {
41
- throw new Error(`An error occured when reading ${node_path_1.default.relative(cwd, tsConfigPath)}`);
45
+ throw new errors_1.ConfigurationError(`An error occured when reading ${node_path_1.default.relative(cwd, tsConfigPath)}`);
42
46
  }
43
47
  }
44
- const projectOptions = tsConfigFilePath ? { tsConfigFilePath } : { compilerOptions: { allowJs: true } };
48
+ const projectOptions = tsConfigPath ? { tsConfigFilePath: tsConfigPath } : { compilerOptions: { allowJs: true } };
45
49
  const entryPaths = await (0, path_1.resolvePaths)({
46
50
  cwd,
47
51
  workingDir,
@@ -49,10 +53,13 @@ const main = async (options) => {
49
53
  ignore,
50
54
  gitignore,
51
55
  });
56
+ (0, debug_1.debugLogFiles)(options, 1, 'Globbed entry paths', entryPaths);
52
57
  const production = (0, project_1.createProject)({ projectOptions, paths: entryPaths });
53
58
  const entryFiles = production.getSourceFiles();
59
+ (0, debug_1.debugLogSourceFiles)(options, 1, 'Included entry source files', entryFiles);
54
60
  production.resolveSourceFileDependencies();
55
61
  const productionFiles = production.getSourceFiles();
62
+ (0, debug_1.debugLogSourceFiles)(options, 1, 'Included production source files', productionFiles);
56
63
  const projectPaths = await (0, path_1.resolvePaths)({
57
64
  cwd,
58
65
  workingDir,
@@ -60,8 +67,10 @@ const main = async (options) => {
60
67
  ignore,
61
68
  gitignore,
62
69
  });
70
+ (0, debug_1.debugLogFiles)(options, 1, 'Globbed project paths', projectPaths);
63
71
  const project = (0, project_1.createProject)({ projectOptions, paths: projectPaths });
64
72
  const projectFiles = project.getSourceFiles();
73
+ (0, debug_1.debugLogSourceFiles)(options, 1, 'Included project source files', projectFiles);
65
74
  const config = {
66
75
  workingDir,
67
76
  report,
@@ -76,8 +85,10 @@ const main = async (options) => {
76
85
  jsDocOptions: {
77
86
  isReadPublicTag: jsDoc.includes('public'),
78
87
  },
88
+ debug,
79
89
  };
80
90
  const { issues, counters } = await (0, runner_1.findIssues)(config);
91
+ (0, debug_1.debugLogObject)(options, 2, 'Issues', issues);
81
92
  return { report, issues, counters };
82
93
  };
83
94
  exports.main = main;
package/dist/runner.js CHANGED
@@ -11,6 +11,7 @@ const project_1 = require("./util/project");
11
11
  const type_1 = require("./util/type");
12
12
  const dependencies_1 = require("./util/dependencies");
13
13
  const log_1 = require("./log");
14
+ const debug_1 = require("./util/debug");
14
15
  const lineRewriter = new log_1.LineRewriter();
15
16
  async function findIssues(configuration) {
16
17
  const { workingDir, isShowProgress, report, isDev, jsDocOptions } = configuration;
@@ -18,6 +19,10 @@ async function findIssues(configuration) {
18
19
  const { getUnresolvedDependencies, getUnusedDependencies, getUnusedDevDependencies } = (0, dependencies_1.getDependencyAnalyzer)(configuration);
19
20
  const [usedProductionFiles, unreferencedProductionFiles] = (0, project_1.partitionSourceFiles)(projectFiles, productionFiles);
20
21
  const [usedEntryFiles, usedNonEntryFiles] = (0, project_1.partitionSourceFiles)(usedProductionFiles, entryFiles);
22
+ (0, debug_1.debugLogSourceFiles)(configuration, 1, 'usedProductionFiles', usedProductionFiles);
23
+ (0, debug_1.debugLogSourceFiles)(configuration, 1, 'unreferencedProductionFiles', unreferencedProductionFiles);
24
+ (0, debug_1.debugLogSourceFiles)(configuration, 1, 'usedEntryFiles', usedEntryFiles);
25
+ (0, debug_1.debugLogSourceFiles)(configuration, 1, 'usedNonEntryFiles', usedNonEntryFiles);
21
26
  const issues = {
22
27
  files: new Set(unreferencedProductionFiles.map(file => file.getFilePath())),
23
28
  dependencies: new Set(),
@@ -44,8 +49,8 @@ async function findIssues(configuration) {
44
49
  const updateProcessingOutput = (item) => {
45
50
  if (!isShowProgress)
46
51
  return;
47
- const counter = unreferencedProductionFiles.length + counters.processed;
48
- const total = unreferencedProductionFiles.length + usedNonEntryFiles.length;
52
+ const counter = counters.processed;
53
+ const total = projectFiles.length;
49
54
  const percentage = Math.floor((counter / total) * 100);
50
55
  const messages = [(0, log_1.getLine)(`${percentage}%`, `of files processed (${counter} of ${total})`)];
51
56
  report.files && messages.push((0, log_1.getLine)(unreferencedProductionFiles.length, 'unused files'));
@@ -78,6 +83,7 @@ async function findIssues(configuration) {
78
83
  };
79
84
  if (report.dependencies || report.unlisted) {
80
85
  usedEntryFiles.forEach(sourceFile => {
86
+ counters.processed++;
81
87
  const unresolvedDependencies = getUnresolvedDependencies(sourceFile);
82
88
  unresolvedDependencies.forEach(issue => addSymbolIssue('unresolved', issue));
83
89
  });
@@ -90,6 +96,7 @@ async function findIssues(configuration) {
90
96
  report.nsTypes ||
91
97
  report.duplicates) {
92
98
  usedNonEntryFiles.forEach(sourceFile => {
99
+ counters.processed++;
93
100
  const filePath = sourceFile.getFilePath();
94
101
  if (report.dependencies || report.unlisted) {
95
102
  const unresolvedDependencies = getUnresolvedDependencies(sourceFile);
@@ -175,7 +182,6 @@ async function findIssues(configuration) {
175
182
  });
176
183
  });
177
184
  }
178
- counters.processed++;
179
185
  });
180
186
  }
181
187
  if (report.dependencies) {
package/dist/types.d.ts CHANGED
@@ -47,6 +47,10 @@ export declare type UnresolvedConfiguration = {
47
47
  isDev: boolean;
48
48
  isShowProgress: boolean;
49
49
  jsDoc: string[];
50
+ debug: {
51
+ isEnabled: boolean;
52
+ level: number;
53
+ };
50
54
  };
51
55
  export declare type Report = {
52
56
  [key in IssueGroup]: boolean;
@@ -65,5 +69,9 @@ export declare type Configuration = {
65
69
  jsDocOptions: {
66
70
  isReadPublicTag: boolean;
67
71
  };
72
+ debug: {
73
+ isEnabled: boolean;
74
+ level: number;
75
+ };
68
76
  };
69
77
  export {};
@@ -0,0 +1,12 @@
1
+ import type { SourceFile } from 'ts-morph';
2
+ declare type Config = {
3
+ debug: {
4
+ isEnabled: boolean;
5
+ level: number;
6
+ };
7
+ };
8
+ export declare const debugLogObject: (config: Config, minimumLevel: number, name: string, obj: unknown) => void;
9
+ export declare const debugLogFiles: (config: Config, minimumLevel: number, name: string, filePaths: string[]) => void;
10
+ export declare const debugLogSourceFiles: (config: Config, minimumLevel: number, name: string, sourceFiles: SourceFile[]) => void;
11
+ export declare const debugLogDiff: (config: Config, minimumLevel: number, name: string, arrA: string[], arrB: string[]) => void;
12
+ export {};
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.debugLogDiff = exports.debugLogSourceFiles = exports.debugLogFiles = exports.debugLogObject = void 0;
7
+ const node_util_1 = __importDefault(require("node:util"));
8
+ const logArray = (collection) => console.log(node_util_1.default.inspect(collection, { maxArrayLength: null }));
9
+ const debugLogObject = (config, minimumLevel, name, obj) => {
10
+ if (minimumLevel > config.debug.level)
11
+ return;
12
+ console.log(`[exportman] ${name}:`);
13
+ console.log(node_util_1.default.inspect(obj, { depth: null, colors: true }));
14
+ };
15
+ exports.debugLogObject = debugLogObject;
16
+ const debugLogFiles = (config, minimumLevel, name, filePaths) => {
17
+ if (minimumLevel > config.debug.level)
18
+ return;
19
+ const { debug } = config;
20
+ if (debug.level > 1) {
21
+ console.debug(`[exportman] ${name} (${filePaths.length}):`);
22
+ logArray(filePaths);
23
+ }
24
+ else {
25
+ console.debug(`[exportman] ${name} (${filePaths.length})`);
26
+ }
27
+ };
28
+ exports.debugLogFiles = debugLogFiles;
29
+ const debugLogSourceFiles = (config, minimumLevel, name, sourceFiles) => {
30
+ if (minimumLevel > config.debug.level)
31
+ return;
32
+ const { debug } = config;
33
+ if (debug.level > 1) {
34
+ console.debug(`[exportman] ${name} (${sourceFiles.length}):`);
35
+ logArray(sourceFiles.map(sourceFile => sourceFile.getFilePath()));
36
+ }
37
+ else {
38
+ console.debug(`[exportman] ${name} (${sourceFiles.length})`);
39
+ }
40
+ };
41
+ exports.debugLogSourceFiles = debugLogSourceFiles;
42
+ const debugLogDiff = (config, minimumLevel, name, arrA, arrB) => {
43
+ if (minimumLevel > config.debug.level)
44
+ return;
45
+ const onlyInA = arrA.filter(itemA => !arrB.includes(itemA)).sort();
46
+ const onlyInB = arrB.filter(itemB => !arrA.includes(itemB)).sort();
47
+ console.log(`[exportman] ${name}`);
48
+ console.log(`[exportman] Only in left:`);
49
+ logArray(onlyInA);
50
+ console.log();
51
+ console.log(`[exportman] Only in right:`);
52
+ logArray(onlyInB);
53
+ };
54
+ exports.debugLogDiff = debugLogDiff;
@@ -0,0 +1,2 @@
1
+ export declare class ConfigurationError extends Error {
2
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConfigurationError = void 0;
4
+ class ConfigurationError extends Error {
5
+ }
6
+ exports.ConfigurationError = ConfigurationError;
package/package.json CHANGED
@@ -1,12 +1,14 @@
1
1
  {
2
2
  "name": "knip",
3
- "version": "0.4.1",
4
- "description": "Find unused files and exports in your TypeScript project",
3
+ "version": "0.5.0",
4
+ "description": "Find unused files, dependencies and exports in your TypeScript and JavaScript project",
5
5
  "keywords": [
6
6
  "find",
7
7
  "detect",
8
8
  "unused",
9
+ "unreferenced",
9
10
  "files",
11
+ "dependencies",
10
12
  "exports",
11
13
  "types",
12
14
  "duplicates",