-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
files.ts
1707 lines (1492 loc) · 51.8 KB
/
files.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
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///
/// utility functions for files and directories. includes both generic
/// helper functions (such as rm_recursive), and meteor-specific ones
/// (such as testing whether an directory is a meteor app)
///
import fs, { PathLike, Stats, Dirent } from "fs";
import os from "os";
import { execFile } from "child_process";
import { EventEmitter } from "events";
import { Slot } from "@wry/context";
import { dep } from "optimism";
const _ = require('underscore');
const Fiber = require("fibers");
const rimraf = require('rimraf');
const sourcemap = require('source-map');
const sourceMapRetrieverStack = require('../tool-env/source-map-retriever-stack.js');
const utils = require('../utils/utils.js');
const cleanup = require('../tool-env/cleanup.js');
const buildmessage = require('../utils/buildmessage.js');
const fiberHelpers = require('../utils/fiber-helpers.js');
const colonConverter = require('../utils/colon-converter.js');
const Profile = require('../tool-env/profile').Profile;
export * from '../static-assets/server/mini-files';
import {
convertToOSPath,
convertToPosixPath,
convertToStandardLineEndings,
convertToStandardPath,
convertToWindowsPath,
isWindowsLikeFilesystem,
pathBasename,
pathDirname,
pathJoin,
pathNormalize,
pathOsDelimiter,
pathRelative,
pathResolve,
pathSep,
} from "../static-assets/server/mini-files";
const { hasOwnProperty } = Object.prototype;
const parsedSourceMaps: Record<string, any> = {};
let nextStackFilenameCounter = 1;
// Use the source maps specified to runJavaScript
function useParsedSourceMap(pathForSourceMap: string) {
// Check our fancy source map data structure, used for isopacks
if (hasOwnProperty.call(parsedSourceMaps, pathForSourceMap)) {
return {map: parsedSourceMaps[pathForSourceMap]};
}
return null;
}
// Try this source map first
sourceMapRetrieverStack.push(useParsedSourceMap);
function canYield() {
return Fiber.current &&
Fiber.yield &&
! Fiber.yield.disallowed;
}
// given a predicate function and a starting path, traverse upwards
// from the path until we find a path that satisfies the predicate.
//
// returns either the path to the lowest level directory that passed
// the test or null for none found. if starting path isn't given, use
// cwd.
function findUpwards(
predicate: (path: string) => boolean,
startPath: string = cwd(),
): string | null {
let testDir: string | null = startPath;
while (testDir) {
if (predicate(testDir)) {
break;
}
var newDir: string = pathDirname(testDir);
if (newDir === testDir) {
testDir = null;
} else {
testDir = newDir;
}
}
return testDir || null;
}
export function cwd() {
return convertToStandardPath(process.cwd());
}
// Determine if 'filepath' (a path, or omit for cwd) is within an app
// directory. If so, return the top-level app directory.
export function findAppDir(filepath: string) {
return findUpwards(function isAppDir(filepath) {
// XXX once we are done with the transition to engine, this should
// change to: `return exists(path.join(filepath, '.meteor',
// 'release'))`
// .meteor/packages can be a directory, if .meteor is a warehouse
// directory. since installing meteor initializes a warehouse at
// $HOME/.meteor, we want to make sure your home directory (and all
// subdirectories therein) don't count as being within a meteor app.
try { // use try/catch to avoid the additional syscall to exists
return stat(
pathJoin(filepath, '.meteor', 'packages')).isFile();
} catch (e) {
return false;
}
}, filepath);
}
export function findPackageDir(filepath: string) {
return findUpwards(function isPackageDir(filepath) {
try {
return stat(pathJoin(filepath, 'package.js')).isFile();
} catch (e) {
return false;
}
}, filepath);
}
// Returns the hash of the current Git HEAD revision of the application,
// if possible. Always resolves rather than rejecting (unless something
// truly unexpected happens). The result value is a string when a Git
// revision was successfully resolved, or undefined otherwise.
export function findGitCommitHash(path: string) {
return new Promise<string|void>(resolve => {
const appDir = findAppDir(path);
if (appDir) {
execFile("git", ["rev-parse", "HEAD"], {
cwd: convertToOSPath(appDir),
}, (error: any, stdout: string) => {
if (! error && typeof stdout === "string") {
resolve(stdout.trim());
} else {
resolve();
}
});
} else {
resolve();
}
}).await();
}
// create a .gitignore file in dirPath if one doesn't exist. add
// 'entry' to the .gitignore on its own line at the bottom of the
// file, if the exact line does not already exist in the file.
export function addToGitignore(dirPath: string, entry: string) {
const filePath = pathJoin(dirPath, ".gitignore");
if (exists(filePath)) {
let data = readFile(filePath, 'utf8') as string;
const lines = data.split(/\n/);
if (lines.some(line => line === entry)) {
// already there do nothing
} else {
// rewrite file w/ new entry.
if (data.substr(-1) !== "\n") {
data = data + "\n";
}
data = data + entry + "\n";
writeFile(filePath, data, 'utf8');
}
} else {
// doesn't exist, just write it.
writeFile(filePath, entry + "\n", 'utf8');
}
}
// Are we running Meteor from a git checkout?
export const inCheckout = _.once(function () {
try {
if (exists(pathJoin(getCurrentToolsDir(), '.git'))) {
return true;
}
} catch (e) { console.log(e); }
return false;
});
// True if we are using a warehouse: either installed Meteor, or if
// $METEOR_WAREHOUSE_DIR is set. Otherwise false (we're in a git checkout and
// just using packages from the checkout).
export function usesWarehouse() {
// Test hook: act like we're "installed" using a non-homedir warehouse
// directory.
if (process.env.METEOR_WAREHOUSE_DIR) {
return true;
} else {
return ! inCheckout();
}
}
// Read the '.tools_version.txt' file. If in a checkout, throw an error.
export function getToolsVersion() {
if (! inCheckout()) {
const isopackJsonPath = pathJoin(getCurrentToolsDir(),
'..', // get out of tool, back to package
'isopack.json');
let parsed;
if (exists(isopackJsonPath)) {
// XXX "isopack-1" is duplicate of isopack.currentFormat
parsed = JSON.parse(readFile(isopackJsonPath))["isopack-1"];
return parsed.name + '@' + parsed.version;
}
// XXX COMPAT WITH 0.9.3
const unipackageJsonPath = pathJoin(
getCurrentToolsDir(),
'..', // get out of tool, back to package
'unipackage.json'
);
parsed = JSON.parse(readFile(unipackageJsonPath));
return parsed.name + '@' + parsed.version;
} else {
throw new Error("Unexpected. Git checkouts don't have tools versions.");
}
}
// Return the root of dev_bundle (probably /usr/local/meteor in an
// install, or (checkout root)/dev_bundle in a checkout.).
export function getDevBundle() {
return pathJoin(getCurrentToolsDir(), 'dev_bundle');
}
export function getCurrentNodeBinDir() {
return pathJoin(getDevBundle(), "bin");
}
// Return the top-level directory for this meteor install or checkout
export function getCurrentToolsDir() {
return pathDirname(pathDirname(convertToStandardPath(__dirname)));
}
// Read a settings file and sanity-check it. Returns a string on
// success or null on failure (in which case buildmessages will be
// emitted).
export function getSettings(
filename: string,
watchSet: import("./watch").WatchSet,
) {
buildmessage.assertInCapture();
const absPath = pathResolve(filename);
const buffer = require("./watch").readAndWatchFile(watchSet, absPath);
if (buffer === null) {
buildmessage.error("file not found (settings file)",
{ file: filename });
return null;
}
if (buffer.length > 0x10000) {
buildmessage.error("settings file is too large (must be less than 64k)",
{ file: filename });
return null;
}
let str = buffer.toString('utf8');
// The use of a byte order mark crashes JSON parsing. Since a BOM is not
// required (or recommended) when using UTF-8, let's remove it if it exists.
str = str.charCodeAt(0) === 0xFEFF ? str.slice(1) : str;
// Ensure that the string is parseable in JSON, but there's no reason to use
// the object value of it yet.
if (str.match(/\S/)) {
try {
JSON.parse(str);
} catch (e) {
buildmessage.error("parse error reading settings file",
{ file: filename });
}
}
return str;
}
// Returns true if the first path is a parent of the second path
export function containsPath(path1: string, path2: string) {
const relPath = pathRelative(path1, path2);
// On Windows, if the two paths are on different drives the relative
// path starts with /
return !(relPath.startsWith("..") || relPath.startsWith("/"));
}
// Try to find the prettiest way to present a path to the
// user. Presently, the main thing it does is replace $HOME with ~.
export function prettyPath(p: string) {
p = realpath(p);
const home = getHomeDir();
if (! home) {
return p;
}
const relativeToHome = pathRelative(home, p);
if (relativeToHome.substr(0, 3) === ('..' + pathSep)) {
return p;
}
return pathJoin('~', relativeToHome);
}
// Like statSync, but null if file not found
export function statOrNull(path: string) {
return statOrNullHelper(path, false);
}
function statOrNullHelper(path: string, preserveSymlinks = false) {
try {
return preserveSymlinks
? lstat(path)
: stat(path);
} catch (e: any) {
if (e.code === "ENOENT") {
return null;
}
throw e;
}
}
export function realpathOrNull(path: string) {
try {
return realpath(path);
} catch (e: any) {
if (e.code !== "ENOENT") throw e;
return null;
}
}
export function rm_recursive_async(path: string) {
return new Promise<void>((resolve, reject) => {
rimraf(convertToOSPath(path), (err: Error) => err
? reject(err)
: resolve());
});
}
// Like rm -r.
export const rm_recursive = Profile("files.rm_recursive", (path: string) => {
try {
rimraf.sync(convertToOSPath(path));
} catch (e: any) {
if ((e.code === "ENOTEMPTY" ||
e.code === "EPERM") &&
canYield()) {
rm_recursive_async(path).await();
return;
}
throw e;
}
});
// Returns the base64 SHA256 of the given file.
export function fileHash(filename: string) {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.setEncoding('base64');
const rs = createReadStream(filename);
return new Promise(function (resolve) {
rs.on('end', function () {
rs.close();
resolve(hash.digest('base64'));
});
rs.pipe(hash, { end: false });
}).await();
}
// This is the result of running fileHash on a blank file.
export const blankHash = "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";
// Returns a base64 SHA256 hash representing a tree on disk. It is not sensitive
// to modtime, uid/gid, or any permissions bits other than the current-user-exec
// bit on normal files.
export function treeHash(root: string, optionsParams: {
ignore?: (path: string) => boolean;
}) {
const options = {
ignore() { return false; },
...optionsParams,
};
const hash = require('crypto').createHash('sha256');
function traverse(relativePath: string) {
if (options.ignore(relativePath)) {
return;
}
var absPath = pathJoin(root, relativePath);
var stat = lstat(absPath);
if (stat?.isDirectory()) {
if (relativePath) {
hash.update('dir ' + JSON.stringify(relativePath) + '\n');
}
readdir(absPath).forEach(entry => {
traverse(pathJoin(relativePath, entry));
});
} else if (stat?.isFile()) {
if (!relativePath) {
throw Error("must call files.treeHash on a directory");
}
hash.update('file ' + JSON.stringify(relativePath) + ' ' +
stat?.size + ' ' + fileHash(absPath) + '\n');
// @ts-ignore
if (stat.mode & 0o100) {
hash.update('exec\n');
}
} else if (stat?.isSymbolicLink()) {
if (!relativePath) {
throw Error("must call files.treeHash on a directory");
}
hash.update('symlink ' + JSON.stringify(relativePath) + ' ' +
JSON.stringify(readlink(absPath)) + '\n');
}
// ignore anything weirder
}
traverse('');
return hash.digest('base64');
}
// like mkdir -p. if it returns true, the item is a directory (even if
// it was already created). if it returns false, the item is not a
// directory and we couldn't make it one.
export function mkdir_p(dir: string, mode: number | null = null) {
const p = pathResolve(dir);
const ps = pathNormalize(p).split(pathSep);
const stat = statOrNull(p);
if (stat) {
return stat.isDirectory();
}
// doesn't exist. recurse to build parent.
// Don't use pathJoin here because it can strip off the leading slash
// accidentally.
const parentPath = ps.slice(0, -1).join(pathSep);
const success = mkdir_p(parentPath, mode);
// parent is not a directory.
if (! success) { return false; }
try {
mkdir(p, mode);
} catch (err: any) {
if (err.code === "EEXIST") {
if (pathIsDirectory(p)) {
// all good, someone else created this directory for us while we were
// yielding
return true;
} else {
return false;
}
} else {
throw err;
}
}
// double check we exist now
return pathIsDirectory(p);
}
function pathIsDirectory(path: string) {
const stat = statOrNull(path);
return stat && stat.isDirectory();
}
// Roughly like cp -R.
//
// The output files will be readable and writable by everyone that the umask
// allows, and executable by everyone (modulo umask) if the original file was
// owner-executable. Symlinks are treated transparently (ie the contents behind
// them are copied, and it's an error if that points nowhere).
//
// If options.transform{Filename, Contents} is present, it should
// be a function, and the contents (as a buffer) or filename will be
// passed through the function. Use this to, eg, fill templates.
//
// If options.ignore is present, it should be a list of regexps. Any
// file whose basename matches one of the regexps, before
// transformation, will be skipped.
export function cp_r(from: string, to: string, options: {
preserveSymlinks?: boolean;
ignore?: RegExp[];
transformFilename?: (f: string) => string;
transformContents?: (
contents: ReturnType<typeof readFile>,
file: string,
) => typeof contents;
} = {}) {
from = pathResolve(from);
const stat = statOrNullHelper(from, options.preserveSymlinks);
if (! stat) {
return;
}
if (stat.isDirectory()) {
mkdir_p(to, 0o755);
readdir(from).forEach(f => {
if (options.ignore &&
options.ignore.some(pattern => f.match(pattern))) {
return;
}
const fullFrom = pathJoin(from, f);
if (options.transformFilename) {
f = options.transformFilename(f);
}
cp_r(
fullFrom,
pathJoin(to, f),
options
);
})
return;
}
mkdir_p(pathDirname(to));
if (stat.isSymbolicLink()) {
symlinkWithOverwrite(readlink(from), to);
} else if (options.transformContents) {
writeFile(to, options.transformContents(
readFile(from),
pathBasename(from)
), {
// Create the file as readable and writable by everyone, and
// executable by everyone if the original file is executable by
// owner. (This mode will be modified by umask.) We don't copy the
// mode *directly* because this function is used by 'meteor create'
// which is copying from the read-only tools tree into a writable app.
// @ts-ignore
mode: (stat.mode & 0o100) ? 0o777 : 0o666,
});
} else {
// Note: files.copyFile applies the same stat.mode logic as above.
copyFile(from, to);
}
}
// create a symlink, overwriting the target link, file, or directory
// if it exists
export const symlinkWithOverwrite =
Profile("files.symlinkWithOverwrite", function symlinkWithOverwrite(
source: string,
target: string,
) {
const args: [string, string, "junction"?] = [source, target];
if (process.platform === "win32") {
const absoluteSource = pathResolve(target, source);
if (stat(absoluteSource).isDirectory()) {
args[2] = "junction";
}
}
try {
symlink(...args);
} catch (e: any) {
if (e.code === "EEXIST") {
function normalizePath(path: string) {
return convertToOSPath(path).replace(/[\/\\]$/, "")
}
if (lstat(target)?.isSymbolicLink() &&
normalizePath(readlink(target)) === normalizePath(source)) {
// If the target already points to the desired source, we don't
// need to do anything.
return;
}
// overwrite existing link, file, or directory
rm_recursive(target);
symlink(...args);
} else {
throw e;
}
}
})
/**
* Get every path in a directory recursively, treating symlinks as files
* @param {String} dir The directory to walk, either relative to options.cwd or completely absolute
* @param {Object} options Some options
* @param {String} options.cwd The directory that paths should be relative to
* @param {String[]} options.output An array to push results to
* @return {String[]} All of the paths in the directory recursively
*/
export function getPathsInDir(dir: string, options: {
cwd?: string;
output?: string[];
}) {
// Don't let this function yield so that the file system doesn't get changed
// underneath us
return fiberHelpers.noYieldsAllowed(function () {
var cwd = options.cwd || convertToStandardPath(process.cwd());
if (! exists(cwd)) {
throw new Error("Specified current working directory doesn't exist: " +
cwd);
}
const absoluteDir = pathResolve(cwd, dir);
if (! exists(absoluteDir)) {
// There are no paths in this dir, so don't do anything
return;
}
const output = options.output || [];
function pathIsDirectory(path: string) {
var stat = lstat(path);
return stat?.isDirectory() || false;
}
readdir(absoluteDir).forEach(entry => {
const newPath = pathJoin(dir, entry);
const newAbsPath = pathJoin(absoluteDir, entry);
output.push(newPath);
if (pathIsDirectory(newAbsPath)) {
getPathsInDir(newPath, {
cwd: cwd,
output: output
});
}
});
return output;
});
}
export function findPathsWithRegex(
dir: string,
regex: RegExp,
options: {
cwd: string;
},
) {
return getPathsInDir(dir, {
cwd: options.cwd
}).filter(function (path: string) {
return path.match(regex);
});
}
// Make a temporary directory. Returns the path to the newly created
// directory. Only the current user is allowed to read or write the
// files in the directory (or add files to it). The directory will
// be cleaned up on exit.
const tempDirs = Object.create(null);
export function mkdtemp(prefix: string): string {
function make(): string {
prefix = prefix || 'mt-';
// find /tmp
let tmpDir: string | undefined;
['TMPDIR', 'TMP', 'TEMP'].some(t => {
const value = process.env[t];
if (value) {
tmpDir = value;
return true;
}
});
if (! tmpDir && process.platform !== 'win32') {
tmpDir = '/tmp';
}
if (! tmpDir) {
throw new Error("Couldn't create a temporary directory.");
}
tmpDir = realpath(tmpDir);
// make the directory. give it 3 tries in case of collisions from
// crappy random.
var tries = 3;
while (tries > 0) {
const dirPath = pathJoin(
tmpDir,
prefix + (Math.random() * 0x100000000 + 1).toString(36),
);
try {
mkdir(dirPath, 0o700);
return dirPath;
} catch (err) {
tries--;
}
}
throw new Error("failed to make temporary directory in " + tmpDir);
};
const dir = make();
tempDirs[dir] = true;
return dir;
}
// Call this if you're done using a temporary directory. It will asynchronously
// be deleted.
export function freeTempDir(dir: string) {
if (! tempDirs[dir]) {
throw Error("not a tracked temp dir: " + dir);
}
if (process.env.METEOR_SAVE_TMPDIRS) {
return;
}
return rm_recursive_async(dir).then(() => {
// Delete tempDirs[dir] only when the removal finishes, so that the
// cleanup.onExit handler can attempt the removal synchronously if it
// fires in the meantime.
delete tempDirs[dir];
}, error => {
// Leave tempDirs[dir] in place so the cleanup.onExit handler can try
// to delete it again when the process exits.
console.log(error);
});
}
// Change the status of a dir
export function changeTempDirStatus(dir: string, status: boolean) {
if (! tempDirs[dir]) {
throw Error("not a tracked temp dir: " + dir);
}
tempDirs[dir] = status;
}
if (! process.env.METEOR_SAVE_TMPDIRS) {
cleanup.onExit(function () {
Object.entries(tempDirs).filter(([_, isTmp]) => !!isTmp).map(([dir]) => dir).forEach(dir => {
delete tempDirs[dir];
try {
rm_recursive(dir);
} catch (err) {
// Don't crash and print a stack trace because we failed to delete
// a temp directory. This happens sometimes on Windows and seems
// to be unavoidable.
}
});
});
}
type TarOptions = {
verbose?: boolean;
forceConvert?: boolean;
}
// Takes a buffer containing `.tar.gz` data and extracts the archive
// into a destination directory. destPath should not exist yet, and
// the archive should contain a single top-level directory, which will
// be renamed atomically to destPath.
export function extractTarGz(
buffer: Buffer,
destPath: string,
options: TarOptions = {},
) {
const parentDir = pathDirname(destPath);
const tempDir = pathJoin(parentDir, '.tmp' + utils.randomToken());
mkdir_p(tempDir);
if (! hasOwnProperty.call(options, "verbose")) {
options.verbose = require("../console/console.js").Console.verbose;
}
const startTime = +new Date;
// standardize only one way of extracting, as native ones can be tricky
const promise = tryExtractWithNpmTar(buffer, tempDir, options)
promise.await();
// succeed!
const topLevelOfArchive = readdir(tempDir)
// On Windows, the 7z.exe tool sometimes creates an auxiliary
// PaxHeader directory.
.filter(file => ! file.startsWith("PaxHeader"));
if (topLevelOfArchive.length !== 1) {
throw new Error(
"Extracted archive '" + tempDir + "' should only contain one entry");
}
const extractDir = pathJoin(tempDir, topLevelOfArchive[0]);
rename(extractDir, destPath);
rm_recursive(tempDir);
if (options.verbose) {
console.log("Finished extracting in", Date.now() - startTime, "ms");
}
}
function ensureDirectoryEmpty(dir: string) {
readdir(dir).forEach(file => {
rm_recursive(pathJoin(dir, file));
});
}
function tryExtractWithNpmTar(
buffer: Buffer,
tempDir: string,
options: TarOptions = {},
) {
ensureDirectoryEmpty(tempDir);
const tar = require("tar-fs");
const zlib = require("zlib");
return new Promise((resolve, reject) => {
const gunzip = zlib.createGunzip().on('error', reject);
const extractor = tar.extract(convertToOSPath(tempDir), {
/* the following lines guarantees that archives created on windows
are going to be readable and writable on unixes */
readable: true, // all dirs and files should be readable
writable: true, // all dirs and files should be writable
map: function(header: any) {
if (process.platform === "win32" || options.forceConvert) {
// On Windows, try to convert old packages that have colons in
// paths by blindly replacing all of the paths. Otherwise, we
// can't even extract the tarball
header.name = colonConverter.convert(header.name);
}
return header
}
}).on('error', reject)
.on('finish', resolve);
// write the buffer to the (gunzip|untar) pipeline; these calls
// cause the tar to be extracted to disk.
gunzip.pipe(extractor);
gunzip.write(buffer);
gunzip.end();
});
}
// In the same fashion as node-pre-gyp does, add the executable
// bit but only if the read bit was present. Same as:
// https://github.com/mapbox/node-pre-gyp/blob/7a28f4b0f562ba4712722fefe4eeffb7b20fbf7a/lib/install.js#L71-L77
// and others reported in: https://github.com/npm/node-tar/issues/7
function addExecBitWhenReadBitPresent(fileMode: number) {
return fileMode |= (fileMode >>> 2) & 0o111;
}
// Tar-gzips a directory, returning a stream that can then be piped as
// needed. The tar archive will contain a top-level directory named
// after dirPath.
export function createTarGzStream(dirPath: string) {
const tar = require("tar-fs");
const zlib = require("zlib");
const basename = pathBasename(dirPath);
// Create a segment of the file path which we will look for to
// identify exactly what we think is a "bin" file (that is, something
// which should be expected to work within the context of an
// 'npm run-script').
// tar-fs doesn't use native paths in the header, so we are joining with a slash
const binPathMatch = ["", "node_modules", ".bin", ""].join('/');
const tarStream = tar.pack(convertToOSPath(dirPath), {
map: (header: any) => {
header.name = `${basename}/${header.name}`
if (process.platform !== "win32") {
return header;
}
if (header.type === "directory") {
header.mode = addExecBitWhenReadBitPresent(header.mode);
}
if (header.type === "file" && header.name.includes(binPathMatch)) {
header.mode = addExecBitWhenReadBitPresent(header.mode);
}
return header
},
readable: true, // all dirs and files should be readable
writable: true, // all dirs and files should be writable
});
return tarStream.pipe(zlib.createGzip());
}
// Tar-gzips a directory into a tarball on disk, synchronously.
// The tar archive will contain a top-level directory named after dirPath.
export const createTarball = Profile(function (_: string, tarball: string) {
return "files.createTarball " + pathBasename(tarball);
}, function (dirPath: string, tarball: string) {
const out = createWriteStream(tarball);
new Promise(function (resolve, reject) {
out.on('error', reject);
out.on('close', resolve);
createTarGzStream(dirPath).pipe(out);
}).await();
});
// Use this if you'd like to replace a directory with another
// directory as close to atomically as possible. It's better than
// recursively deleting the target directory first and then
// renaming. (Failure modes here include "there's a brief moment where
// toDir does not exist" and "you can end up with garbage directories
// sitting around", but not "there's any time where toDir exists but
// is in a state other than initial or final".)
export const renameDirAlmostAtomically =
Profile("files.renameDirAlmostAtomically", (fromDir: string, toDir: string) => {
const garbageDir = pathJoin(
pathDirname(toDir),
// Begin the base filename with a '.' character so that it can be
// ignored by other directory-scanning code.
`.${pathBasename(toDir)}-garbage-${utils.randomToken()}`,
);
// Get old dir out of the way, if it exists.
let cleanupGarbage = false;
let forceCopy = false;
try {
rename(toDir, garbageDir);
cleanupGarbage = true;
} catch (e: any) {
if (e.code === 'EXDEV') {
// Some (notably Docker) file systems will fail to do a seemingly
// harmless operation, such as renaming, on what is apparently the same
// file system. AUFS will do this even if the `fromDir` and `toDir`
// are on the same layer, and OverlayFS will fail if the `fromDir` and
// `toDir` are on different layers. In these cases, we will not be
// atomic and will need to do a recursive copy.
forceCopy = true;
} else if (e.code !== 'ENOENT') {
// No such file or directory is okay, but anything else is not.
throw e;
}
}
if (! forceCopy) {
try {
rename(fromDir, toDir);
} catch (e: any) {
// It's possible that there may not have been a `toDir` to have
// advanced warning about this, so we're prepared to handle it again.
if (e.code === 'EXDEV') {
forceCopy = true;
} else {
throw e;
}
}
}
// If we've been forced to jeopardize our atomicity due to file-system
// limitations, we'll resort to copying.
if (forceCopy) {
rm_recursive(toDir);
cp_r(fromDir, toDir, {
preserveSymlinks: true,
});
}
// ... and take out the trash.
if (cleanupGarbage) {
// We don't care about how long this takes, so we'll let it go async.
rm_recursive_async(garbageDir);
}
});
export const writeFileAtomically =
Profile("files.writeFileAtomically", function (filename: string, contents: string | Buffer) {
const parentDir = pathDirname(filename);
mkdir_p(parentDir);
const tmpFile = pathJoin(
parentDir,
'.' + pathBasename(filename) + '.' + utils.randomToken()
);
writeFile(tmpFile, contents);
rename(tmpFile, filename);
});
// Like fs.symlinkSync, but creates a temporary link and renames it over the
// file; this means it works even if the file already exists.
// Do not use this function on Windows, it won't work.
export function symlinkOverSync(linkText: string, file: string) {
file = pathResolve(file);