-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathzip_build.plugin.ts
70 lines (67 loc) · 1.97 KB
/
zip_build.plugin.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
import { type Plugin } from "$fresh/server.ts";
import { assert } from "@std/assert/assert";
import { relative, resolve } from "jsr:@std/path@~1";
import { terminateWorkers, ZipWriter } from "jsr:@zip-js/[email protected]";
let buildDir: string = "./_fresh";
const zipFilename = "./_fresh.zip";
async function addDirectories(path: string) {
const stat = await Deno.stat(path);
if (stat.isDirectory) {
const result: string[] = [];
for await (const entry of Deno.readDir(path)) {
const stat = await Deno.stat(`${path}/${entry.name}`);
if (stat.isFile) {
result.push(`${path}/${entry.name}`);
} else if (stat.isDirectory) {
result.push(...(await addDirectories(`${path}/${entry.name}`)));
}
}
return result.flat();
}
return [path];
}
export default function zipBuild(): Plugin {
return {
name: "zip_build",
async buildStart(config) {
buildDir = config.build.outDir;
try {
await Deno.remove(zipFilename);
} catch {
// just swallow the error
}
},
async buildEnd() {
const list = (await addDirectories(buildDir)).map((path) => ({
path,
relative: relative(buildDir, path),
}));
const zipFile = await Deno.open(zipFilename, {
create: true,
write: true,
});
const zipWriter = new ZipWriter(zipFile, {
bufferedWrite: true,
keepOrder: true,
});
try {
for (const { path, relative } of list) {
try {
const file = await Deno.open(path);
await zipWriter.add(relative, file.readable);
} catch (error) {
assert(error instanceof Error);
console.error(` error: ${error.message}, file: ${path}`);
}
}
await zipWriter.close();
} finally {
await terminateWorkers();
}
console.log(
`Build archived to: %c${resolve(Deno.cwd(), zipFilename)}`,
"color:green",
);
},
};
}