forked from babel/babel
/
dir.ts
248 lines (204 loc) 路 6.85 KB
/
dir.ts
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
import slash from "slash";
import path from "path";
import fs from "fs";
import * as util from "./util";
import * as watcher from "./watcher";
import type { CmdOptions } from "./options";
const FILE_TYPE = Object.freeze({
NON_COMPILABLE: "NON_COMPILABLE",
COMPILED: "COMPILED",
IGNORED: "IGNORED",
ERR_COMPILATION: "ERR_COMPILATION",
} as const);
function outputFileSync(filePath: string, data: string | Buffer): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, data);
}
export default async function ({
cliOptions,
babelOptions,
}: CmdOptions): Promise<void> {
async function write(
src: string,
base: string,
): Promise<keyof typeof FILE_TYPE> {
let relative = path.relative(base, src);
if (!util.isCompilableExtension(relative, cliOptions.extensions)) {
return FILE_TYPE.NON_COMPILABLE;
}
relative = util.withExtension(
relative,
cliOptions.keepFileExtension
? path.extname(relative)
: cliOptions.outFileExtension,
);
const dest = getDest(relative, base);
try {
const res = await util.compile(src, {
...babelOptions,
sourceFileName: slash(path.relative(dest + "/..", src)),
});
if (!res) return FILE_TYPE.IGNORED;
// we've requested explicit sourcemaps to be written to disk
if (
res.map &&
babelOptions.sourceMaps &&
babelOptions.sourceMaps !== "inline"
) {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
res.map.file = path.basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
outputFileSync(dest, res.code);
util.chmod(src, dest);
if (cliOptions.verbose) {
console.log(path.relative(process.cwd(), src) + " -> " + dest);
}
return FILE_TYPE.COMPILED;
} catch (err) {
if (cliOptions.watch) {
console.error(err);
return FILE_TYPE.ERR_COMPILATION;
}
throw err;
}
}
function getDest(filename: string, base: string): string {
if (cliOptions.relative) {
return path.join(base, cliOptions.outDir, filename);
}
return path.join(cliOptions.outDir, filename);
}
async function handleFile(src: string, base: string): Promise<boolean> {
const written = await write(src, base);
if (
(cliOptions.copyFiles && written === FILE_TYPE.NON_COMPILABLE) ||
(cliOptions.copyIgnored && written === FILE_TYPE.IGNORED)
) {
const filename = path.relative(base, src);
const dest = getDest(filename, base);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
}
return written === FILE_TYPE.COMPILED;
}
async function handle(filenameOrDir: string): Promise<number> {
if (!fs.existsSync(filenameOrDir)) return 0;
const stat = fs.statSync(filenameOrDir);
if (stat.isDirectory()) {
const dirname = filenameOrDir;
let count = 0;
const files = util.readdir(dirname, cliOptions.includeDotfiles);
for (const filename of files) {
const src = path.join(dirname, filename);
const written = await handleFile(src, dirname);
if (written) count += 1;
}
return count;
} else {
const filename = filenameOrDir;
const written = await handleFile(filename, path.dirname(filename));
return written ? 1 : 0;
}
}
let compiledFiles = 0;
let startTime = null;
const logSuccess = util.debounce(function () {
if (startTime === null) {
// This should never happen, but just in case it's better
// to ignore the log message rather than making @babel/cli crash.
return;
}
const diff = process.hrtime(startTime);
console.log(
`Successfully compiled ${compiledFiles} ${
compiledFiles !== 1 ? "files" : "file"
} with Babel (${diff[0] * 1e3 + Math.round(diff[1] / 1e6)}ms).`,
);
compiledFiles = 0;
startTime = null;
}, 100);
if (cliOptions.watch) watcher.enable({ enableGlobbing: true });
if (!cliOptions.skipInitialBuild) {
if (cliOptions.deleteDirOnStart) {
util.deleteDir(cliOptions.outDir);
}
fs.mkdirSync(cliOptions.outDir, { recursive: true });
startTime = process.hrtime();
for (const filename of cliOptions.filenames) {
// compiledFiles is just incremented without reading its value, so we
// don't risk race conditions.
// eslint-disable-next-line require-atomic-updates
compiledFiles += await handle(filename);
}
if (!cliOptions.quiet) {
logSuccess();
logSuccess.flush();
}
}
if (cliOptions.watch) {
// This, alongside with debounce, allows us to only log
// when we are sure that all the files have been compiled.
let processing = 0;
const { filenames } = cliOptions;
let getBase;
if (filenames.length === 1) {
// fast path: If there is only one filenames, we know it must be the base
const base = filenames[0];
const absoluteBase = path.resolve(base);
getBase = filename => {
return filename === absoluteBase ? path.dirname(base) : base;
};
} else {
// A map from absolute compiled file path to its base, from which
// the output destination will be determined
const filenameToBaseMap: Map<string, string> = new Map(
filenames.map(filename => {
const absoluteFilename = path.resolve(filename);
return [absoluteFilename, path.dirname(filename)];
}),
);
const absoluteFilenames: Map<string, string> = new Map(
filenames.map(filename => {
const absoluteFilename = path.resolve(filename);
return [absoluteFilename, filename];
}),
);
const { sep } = path;
// determine base from the absolute file path
getBase = filename => {
const base = filenameToBaseMap.get(filename);
if (base !== undefined) {
return base;
}
for (const [absoluteFilenameOrDir, relative] of absoluteFilenames) {
if (filename.startsWith(absoluteFilenameOrDir + sep)) {
filenameToBaseMap.set(filename, relative);
return relative;
}
}
// Can't determine the base, probably external deps
return "";
};
}
filenames.forEach(filenameOrDir => {
watcher.watch(filenameOrDir);
});
watcher.startWatcher();
watcher.onFilesChange(async filenames => {
processing++;
if (startTime === null) startTime = process.hrtime();
try {
const written = await Promise.all(
filenames.map(filename => handleFile(filename, getBase(filename))),
);
compiledFiles += written.filter(Boolean).length;
} catch (err) {
console.error(err);
}
processing--;
if (processing === 0 && !cliOptions.quiet) logSuccess();
});
}
}