Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tar.ts

146 lines4.7 KB

1/**
2 * A small tar writer for dockerode `container.putArchive`, so copying files
3 * into a container needs no tar dependency.
4 *
5 * Each entry gets a POSIX ustar header. When a path or link target does not
6 * fit a ustar field (over 100 bytes, or not plain ASCII), a PAX header with
7 * the full value comes first.
8 */
9import { Readable } from 'node:stream'
10​
11/**
12 * One archive entry. `path` is relative and `/`-separated. A file keeps only
13 * the permission bits of `mode` (for example `0o644` or `0o755`).
14 */
15export type TarEntry =
16 | { path: string; mode: number; data: Buffer }
17 | { path: string; linkTarget: string }
18​
19/** One tar member: a file, a symlink, or a PAX header. */
20type Member = {
21 name: string
22 type: '0' | '2' | 'x'
23 mode: number
24 linkTarget: string
25 data: Buffer
27​
28const BLOCK = 512
29/** The ustar name and linkname fields hold at most this many bytes. */
30const NAME_BYTES = 100
31​
32/**
33 * Stream `entries` as a tar archive. The stream pulls the next entry only when
34 * it needs more bytes, so the archive is never all in memory. An error from
35 * `entries` destroys the stream with that error.
36 */
37export function tarStream(
38 entries: Iterable<TarEntry> | AsyncIterable<TarEntry>,
39) {
40 // One mtime for all entries: the time the stream was made.
41 const mtime = Math.floor(Date.now() / 1000)
42 async function* chunks() {
43 for await (const entry of entries) {
44 const member: Member =
45 'data' in entry
46 ? {
47 name: entry.path,
48 type: '0',
49 mode: entry.mode & 0o777,
50 linkTarget: '',
51 data: entry.data,
52 }
53 : {
54 name: entry.path,
55 type: '2',
56 mode: 0o777,
57 linkTarget: entry.linkTarget,
58 data: Buffer.alloc(0),
59 }
60 const pax = paxRecords(member)
61 if (pax.length > 0) {
62 yield* memberChunks(
63 {
64 name: 'PaxHeader',
65 type: 'x',
66 mode: 0o644,
67 linkTarget: '',
68 data: pax,
69 },
70 mtime,
71 )
72 }
73 yield* memberChunks(member, mtime)
74 }
75 // Two zero blocks end the archive.
76 yield Buffer.alloc(2 * BLOCK)
77 }
78 return Readable.from(chunks(), { objectMode: false })
80​
81/** A member's header, then its data, then zeros up to the next block. */
82function* memberChunks(member: Member, mtime: number) {
83 yield header(member, mtime)
84 const size = member.data.length
85 if (size === 0) return
86 yield member.data
87 const rest = size % BLOCK
88 if (rest > 0) yield Buffer.alloc(BLOCK - rest)
90​
91function header(member: Member, mtime: number) {
92 const block = Buffer.alloc(BLOCK)
93 // A value that does not fit is cut here. Its PAX record has all of it.
94 block.write(member.name, 0, NAME_BYTES)
95 block.write(octal(member.mode, 8), 100)
96 block.write(octal(0, 8), 108) // uid
97 block.write(octal(0, 8), 116) // gid
98 block.write(octal(member.data.length, 12), 124)
99 block.write(octal(mtime, 12), 136)
100 block.write(member.type, 156)
101 block.write(member.linkTarget, 157, NAME_BYTES)
102 block.write('ustar', 257) // the magic is "ustar" and a NUL
103 block.write('00', 263) // version
104 // The checksum is the sum of all header bytes, with its own field read as
105 // spaces. Tar writes it as six octal digits, a NUL, and a space.
106 block.fill(' ', 148, 156)
107 const sum = block.reduce((total, byte) => total + byte, 0)
108 block.write(`${octal(sum, 7)}\0`, 148)
109 return block
111​
112/** Zero-padded octal digits for a numeric field, with room for the NUL. */
113function octal(value: number, fieldBytes: number) {
114 const digits = value.toString(8).padStart(fieldBytes - 1, '0')
115 // The 12-byte size field holds up to 8 GiB.
116 if (digits.length >= fieldBytes) {
117 throw new Error(`tar: ${value} does not fit a ${fieldBytes}-byte field`)
118 }
119 return digits
121​
122/** PAX records for a name or link target that a ustar field cannot hold. */
123function paxRecords(member: Member) {
124 let records = ''
125 if (needsPax(member.name)) records += paxRecord('path', member.name)
126 if (needsPax(member.linkTarget)) {
127 records += paxRecord('linkpath', member.linkTarget)
128 }
129 return Buffer.from(records)
131​
132function needsPax(value: string) {
133 const bytes = Buffer.byteLength(value)
134 // A non-ASCII character takes more than one UTF-8 byte.
135 return bytes > NAME_BYTES || bytes !== value.length
137​
138/** One PAX record: `<length> <key>=<value>\n`. The length counts itself. */
139function paxRecord(key: string, value: string) {
140 const body = ` ${key}=${value}\n`
141 const bodyBytes = Buffer.byteLength(body)
142 // Adding the length's own digits can add one more digit, so count twice.
143 const guess = bodyBytes + String(bodyBytes).length
144 const length = bodyBytes + String(guess).length
145 return `${length}${body}`