-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
format-files.js
353 lines (323 loc) · 9.04 KB
/
format-files.js
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
/* eslint no-console:0 */
/* eslint complexity:[1, 7] */
import path from 'path';
import fs from 'fs';
import glob from 'glob';
import { bindNodeCallback, from, of } from 'rxjs';
import { catchError, concatAll, distinct, map, mergeMap } from 'rxjs/operators';
import chalk from 'chalk';
import getStdin from 'get-stdin';
import nodeIgnore from 'ignore';
import findUp from 'find-up';
import memoize from 'lodash.memoize';
import indentString from 'indent-string';
import getLogger from 'loglevel-colored-level-prefix';
import format from './prettier-eslint';
import * as messages from './messages';
const LINE_SEPERATOR_REGEX = /(\r|\n|\r\n)/;
const rxGlob = bindNodeCallback(glob);
const rxReadFile = bindNodeCallback(fs.readFile);
const rxWriteFile = bindNodeCallback(fs.writeFile);
const findUpEslintignoreSyncMemoized = memoize(
findUpEslintignoreSync,
findUpMemoizeResolver
);
const findUpPrettierignoreSyncMemoized = memoize(
findUpPrettierignoreSync,
findUpMemoizeResolver
);
const getIsIgnoredMemoized = memoize(getIsIgnored);
const logger = getLogger({ prefix: 'prettier-eslint-cli' });
export default formatFilesFromArgv;
function formatFilesFromArgv({
_: fileGlobs,
$0: _$0, //eslint-disable-line
help: _help,
h: _help_,
version: _version,
logLevel = logger.getLevel(),
l: _logLevelAlias,
config: _config,
listDifferent,
stdin,
stdinFilepath,
write,
eslintPath,
prettierPath,
ignore: ignoreGlobs = [],
eslintIgnore: applyEslintIgnore = true,
prettierIgnore: applyPrettierIgnore = true,
eslintConfigPath,
prettierLast,
...prettierOptions
}) {
logger.setLevel(logLevel);
const prettierESLintOptions = {
logLevel,
eslintPath,
prettierPath,
prettierLast,
prettierOptions
};
if (eslintConfigPath) {
prettierESLintOptions.eslintConfig = {
overrideConfigFile: eslintConfigPath
};
}
const cliOptions = { write, listDifferent };
if (stdin) {
return formatStdin({ filePath: stdinFilepath, ...prettierESLintOptions });
} else {
return formatFilesFromGlobs({
fileGlobs,
ignoreGlobs: [...ignoreGlobs], // make a copy to avoid manipulation
cliOptions,
prettierESLintOptions,
applyEslintIgnore,
applyPrettierIgnore
});
}
}
async function formatStdin(prettierESLintOptions) {
const stdinValue = (await getStdin()).trim();
try {
const formatted = await format({
text: stdinValue,
...prettierESLintOptions
});
process.stdout.write(formatted);
return Promise.resolve(formatted);
} catch (error) {
logger.error(
'There was a problem trying to format the stdin text',
`\n${indentString(error.stack, 4)}`
);
process.exitCode = 1;
return Promise.resolve(stdinValue);
}
}
function formatFilesFromGlobs({
fileGlobs,
ignoreGlobs,
cliOptions,
prettierESLintOptions,
applyEslintIgnore,
applyPrettierIgnore
}) {
const concurrentGlobs = 3;
const concurrentFormats = 10;
return new Promise(resolve => {
const successes = [];
const failures = [];
const unchanged = [];
from(fileGlobs)
.pipe(
mergeMap(
getFilesFromGlob.bind(
null,
ignoreGlobs,
applyEslintIgnore,
applyPrettierIgnore
),
null,
concurrentGlobs
),
concatAll(),
distinct(),
mergeMap(filePathToFormatted, null, concurrentFormats)
)
.subscribe(onNext, onError, onComplete);
function filePathToFormatted(filePath) {
const absoluteFilePath = path.resolve(filePath);
return formatFile(absoluteFilePath, prettierESLintOptions, cliOptions);
}
function onNext(info) {
if (info.error) {
failures.push(info);
} else if (info.unchanged) {
unchanged.push(info);
} else {
successes.push(info);
}
}
function onError(error) {
logger.error(
'There was an unhandled error while formatting the files',
`\n${indentString(error.stack, 4)}`
);
process.exitCode = 1;
resolve({ error, successes, failures });
}
function onComplete() {
const isSilent = logger.getLevel() === logger.levels.SILENT || cliOptions.listDifferent;
/* use console.error directly here because
* - we don't want these messages prefixed
* - we want them to go to stderr, not stdout
*/
if (!isSilent) {
if (successes.length) {
console.error(
messages.success({
success: chalk.green('success'),
count: successes.length,
countString: chalk.bold(successes.length)
})
);
}
if (failures.length) {
process.exitCode = 1;
console.error(
messages.failure({
failure: chalk.red('failure'),
count: failures.length,
countString: chalk.bold(failures.length)
})
);
}
if (unchanged.length) {
console.error(
messages.unchanged({
unchanged: chalk.gray('unchanged'),
count: unchanged.length,
countString: chalk.bold(unchanged.length)
})
);
}
}
resolve({ successes, failures });
}
});
}
function getFilesFromGlob(
ignoreGlobs,
applyEslintIgnore,
applyPrettierIgnore,
fileGlob
) {
const globOptions = { ignore: ignoreGlobs };
if (!fileGlob.includes('node_modules')) {
// basically, we're going to protect you from doing something
// not smart unless you explicitly include it in your glob
globOptions.ignore.push('**/node_modules/**');
}
return rxGlob(fileGlob, globOptions).pipe(
map(filePaths => {
return filePaths.filter(filePath => {
if (applyEslintIgnore && isFilePathMatchedByEslintignore(filePath)) {
return false;
}
if (
applyPrettierIgnore &&
isFilePathMatchedByPrettierignore(filePath)
) {
return false;
}
return true;
});
})
);
}
function formatFile(filePath, prettierESLintOptions, cliOptions) {
const fileInfo = { filePath };
let format$ = rxReadFile(filePath, 'utf8').pipe(
mergeMap(async text => {
fileInfo.text = text;
fileInfo.formatted = await format({
text,
filePath,
...prettierESLintOptions
});
fileInfo.unchanged = fileInfo.text === fileInfo.formatted;
return fileInfo;
})
);
if (cliOptions.write) {
format$ = format$.pipe(
mergeMap(info => {
if (info.unchanged) {
return of(info);
} else {
return rxWriteFile(filePath, info.formatted).pipe(map(() => info));
}
})
);
} else if (cliOptions.listDifferent) {
format$ = format$.pipe(
map(info => {
if (!info.unchanged) {
process.exitCode = 1;
console.log(info.filePath);
}
return info;
})
);
} else {
format$ = format$.pipe(
map(info => {
process.stdout.write(info.formatted);
return info;
})
);
}
return format$.pipe(
catchError(error => {
logger.error(
`There was an error formatting "${fileInfo.filePath}":`,
`\n${indentString(error.stack, 4)}`
);
return of(Object.assign(fileInfo, { error }));
})
);
}
function getNearestEslintignorePath(filePath) {
const { dir } = path.parse(filePath);
return findUpEslintignoreSyncMemoized('.eslintignore', dir);
}
function isFilePathMatchedByEslintignore(filePath) {
const eslintignorePath = getNearestEslintignorePath(filePath);
if (!eslintignorePath) {
return false;
}
const eslintignoreDir = path.parse(eslintignorePath).dir;
const filePathRelativeToEslintignoreDir = path.relative(
eslintignoreDir,
filePath
);
const isIgnored = getIsIgnoredMemoized(eslintignorePath);
return isIgnored(filePathRelativeToEslintignoreDir);
}
function getNearestPrettierignorePath(filePath) {
const { dir } = path.parse(filePath);
return findUpPrettierignoreSyncMemoized('.prettierignore', dir);
}
function isFilePathMatchedByPrettierignore(filePath) {
const prettierignorePath = getNearestPrettierignorePath(filePath);
if (!prettierignorePath) {
return false;
}
const prettierignoreDir = path.parse(prettierignorePath).dir;
const filePathRelativeToPrettierignoreDir = path.relative(
prettierignoreDir,
filePath
);
const isIgnored = getIsIgnoredMemoized(prettierignorePath);
return isIgnored(filePathRelativeToPrettierignoreDir);
}
function findUpMemoizeResolver(...args) {
return args.join('::');
}
function findUpEslintignoreSync(filename, cwd) {
return findUp.sync('.eslintignore', { cwd });
}
function findUpPrettierignoreSync(filename, cwd) {
return findUp.sync('.prettierignore', { cwd });
}
function getIsIgnored(filename) {
const ignoreLines = fs
.readFileSync(filename, 'utf8')
.split(LINE_SEPERATOR_REGEX)
.filter(line => Boolean(line.trim()));
const instance = nodeIgnore();
instance.add(ignoreLines);
return instance.ignores.bind(instance);
}