-
-
Notifications
You must be signed in to change notification settings - Fork 460
Expand file tree
/
Copy pathcli.ts
More file actions
163 lines (140 loc) · 5.53 KB
/
Copy pathcli.ts
File metadata and controls
163 lines (140 loc) · 5.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// biome-ignore-all lint/suspicious/noConsole: ignore
import { fix } from './IssueFixer.js';
import { run } from './run.js';
import type { IssueType, ReporterOptions } from './types/issues.js';
import parseArgs, { helpText } from './util/cli-arguments.js';
import { createOptions } from './util/create-options.js';
import {
getKnownErrors,
hasErrorCause,
isConfigurationError,
isKnownError,
isLoaderError,
isModuleNotFoundError,
} from './util/errors.js';
import { logError, logWarning } from './util/log.js';
import { perfObserver } from './util/Performance.js';
import { runPreprocessors, runReporters } from './util/reporter.js';
import { prettyMilliseconds } from './util/string.js';
import { _handleSuppressions } from './util/suppressions.js';
import { version } from './version.js';
let args: ReturnType<typeof parseArgs> = {};
try {
args = parseArgs();
} catch (error: unknown) {
if (error instanceof Error) {
console.error(error.message);
console.log(`\n${helpText}`);
process.exit(1);
}
throw error;
}
const main = async () => {
try {
if (args.help) {
console.log(helpText);
process.exit(0);
}
if (args.version) {
console.log(version);
process.exit(0);
}
const options = await createOptions({ args });
const { results } = await run(options);
const {
issues,
counters,
tagHints,
configurationHints,
includedWorkspaceDirs,
enabledPlugins,
selectedWorkspaces,
} = results;
// These modes have their own reporting mechanism
if (options.isWatch || options.isTrace) return;
let suppressedCount = 0;
let expiredCount = 0;
if (!options.isProduction) {
const suppressionResult = await _handleSuppressions(issues, counters, options);
if (suppressionResult.action === 'generated') {
console.log(suppressionResult.message);
process.exit(0);
}
if (suppressionResult.action === 'applied') {
suppressedCount = suppressionResult.suppressedCount;
expiredCount = suppressionResult.expiredCount;
if (suppressionResult.isChanged && options.checkSuppressions) {
console.log('Suppressions file has been updated. Please commit the changes.');
process.exit(1);
}
}
}
const initialData: ReporterOptions = {
report: options.includedIssueTypes,
issues,
counters,
tagHints,
configurationHints,
enabledPlugins,
includedWorkspaceDirs,
cwd: options.cwd,
configFilePath: options.configFilePath,
isDisableConfigHints: options.isDisableConfigHints,
isProduction: options.isProduction,
isShowProgress: options.isShowProgress,
isTreatConfigHintsAsErrors: options.isTreatConfigHintsAsErrors,
maxShowIssues: args['max-show-issues'] ? Number(args['max-show-issues']) : undefined,
options: args['reporter-options'] ?? '',
preprocessorOptions: args['preprocessor-options'] ?? '',
selectedWorkspaces,
suppressedCount,
expiredCount,
};
const finalData = await runPreprocessors(args.preprocessor ?? [], initialData);
if (options.isFix) await fix(finalData.issues, options);
await runReporters(args.reporter ?? ['symbols'], finalData);
const totalErrorCount = (Object.keys(finalData.report) as IssueType[])
.filter(reportGroup => finalData.report[reportGroup] && options.rules[reportGroup] === 'error')
.reduce((errorCount: number, reportGroup) => errorCount + finalData.counters[reportGroup], 0);
if (perfObserver.isEnabled) await perfObserver.finalize();
if (perfObserver.isTimerifyFunctions) console.log(`\n${perfObserver.getTimerifiedFunctionsTable()}`);
if (perfObserver.isMemoryUsageEnabled && !args['memory-realtime'])
console.log(`\n${perfObserver.getMemoryUsageTable()}`);
if (perfObserver.isEnabled) {
const duration = perfObserver.getCurrentDurationInMs();
console.log('\nTotal running time:', prettyMilliseconds(duration));
perfObserver.reset();
}
if (args['experimental-tags'] && args['experimental-tags'].length > 0) {
logWarning('DEPRECATION WARNING', '--experimental-tags is deprecated, please start using --tags instead');
}
if (options.isIsolateWorkspaces && options.includedIssueTypes.classMembers) {
logWarning('WARNING', 'Class members are not tracked when using the --isolate-workspaces flag');
}
if (
(!args['no-exit-code'] && totalErrorCount > Number(args['max-issues'] ?? 0)) ||
(!options.isDisableConfigHints && options.isTreatConfigHintsAsErrors && configurationHints.length > 0)
) {
process.exit(1);
}
} catch (error: unknown) {
process.exitCode = 2;
if (!args.debug && error instanceof Error && isKnownError(error)) {
const knownErrors = getKnownErrors(error);
for (const knownError of knownErrors) logError('ERROR', knownError.message);
if (hasErrorCause(knownErrors[0])) {
console.error('Reason:', knownErrors[0].cause.message);
if (isModuleNotFoundError(knownErrors[0].cause))
console.log('Module load error? Visit https://knip.dev/reference/known-issues');
if (isLoaderError(knownErrors[0]))
console.log('Configuration file load error? Visit https://knip.dev/reference/known-issues');
}
if (isConfigurationError(knownErrors[0])) console.log('\nRun `knip --help` or visit https://knip.dev for help');
process.exit(2);
}
// We shouldn't arrive here, but not swallow either, so re-throw
throw error;
}
process.exit(0);
};
await main();