-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathget-tar-stream.ts
68 lines (54 loc) · 1.84 KB
/
get-tar-stream.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
import { NotUnixFSError } from '@helia/unixfs/errors'
import { exporter, recursive, type UnixFSEntry } from 'ipfs-unixfs-exporter'
import map from 'it-map'
import { pipe } from 'it-pipe'
import { pack, type TarEntryHeader, type TarImportCandidate } from 'it-tar'
import type { AbortOptions } from '@libp2p/interface'
import type { Blockstore } from 'interface-blockstore'
const EXPORTABLE = ['file', 'raw', 'directory']
function toHeader (file: UnixFSEntry): Partial<TarEntryHeader> & { name: string } {
let mode: number | undefined
let mtime: Date | undefined
if (file.type === 'file' || file.type === 'directory') {
mode = file.unixfs.mode
mtime = file.unixfs.mtime != null ? new Date(Number(file.unixfs.mtime.secs * 1000n)) : undefined
}
return {
name: file.path,
mode,
mtime,
size: Number(file.size),
type: file.type === 'directory' ? 'directory' : 'file'
}
}
function toTarImportCandidate (entry: UnixFSEntry): TarImportCandidate {
if (!EXPORTABLE.includes(entry.type)) {
throw new NotUnixFSError(`${entry.type} is not a UnixFS node`)
}
const candidate: TarImportCandidate = {
header: toHeader(entry)
}
if (entry.type === 'file' || entry.type === 'raw') {
candidate.body = entry.content()
}
return candidate
}
export async function * tarStream (ipfsPath: string, blockstore: Blockstore, options?: AbortOptions): AsyncGenerator<Uint8Array> {
const file = await exporter(ipfsPath, blockstore, options)
if (file.type === 'file' || file.type === 'raw') {
yield * pipe(
[toTarImportCandidate(file)],
pack()
)
return
}
if (file.type === 'directory') {
yield * pipe(
recursive(ipfsPath, blockstore, options),
(source) => map(source, (entry) => toTarImportCandidate(entry)),
pack()
)
return
}
throw new NotUnixFSError('Not a UnixFS node')
}