-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpersist.ts
More file actions
85 lines (77 loc) · 2.25 KB
/
Copy pathpersist.ts
File metadata and controls
85 lines (77 loc) · 2.25 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
79
80
81
82
83
84
85
import { mkdir, stat, writeFile } from 'node:fs/promises';
import type { Format, PersistConfig, Report } from '@code-pushup/models';
import {
type MultipleFileResults,
type ScoredReport,
createReportPath,
directoryExists,
generateMdReport,
logMultipleFileResults,
ui,
} from '@code-pushup/utils';
export class PersistDirError extends Error {
constructor(outputDir: string) {
super(`outPath: ${outputDir} is no directory.`);
}
}
export class PersistError extends Error {
constructor(reportPath: string) {
super(`fileName: ${reportPath} could not be saved.`);
}
}
export async function persistReport(
report: Report,
sortedScoredReport: ScoredReport,
options: Required<Omit<PersistConfig, 'skipReports'>>,
): Promise<MultipleFileResults> {
const { outputDir, filename, format } = options;
// collect physical format outputs
const results = format.map(
(reportType): { format: Format; content: string } => {
switch (reportType) {
case 'json':
return {
format: 'json',
content: JSON.stringify(report, null, 2),
};
case 'md':
return {
format: 'md',
content: generateMdReport(sortedScoredReport, { outputDir }),
};
}
},
);
if (!(await directoryExists(outputDir))) {
try {
await mkdir(outputDir, { recursive: true });
} catch (error) {
ui().logger.warning((error as Error).toString());
throw new PersistDirError(outputDir);
}
}
// write relevant format outputs to file system
return Promise.allSettled(
results.map(result =>
persistResult(
createReportPath({ outputDir, filename, format: result.format }),
result.content,
),
),
);
}
async function persistResult(reportPath: string, content: string) {
return (
writeFile(reportPath, content)
// return reportPath instead of void
.then(() => stat(reportPath))
.then(stats => [reportPath, stats.size] as const)
.catch(error => {
ui().logger.warning((error as Error).toString());
throw new PersistError(reportPath);
})
);
}
export function logPersistedResults(persistResults: MultipleFileResults) {
logMultipleFileResults(persistResults, 'Generated reports');
}