forked from alibaba/lowcode-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
78 lines (66 loc) · 1.99 KB
/
utils.ts
File metadata and controls
78 lines (66 loc) · 1.99 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
71
72
73
74
75
76
77
78
import * as systemFs from 'fs';
import { join } from 'path';
import { ResultDir, ResultFile } from '@alilc/lowcode-types';
export interface IFileSystem {
existsSync: typeof systemFs.existsSync;
mkdir: typeof systemFs.mkdir;
writeFile: typeof systemFs.writeFile;
}
export const writeFolder = async (
folder: ResultDir,
currentPath: string,
createProjectFolder = true,
fs: IFileSystem = systemFs,
): Promise<void> => {
const { name, files, dirs } = folder;
const folderPath = createProjectFolder ? join(currentPath, name) : currentPath;
if (!fs.existsSync(folderPath)) {
await createDirectory(folderPath, fs);
}
const promises = [
writeFilesToFolder(folderPath, files, fs),
writeSubFoldersToFolder(folderPath, dirs, fs),
];
await Promise.all(promises);
};
const writeFilesToFolder = async (
folderPath: string,
files: ResultFile[],
fs: IFileSystem,
): Promise<void> => {
const promises = files.map((file) => {
const fileName = file.ext ? `${file.name}.${file.ext}` : file.name;
const filePath = join(folderPath, fileName);
return writeContentToFile(filePath, file.content, 'utf8', fs);
});
await Promise.all(promises);
};
const writeSubFoldersToFolder = async (
folderPath: string,
subFolders: ResultDir[],
fs: IFileSystem,
): Promise<void> => {
const promises = subFolders.map((subFolder) => {
return writeFolder(subFolder, folderPath, true, fs);
});
await Promise.all(promises);
};
const createDirectory = (pathToDir: string, fs: IFileSystem): Promise<void> => {
return new Promise((resolve, reject) => {
fs.mkdir(pathToDir, { recursive: true }, (err) => {
err ? reject(err) : resolve();
});
});
};
const writeContentToFile = (
filePath: string,
fileContent: string,
encoding = 'utf8',
fs: IFileSystem,
): Promise<void> => {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, fileContent, { encoding: encoding as BufferEncoding }, (err) => {
err ? reject(err) : resolve();
});
});
};