-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathfs.js
853 lines (737 loc) · 23.9 KB
/
fs.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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
/* @flow */
import type {ReadStream} from 'fs';
import type Reporter from '../reporters/base-reporter.js';
import type {CopyFileAction} from './fs-normalized.js';
import fs from 'fs';
import globModule from 'glob';
import os from 'os';
import path from 'path';
import BlockingQueue from './blocking-queue.js';
import * as promise from './promise.js';
import {promisify} from './promise.js';
import map from './map.js';
import {copyFile, fileDatesEqual, unlink} from './fs-normalized.js';
export const constants =
typeof fs.constants !== 'undefined'
? fs.constants
: {
R_OK: fs.R_OK,
W_OK: fs.W_OK,
X_OK: fs.X_OK,
};
export const lockQueue = new BlockingQueue('fs lock');
export const readFileBuffer = promisify(fs.readFile);
export const open: (path: string, flags: string, mode?: number) => Promise<Array<string>> = promisify(fs.open);
export const writeFile: (path: string, data: string | Buffer, options?: Object) => Promise<void> = promisify(
fs.writeFile,
);
export const readlink: (path: string, opts: void) => Promise<string> = promisify(fs.readlink);
export const realpath: (path: string, opts: void) => Promise<string> = promisify(fs.realpath);
export const readdir: (path: string, opts: void) => Promise<Array<string>> = promisify(fs.readdir);
export const rename: (oldPath: string, newPath: string) => Promise<void> = promisify(fs.rename);
export const access: (path: string, mode?: number) => Promise<void> = promisify(fs.access);
export const stat: (path: string) => Promise<fs.Stats> = promisify(fs.stat);
export const mkdirp: (path: string) => Promise<void> = promisify(require('mkdirp'));
export const exists: (path: string) => Promise<boolean> = promisify(fs.exists, true);
export const lstat: (path: string) => Promise<fs.Stats> = promisify(fs.lstat);
export const chmod: (path: string, mode: number | string) => Promise<void> = promisify(fs.chmod);
export const link: (src: string, dst: string) => Promise<fs.Stats> = promisify(fs.link);
export const glob: (path: string, options?: Object) => Promise<Array<string>> = promisify(globModule);
export {unlink};
// fs.copyFile uses the native file copying instructions on the system, performing much better
// than any JS-based solution and consumes fewer resources. Repeated testing to fine tune the
// concurrency level revealed 128 as the sweet spot on a quad-core, 16 CPU Intel system with SSD.
const CONCURRENT_QUEUE_ITEMS = fs.copyFile ? 128 : 4;
const fsSymlink: (target: string, path: string, type?: 'dir' | 'file' | 'junction') => Promise<void> = promisify(
fs.symlink,
);
const invariant = require('invariant');
const stripBOM = require('strip-bom');
const noop = () => {};
export type CopyQueueItem = {
src: string,
dest: string,
type?: string,
onFresh?: ?() => void,
onDone?: ?() => void,
};
type CopyQueue = Array<CopyQueueItem>;
type LinkFileAction = {
src: string,
dest: string,
removeDest: boolean,
};
type CopySymlinkAction = {
dest: string,
linkname: string,
};
type CopyActions = {
file: Array<CopyFileAction>,
symlink: Array<CopySymlinkAction>,
link: Array<LinkFileAction>,
};
type CopyOptions = {
onProgress: (dest: string) => void,
onStart: (num: number) => void,
possibleExtraneous: Set<string>,
ignoreBasenames: Array<string>,
artifactFiles: Array<string>,
};
type FailedFolderQuery = {
error: Error,
folder: string,
};
type FolderQueryResult = {
skipped: Array<FailedFolderQuery>,
folder: ?string,
};
async function buildActionsForCopy(
queue: CopyQueue,
events: CopyOptions,
possibleExtraneous: Set<string>,
reporter: Reporter,
): Promise<CopyActions> {
const artifactFiles: Set<string> = new Set(events.artifactFiles || []);
const files: Set<string> = new Set();
// initialise events
for (const item of queue) {
const onDone = item.onDone;
item.onDone = () => {
events.onProgress(item.dest);
if (onDone) {
onDone();
}
};
}
events.onStart(queue.length);
// start building actions
const actions: CopyActions = {
file: [],
symlink: [],
link: [],
};
// custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items
// at a time due to the requirement to push items onto the queue
while (queue.length) {
const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);
await Promise.all(items.map(build));
}
// simulate the existence of some files to prevent considering them extraneous
for (const file of artifactFiles) {
if (possibleExtraneous.has(file)) {
reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));
possibleExtraneous.delete(file);
}
}
for (const loc of possibleExtraneous) {
if (files.has(loc.toLowerCase())) {
possibleExtraneous.delete(loc);
}
}
return actions;
//
async function build(data: CopyQueueItem): Promise<void> {
const {src, dest, type} = data;
const onFresh = data.onFresh || noop;
const onDone = data.onDone || noop;
// TODO https://github.com/yarnpkg/yarn/issues/3751
// related to bundled dependencies handling
if (files.has(dest.toLowerCase())) {
reporter.verbose(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`);
} else {
files.add(dest.toLowerCase());
}
if (type === 'symlink') {
await mkdirp(path.dirname(dest));
onFresh();
actions.symlink.push({
dest,
linkname: src,
});
onDone();
return;
}
if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {
// ignored file
return;
}
const srcStat = await lstat(src);
let srcFiles;
if (srcStat.isDirectory()) {
srcFiles = await readdir(src);
}
let destStat;
try {
// try accessing the destination
destStat = await lstat(dest);
} catch (e) {
// proceed if destination doesn't exist, otherwise error
if (e.code !== 'ENOENT') {
throw e;
}
}
// if destination exists
if (destStat) {
const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();
const bothFolders = srcStat.isDirectory() && destStat.isDirectory();
const bothFiles = srcStat.isFile() && destStat.isFile();
// EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving
// us modes that aren't valid. investigate this, it's generally safe to proceed.
/* if (srcStat.mode !== destStat.mode) {
try {
await access(dest, srcStat.mode);
} catch (err) {}
} */
if (bothFiles && artifactFiles.has(dest)) {
// this file gets changed during build, likely by a custom install script. Don't bother checking it.
onDone();
reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));
return;
}
if (bothFiles && srcStat.size === destStat.size && fileDatesEqual(srcStat.mtime, destStat.mtime)) {
// we can safely assume this is the same file
onDone();
reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime));
return;
}
if (bothSymlinks) {
const srcReallink = await readlink(src);
if (srcReallink === (await readlink(dest))) {
// if both symlinks are the same then we can continue on
onDone();
reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));
return;
}
}
if (bothFolders) {
// mark files that aren't in this folder as possibly extraneous
const destFiles = await readdir(dest);
invariant(srcFiles, 'src files not initialised');
for (const file of destFiles) {
if (srcFiles.indexOf(file) < 0) {
const loc = path.join(dest, file);
possibleExtraneous.add(loc);
if ((await lstat(loc)).isDirectory()) {
for (const file of await readdir(loc)) {
possibleExtraneous.add(path.join(loc, file));
}
}
}
}
}
}
if (destStat && destStat.isSymbolicLink()) {
await unlink(dest);
destStat = null;
}
if (srcStat.isSymbolicLink()) {
onFresh();
const linkname = await readlink(src);
actions.symlink.push({
dest,
linkname,
});
onDone();
} else if (srcStat.isDirectory()) {
if (!destStat) {
reporter.verbose(reporter.lang('verboseFileFolder', dest));
await mkdirp(dest);
}
const destParts = dest.split(path.sep);
while (destParts.length) {
files.add(destParts.join(path.sep).toLowerCase());
destParts.pop();
}
// push all files to queue
invariant(srcFiles, 'src files not initialised');
let remaining = srcFiles.length;
if (!remaining) {
onDone();
}
for (const file of srcFiles) {
queue.push({
dest: path.join(dest, file),
onFresh,
onDone: () => {
if (--remaining === 0) {
onDone();
}
},
src: path.join(src, file),
});
}
} else if (srcStat.isFile()) {
onFresh();
actions.file.push({
src,
dest,
atime: srcStat.atime,
mtime: srcStat.mtime,
mode: srcStat.mode,
});
onDone();
} else {
throw new Error(`unsure how to copy this: ${src}`);
}
}
}
async function buildActionsForHardlink(
queue: CopyQueue,
events: CopyOptions,
possibleExtraneous: Set<string>,
reporter: Reporter,
): Promise<CopyActions> {
const artifactFiles: Set<string> = new Set(events.artifactFiles || []);
const files: Set<string> = new Set();
// initialise events
for (const item of queue) {
const onDone = item.onDone || noop;
item.onDone = () => {
events.onProgress(item.dest);
onDone();
};
}
events.onStart(queue.length);
// start building actions
const actions: CopyActions = {
file: [],
symlink: [],
link: [],
};
// custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items
// at a time due to the requirement to push items onto the queue
while (queue.length) {
const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);
await Promise.all(items.map(build));
}
// simulate the existence of some files to prevent considering them extraneous
for (const file of artifactFiles) {
if (possibleExtraneous.has(file)) {
reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));
possibleExtraneous.delete(file);
}
}
for (const loc of possibleExtraneous) {
if (files.has(loc.toLowerCase())) {
possibleExtraneous.delete(loc);
}
}
return actions;
//
async function build(data: CopyQueueItem): Promise<void> {
const {src, dest} = data;
const onFresh = data.onFresh || noop;
const onDone = data.onDone || noop;
if (files.has(dest.toLowerCase())) {
// Fixes issue https://github.com/yarnpkg/yarn/issues/2734
// When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1,
// package-linker passes that modules A1 and B1 need to be hardlinked,
// the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case
// an exception.
onDone();
return;
}
files.add(dest.toLowerCase());
if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {
// ignored file
return;
}
const srcStat = await lstat(src);
let srcFiles;
if (srcStat.isDirectory()) {
srcFiles = await readdir(src);
}
const destExists = await exists(dest);
if (destExists) {
const destStat = await lstat(dest);
const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();
const bothFolders = srcStat.isDirectory() && destStat.isDirectory();
const bothFiles = srcStat.isFile() && destStat.isFile();
if (srcStat.mode !== destStat.mode) {
try {
await access(dest, srcStat.mode);
} catch (err) {
// EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving
// us modes that aren't valid. investigate this, it's generally safe to proceed.
reporter.verbose(err);
}
}
if (bothFiles && artifactFiles.has(dest)) {
// this file gets changed during build, likely by a custom install script. Don't bother checking it.
onDone();
reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));
return;
}
// correct hardlink
if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) {
onDone();
reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino));
return;
}
if (bothSymlinks) {
const srcReallink = await readlink(src);
if (srcReallink === (await readlink(dest))) {
// if both symlinks are the same then we can continue on
onDone();
reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));
return;
}
}
if (bothFolders) {
// mark files that aren't in this folder as possibly extraneous
const destFiles = await readdir(dest);
invariant(srcFiles, 'src files not initialised');
for (const file of destFiles) {
if (srcFiles.indexOf(file) < 0) {
const loc = path.join(dest, file);
possibleExtraneous.add(loc);
if ((await lstat(loc)).isDirectory()) {
for (const file of await readdir(loc)) {
possibleExtraneous.add(path.join(loc, file));
}
}
}
}
}
}
if (srcStat.isSymbolicLink()) {
onFresh();
const linkname = await readlink(src);
actions.symlink.push({
dest,
linkname,
});
onDone();
} else if (srcStat.isDirectory()) {
reporter.verbose(reporter.lang('verboseFileFolder', dest));
await mkdirp(dest);
const destParts = dest.split(path.sep);
while (destParts.length) {
files.add(destParts.join(path.sep).toLowerCase());
destParts.pop();
}
// push all files to queue
invariant(srcFiles, 'src files not initialised');
let remaining = srcFiles.length;
if (!remaining) {
onDone();
}
for (const file of srcFiles) {
queue.push({
onFresh,
src: path.join(src, file),
dest: path.join(dest, file),
onDone: () => {
if (--remaining === 0) {
onDone();
}
},
});
}
} else if (srcStat.isFile()) {
onFresh();
actions.link.push({
src,
dest,
removeDest: destExists,
});
onDone();
} else {
throw new Error(`unsure how to copy this: ${src}`);
}
}
}
export function copy(src: string, dest: string, reporter: Reporter): Promise<void> {
return copyBulk([{src, dest}], reporter);
}
export async function copyBulk(
queue: CopyQueue,
reporter: Reporter,
_events?: {
onProgress?: ?(dest: string) => void,
onStart?: ?(num: number) => void,
possibleExtraneous: Set<string>,
ignoreBasenames?: Array<string>,
artifactFiles?: Array<string>,
},
): Promise<void> {
const events: CopyOptions = {
onStart: (_events && _events.onStart) || noop,
onProgress: (_events && _events.onProgress) || noop,
possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),
ignoreBasenames: (_events && _events.ignoreBasenames) || [],
artifactFiles: (_events && _events.artifactFiles) || [],
};
const actions: CopyActions = await buildActionsForCopy(queue, events, events.possibleExtraneous, reporter);
events.onStart(actions.file.length + actions.symlink.length + actions.link.length);
const fileActions: Array<CopyFileAction> = actions.file;
const currentlyWriting: Map<string, Promise<void>> = new Map();
await promise.queue(
fileActions,
async (data: CopyFileAction): Promise<void> => {
let writePromise;
while ((writePromise = currentlyWriting.get(data.dest))) {
await writePromise;
}
reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest));
const copier = copyFile(data, () => currentlyWriting.delete(data.dest));
currentlyWriting.set(data.dest, copier);
events.onProgress(data.dest);
return copier;
},
CONCURRENT_QUEUE_ITEMS,
);
// we need to copy symlinks last as they could reference files we were copying
const symlinkActions: Array<CopySymlinkAction> = actions.symlink;
await promise.queue(symlinkActions, (data): Promise<void> => {
const linkname = path.resolve(path.dirname(data.dest), data.linkname);
reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));
return symlink(linkname, data.dest);
});
}
export async function hardlinkBulk(
queue: CopyQueue,
reporter: Reporter,
_events?: {
onProgress?: ?(dest: string) => void,
onStart?: ?(num: number) => void,
possibleExtraneous: Set<string>,
artifactFiles?: Array<string>,
},
): Promise<void> {
const events: CopyOptions = {
onStart: (_events && _events.onStart) || noop,
onProgress: (_events && _events.onProgress) || noop,
possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),
artifactFiles: (_events && _events.artifactFiles) || [],
ignoreBasenames: [],
};
const actions: CopyActions = await buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter);
events.onStart(actions.file.length + actions.symlink.length + actions.link.length);
const fileActions: Array<LinkFileAction> = actions.link;
await promise.queue(
fileActions,
async (data): Promise<void> => {
reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest));
if (data.removeDest) {
await unlink(data.dest);
}
await link(data.src, data.dest);
},
CONCURRENT_QUEUE_ITEMS,
);
// we need to copy symlinks last as they could reference files we were copying
const symlinkActions: Array<CopySymlinkAction> = actions.symlink;
await promise.queue(symlinkActions, (data): Promise<void> => {
const linkname = path.resolve(path.dirname(data.dest), data.linkname);
reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));
return symlink(linkname, data.dest);
});
}
function _readFile(loc: string, encoding: string): Promise<any> {
return new Promise((resolve, reject) => {
fs.readFile(loc, encoding, function(err, content) {
if (err) {
reject(err);
} else {
resolve(content);
}
});
});
}
export function readFile(loc: string): Promise<string> {
return _readFile(loc, 'utf8').then(normalizeOS);
}
export function readFileRaw(loc: string): Promise<Buffer> {
return _readFile(loc, 'binary');
}
export async function readFileAny(files: Array<string>): Promise<?string> {
for (const file of files) {
if (await exists(file)) {
return readFile(file);
}
}
return null;
}
export async function readJson(loc: string): Promise<Object> {
return (await readJsonAndFile(loc)).object;
}
export async function readJsonAndFile(
loc: string,
): Promise<{
object: Object,
content: string,
}> {
const file = await readFile(loc);
try {
return {
object: map(JSON.parse(stripBOM(file))),
content: file,
};
} catch (err) {
err.message = `${loc}: ${err.message}`;
throw err;
}
}
export async function find(filename: string, dir: string): Promise<string | false> {
const parts = dir.split(path.sep);
while (parts.length) {
const loc = parts.concat(filename).join(path.sep);
if (await exists(loc)) {
return loc;
} else {
parts.pop();
}
}
return false;
}
export async function symlink(src: string, dest: string): Promise<void> {
if (process.platform !== 'win32') {
// use relative paths otherwise which will be retained if the directory is moved
src = path.relative(path.dirname(dest), src);
// When path.relative returns an empty string for the current directory, we should instead use
// '.', which is a valid fs.symlink target.
src = src || '.';
}
try {
const stats = await lstat(dest);
if (stats.isSymbolicLink()) {
const resolved = dest;
if (resolved === src) {
return;
}
}
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
// We use rimraf for unlink which never throws an ENOENT on missing target
await unlink(dest);
if (process.platform === 'win32') {
// use directory junctions if possible on win32, this requires absolute paths
await fsSymlink(src, dest, 'junction');
} else {
await fsSymlink(src, dest);
}
}
export type WalkFiles = Array<{
relative: string,
absolute: string,
basename: string,
mtime: number,
}>;
export async function walk(
dir: string,
relativeDir?: ?string,
ignoreBasenames?: Set<string> = new Set(),
): Promise<WalkFiles> {
let files = [];
let filenames = await readdir(dir);
if (ignoreBasenames.size) {
filenames = filenames.filter(name => !ignoreBasenames.has(name));
}
for (const name of filenames) {
const relative = relativeDir ? path.join(relativeDir, name) : name;
const loc = path.join(dir, name);
const stat = await lstat(loc);
files.push({
relative,
basename: name,
absolute: loc,
mtime: +stat.mtime,
});
if (stat.isDirectory()) {
files = files.concat(await walk(loc, relative, ignoreBasenames));
}
}
return files;
}
export async function getFileSizeOnDisk(loc: string): Promise<number> {
const stat = await lstat(loc);
const {size, blksize: blockSize} = stat;
return Math.ceil(size / blockSize) * blockSize;
}
export function normalizeOS(body: string): string {
return body.replace(/\r\n/g, '\n');
}
const cr = '\r'.charCodeAt(0);
const lf = '\n'.charCodeAt(0);
async function getEolFromFile(path: string): Promise<string | void> {
if (!await exists(path)) {
return undefined;
}
const buffer = await readFileBuffer(path);
for (let i = 0; i < buffer.length; ++i) {
if (buffer[i] === cr) {
return '\r\n';
}
if (buffer[i] === lf) {
return '\n';
}
}
return undefined;
}
export async function writeFilePreservingEol(path: string, data: string): Promise<void> {
const eol = (await getEolFromFile(path)) || os.EOL;
if (eol !== '\n') {
data = data.replace(/\n/g, eol);
}
await writeFile(path, data);
}
export async function hardlinksWork(dir: string): Promise<boolean> {
const filename = 'test-file' + Math.random();
const file = path.join(dir, filename);
const fileLink = path.join(dir, filename + '-link');
try {
await writeFile(file, 'test');
await link(file, fileLink);
} catch (err) {
return false;
} finally {
await unlink(file);
await unlink(fileLink);
}
return true;
}
// not a strict polyfill for Node's fs.mkdtemp
export async function makeTempDir(prefix?: string): Promise<string> {
const dir = path.join(os.tmpdir(), `yarn-${prefix || ''}-${Date.now()}-${Math.random()}`);
await unlink(dir);
await mkdirp(dir);
return dir;
}
export async function readFirstAvailableStream(paths: Iterable<string>): Promise<?ReadStream> {
for (const path of paths) {
try {
const fd = await open(path, 'r');
return fs.createReadStream(path, {fd});
} catch (err) {
// Try the next one
}
}
return null;
}
export async function getFirstSuitableFolder(
paths: Iterable<string>,
mode: number = constants.W_OK | constants.X_OK, // eslint-disable-line no-bitwise
): Promise<FolderQueryResult> {
const result: FolderQueryResult = {
skipped: [],
folder: null,
};
for (const folder of paths) {
try {
await mkdirp(folder);
await access(folder, mode);
result.folder = folder;
return result;
} catch (error) {
result.skipped.push({
error,
folder,
});
}
}
return result;
}