Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
replace.js221 linesDownload Raw Back to esm
1// tar -r
2import { WriteStream, WriteStreamSync } from '@isaacs/fs-minipass';
3import fs from 'node:fs';
4import path from 'node:path';
5import { Header } from './header.js';
6import { list } from './list.js';
7import { makeCommand } from './make-command.js';
8import { isFile } from './options.js';
9import { Pack, PackSync } from './pack.js';
10// starting at the head of the file, read a Header
11// If the checksum is invalid, that's our position to start writing
12// If it is, jump forward by the specified size (round up to 512)
13// and try again.
14// Write the new Pack stream starting there.
15const replaceSync = (opt, files) => {
16    const p = new PackSync(opt);
17    let threw = true;
18    let fd;
19    let position;
20    try {
21        try {
22            fd = fs.openSync(opt.file, 'r+');
23        }
24        catch (er) {
25            if (er?.code === 'ENOENT') {
26                fd = fs.openSync(opt.file, 'w+');
27            }
28            else {
29                throw er;
30            }
31        }
32        const st = fs.fstatSync(fd);
33        const headBuf = Buffer.alloc(512);
34        POSITION: for (position = 0; position < st.size; position += 512) {
35            for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) {
36                bytes = fs.readSync(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos);
37                if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) {
38                    throw new Error('cannot append to compressed archives');
39                }
40                if (!bytes) {
41                    break POSITION;
42                }
43            }
44            const h = new Header(headBuf);
45            if (!h.cksumValid) {
46                break;
47            }
48            const entryBlockSize = 512 * Math.ceil((h.size || 0) / 512);
49            if (position + entryBlockSize + 512 > st.size) {
50                break;
51            }
52            // the 512 for the header we just parsed will be added as well
53            // also jump ahead all the blocks for the body
54            position += entryBlockSize;
55            if (opt.mtimeCache && h.mtime) {
56                opt.mtimeCache.set(String(h.path), h.mtime);
57            }
58        }
59        threw = false;
60        streamSync(opt, p, position, fd, files);
61    }
62    finally {
63        if (threw) {
64            try {
65                fs.closeSync(fd);
66            }
67            catch { }
68        }
69    }
70};
71const streamSync = (opt, p, position, fd, files) => {
72    const stream = new WriteStreamSync(opt.file, {
73        fd: fd,
74        start: position,
75    });
76    p.pipe(stream);
77    addFilesSync(p, files);
78};
79const replaceAsync = (opt, files) => {
80    files = Array.from(files);
81    const p = new Pack(opt);
82    const getPos = (fd, size, cb_) => {
83        const cb = (er, pos) => {
84            if (er) {
85                fs.close(fd, _ => cb_(er));
86            }
87            else {
88                cb_(null, pos);
89            }
90        };
91        let position = 0;
92        if (size === 0) {
93            return cb(null, 0);
94        }
95        let bufPos = 0;
96        const headBuf = Buffer.alloc(512);
97        const onread = (er, bytes) => {
98            if (er || bytes === undefined) {
99                return cb(er);
100            }
101            bufPos += bytes;
102            if (bufPos < 512 && bytes) {
103                return fs.read(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread);
104            }
105            if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) {
106                return cb(new Error('cannot append to compressed archives'));
107            }
108            // truncated header
109            if (bufPos < 512) {
110                return cb(null, position);
111            }
112            const h = new Header(headBuf);
113            if (!h.cksumValid) {
114                return cb(null, position);
115            }
116            /* c8 ignore next */
117            const entryBlockSize = 512 * Math.ceil((h.size ?? 0) / 512);
118            if (position + entryBlockSize + 512 > size) {
119                return cb(null, position);
120            }
121            position += entryBlockSize + 512;
122            if (position >= size) {
123                return cb(null, position);
124            }
125            if (opt.mtimeCache && h.mtime) {
126                opt.mtimeCache.set(String(h.path), h.mtime);
127            }
128            bufPos = 0;
129            fs.read(fd, headBuf, 0, 512, position, onread);
130        };
131        fs.read(fd, headBuf, 0, 512, position, onread);
132    };
133    const promise = new Promise((resolve, reject) => {
134        p.on('error', reject);
135        let flag = 'r+';
136        const onopen = (er, fd) => {
137            if (er && er.code === 'ENOENT' && flag === 'r+') {
138                flag = 'w+';
139                return fs.open(opt.file, flag, onopen);
140            }
141            if (er || !fd) {
142                return reject(er);
143            }
144            fs.fstat(fd, (er, st) => {
145                if (er) {
146                    return fs.close(fd, () => reject(er));
147                }
148                getPos(fd, st.size, (er, position) => {
149                    if (er) {
150                        return reject(er);
151                    }
152                    const stream = new WriteStream(opt.file, {
153                        fd: fd,
154                        start: position,
155                    });
156                    p.pipe(stream);
157                    stream.on('error', reject);
158                    stream.on('close', resolve);
159                    addFilesAsync(p, files);
160                });
161            });
162        };
163        fs.open(opt.file, flag, onopen);
164    });
165    return promise;
166};
167const addFilesSync = (p, files) => {
168    files.forEach(file => {
169        if (file.charAt(0) === '@') {
170            list({
171                file: path.resolve(p.cwd, file.slice(1)),
172                sync: true,
173                noResume: true,
174                onReadEntry: entry => p.add(entry),
175            });
176        }
177        else {
178            p.add(file);
179        }
180    });
181    p.end();
182};
183const addFilesAsync = async (p, files) => {
184    for (const file of files) {
185        if (file.charAt(0) === '@') {
186            await list({
187                file: path.resolve(String(p.cwd), file.slice(1)),
188                noResume: true,
189                onReadEntry: entry => p.add(entry),
190            });
191        }
192        else {
193            p.add(file);
194        }
195    }
196    p.end();
197};
198export const replace = makeCommand(replaceSync, replaceAsync,
199/* c8 ignore start */
200() => {
201    throw new TypeError('file is required');
202}, () => {
203    throw new TypeError('file is required');
204},
205/* c8 ignore stop */
206(opt, entries) => {
207    if (!isFile(opt)) {
208        throw new TypeError('file is required');
209    }
210    if (opt.gzip ||
211        opt.brotli ||
212        opt.zstd ||
213        opt.file.endsWith('.br') ||
214        opt.file.endsWith('.tbr')) {
215        throw new TypeError('cannot append to compressed archives');
216    }
217    if (!entries?.length) {
218        throw new TypeError('no paths specified to add/replace');
219    }
220});
221//# sourceMappingURL=replace.js.map
codekingpro/portable-devtools · Team Ai