1
0
silverbullet/plugos/asset_bundle/builder.ts

60 lines
1.6 KiB
TypeScript
Raw Normal View History

import { globToRegExp, mime, path, walk } from "../deps.ts";
2022-10-12 09:47:13 +00:00
import { AssetBundle } from "./bundle.ts";
export async function bundleAssets(
rootPath: string,
patterns: string[],
): Promise<AssetBundle> {
const bundle = new AssetBundle();
2022-10-14 13:53:51 +00:00
if (patterns.length === 0) {
return bundle;
}
const matchRegexes = patterns.map((pat) => globToRegExp(pat));
2022-10-12 09:47:13 +00:00
for await (
2022-10-14 13:53:51 +00:00
const file of walk(rootPath)
2022-10-12 09:47:13 +00:00
) {
2022-10-14 13:53:51 +00: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 13:53:51 +00:00
}
2022-10-12 09:47:13 +00:00
}
return bundle;
}
export async function bundleFolder(
rootPath: string,
bundlePath: string,
) {
2022-10-12 09:47:13 +00:00
const bundle = new AssetBundle();
await Deno.mkdir(path.dirname(bundlePath), { recursive: true });
for await (
const { path: filePath } of walk(rootPath, { includeDirs: false })
) {
console.log("Bundling", filePath);
const stat = await Deno.stat(filePath);
2022-10-12 09:47:13 +00: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 09:47:13 +00:00
}
await Deno.writeTextFile(
bundlePath,
JSON.stringify(bundle.toJSON(), null, 2),
);
}