forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprettier.js
93 lines (77 loc) · 2.45 KB
/
prettier.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
/* eslint-disable no-console */
// Based on similar script in React
// https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/scripts/prettier/index.js
// supported modes = check, check-changed, write, write-changed
const glob = require('glob-gitignore');
const prettier = require('prettier');
const fs = require('fs');
const path = require('path');
const listChangedFiles = require('./listChangedFiles');
const mode = process.argv[2] || 'write-changed';
const shouldWrite = mode === 'write' || mode === 'write-changed';
const onlyChanged = mode === 'check-changed' || mode === 'write-changed';
function runPrettier(changedFiles) {
let didWarn = false;
let didError = false;
const warnedFiles = [];
const ignoredFiles = fs
.readFileSync('.eslintignore', 'utf-8')
.split(/\r*\n/)
.filter(notEmpty => notEmpty);
const files = glob
.sync('**/*.{js,tsx,d.ts}', { ignore: ['**/node_modules/**', ...ignoredFiles] })
.filter(f => !changedFiles || changedFiles.has(f));
if (!files.length) {
process.exit(0);
}
const prettierConfigPath = path.join(__dirname, '../prettier.config.js');
files.forEach(file => {
const options = prettier.resolveConfig.sync(file, {
config: prettierConfigPath,
});
try {
const input = fs.readFileSync(file, 'utf8');
if (shouldWrite) {
console.log(`Formatting ${file}`);
const output = prettier.format(input, { ...options, filepath: file });
if (output !== input) {
fs.writeFileSync(file, output, 'utf8');
}
} else {
console.log(`Checking ${file}`);
if (!prettier.check(input, { ...options, filepath: file })) {
warnedFiles.push(file);
didWarn = true;
}
}
} catch (error) {
didError = true;
console.log(`\n\n${error.message}`);
console.log(file);
}
});
if (didWarn) {
console.log(
'\n\nThis project uses prettier to format all JavaScript code.\n' +
`Please run '${!changedFiles ? 'yarn prettier:all' : 'yarn prettier'}'` +
'and commit the changes to the files listed below:\n\n',
);
console.log(warnedFiles.join('\n'));
}
if (didWarn || didError) {
process.exit(1);
}
}
async function run() {
try {
if (onlyChanged) {
const changedFiles = await listChangedFiles();
runPrettier(changedFiles);
return;
}
runPrettier();
} catch (err) {
console.error(err);
}
}
run();