-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsave-generation-result.ts
More file actions
48 lines (47 loc) · 1.91 KB
/
save-generation-result.ts
File metadata and controls
48 lines (47 loc) · 1.91 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
import fs from 'fs';
import path from 'path';
import * as R from 'ramda';
import {ClientGenerationResultFile} from '../schema-to-typescript/config';
export async function saveGenerationResult({
files,
outputDirPath,
cleanupDirectories
}: {
files: ClientGenerationResultFile[];
outputDirPath: string;
cleanupDirectories: string[];
}) {
const filesIndex = R.indexBy(({filename}) => path.resolve(outputDirPath, filename), files);
await Promise.all([
...cleanupDirectories.map(async (directoryRelativePath) => {
const directoryPath = path.resolve(outputDirPath, directoryRelativePath);
for (const filename of await fs.promises.readdir(directoryPath)) {
const fullFilename = path.resolve(directoryPath, filename);
if (!Object.prototype.hasOwnProperty.call(filesIndex, fullFilename)) {
console.log('[deleted] ' + fullFilename);
await fs.promises.rm(fullFilename, {recursive: true});
}
}
}),
...files.map(async ({filename, data}) => {
const fullFilename = path.resolve(outputDirPath, filename);
try {
let exists = false;
try {
const existingContent = await fs.promises.readFile(fullFilename, 'utf8');
exists = true;
if (existingContent === data) {
console.log('[no change] ' + fullFilename);
return;
}
} catch (e) {
// ok
}
await fs.promises.writeFile(fullFilename, data);
console.log(`[${exists ? 'updated' : 'created'}] ${fullFilename}`);
} catch (e) {
throw new Error(`Could not save file "${fullFilename}": ${e instanceof Error ? e.message : e}.`);
}
})
]);
}