-
Notifications
You must be signed in to change notification settings - Fork 2
/
prelim-cli.js
executable file
·225 lines (198 loc) · 5.16 KB
/
prelim-cli.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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const commander = require('commander');
const glob = require('glob-gitignore');
const ignore = require('ignore');
const { transform } = require('@codemod/core');
const packageJson = require('./package.json');
const plugin = require('./src/plugin').default;
const GRAY = '\x1b[2m';
const GREEN = '\x1b[32;1m';
const ORANGE = '\x1b[33m';
const RESET = '\x1b[0m';
const STATUS_INFO = {
error: {
icon: '⚠️ ',
letter: 'X',
color: ORANGE,
},
modified: {
icon: '✅',
letter: 'M',
color: GREEN,
},
unchanged: {
icon: ' ',
letter: 'U',
color: GRAY,
},
};
const program = new commander.Command();
const defaultIgnorePaths = ['.gitignore'];
const addIgnore = (item, prev) => (item === '' ? [] : prev.concat([item]));
const addIgnorePath = (item, prev) =>
item === '' ? [] : prev === defaultIgnorePaths ? [item] : prev.concat([item]);
program
.name(packageJson.name)
.arguments('[--] <filesOrPatterns...>')
.option(
'--strict',
'turn on strict mode and disable probably-safe optimizations (default: loose mode)'
)
.option(
'--ignore <pattern>',
'Filename pattern to ignore (repeatable)',
addIgnore,
['node_modules/']
)
.option(
'--ignore-path <file>',
'Path to a file with patterns describing files to ignore (repeatable)',
addIgnorePath,
defaultIgnorePaths
)
.option(
'--source-type <script|module>',
'parse as a JS script, an ES module, or specify "unambiguous" to let babel determine',
'unambiguous'
)
.option(
'--printer <recast|prettier|babel>',
'which code printer to use',
'recast'
)
.option(
'--colors <auto|always|off>',
'whether to display colours. "auto" defaults to true of running in a TTY.',
'auto'
)
.version(
packageJson.version,
'-v, --version',
'output the current prelim version'
)
.on('--help', () => console.log() /* print a newline after help */);
program.parse(process.argv);
if (program.args.length === 0) {
program.outputHelp();
process.exit(1);
}
let rawFiles = [];
let patterns = [];
for (let fileOrPattern of program.args) {
try {
let stats = fs.statSync(fileOrPattern);
if (stats.isFile()) {
rawFiles.push(fileOrPattern);
} else if (stats.isDirectory()) {
patterns.push(`${fileOrPattern}/**/*.{js,mjs,cjs,jsx,ts,tsx,vue}`);
} else {
patterns.push(fileOrPattern);
}
} catch (e) {
// we expect an ENOENT, which means it was not a file
if (e.code === 'ENOENT') {
patterns.push(fileOrPattern);
} else {
throw e;
}
}
}
let ignores = ignore();
for (let ignoreFile of program.ignorePath) {
try {
ignores.add(fs.readFileSync(ignoreFile, 'utf8'));
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
}
ignores.add(program.ignore);
let individualIgnores = ignore().add(program.ignore);
// Fix a crash where patterns starting with './' are invalid
patterns = patterns.map((p) => p.replace(/^\.\//, ''));
let files = individualIgnores.filter(rawFiles).concat(
patterns.length === 0
? []
: glob.sync(patterns, {
ignore: ignores,
})
);
if (files.length === 0) {
console.log('No matching files found.');
process.exit(0);
}
const useColors =
program.colors === 'auto'
? process.stdout.isTTY
: program.colors === 'always';
const printStatus = (statusCode) => {
let symbol = useColors
? STATUS_INFO[statusCode].icon
: STATUS_INFO[statusCode].letter;
process.stdout.write(symbol + ' ');
if (useColors && process.stdout.isTTY) {
readline.cursorTo(process.stdout, 3);
}
};
const colorByStatus = (statusCode) => {
if (useColors) {
process.stdout.write(STATUS_INFO[statusCode].color);
}
};
for (let file of files) {
if (useColors && process.stdout.isTTY) {
process.stdout.write(' ' + file);
readline.cursorTo(process.stdout, 0);
}
let status = 'unchanged';
let error = null;
try {
let fileSource = fs.readFileSync(file, 'utf8');
let code = fileSource;
if (file.endsWith('.vue')) {
let match = /<script(?: [^>]+)?>([\s\S]*?)<\/script>/.exec(fileSource);
if (match) {
code = match[1];
}
}
let { code: result } = transform(code, {
plugins: [[plugin, { loose: !program.strict }]],
printer: program.printer,
sourceType: program.sourceType,
babelrc: false,
configFile: false,
});
if (result !== code) {
status = 'modified';
if (file.endsWith('.vue') && code !== fileSource) {
result = fileSource.replace(
/(<script(?: [^>]+)?>)([\s\S]*?)(<\/script>)/,
(all, tag, code, close) => {
return tag + result + close;
}
);
}
fs.writeFileSync(file, result, 'utf8');
}
} catch (e) {
status = 'error';
error = e;
}
if (useColors && process.stdout.isTTY) {
readline.clearLine(process.stdout, 0);
}
printStatus(status);
colorByStatus(status);
process.stdout.write(file);
if (useColors) {
process.stdout.write(RESET);
}
process.stdout.write('\n');
if (error) {
console.error(error);
}
}