deno.land / std@0.166.0 / archive / tar.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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
/*! * Ported and modified from: https://github.com/beatgammit/tar-js and * licensed as: * * (The MIT License) * * Copyright (c) 2011 T. Jameson Little * Copyright (c) 2019 Jun Kato * Copyright (c) 2018-2022 the Deno authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */
/** * Provides a `Tar` and `Untar` classes for compressing and decompressing * arbitrary data. * * ## Examples * * ### Tar * * ```ts * import { Tar } from "https://deno.land/std@$STD_VERSION/archive/tar.ts"; * import { Buffer } from "https://deno.land/std@$STD_VERSION/io/buffer.ts"; * import { copy } from "https://deno.land/std@$STD_VERSION/streams/conversion.ts"; * * const tar = new Tar(); * const content = new TextEncoder().encode("Deno.land"); * await tar.append("deno.txt", { * reader: new Buffer(content), * contentSize: content.byteLength, * }); * * // Or specifying a filePath. * await tar.append("land.txt", { * filePath: "./land.txt", * }); * * // use tar.getReader() to read the contents. * * const writer = await Deno.open("./out.tar", { write: true, create: true }); * await copy(tar.getReader(), writer); * writer.close(); * ``` * * ### Untar * * ```ts * import { Untar } from "https://deno.land/std@$STD_VERSION/archive/tar.ts"; * import { ensureFile } from "https://deno.land/std@$STD_VERSION/fs/ensure_file.ts"; * import { ensureDir } from "https://deno.land/std@$STD_VERSION/fs/ensure_dir.ts"; * import { copy } from "https://deno.land/std@$STD_VERSION/streams/conversion.ts"; * * const reader = await Deno.open("./out.tar", { read: true }); * const untar = new Untar(reader); * * for await (const entry of untar) { * console.log(entry); // metadata * * if (entry.type === "directory") { * await ensureDir(entry.fileName); * continue; * } * * await ensureFile(entry.fileName); * const file = await Deno.open(entry.fileName, { write: true }); * // <entry> is a reader. * await copy(entry, file); * } * reader.close(); * ``` * * @module */
import { MultiReader } from "../io/readers.ts";import { Buffer, PartialReadError } from "../io/buffer.ts";import { assert } from "../_util/asserts.ts";import { readAll } from "../streams/conversion.ts";
type Reader = Deno.Reader;type Seeker = Deno.Seeker;
const recordSize = 512;const ustar = "ustar\u000000";
// https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06// eight checksum bytes taken to be ascii spaces (decimal value 32)const initialChecksum = 8 * 32;
async function readBlock( reader: Deno.Reader, p: Uint8Array,): Promise<number | null> { let bytesRead = 0; while (bytesRead < p.length) { const rr = await reader.read(p.subarray(bytesRead)); if (rr === null) { if (bytesRead === 0) { return null; } else { throw new PartialReadError(); } } bytesRead += rr; } return bytesRead;}
/** * Simple file reader */class FileReader implements Reader { #file?: Deno.FsFile;
constructor(private filePath: string) {}
public async read(p: Uint8Array): Promise<number | null> { if (!this.#file) { this.#file = await Deno.open(this.filePath, { read: true }); } const res = await this.#file.read(p); if (res === null) { this.#file.close(); this.#file = undefined; } return res; }}
/** * Remove the trailing null codes * @param buffer */function trim(buffer: Uint8Array): Uint8Array { const index = buffer.findIndex((v): boolean => v === 0); if (index < 0) return buffer; return buffer.subarray(0, index);}
/** * Initialize Uint8Array of the specified length filled with 0 * @param length */function clean(length: number): Uint8Array { const buffer = new Uint8Array(length); buffer.fill(0, 0, length - 1); return buffer;}
function pad(num: number, bytes: number, base = 8): string { const numString = num.toString(base); return "000000000000".substr(numString.length + 12 - bytes) + numString;}
enum FileTypes { "file" = 0, "link" = 1, "symlink" = 2, "character-device" = 3, "block-device" = 4, "directory" = 5, "fifo" = 6, "contiguous-file" = 7,}
/*struct posix_header { // byte offset char name[100]; // 0 char mode[8]; // 100 char uid[8]; // 108 char gid[8]; // 116 char size[12]; // 124 char mtime[12]; // 136 char chksum[8]; // 148 char typeflag; // 156 char linkname[100]; // 157 char magic[6]; // 257 char version[2]; // 263 char uname[32]; // 265 char gname[32]; // 297 char devmajor[8]; // 329 char devminor[8]; // 337 char prefix[155]; // 345 // 500};*/
const ustarStructure: Array<{ field: string; length: number }> = [ { field: "fileName", length: 100, }, { field: "fileMode", length: 8, }, { field: "uid", length: 8, }, { field: "gid", length: 8, }, { field: "fileSize", length: 12, }, { field: "mtime", length: 12, }, { field: "checksum", length: 8, }, { field: "type", length: 1, }, { field: "linkName", length: 100, }, { field: "ustar", length: 8, }, { field: "owner", length: 32, }, { field: "group", length: 32, }, { field: "majorNumber", length: 8, }, { field: "minorNumber", length: 8, }, { field: "fileNamePrefix", length: 155, }, { field: "padding", length: 12, },];
/** * Create header for a file in a tar archive */function formatHeader(data: TarData): Uint8Array { const encoder = new TextEncoder(), buffer = clean(512); let offset = 0; ustarStructure.forEach(function (value) { const entry = encoder.encode(data[value.field as keyof TarData] || ""); buffer.set(entry, offset); offset += value.length; // space it out with nulls }); return buffer;}
/** * Parse file header in a tar archive * @param length */function parseHeader(buffer: Uint8Array): { [key: string]: Uint8Array } { const data: { [key: string]: Uint8Array } = {}; let offset = 0; ustarStructure.forEach(function (value) { const arr = buffer.subarray(offset, offset + value.length); data[value.field] = arr; offset += value.length; }); return data;}
export interface TarHeader { [key: string]: Uint8Array;}
export interface TarData { fileName?: string; fileNamePrefix?: string; fileMode?: string; uid?: string; gid?: string; fileSize?: string; mtime?: string; checksum?: string; type?: string; ustar?: string; owner?: string; group?: string;}
export interface TarDataWithSource extends TarData { /** * file to read */ filePath?: string; /** * buffer to read */ reader?: Reader;}
export interface TarInfo { fileMode?: number; mtime?: number; uid?: number; gid?: number; owner?: string; group?: string; type?: string;}
export interface TarOptions extends TarInfo { /** * append file */ filePath?: string;
/** * append any arbitrary content */ reader?: Reader;
/** * size of the content to be appended */ contentSize?: number;}
export interface TarMeta extends TarInfo { fileName: string; fileSize?: number;}
// deno-lint-ignore no-empty-interfaceinterface TarEntry extends TarMeta {}
/** * A class to create a tar archive */export class Tar { data: TarDataWithSource[];
constructor() { this.data = []; }
/** * Append a file to this tar archive * @param fn file name * e.g., test.txt; use slash for directory separators * @param opts options */ async append(fn: string, opts: TarOptions) { if (typeof fn !== "string") { throw new Error("file name not specified"); } let fileName = fn; // separate file name into two parts if needed let fileNamePrefix: string | undefined; if (fileName.length > 100) { let i = fileName.length; while (i >= 0) { i = fileName.lastIndexOf("/", i); if (i <= 155) { fileNamePrefix = fileName.substr(0, i); fileName = fileName.substr(i + 1); break; } i--; } const errMsg = "ustar format does not allow a long file name (length of [file name" + "prefix] + / + [file name] must be shorter than 256 bytes)"; if (i < 0 || fileName.length > 100) { throw new Error(errMsg); } else { assert(fileNamePrefix != null); if (fileNamePrefix.length > 155) { throw new Error(errMsg); } } }
opts = opts || {};
// set meta data let info: Deno.FileInfo | undefined; if (opts.filePath) { info = await Deno.stat(opts.filePath); if (info.isDirectory) { info.size = 0; opts.reader = new Buffer(); } }
const mode = opts.fileMode || (info && info.mode) || parseInt("777", 8) & 0xfff, mtime = Math.floor( opts.mtime ?? (info?.mtime ?? new Date()).valueOf() / 1000, ), uid = opts.uid || 0, gid = opts.gid || 0; if (typeof opts.owner === "string" && opts.owner.length >= 32) { throw new Error( "ustar format does not allow owner name length >= 32 bytes", ); } if (typeof opts.group === "string" && opts.group.length >= 32) { throw new Error( "ustar format does not allow group name length >= 32 bytes", ); }
const fileSize = info?.size ?? opts.contentSize; assert(fileSize != null, "fileSize must be set");
const type = opts.type ? FileTypes[opts.type as keyof typeof FileTypes] : (info?.isDirectory ? FileTypes.directory : FileTypes.file); const tarData: TarDataWithSource = { fileName, fileNamePrefix, fileMode: pad(mode, 7), uid: pad(uid, 7), gid: pad(gid, 7), fileSize: pad(fileSize, 11), mtime: pad(mtime, 11), checksum: " ", type: type.toString(), ustar, owner: opts.owner || "", group: opts.group || "", filePath: opts.filePath, reader: opts.reader, };
// calculate the checksum let checksum = 0; const encoder = new TextEncoder(); Object.keys(tarData) .filter((key): boolean => ["filePath", "reader"].indexOf(key) < 0) .forEach(function (key) { checksum += encoder .encode(tarData[key as keyof TarData]) .reduce((p, c): number => p + c, 0); });
tarData.checksum = pad(checksum, 6) + "\u0000 "; this.data.push(tarData); }
/** * Get a Reader instance for this tar data */ getReader(): Reader { const readers: Reader[] = []; this.data.forEach((tarData) => { let { reader } = tarData; const { filePath } = tarData; const headerArr = formatHeader(tarData); readers.push(new Buffer(headerArr)); if (!reader) { assert(filePath != null); reader = new FileReader(filePath); } readers.push(reader);
// to the nearest multiple of recordSize assert(tarData.fileSize != null, "fileSize must be set"); readers.push( new Buffer( clean( recordSize - (parseInt(tarData.fileSize, 8) % recordSize || recordSize), ), ), ); });
// append 2 empty records readers.push(new Buffer(clean(recordSize * 2))); return new MultiReader(readers); }}
class TarEntry implements Reader { #header: TarHeader; #reader: Reader | (Reader & Deno.Seeker); #size: number; #read = 0; #consumed = false; #entrySize: number; constructor( meta: TarMeta, header: TarHeader, reader: Reader | (Reader & Deno.Seeker), ) { Object.assign(this, meta); this.#header = header; this.#reader = reader;
// File Size this.#size = this.fileSize || 0; // Entry Size const blocks = Math.ceil(this.#size / recordSize); this.#entrySize = blocks * recordSize; }
get consumed(): boolean { return this.#consumed; }
async read(p: Uint8Array): Promise<number | null> { // Bytes left for entry const entryBytesLeft = this.#entrySize - this.#read; const bufSize = Math.min( // bufSize can't be greater than p.length nor bytes left in the entry p.length, entryBytesLeft, );
if (entryBytesLeft <= 0) { this.#consumed = true; return null; }
const block = new Uint8Array(bufSize); const n = await readBlock(this.#reader, block); const bytesLeft = this.#size - this.#read;
this.#read += n || 0; if (n === null || bytesLeft <= 0) { if (n === null) this.#consumed = true; return null; }
// Remove zero filled const offset = bytesLeft < n ? bytesLeft : n; p.set(block.subarray(0, offset), 0);
return offset < 0 ? n - Math.abs(offset) : offset; }
async discard() { // Discard current entry if (this.#consumed) return; this.#consumed = true;
if (typeof (this.#reader as Seeker).seek === "function") { await (this.#reader as Seeker).seek( this.#entrySize - this.#read, Deno.SeekMode.Current, ); this.#read = this.#entrySize; } else { await readAll(this); } }}
/** * A class to extract a tar archive */export class Untar { reader: Reader; block: Uint8Array; #entry: TarEntry | undefined;
constructor(reader: Reader) { this.reader = reader; this.block = new Uint8Array(recordSize); }
#checksum(header: Uint8Array): number { let sum = initialChecksum; for (let i = 0; i < 512; i++) { if (i >= 148 && i < 156) { // Ignore checksum header continue; } sum += header[i]; } return sum; }
async #getHeader(): Promise<TarHeader | null> { await readBlock(this.reader, this.block); const header = parseHeader(this.block);
// calculate the checksum const decoder = new TextDecoder(); const checksum = this.#checksum(this.block);
if (parseInt(decoder.decode(header.checksum), 8) !== checksum) { if (checksum === initialChecksum) { // EOF return null; } throw new Error("checksum error"); }
const magic = decoder.decode(header.ustar);
if (magic.indexOf("ustar")) { throw new Error(`unsupported archive format: ${magic}`); }
return header; }
#getMetadata(header: TarHeader): TarMeta { const decoder = new TextDecoder(); // get meta data const meta: TarMeta = { fileName: decoder.decode(trim(header.fileName)), }; const fileNamePrefix = trim(header.fileNamePrefix); if (fileNamePrefix.byteLength > 0) { meta.fileName = decoder.decode(fileNamePrefix) + "/" + meta.fileName; } (["fileMode", "mtime", "uid", "gid"] as [ "fileMode", "mtime", "uid", "gid", ]).forEach((key) => { const arr = trim(header[key]); if (arr.byteLength > 0) { meta[key] = parseInt(decoder.decode(arr), 8); } }); (["owner", "group", "type"] as ["owner", "group", "type"]).forEach( (key) => { const arr = trim(header[key]); if (arr.byteLength > 0) { meta[key] = decoder.decode(arr); } }, );
meta.fileSize = parseInt(decoder.decode(header.fileSize), 8); meta.type = FileTypes[parseInt(meta.type!)] ?? meta.type;
return meta; }
async extract(): Promise<TarEntry | null> { if (this.#entry && !this.#entry.consumed) { // If entry body was not read, discard the body // so we can read the next entry. await this.#entry.discard(); }
const header = await this.#getHeader(); if (header === null) return null;
const meta = this.#getMetadata(header);
this.#entry = new TarEntry(meta, header, this.reader);
return this.#entry; }
async *[Symbol.asyncIterator](): AsyncIterableIterator<TarEntry> { while (true) { const entry = await this.extract();
if (entry === null) return;
yield entry; } }}
export { TarEntry };
std
Deno standard library
GitHub Repositorydenoland/deno_std
GitHub Stars
2458

Version Info

Tagged at
2 months ago