-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.ts
93 lines (85 loc) · 2.3 KB
/
build.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
import fs from "node:fs";
import path from "node:path";
import ChildProcess from "node:child_process";
const DEST = path.resolve(__dirname, "dist");
const SOURCES = ["pages", "public"].map((s) => path.resolve(__dirname, s));
const CACHE_PATH = ["pages", "public"].map((s) => path.resolve(__dirname, s));
function copy(src: string, dest: string) {
const stat = fs.statSync(src);
if (stat.isDirectory()) {
copyDir(src, dest);
} else {
fs.copyFileSync(src, dest);
}
}
function copyDir(srcDir: string, destDir: string) {
fs.mkdirSync(destDir, { recursive: true });
for (const file of fs.readdirSync(srcDir)) {
const srcFile = path.resolve(srcDir, file);
const destFile = path.resolve(destDir, file);
copy(srcFile, destFile);
}
}
function getCacheURL() {
const cache_url: string[] = [];
const _travel = (dir: string) => {
const stat = fs.statSync(dir);
if (stat.isDirectory()) {
const files = fs.readdirSync(dir);
files.forEach((file) => {
if (fs.statSync(path.resolve(dir, file)).isDirectory()) {
const navDir =
"/" +
path
.relative(__dirname, path.resolve(dir, file))
.split("/")
.slice(1)
.join("/");
cache_url.push(navDir);
cache_url.push(navDir + "/");
_travel(path.resolve(dir, file));
} else {
cache_url.push(
"/" +
path
.relative(__dirname, path.resolve(dir, file))
.split("/")
.slice(1)
.join("/")
);
}
});
}
};
CACHE_PATH.forEach((p) => _travel(p));
cache_url.push("/");
return cache_url;
}
function getVersion() {
try {
return ChildProcess.execSync("git rev-parse --short HEAD")
.toString()
.trim();
} catch (e) {
console.error("Failed to get git version");
return "unknown";
}
}
function build() {
// copy
SOURCES.forEach((s) => {
copyDir(s, DEST);
});
const str = fs
.readFileSync("./_serviceWorker.js")
.toString()
.replace(
'"$CACHE_URL$"',
`[${getCacheURL()
.map((i) => `"${i}"`)
.join(", ")}]`
)
.replace('"$VERSION$"', `"${getVersion()}"`);
fs.writeFileSync(path.resolve(DEST, "./serviceWorker.js"), str);
}
build();