generated from SAP/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathutil.ts
45 lines (40 loc) · 1.33 KB
/
util.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
import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
/**
* @internal
*/
export async function transformFile(
filePath: string,
transformFn: (file: string) => Promise<string> | string
): Promise<void> {
const file = await readFile(filePath, { encoding: 'utf8' });
const transformedFile = await transformFn(file);
await writeFile(filePath, transformedFile, { encoding: 'utf8' });
}
/**
* @internal
*/
export async function transformFilesInDirectory(
dirPath: string,
transformFn: (file: string) => Promise<string> | string,
opts?: {
includeDir?: (dirPath: string) => boolean;
includeFile?: (filePath: string) => boolean;
}
): Promise<void> {
const { includeDir = () => true, includeFile = () => true } = opts || {};
const files = await readdir(dirPath);
for (const file of files) {
const filePath = join(dirPath, file);
try {
const fileStats = await stat(filePath);
if (fileStats.isDirectory() && includeDir(filePath)) {
await transformFilesInDirectory(filePath, transformFn, opts); // Recursive traversal for directories
} else if (fileStats.isFile() && includeFile(filePath)) {
await transformFile(filePath, transformFn);
}
} catch (err) {
throw new Error(`Error processing ${filePath}: ${err}`);
}
}
}