-
Notifications
You must be signed in to change notification settings - Fork 30.3k
/
Copy pathutil.ts
382 lines (302 loc) · 9.79 KB
/
util.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
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as es from 'event-stream';
import _debounce = require('debounce');
import * as _filter from 'gulp-filter';
import * as rename from 'gulp-rename';
import * as path from 'path';
import * as fs from 'fs';
import * as _rimraf from 'rimraf';
import * as VinylFile from 'vinyl';
import { ThroughStream } from 'through';
import * as sm from 'source-map';
import { pathToFileURL } from 'url';
import * as ternaryStream from 'ternary-stream';
const root = path.dirname(path.dirname(__dirname));
export interface ICancellationToken {
isCancellationRequested(): boolean;
}
const NoCancellationToken: ICancellationToken = { isCancellationRequested: () => false };
export interface IStreamProvider {
(cancellationToken?: ICancellationToken): NodeJS.ReadWriteStream;
}
export function incremental(streamProvider: IStreamProvider, initial: NodeJS.ReadWriteStream, supportsCancellation?: boolean): NodeJS.ReadWriteStream {
const input = es.through();
const output = es.through();
let state = 'idle';
let buffer = Object.create(null);
const token: ICancellationToken | undefined = !supportsCancellation ? undefined : { isCancellationRequested: () => Object.keys(buffer).length > 0 };
const run = (input: NodeJS.ReadWriteStream, isCancellable: boolean) => {
state = 'running';
const stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
input
.pipe(stream)
.pipe(es.through(undefined, () => {
state = 'idle';
eventuallyRun();
}))
.pipe(output);
};
if (initial) {
run(initial, false);
}
const eventuallyRun = _debounce(() => {
const paths = Object.keys(buffer);
if (paths.length === 0) {
return;
}
const data = paths.map(path => buffer[path]);
buffer = Object.create(null);
run(es.readArray(data), true);
}, 500);
input.on('data', (f: any) => {
buffer[f.path] = f;
if (state === 'idle') {
eventuallyRun();
}
});
return es.duplex(input, output);
}
export function debounce(task: () => NodeJS.ReadWriteStream, duration = 500): NodeJS.ReadWriteStream {
const input = es.through();
const output = es.through();
let state = 'idle';
const run = () => {
state = 'running';
task()
.pipe(es.through(undefined, () => {
const shouldRunAgain = state === 'stale';
state = 'idle';
if (shouldRunAgain) {
eventuallyRun();
}
}))
.pipe(output);
};
run();
const eventuallyRun = _debounce(() => run(), duration);
input.on('data', () => {
if (state === 'idle') {
eventuallyRun();
} else {
state = 'stale';
}
});
return es.duplex(input, output);
}
export function fixWin32DirectoryPermissions(): NodeJS.ReadWriteStream {
if (!/win32/.test(process.platform)) {
return es.through();
}
return es.mapSync<VinylFile, VinylFile>(f => {
if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
f.stat.mode = 16877;
}
return f;
});
}
export function setExecutableBit(pattern?: string | string[]): NodeJS.ReadWriteStream {
const setBit = es.mapSync<VinylFile, VinylFile>(f => {
if (!f.stat) {
f.stat = { isFile() { return true; } } as any;
}
f.stat.mode = /* 100755 */ 33261;
return f;
});
if (!pattern) {
return setBit;
}
const input = es.through();
const filter = _filter(pattern, { restore: true });
const output = input
.pipe(filter)
.pipe(setBit)
.pipe(filter.restore);
return es.duplex(input, output);
}
export function toFileUri(filePath: string): string {
const match = filePath.match(/^([a-z])\:(.*)$/i);
if (match) {
filePath = '/' + match[1].toUpperCase() + ':' + match[2];
}
return 'file://' + filePath.replace(/\\/g, '/');
}
export function skipDirectories(): NodeJS.ReadWriteStream {
return es.mapSync<VinylFile, VinylFile | undefined>(f => {
if (!f.isDirectory()) {
return f;
}
});
}
export function cleanNodeModules(rulePath: string): NodeJS.ReadWriteStream {
const rules = fs.readFileSync(rulePath, 'utf8')
.split(/\r?\n/g)
.map(line => line.trim())
.filter(line => line && !/^#/.test(line));
const excludes = rules.filter(line => !/^!/.test(line)).map(line => `!**/node_modules/${line}`);
const includes = rules.filter(line => /^!/.test(line)).map(line => `**/node_modules/${line.substr(1)}`);
const input = es.through();
const output = es.merge(
input.pipe(_filter(['**', ...excludes])),
input.pipe(_filter(includes))
);
return es.duplex(input, output);
}
declare class FileSourceMap extends VinylFile {
public sourceMap: sm.RawSourceMap;
}
export function loadSourcemaps(): NodeJS.ReadWriteStream {
const input = es.through();
const output = input
.pipe(es.map<FileSourceMap, FileSourceMap | undefined>((f, cb): FileSourceMap | undefined => {
if (f.sourceMap) {
cb(undefined, f);
return;
}
if (!f.contents) {
cb(undefined, f);
return;
}
const contents = (<Buffer>f.contents).toString('utf8');
const reg = /\/\/# sourceMappingURL=(.*)$/g;
let lastMatch: RegExpExecArray | null = null;
let match: RegExpExecArray | null = null;
while (match = reg.exec(contents)) {
lastMatch = match;
}
if (!lastMatch) {
f.sourceMap = {
version: '3',
names: [],
mappings: '',
sources: [f.relative.replace(/\\/g, '/')],
sourcesContent: [contents]
};
cb(undefined, f);
return;
}
f.contents = Buffer.from(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8');
fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', (err, contents) => {
if (err) { return cb(err); }
f.sourceMap = JSON.parse(contents);
cb(undefined, f);
});
}));
return es.duplex(input, output);
}
export function stripSourceMappingURL(): NodeJS.ReadWriteStream {
const input = es.through();
const output = input
.pipe(es.mapSync<VinylFile, VinylFile>(f => {
const contents = (<Buffer>f.contents).toString('utf8');
f.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8');
return f;
}));
return es.duplex(input, output);
}
/** Splits items in the stream based on the predicate, sending them to onTrue if true, or onFalse otherwise */
export function $if(test: boolean | ((f: VinylFile) => boolean), onTrue: NodeJS.ReadWriteStream, onFalse: NodeJS.ReadWriteStream = es.through()) {
if (typeof test === 'boolean') {
return test ? onTrue : onFalse;
}
return ternaryStream(test, onTrue, onFalse);
}
/** Operator that appends the js files' original path a sourceURL, so debug locations map */
export function appendOwnPathSourceURL(): NodeJS.ReadWriteStream {
const input = es.through();
const output = input
.pipe(es.mapSync<VinylFile, VinylFile>(f => {
if (!(f.contents instanceof Buffer)) {
throw new Error(`contents of ${f.path} are not a buffer`);
}
f.contents = Buffer.concat([f.contents, Buffer.from(`\n//# sourceURL=${pathToFileURL(f.path)}`)]);
return f;
}));
return es.duplex(input, output);
}
export function rewriteSourceMappingURL(sourceMappingURLBase: string): NodeJS.ReadWriteStream {
const input = es.through();
const output = input
.pipe(es.mapSync<VinylFile, VinylFile>(f => {
const contents = (<Buffer>f.contents).toString('utf8');
const str = `//# sourceMappingURL=${sourceMappingURLBase}/${path.dirname(f.relative).replace(/\\/g, '/')}/$1`;
f.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, str));
return f;
}));
return es.duplex(input, output);
}
export function rimraf(dir: string): () => Promise<void> {
const result = () => new Promise<void>((c, e) => {
let retries = 0;
const retry = () => {
_rimraf(dir, { maxBusyTries: 1 }, (err: any) => {
if (!err) {
return c();
}
if (err.code === 'ENOTEMPTY' && ++retries < 5) {
return setTimeout(() => retry(), 10);
}
return e(err);
});
};
retry();
});
result.taskName = `clean-${path.basename(dir).toLowerCase()}`;
return result;
}
function _rreaddir(dirPath: string, prepend: string, result: string[]): void {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
_rreaddir(path.join(dirPath, entry.name), `${prepend}/${entry.name}`, result);
} else {
result.push(`${prepend}/${entry.name}`);
}
}
}
export function rreddir(dirPath: string): string[] {
const result: string[] = [];
_rreaddir(dirPath, '', result);
return result;
}
export function ensureDir(dirPath: string): void {
if (fs.existsSync(dirPath)) {
return;
}
ensureDir(path.dirname(dirPath));
fs.mkdirSync(dirPath);
}
export function rebase(count: number): NodeJS.ReadWriteStream {
return rename(f => {
const parts = f.dirname ? f.dirname.split(/[\/\\]/) : [];
f.dirname = parts.slice(count).join(path.sep);
});
}
export interface FilterStream extends NodeJS.ReadWriteStream {
restore: ThroughStream;
}
export function filter(fn: (data: any) => boolean): FilterStream {
const result = <FilterStream><any>es.through(function (data) {
if (fn(data)) {
this.emit('data', data);
} else {
result.restore.push(data);
}
});
result.restore = es.through();
return result;
}
export function streamToPromise(stream: NodeJS.ReadWriteStream): Promise<void> {
return new Promise((c, e) => {
stream.on('error', err => e(err));
stream.on('end', () => c());
});
}
export function getElectronVersion(): Record<string, string> {
const npmrc = fs.readFileSync(path.join(root, '.npmrc'), 'utf8');
const electronVersion = /^target="(.*)"$/m.exec(npmrc)![1];
const msBuildId = /^ms_build_id="(.*)"$/m.exec(npmrc)![1];
return { electronVersion, msBuildId };
}