-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathgenerate_static_assets.ts
84 lines (76 loc) · 1.98 KB
/
generate_static_assets.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
import { join, relative, walk } from "./deps.ts";
import { logger } from "./logger_util.ts";
export async function checkStaticDir(dir: string): Promise<boolean> {
try {
const stat = await Deno.lstat(dir);
if (stat.isDirectory) {
logger.info(`Using "${dir}" as static directory`);
return true;
} else {
logger.warn(`Error: "${dir}" is not directory`);
return false;
}
} catch (e) {
if (e.name === "NotFound") {
logger.info(`No static dir "${dir}"`);
return false;
}
logger.error(e);
return false;
}
}
type GenerateStaticAssetsOptions = {
distPrefix: string;
};
export async function* generateStaticAssets(
dir: string,
opts: GenerateStaticAssetsOptions,
): AsyncIterable<File> {
if (!await checkStaticDir(dir)) {
return;
}
for await (const entry of walk(dir)) {
if (!entry.isDirectory) {
yield createStaticAssetFromPath(entry.path, dir, opts.distPrefix);
}
}
}
export async function* watchAndGenStaticAssets(
dir: string,
opts: GenerateStaticAssetsOptions,
): AsyncIterable<File> {
if (!await checkStaticDir(dir)) {
return;
}
for await (const entry of walk(dir)) {
if (!entry.isDirectory) {
yield createStaticAssetFromPath(entry.path, dir, opts.distPrefix);
}
}
for await (const e of Deno.watchFs(dir)) {
for (const path of e.paths) {
// TODO(kt3k): Make this concurrent
try {
const stat = await Deno.lstat(path);
if (stat.isDirectory) {
continue;
}
yield await createStaticAssetFromPath(path, dir, opts.distPrefix);
} catch (e) {
logger.error(e);
}
}
}
}
async function createStaticAssetFromPath(
path: string,
root: string,
distPrefix: string,
): Promise<File> {
logger.debug("Reading", path);
const bytes = await Deno.readFile(path);
const webkitRelativePath = relative(root, path);
return new File([bytes], join(distPrefix, webkitRelativePath), {
lastModified: 0,
});
}