file.ts
2.29 KB
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 fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";
export function isTextFile(file: string): boolean {
const ext = path.extname(file).toLowerCase();
return [ ".css", ".html", ".js", ".json", ".jsx", ".less", ".md", ".scss", ".ts", ".tsx", ".vue" ].includes(ext);
}
export async function ensureDir(dir: string): Promise<void> {
await fsp.mkdir(dir, { recursive: true });
}
export async function copyDir(
src: string,
dest: string,
options?: { skip?: (relPath: string) => boolean },
): Promise<void> {
const entries = await fsp.readdir(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const rel = path.relative(src, srcPath);
if (options?.skip?.(rel)) continue;
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
await ensureDir(destPath);
await copyDir(srcPath, destPath, options);
} else if (entry.isFile()) {
await ensureDir(path.dirname(destPath));
await fsp.copyFile(srcPath, destPath);
}
}
}
export async function replacePlaceholders(destRoot: string, replacements: Record<string, string>): Promise<void> {
const walk = async (dir: string) => {
const entries = await fsp.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) await walk(full);
else if (entry.isFile() && isTextFile(full)) {
let content = await fsp.readFile(full, "utf8");
for (const [ from, to ] of Object.entries(replacements)) {
content = content.split(from).join(to);
}
await fsp.writeFile(full, content);
}
}
};
await walk(destRoot);
}
export async function applyOptionalFeature(
destRoot: string,
tplRoot: string,
featurePath: string,
mergeJson: (targetPath: string, mergeObj: Record<string, any>) => Promise<void>,
): Promise<void> {
const src = path.join(tplRoot, featurePath);
if (!fs.existsSync(src)) return;
// Copy files excluding merge manifest
await copyDir(src, destRoot, {
skip: (rel) => rel.endsWith("_package.merge.json"),
});
const mergeFile = path.join(src, "_package.merge.json");
if (fs.existsSync(mergeFile)) {
const mergeObj = JSON.parse(await fsp.readFile(mergeFile, "utf8"));
await mergeJson(path.join(destRoot, "package.json"), mergeObj);
}
}