-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.ts
More file actions
412 lines (365 loc) · 11.6 KB
/
Copy pathcli.ts
File metadata and controls
412 lines (365 loc) · 11.6 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import path from 'node:path';
import { performance } from 'node:perf_hooks';
import { color, logger } from 'rslog';
import { parseArgs } from '../cli/args.ts';
import { printCommandHelp } from '../cli/help.ts';
import { loadRstackConfig } from '../config.ts';
import { ensureProjectCacheDir } from '../projectCache.ts';
import { fmtCacheFileName } from './cacheStore.ts';
import { resolveFmtConfig } from './config.ts';
import { discoverFmtFiles } from './discovery.ts';
import { createRelativePathResolver, toPosixPath } from './pathHelpers.ts';
import { runFmtFiles } from './runner.ts';
import type { FmtMode, FmtRunResult, ResolvedFmtConfig } from './types.ts';
interface ParsedFmtCLIArgs {
cache: boolean;
cacheLocation?: string;
mode: FmtMode;
patterns: string[];
ignorePaths: string[];
ignoreUnknown: boolean;
noErrorOnUnmatchedPattern: boolean;
withNodeModules: boolean;
maxWorkers?: number;
help: boolean;
/** Path the stdin content is formatted as; it need not exist on disk. */
stdinFilepath?: string;
/** Serve formatting over the Language Server Protocol instead of exiting. */
lsp: boolean;
}
const parseMaxWorkers = (value: string | undefined): number | undefined => {
if (value === undefined) {
return undefined;
}
const maxWorkers = Number(value);
if (
!/^\d+$/.test(value) ||
!Number.isSafeInteger(maxWorkers) ||
maxWorkers < 1
) {
throw new Error(
'The --parallel-workers option must be a positive integer.',
);
}
return maxWorkers;
};
/** Rejects the mode flags and file arguments that a server-like option replaces. */
const assertExclusiveMode = (
option: string,
hasMode: boolean,
positionals: string[],
): void => {
if (hasMode) {
throw new Error(
`The ${option} option cannot be used with --write, --check, or --list-different.`,
);
}
if (positionals.length > 0) {
throw new Error(`The ${option} option cannot be used with file arguments.`);
}
};
const parseFmtArgs = (args: string[]): ParsedFmtCLIArgs => {
const { values, positionals } = parseArgs({
args,
options: {
write: { type: 'boolean', short: 'w' },
check: { type: 'boolean' },
'list-different': { type: 'boolean', short: 'l' },
'ignore-path': { type: 'string', multiple: true },
'ignore-unknown': { type: 'boolean', short: 'u' },
'no-cache': { type: 'boolean' },
'cache-location': { type: 'string' },
'no-error-on-unmatched-pattern': { type: 'boolean' },
'with-node-modules': { type: 'boolean' },
'parallel-workers': { type: 'string' },
'stdin-filepath': { type: 'string' },
lsp: { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
},
allowPositionals: true,
strict: true,
});
const write = values.write;
const check = values.check;
const listDifferent = values.listDifferent;
const modes = [write, check, listDifferent].filter(Boolean);
if (modes.length > 1) {
throw new Error(
'The --write, --check, and --list-different options cannot be used together.',
);
}
const mode = check ? 'check' : listDifferent ? 'list-different' : 'write';
const cache = !(values.noCache ?? false);
const cacheLocation = cache ? values.cacheLocation : undefined;
if (cacheLocation === '') {
throw new Error('The --cache-location option requires a path.');
}
const ignorePaths = values.ignorePath ?? [];
const ignoreUnknown = values.ignoreUnknown ?? false;
const noErrorOnUnmatchedPattern = values.noErrorOnUnmatchedPattern ?? false;
const withNodeModules = values.withNodeModules ?? false;
const parallelWorkers = values.parallelWorkers;
const maxWorkers = parseMaxWorkers(parallelWorkers);
const help = values.help ?? false;
const stdinFilepath = values.stdinFilepath;
const lsp = values.lsp ?? false;
if (lsp) {
assertExclusiveMode('--lsp', modes.length > 0, positionals);
if (stdinFilepath !== undefined) {
throw new Error('The --lsp option cannot be used with --stdin-filepath.');
}
}
if (stdinFilepath !== undefined) {
assertExclusiveMode('--stdin-filepath', modes.length > 0, positionals);
}
return {
cache,
cacheLocation,
mode,
patterns: positionals,
ignorePaths,
ignoreUnknown,
noErrorOnUnmatchedPattern,
withNodeModules,
maxWorkers,
help,
stdinFilepath,
lsp,
};
};
const createDisplayPathResolver = (
cwd: string,
): ((filePath: string) => string) => {
const resolveRelativePath = createRelativePathResolver(cwd);
return (filePath) => toPosixPath(resolveRelativePath(filePath));
};
const prettyTime = (seconds: number): string => {
const format = (time: string, unit: 'm' | 's') =>
color.bold(`${time}${unit}`);
if (seconds < 10) {
const digits = seconds >= 0.01 ? 2 : 3;
return format(seconds.toFixed(digits), 's');
}
if (seconds < 60) {
return format(seconds.toFixed(1), 's');
}
const minutes = Math.floor(seconds / 60);
const minutesLabel = format(minutes.toFixed(0), 'm');
const remainingSeconds = seconds % 60;
if (remainingSeconds === 0) {
return minutesLabel;
}
const secondsLabel = format(
remainingSeconds.toFixed(remainingSeconds % 1 === 0 ? 0 : 1),
's',
);
return `${minutesLabel} ${secondsLabel}`;
};
const formatCount = (count: number): string => color.bold(count);
const formatFileCount = (count: number, isError = false): string => {
const formattedCount = formatCount(count);
return `${isError ? color.red(formattedCount) : formattedCount} ${count === 1 ? 'file' : 'files'}`;
};
const reportNoSupportedFiles = (patterns: string[]): void => {
const targets = (patterns.length ? patterns : ['.'])
.map((pattern) => color.cyan(JSON.stringify(pattern)))
.join(', ');
logger.error(
`No supported files matched ${targets}, or all matching files were ignored.`,
);
process.exitCode = 2;
};
const logFmtResult = (
result: FmtRunResult,
mode: FmtMode,
cwd: string,
processedFileCount: number,
durationSeconds: number,
): void => {
let writtenCount = 0;
let differentCount = 0;
const resolveDisplayPath = createDisplayPathResolver(cwd);
for (const file of result.files) {
if (file.status === 'written') {
writtenCount++;
continue;
}
const displayPath = resolveDisplayPath(file.path);
if (file.status === 'different') {
differentCount++;
logger[mode === 'check' ? 'error' : 'log'](displayPath);
} else if (file.status === 'error') {
logger.error(`${displayPath}: ${String(file.error)}`);
}
}
if (mode === 'write') {
if (writtenCount === 0 && result.exitCode !== 0) {
return;
}
const processedFiles = formatFileCount(processedFileCount);
const time = prettyTime(durationSeconds);
const message =
writtenCount > 0
? `Formatted ${formatCount(writtenCount)} of ${processedFiles} in ${time}.`
: `Checked ${processedFiles} in ${time}. No changes needed.`;
logger[result.exitCode === 0 ? 'success' : 'info'](message);
return;
}
if (mode !== 'check') {
return;
}
if (differentCount > 0) {
const differentFiles = formatFileCount(differentCount, true);
const processedFiles = formatFileCount(processedFileCount);
const checkOption = color.cyan('--check');
logger.error(
`Formatting issues found in ${differentFiles}. Run without ${checkOption} to fix.`,
);
logger.info(`Checked ${processedFiles} in ${prettyTime(durationSeconds)}.`);
} else if (result.exitCode === 0) {
logger.success(
`Checked ${formatFileCount(processedFileCount)} in ${prettyTime(durationSeconds)}. No issues found.`,
);
}
};
const loadFmtConfig = async (cwd: string): Promise<ResolvedFmtConfig> => {
const { configs, filePath } = await loadRstackConfig({ cwd });
return resolveFmtConfig({
definition: configs.fmt,
configFilePath: filePath,
cwd,
});
};
const runFmtCLI = async (args: string[]): Promise<void> => {
const cwd = process.cwd();
const startTime = performance.now();
// Argument errors are reported like every other failure so that a single
// exit code identifies "rs fmt refused to run".
try {
const {
cache,
cacheLocation,
help,
ignorePaths,
ignoreUnknown,
lsp,
maxWorkers,
mode,
noErrorOnUnmatchedPattern,
patterns,
stdinFilepath,
withNodeModules,
} = parseFmtArgs(args);
if (help) {
await printCommandHelp('fmt');
return;
}
if (lsp) {
const { runFmtLsp } = await import(
/* rspackChunkName: 'fmtLsp' */
'./lsp/server.ts'
);
await runFmtLsp({
// The client's workspace root is not necessarily the directory the
// editor spawned the server in; the server resolves relative
// `--ignore-path` values from this cwd so they stay based on the same
// directory as a relative `--config`.
cwd,
ignorePaths,
loadConfig: loadFmtConfig,
});
return;
}
if (stdinFilepath !== undefined) {
const { runFmtStdin } = await import(
/* rspackChunkName: 'fmtStdin' */
'./stdin.ts'
);
await runFmtStdin({
filepath: stdinFilepath,
cwd,
ignorePaths,
ignoreUnknown,
loadConfig: () => loadFmtConfig(cwd),
});
return;
}
const cacheDirPath = cacheLocation
? path.resolve(cwd, cacheLocation)
: undefined;
if (cacheDirPath) {
const cacheDirPrefix = cacheDirPath.endsWith(path.sep)
? cacheDirPath
: `${cacheDirPath}${path.sep}`;
if (cwd === cacheDirPath || cwd.startsWith(cacheDirPrefix)) {
throw new Error(
'The --cache-location directory cannot be the current working directory or an ancestor.',
);
}
}
const config = await loadFmtConfig(cwd);
const files = await discoverFmtFiles({
cwd,
patterns,
config,
excludedDirPath: cacheDirPath,
ignorePaths,
withNodeModules,
});
if (files.length === 0) {
// Staged tasks may pass only paths excluded by formatter ignore rules.
const allowUnmatched =
noErrorOnUnmatchedPattern || process.env.RSTACK_STAGED === '1';
if (allowUnmatched) {
return;
}
reportNoSupportedFiles(patterns);
return;
}
let cacheContext;
if (cacheDirPath) {
cacheContext = {
filePath: path.join(cacheDirPath, fmtCacheFileName),
rootPath: config.rootPath,
};
} else if (cache) {
const cacheDir = await ensureProjectCacheDir(config.rootPath);
if (cacheDir.status === 'available') {
cacheContext = {
filePath: path.join(cacheDir.path, 'fmt', fmtCacheFileName),
rootPath: config.rootPath,
};
}
}
if (mode === 'write') {
logger.start('Formatting...');
} else if (mode === 'check') {
logger.start('Checking formatting...');
}
const result = await runFmtFiles({
files,
mode,
maxWorkers,
cache: cacheContext,
});
if (result.processedFileCount === 0) {
if (ignoreUnknown) {
if (mode === 'check') {
logger.success('No supported files to check.');
} else if (mode === 'write') {
logger.success('No supported files to format.');
}
return;
}
reportNoSupportedFiles(patterns);
return;
}
const durationSeconds = (performance.now() - startTime) / 1000;
logFmtResult(result, mode, cwd, result.processedFileCount, durationSeconds);
process.exitCode = result.exitCode;
} catch (error) {
logger.error(error);
process.exitCode = 2;
}
};
export { runFmtCLI };