Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
unpack.js916 linesDownload Raw Back to esm
1// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet.
2// but the path reservations are required to avoid race conditions where
3// parallelized unpack ops may mess with one another, due to dependencies
4// (like a Link depending on its target) or destructive operations (like
5// clobbering an fs object to create one of a different type.)
6import * as fsm from '@isaacs/fs-minipass';
7import assert from 'node:assert';
8import { randomBytes } from 'node:crypto';
9import fs from 'node:fs';
10import path from 'node:path';
11import { getWriteFlag } from './get-write-flag.js';
12import { mkdir, mkdirSync } from './mkdir.js';
13import { normalizeWindowsPath } from './normalize-windows-path.js';
14import { Parser } from './parse.js';
15import { stripAbsolutePath } from './strip-absolute-path.js';
16import * as wc from './winchars.js';
17import { PathReservations } from './path-reservations.js';
18import { SymlinkError } from './symlink-error.js';
19import { umask } from './process-umask.js';
20const ONENTRY = Symbol('onEntry');
21const CHECKFS = Symbol('checkFs');
22const CHECKFS2 = Symbol('checkFs2');
23const ISREUSABLE = Symbol('isReusable');
24const MAKEFS = Symbol('makeFs');
25const FILE = Symbol('file');
26const DIRECTORY = Symbol('directory');
27const LINK = Symbol('link');
28const SYMLINK = Symbol('symlink');
29const HARDLINK = Symbol('hardlink');
30const ENSURE_NO_SYMLINK = Symbol('ensureNoSymlink');
31const UNSUPPORTED = Symbol('unsupported');
32const CHECKPATH = Symbol('checkPath');
33const STRIPABSOLUTEPATH = Symbol('stripAbsolutePath');
34const MKDIR = Symbol('mkdir');
35const ONERROR = Symbol('onError');
36const PENDING = Symbol('pending');
37const PEND = Symbol('pend');
38const UNPEND = Symbol('unpend');
39const ENDED = Symbol('ended');
40const MAYBECLOSE = Symbol('maybeClose');
41const SKIP = Symbol('skip');
42const DOCHOWN = Symbol('doChown');
43const UID = Symbol('uid');
44const GID = Symbol('gid');
45const CHECKED_CWD = Symbol('checkedCwd');
46const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
47const isWindows = platform === 'win32';
48const DEFAULT_MAX_DEPTH = 1024;
49// Unlinks on Windows are not atomic.
50//
51// This means that if you have a file entry, followed by another
52// file entry with an identical name, and you cannot re-use the file
53// (because it's a hardlink, or because unlink:true is set, or it's
54// Windows, which does not have useful nlink values), then the unlink
55// will be committed to the disk AFTER the new file has been written
56// over the old one, deleting the new file.
57//
58// To work around this, on Windows systems, we rename the file and then
59// delete the renamed file.  It's a sloppy kludge, but frankly, I do not
60// know of a better way to do this, given windows' non-atomic unlink
61// semantics.
62//
63// See: https://github.com/npm/node-tar/issues/183
64/* c8 ignore start */
65const unlinkFile = (path, cb) => {
66    if (!isWindows) {
67        return fs.unlink(path, cb);
68    }
69    const name = path + '.DELETE.' + randomBytes(16).toString('hex');
70    fs.rename(path, name, er => {
71        if (er) {
72            return cb(er);
73        }
74        fs.unlink(name, cb);
75    });
76};
77/* c8 ignore stop */
78/* c8 ignore start */
79const unlinkFileSync = (path) => {
80    if (!isWindows) {
81        return fs.unlinkSync(path);
82    }
83    const name = path + '.DELETE.' + randomBytes(16).toString('hex');
84    fs.renameSync(path, name);
85    fs.unlinkSync(name);
86};
87/* c8 ignore stop */
88// this.gid, entry.gid, this.processUid
89const uint32 = (a, b, c) => a !== undefined && a === a >>> 0 ? a
90    : b !== undefined && b === b >>> 0 ? b
91        : c;
92export class Unpack extends Parser {
93    [ENDED] = false;
94    [CHECKED_CWD] = false;
95    [PENDING] = 0;
96    reservations = new PathReservations();
97    transform;
98    writable = true;
99    readable = false;
100    uid;
101    gid;
102    setOwner;
103    preserveOwner;
104    processGid;
105    processUid;
106    maxDepth;
107    forceChown;
108    win32;
109    newer;
110    keep;
111    noMtime;
112    preservePaths;
113    unlink;
114    cwd;
115    strip;
116    processUmask;
117    umask;
118    dmode;
119    fmode;
120    chmod;
121    constructor(opt = {}) {
122        opt.ondone = () => {
123            this[ENDED] = true;
124            this[MAYBECLOSE]();
125        };
126        super(opt);
127        this.transform = opt.transform;
128        this.chmod = !!opt.chmod;
129        if (typeof opt.uid === 'number' || typeof opt.gid === 'number') {
130            // need both or neither
131            if (typeof opt.uid !== 'number' ||
132                typeof opt.gid !== 'number') {
133                throw new TypeError('cannot set owner without number uid and gid');
134            }
135            if (opt.preserveOwner) {
136                throw new TypeError('cannot preserve owner in archive and also set owner explicitly');
137            }
138            this.uid = opt.uid;
139            this.gid = opt.gid;
140            this.setOwner = true;
141        }
142        else {
143            this.uid = undefined;
144            this.gid = undefined;
145            this.setOwner = false;
146        }
147        // default true for root
148        if (opt.preserveOwner === undefined &&
149            typeof opt.uid !== 'number') {
150            this.preserveOwner = !!(process.getuid && process.getuid() === 0);
151        }
152        else {
153            this.preserveOwner = !!opt.preserveOwner;
154        }
155        this.processUid =
156            (this.preserveOwner || this.setOwner) && process.getuid ?
157                process.getuid()
158                : undefined;
159        this.processGid =
160            (this.preserveOwner || this.setOwner) && process.getgid ?
161                process.getgid()
162                : undefined;
163        // prevent excessively deep nesting of subfolders
164        // set to `Infinity` to remove this restriction
165        this.maxDepth =
166            typeof opt.maxDepth === 'number' ?
167                opt.maxDepth
168                : DEFAULT_MAX_DEPTH;
169        // mostly just for testing, but useful in some cases.
170        // Forcibly trigger a chown on every entry, no matter what
171        this.forceChown = opt.forceChown === true;
172        // turn ><?| in filenames into 0xf000-higher encoded forms
173        this.win32 = !!opt.win32 || isWindows;
174        // do not unpack over files that are newer than what's in the archive
175        this.newer = !!opt.newer;
176        // do not unpack over ANY files
177        this.keep = !!opt.keep;
178        // do not set mtime/atime of extracted entries
179        this.noMtime = !!opt.noMtime;
180        // allow .., absolute path entries, and unpacking through symlinks
181        // without this, warn and skip .., relativize absolutes, and error
182        // on symlinks in extraction path
183        this.preservePaths = !!opt.preservePaths;
184        // unlink files and links before writing. This breaks existing hard
185        // links, and removes symlink directories rather than erroring
186        this.unlink = !!opt.unlink;
187        this.cwd = normalizeWindowsPath(path.resolve(opt.cwd || process.cwd()));
188        this.strip = Number(opt.strip) || 0;
189        // if we're not chmodding, then we don't need the process umask
190        this.processUmask =
191            !this.chmod ? 0
192                : typeof opt.processUmask === 'number' ? opt.processUmask
193                    : umask();
194        this.umask =
195            typeof opt.umask === 'number' ? opt.umask : this.processUmask;
196        // default mode for dirs created as parents
197        this.dmode = opt.dmode || 0o0777 & ~this.umask;
198        this.fmode = opt.fmode || 0o0666 & ~this.umask;
199        this.on('entry', entry => this[ONENTRY](entry));
200    }
201    // a bad or damaged archive is a warning for Parser, but an error
202    // when extracting.  Mark those errors as unrecoverable, because
203    // the Unpack contract cannot be met.
204    warn(code, msg, data = {}) {
205        if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') {
206            data.recoverable = false;
207        }
208        return super.warn(code, msg, data);
209    }
210    [MAYBECLOSE]() {
211        if (this[ENDED] && this[PENDING] === 0) {
212            this.emit('prefinish');
213            this.emit('finish');
214            this.emit('end');
215        }
216    }
217    // return false if we need to skip this file
218    // return true if the field was successfully sanitized
219    [STRIPABSOLUTEPATH](entry, field) {
220        const p = entry[field];
221        const { type } = entry;
222        if (!p || this.preservePaths)
223            return true;
224        // strip off the root
225        const [root, stripped] = stripAbsolutePath(p);
226        const parts = stripped.replace(/\\/g, '/').split('/');
227        if (parts.includes('..') ||
228            /* c8 ignore next */
229            (isWindows && /^[a-z]:\.\.$/i.test(parts[0] ?? ''))) {
230            // For linkpath, check if the resolved path escapes cwd rather than
231            // just rejecting any path with '..' - relative symlinks like
232            // '../sibling/file' are valid if they resolve within the cwd.
233            // For paths, they just simply may not ever use .. at all.
234            if (field === 'path' || type === 'Link') {
235                this.warn('TAR_ENTRY_ERROR', `${field} contains '..'`, {
236                    entry,
237                    [field]: p,
238                });
239                // not ok!
240                return false;
241            }
242            else {
243                // Resolve linkpath relative to the entry's directory.
244                // `path.posix` is safe to use because we're operating on
245                // tar paths, not a filesystem.
246                const entryDir = path.posix.dirname(entry.path);
247                const resolved = path.posix.normalize(path.posix.join(entryDir, parts.join('/')));
248                // If the resolved path escapes (starts with ..), reject it
249                if (resolved.startsWith('../') || resolved === '..') {
250                    this.warn('TAR_ENTRY_ERROR', `${field} escapes extraction directory`, {
251                        entry,
252                        [field]: p,
253                    });
254                    return false;
255                }
256            }
257        }
258        if (root) {
259            // ok, but triggers warning about stripping root
260            entry[field] = String(stripped);
261            this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute ${field}`, {
262                entry,
263                [field]: p,
264            });
265        }
266        return true;
267    }
268    // no IO, just string checking for absolute indicators
269    [CHECKPATH](entry) {
270        const p = normalizeWindowsPath(entry.path);
271        const parts = p.split('/');
272        if (this.strip) {
273            if (parts.length < this.strip) {
274                return false;
275            }
276            if (entry.type === 'Link') {
277                const linkparts = normalizeWindowsPath(String(entry.linkpath)).split('/');
278                if (linkparts.length >= this.strip) {
279                    entry.linkpath = linkparts.slice(this.strip).join('/');
280                }
281                else {
282                    return false;
283                }
284            }
285            parts.splice(0, this.strip);
286            entry.path = parts.join('/');
287        }
288        if (isFinite(this.maxDepth) && parts.length > this.maxDepth) {
289            this.warn('TAR_ENTRY_ERROR', 'path excessively deep', {
290                entry,
291                path: p,
292                depth: parts.length,
293                maxDepth: this.maxDepth,
294            });
295            return false;
296        }
297        if (!this[STRIPABSOLUTEPATH](entry, 'path') ||
298            !this[STRIPABSOLUTEPATH](entry, 'linkpath')) {
299            return false;
300        }
301        if (path.isAbsolute(entry.path)) {
302            entry.absolute = normalizeWindowsPath(path.resolve(entry.path));
303        }
304        else {
305            entry.absolute = normalizeWindowsPath(path.resolve(this.cwd, entry.path));
306        }
307        // if we somehow ended up with a path that escapes the cwd, and we are
308        // not in preservePaths mode, then something is fishy!  This should have
309        // been prevented above, so ignore this for coverage.
310        /* c8 ignore start - defense in depth */
311        if (!this.preservePaths &&
312            typeof entry.absolute === 'string' &&
313            entry.absolute.indexOf(this.cwd + '/') !== 0 &&
314            entry.absolute !== this.cwd) {
315            this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', {
316                entry,
317                path: normalizeWindowsPath(entry.path),
318                resolvedPath: entry.absolute,
319                cwd: this.cwd,
320            });
321            return false;
322        }
323        /* c8 ignore stop */
324        // an archive can set properties on the extraction directory, but it
325        // may not replace the cwd with a different kind of thing entirely.
326        if (entry.absolute === this.cwd &&
327            entry.type !== 'Directory' &&
328            entry.type !== 'GNUDumpDir') {
329            return false;
330        }
331        // only encode : chars that aren't drive letter indicators
332        if (this.win32) {
333            const { root: aRoot } = path.win32.parse(String(entry.absolute));
334            entry.absolute =
335                aRoot + wc.encode(String(entry.absolute).slice(aRoot.length));
336            const { root: pRoot } = path.win32.parse(entry.path);
337            entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length));
338        }
339        return true;
340    }
341    [ONENTRY](entry) {
342        if (!this[CHECKPATH](entry)) {
343            return entry.resume();
344        }
345        assert.equal(typeof entry.absolute, 'string');
346        switch (entry.type) {
347            case 'Directory':
348            case 'GNUDumpDir':
349                if (entry.mode) {
350                    entry.mode = entry.mode | 0o700;
351                }
352            // eslint-disable-next-line no-fallthrough
353            case 'File':
354            case 'OldFile':
355            case 'ContiguousFile':
356            case 'Link':
357            case 'SymbolicLink':
358                return this[CHECKFS](entry);
359            case 'CharacterDevice':
360            case 'BlockDevice':
361            case 'FIFO':
362            default:
363                return this[UNSUPPORTED](entry);
364        }
365    }
366    [ONERROR](er, entry) {
367        // Cwd has to exist, or else nothing works. That's serious.
368        // Other errors are warnings, which raise the error in strict
369        // mode, but otherwise continue on.
370        if (er.name === 'CwdError') {
371            this.emit('error', er);
372        }
373        else {
374            this.warn('TAR_ENTRY_ERROR', er, { entry });
375            this[UNPEND]();
376            entry.resume();
377        }
378    }
379    [MKDIR](dir, mode, cb) {
380        mkdir(normalizeWindowsPath(dir), {
381            uid: this.uid,
382            gid: this.gid,
383            processUid: this.processUid,
384            processGid: this.processGid,
385            umask: this.processUmask,
386            preserve: this.preservePaths,
387            unlink: this.unlink,
388            cwd: this.cwd,
389            mode: mode,
390        }, cb);
391    }
392    [DOCHOWN](entry) {
393        // in preserve owner mode, chown if the entry doesn't match process
394        // in set owner mode, chown if setting doesn't match process
395        return (this.forceChown ||
396            (this.preserveOwner &&
397                ((typeof entry.uid === 'number' &&
398                    entry.uid !== this.processUid) ||
399                    (typeof entry.gid === 'number' &&
400                        entry.gid !== this.processGid))) ||
401            (typeof this.uid === 'number' &&
402                this.uid !== this.processUid) ||
403            (typeof this.gid === 'number' && this.gid !== this.processGid));
404    }
405    [UID](entry) {
406        return uint32(this.uid, entry.uid, this.processUid);
407    }
408    [GID](entry) {
409        return uint32(this.gid, entry.gid, this.processGid);
410    }
411    [FILE](entry, fullyDone) {
412        const mode = typeof entry.mode === 'number' ?
413            entry.mode & 0o7777
414            : this.fmode;
415        const stream = new fsm.WriteStream(String(entry.absolute), {
416            // slight lie, but it can be numeric flags
417            flags: getWriteFlag(entry.size),
418            mode: mode,
419            autoClose: false,
420        });
421        stream.on('error', (er) => {
422            if (stream.fd) {
423                fs.close(stream.fd, () => { });
424            }
425            // flush all the data out so that we aren't left hanging
426            // if the error wasn't actually fatal.  otherwise the parse
427            // is blocked, and we never proceed.
428            stream.write = () => true;
429            this[ONERROR](er, entry);
430            fullyDone();
431        });
432        let actions = 1;
433        const done = (er) => {
434            if (er) {
435                /* c8 ignore start - we should always have a fd by now */
436                if (stream.fd) {
437                    fs.close(stream.fd, () => { });
438                }
439                /* c8 ignore stop */
440                this[ONERROR](er, entry);
441                fullyDone();
442                return;
443            }
444            if (--actions === 0) {
445                if (stream.fd !== undefined) {
446                    fs.close(stream.fd, er => {
447                        if (er) {
448                            this[ONERROR](er, entry);
449                        }
450                        else {
451                            this[UNPEND]();
452                        }
453                        fullyDone();
454                    });
455                }
456            }
457        };
458        stream.on('finish', () => {
459            // if futimes fails, try utimes
460            // if utimes fails, fail with the original error
461            // same for fchown/chown
462            const abs = String(entry.absolute);
463            const fd = stream.fd;
464            if (typeof fd === 'number' && entry.mtime && !this.noMtime) {
465                actions++;
466                const atime = entry.atime || new Date();
467                const mtime = entry.mtime;
468                fs.futimes(fd, atime, mtime, er => er ?
469                    fs.utimes(abs, atime, mtime, er2 => done(er2 && er))
470                    : done());
471            }
472            if (typeof fd === 'number' && this[DOCHOWN](entry)) {
473                actions++;
474                const uid = this[UID](entry);
475                const gid = this[GID](entry);
476                if (typeof uid === 'number' && typeof gid === 'number') {
477                    fs.fchown(fd, uid, gid, er => er ?
478                        fs.chown(abs, uid, gid, er2 => done(er2 && er))
479                        : done());
480                }
481            }
482            done();
483        });
484        const tx = this.transform ? this.transform(entry) || entry : entry;
485        if (tx !== entry) {
486            tx.on('error', (er) => {
487                this[ONERROR](er, entry);
488                fullyDone();
489            });
490            entry.pipe(tx);
491        }
492        tx.pipe(stream);
493    }
494    [DIRECTORY](entry, fullyDone) {
495        const mode = typeof entry.mode === 'number' ?
496            entry.mode & 0o7777
497            : this.dmode;
498        this[MKDIR](String(entry.absolute), mode, er => {
499            if (er) {
500                this[ONERROR](er, entry);
501                fullyDone();
502                return;
503            }
504            let actions = 1;
505            const done = () => {
506                if (--actions === 0) {
507                    fullyDone();
508                    this[UNPEND]();
509                    entry.resume();
510                }
511            };
512            if (entry.mtime && !this.noMtime) {
513                actions++;
514                fs.utimes(String(entry.absolute), entry.atime || new Date(), entry.mtime, done);
515            }
516            if (this[DOCHOWN](entry)) {
517                actions++;
518                fs.chown(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)), done);
519            }
520            done();
521        });
522    }
523    [UNSUPPORTED](entry) {
524        entry.unsupported = true;
525        this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry });
526        entry.resume();
527    }
528    [SYMLINK](entry, done) {
529        const parts = normalizeWindowsPath(path.relative(this.cwd, path.resolve(path.dirname(String(entry.absolute)), String(entry.linkpath)))).split('/');
530        this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, String(entry.linkpath), 'symlink', done), er => {
531            this[ONERROR](er, entry);
532            done();
533        });
534    }
535    [HARDLINK](entry, done) {
536        const linkpath = normalizeWindowsPath(path.resolve(this.cwd, String(entry.linkpath)));
537        const parts = normalizeWindowsPath(String(entry.linkpath)).split('/');
538        this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, linkpath, 'link', done), er => {
539            this[ONERROR](er, entry);
540            done();
541        });
542    }
543    [ENSURE_NO_SYMLINK](entry, cwd, parts, done, onError) {
544        const p = parts.shift();
545        if (this.preservePaths || p === undefined)
546            return done();
547        const t = path.resolve(cwd, p);
548        fs.lstat(t, (er, st) => {
549            if (er)
550                return done();
551            if (st?.isSymbolicLink()) {
552                return onError(new SymlinkError(t, path.resolve(t, parts.join('/'))));
553            }
554            this[ENSURE_NO_SYMLINK](entry, t, parts, done, onError);
555        });
556    }
557    [PEND]() {
558        this[PENDING]++;
559    }
560    [UNPEND]() {
561        this[PENDING]--;
562        this[MAYBECLOSE]();
563    }
564    [SKIP](entry) {
565        this[UNPEND]();
566        entry.resume();
567    }
568    // Check if we can reuse an existing filesystem entry safely and
569    // overwrite it, rather than unlinking and recreating
570    // Windows doesn't report a useful nlink, so we just never reuse entries
571    [ISREUSABLE](entry, st) {
572        return (entry.type === 'File' &&
573            !this.unlink &&
574            st.isFile() &&
575            st.nlink <= 1 &&
576            !isWindows);
577    }
578    // check if a thing is there, and if so, try to clobber it
579    [CHECKFS](entry) {
580        this[PEND]();
581        const paths = [entry.path];
582        if (entry.linkpath) {
583            paths.push(entry.linkpath);
584        }
585        this.reservations.reserve(paths, done => this[CHECKFS2](entry, done));
586    }
587    [CHECKFS2](entry, fullyDone) {
588        const done = (er) => {
589            fullyDone(er);
590        };
591        const checkCwd = () => {
592            this[MKDIR](this.cwd, this.dmode, er => {
593                if (er) {
594                    this[ONERROR](er, entry);
595                    done();
596                    return;
597                }
598                this[CHECKED_CWD] = true;
599                start();
600            });
601        };
602        const start = () => {
603            if (entry.absolute !== this.cwd) {
604                const parent = normalizeWindowsPath(path.dirname(String(entry.absolute)));
605                if (parent !== this.cwd) {
606                    return this[MKDIR](parent, this.dmode, er => {
607                        if (er) {
608                            this[ONERROR](er, entry);
609                            done();
610                            return;
611                        }
612                        afterMakeParent();
613                    });
614                }
615            }
616            afterMakeParent();
617        };
618        const afterMakeParent = () => {
619            fs.lstat(String(entry.absolute), (lstatEr, st) => {
620                if (st &&
621                    (this.keep ||
622                        /* c8 ignore next */
623                        (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
624                    this[SKIP](entry);
625                    done();
626                    return;
627                }
628                if (lstatEr || this[ISREUSABLE](entry, st)) {
629                    return this[MAKEFS](null, entry, done);
630                }
631                if (st.isDirectory()) {
632                    if (entry.type === 'Directory') {
633                        const needChmod = this.chmod &&
634                            entry.mode &&
635                            (st.mode & 0o7777) !== entry.mode;
636                        const afterChmod = (er) => this[MAKEFS](er ?? null, entry, done);
637                        if (!needChmod) {
638                            return afterChmod();
639                        }
640                        return fs.chmod(String(entry.absolute), Number(entry.mode), afterChmod);
641                    }
642                    // Not a dir entry, have to remove it.
643                    // NB: the only way to end up with an entry that is the cwd
644                    // itself, in such a way that == does not detect, is a
645                    // tricky windows absolute path with UNC or 8.3 parts (and
646                    // preservePaths:true, or else it will have been stripped).
647                    // In that case, the user has opted out of path protections
648                    // explicitly, so if they blow away the cwd, c'est la vie.
649                    if (entry.absolute !== this.cwd) {
650                        return fs.rmdir(String(entry.absolute), (er) => this[MAKEFS](er ?? null, entry, done));
651                    }
652                }
653                // not a dir, and not reusable
654                // don't remove if the cwd, we want that error
655                if (entry.absolute === this.cwd) {
656                    return this[MAKEFS](null, entry, done);
657                }
658                unlinkFile(String(entry.absolute), er => this[MAKEFS](er ?? null, entry, done));
659            });
660        };
661        if (this[CHECKED_CWD]) {
662            start();
663        }
664        else {
665            checkCwd();
666        }
667    }
668    [MAKEFS](er, entry, done) {
669        if (er) {
670            this[ONERROR](er, entry);
671            done();
672            return;
673        }
674        switch (entry.type) {
675            case 'File':
676            case 'OldFile':
677            case 'ContiguousFile':
678                return this[FILE](entry, done);
679            case 'Link':
680                return this[HARDLINK](entry, done);
681            case 'SymbolicLink':
682                return this[SYMLINK](entry, done);
683            case 'Directory':
684            case 'GNUDumpDir':
685                return this[DIRECTORY](entry, done);
686        }
687    }
688    [LINK](entry, linkpath, link, done) {
689        fs[link](linkpath, String(entry.absolute), er => {
690            if (er) {
691                this[ONERROR](er, entry);
692            }
693            else {
694                this[UNPEND]();
695                entry.resume();
696            }
697            done();
698        });
699    }
700}
701const callSync = (fn) => {
702    try {
703        return [null, fn()];
704    }
705    catch (er) {
706        return [er, null];
707    }
708};
709export class UnpackSync extends Unpack {
710    sync = true;
711    [MAKEFS](er, entry) {
712        return super[MAKEFS](er, entry, () => { });
713    }
714    [CHECKFS](entry) {
715        if (!this[CHECKED_CWD]) {
716            const er = this[MKDIR](this.cwd, this.dmode);
717            if (er) {
718                return this[ONERROR](er, entry);
719            }
720            this[CHECKED_CWD] = true;
721        }
722        // don't bother to make the parent if the current entry is the cwd,
723        // we've already checked it.
724        if (entry.absolute !== this.cwd) {
725            const parent = normalizeWindowsPath(path.dirname(String(entry.absolute)));
726            if (parent !== this.cwd) {
727                const mkParent = this[MKDIR](parent, this.dmode);
728                if (mkParent) {
729                    return this[ONERROR](mkParent, entry);
730                }
731            }
732        }
733        const [lstatEr, st] = callSync(() => fs.lstatSync(String(entry.absolute)));
734        if (st &&
735            (this.keep ||
736                /* c8 ignore next */
737                (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
738            return this[SKIP](entry);
739        }
740        if (lstatEr || this[ISREUSABLE](entry, st)) {
741            return this[MAKEFS](null, entry);
742        }
743        if (st.isDirectory()) {
744            if (entry.type === 'Directory') {
745                const needChmod = this.chmod &&
746                    entry.mode &&
747                    (st.mode & 0o7777) !== entry.mode;
748                const [er] = needChmod ?
749                    callSync(() => {
750                        fs.chmodSync(String(entry.absolute), Number(entry.mode));
751                    })
752                    : [];
753                return this[MAKEFS](er, entry);
754            }
755            // not a dir entry, have to remove it
756            const [er] = callSync(() => fs.rmdirSync(String(entry.absolute)));
757            this[MAKEFS](er, entry);
758        }
759        // not a dir, and not reusable.
760        // don't remove if it's the cwd, since we want that error.
761        const [er] = entry.absolute === this.cwd ?
762            []
763            : callSync(() => unlinkFileSync(String(entry.absolute)));
764        this[MAKEFS](er, entry);
765    }
766    [FILE](entry, done) {
767        const mode = typeof entry.mode === 'number' ?
768            entry.mode & 0o7777
769            : this.fmode;
770        const oner = (er) => {
771            let closeError;
772            try {
773                fs.closeSync(fd);
774            }
775            catch (e) {
776                closeError = e;
777            }
778            if (er || closeError) {
779                this[ONERROR](er || closeError, entry);
780            }
781            done();
782        };
783        let fd;
784        try {
785            fd = fs.openSync(String(entry.absolute), getWriteFlag(entry.size), mode);
786            /* c8 ignore start - This is only a problem if the file was successfully
787             * statted, BUT failed to open. Testing this is annoying, and we
788             * already have ample testint for other uses of oner() methods.
789             */
790        }
791        catch (er) {
792            return oner(er);
793        }
794        /* c8 ignore stop */
795        const tx = this.transform ? this.transform(entry) || entry : entry;
796        if (tx !== entry) {
797            tx.on('error', (er) => this[ONERROR](er, entry));
798            entry.pipe(tx);
799        }
800        tx.on('data', (chunk) => {
801            try {
802                fs.writeSync(fd, chunk, 0, chunk.length);
803            }
804            catch (er) {
805                oner(er);
806            }
807        });
808        tx.on('end', () => {
809            let er = null;
810            // try both, falling futimes back to utimes
811            // if either fails, handle the first error
812            if (entry.mtime && !this.noMtime) {
813                const atime = entry.atime || new Date();
814                const mtime = entry.mtime;
815                try {
816                    fs.futimesSync(fd, atime, mtime);
817                }
818                catch (futimeser) {
819                    try {
820                        fs.utimesSync(String(entry.absolute), atime, mtime);
821                    }
822                    catch (utimeser) {
823                        er = futimeser;
824                    }
825                }
826            }
827            if (this[DOCHOWN](entry)) {
828                const uid = this[UID](entry);
829                const gid = this[GID](entry);
830                try {
831                    fs.fchownSync(fd, Number(uid), Number(gid));
832                }
833                catch (fchowner) {
834                    try {
835                        fs.chownSync(String(entry.absolute), Number(uid), Number(gid));
836                    }
837                    catch (chowner) {
838                        er = er || fchowner;
839                    }
840                }
841            }
842            oner(er);
843        });
844    }
845    [DIRECTORY](entry, done) {
846        const mode = typeof entry.mode === 'number' ?
847            entry.mode & 0o7777
848            : this.dmode;
849        const er = this[MKDIR](String(entry.absolute), mode);
850        if (er) {
851            this[ONERROR](er, entry);
852            done();
853            return;
854        }
855        if (entry.mtime && !this.noMtime) {
856            try {
857                fs.utimesSync(String(entry.absolute), entry.atime || new Date(), entry.mtime);
858                /* c8 ignore next */
859            }
860            catch (er) { }
861        }
862        if (this[DOCHOWN](entry)) {
863            try {
864                fs.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)));
865            }
866            catch (er) { }
867        }
868        done();
869        entry.resume();
870    }
871    [MKDIR](dir, mode) {
872        try {
873            return mkdirSync(normalizeWindowsPath(dir), {
874                uid: this.uid,
875                gid: this.gid,
876                processUid: this.processUid,
877                processGid: this.processGid,
878                umask: this.processUmask,
879                preserve: this.preservePaths,
880                unlink: this.unlink,
881                cwd: this.cwd,
882                mode: mode,
883            });
884        }
885        catch (er) {
886            return er;
887        }
888    }
889    [ENSURE_NO_SYMLINK](_entry, cwd, parts, done, onError) {
890        if (this.preservePaths || !parts.length)
891            return done();
892        let t = cwd;
893        for (const p of parts) {
894            t = path.resolve(t, p);
895            const [er, st] = callSync(() => fs.lstatSync(t));
896            if (er)
897                return done();
898            if (st.isSymbolicLink()) {
899                return onError(new SymlinkError(t, path.resolve(cwd, parts.join('/'))));
900            }
901        }
902        done();
903    }
904    [LINK](entry, linkpath, link, done) {
905        const linkSync = `${link}Sync`;
906        try {
907            fs[linkSync](linkpath, String(entry.absolute));
908            done();
909            entry.resume();
910        }
911        catch (er) {
912            return this[ONERROR](er, entry);
913        }
914    }
915}
916//# sourceMappingURL=unpack.js.map
codekingpro/portable-devtools · Team Ai