silverbullet/lib/asset_bundle/builder.ts

64 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-10-11 21:52:37 +08:00
// import { globToRegExp, mime, path, walk } from "../deps_server.ts";
import { dirname, globToRegExp } from "@std/path";
2022-10-12 17:47:13 +08:00
import { AssetBundle } from "./bundle.ts";
2024-10-11 21:52:37 +08:00
import { walk } from "@std/fs";
import { mime } from "mimetypes";
2022-10-12 17:47:13 +08:00
export async function bundleAssets(
rootPath: string,
patterns: string[],
): Promise<AssetBundle> {
const bundle = new AssetBundle();
2022-10-14 21:53:51 +08:00
if (patterns.length === 0) {
return bundle;
}
const matchRegexes = patterns.map((pat) => globToRegExp(pat));
2022-10-12 17:47:13 +08:00
for await (
2022-10-14 21:53:51 +08:00
const file of walk(rootPath)
2022-10-12 17:47:13 +08:00
) {
2022-10-14 21:53:51 +08:00
const cleanPath = file.path.substring(rootPath.length + 1);
let match = false;
// console.log("Considering", rootPath, file.path, cleanPath);
for (const matchRegex of matchRegexes) {
if (matchRegex.test(cleanPath)) {
match = true;
break;
}
}
if (match) {
bundle.writeFileSync(
cleanPath,
mime.getType(cleanPath) || "application/octet-stream",
await Deno.readFile(file.path),
);
2022-10-14 21:53:51 +08:00
}
2022-10-12 17:47:13 +08:00
}
return bundle;
}
export async function bundleFolder(
rootPath: string,
bundlePath: string,
) {
2022-10-12 17:47:13 +08:00
const bundle = new AssetBundle();
2024-10-11 21:52:37 +08:00
await Deno.mkdir(dirname(bundlePath), { recursive: true });
2022-10-12 17:47:13 +08:00
for await (
const { path: filePath } of walk(rootPath, { includeDirs: false })
) {
console.log("Bundling", filePath);
const stat = await Deno.stat(filePath);
2022-10-12 17:47:13 +08:00
const cleanPath = filePath.substring(`${rootPath}/`.length);
bundle.writeFileSync(
cleanPath,
mime.getType(filePath) || "application/octet-stream",
await Deno.readFile(filePath),
stat.mtime?.getTime(),
);
2022-10-12 17:47:13 +08:00
}
await Deno.writeTextFile(
bundlePath,
JSON.stringify(bundle.toJSON(), null, 2),
);
}