-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnar.ts
More file actions
100 lines (82 loc) · 2.3 KB
/
Copy pathnar.ts
File metadata and controls
100 lines (82 loc) · 2.3 KB
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
import { sortBy } from "@std/collections";
import { ByteSliceStream, toTransformStream } from "@std/streams";
type Entry =
| RegularEntry
| SymlinkEntry
| DirectoryEntry;
interface RegularEntry {
type: "regular";
narOffset: number;
size: number;
executable?: boolean;
}
interface SymlinkEntry {
type: "symlink";
target: string;
}
interface DirectoryEntry {
type: "directory";
entries: Record<string, Entry>;
}
export interface NarListing {
root: Entry;
version: 1;
}
function* walk(
entry: Entry,
path: string[],
): Generator<{ path: string[]; entry: Entry }, void> {
yield { path, entry };
if (entry.type === "directory") {
for (const [name, child] of Object.entries(entry.entries)) {
yield* walk(child, [...path, name]);
}
}
}
function flatten(nar: NarListing) {
const files: Array<Entry & { path: string }> = [];
for (const { path, entry } of walk(nar.root, [])) {
files.push({ ...entry, path: path.join("/") });
}
const { regular = [], symlink = [], directory = [] } = Object.groupBy(
files,
(entry) => entry.type,
) as {
regular?: Array<RegularEntry & { path: string }>;
symlink?: Array<SymlinkEntry & { path: string }>;
directory?: Array<DirectoryEntry & { path: string }>;
};
return { regular, symlink, directory };
}
export type StreamEntry =
| (RegularEntry & { path: string; body: ReadableStream<Uint8Array> })
| (SymlinkEntry & { path: string })
| (DirectoryEntry & { path: string });
export function isNarListing(value: unknown): value is NarListing {
return (
typeof value === "object" &&
value !== null &&
"root" in value &&
"version" in value &&
value.version === 1
);
}
export function createNarEntryStream(
listing: NarListing,
): TransformStream<Uint8Array, StreamEntry> {
const files = flatten(listing);
sortBy(files.regular, (f) => f.narOffset, { order: "asc" });
return toTransformStream<Uint8Array, StreamEntry>(async function* (stream) {
yield* files.directory;
for (const file of files.regular) {
let stream2;
[stream, stream2] = stream.tee();
const body = stream2.pipeThrough(
new ByteSliceStream(file.narOffset, file.narOffset + file.size),
);
yield { ...file, body };
}
yield* files.symlink;
await stream.cancel();
});
}