-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
sonar-reporter.ts
69 lines (57 loc) · 1.89 KB
/
sonar-reporter.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { dirname, resolve } from 'pathe';
import type { Reporter, File, Vitest } from 'vitest';
import { generateXml } from './xml.js';
/**
* Reporter used by `vitest`
*/
export default class SonarReporter implements Reporter {
ctx!: Vitest;
outputFile!: string;
onInit(ctx: Vitest) {
this.ctx = ctx;
if (!this.ctx.config.outputFile) {
throw new Error(
'SonarReporter requires config.outputFile to be defined in vite config'
);
}
this.outputFile = resolveOutputfile(this.ctx.config);
if (existsSync(this.outputFile)) {
rmSync(this.outputFile);
}
}
onFinished(files?: File[]) {
const reportFile = resolve(this.ctx.config.root, this.outputFile);
const outputDirectory = dirname(reportFile);
if (!existsSync(outputDirectory)) {
mkdirSync(outputDirectory, { recursive: true });
}
writeFileSync(reportFile, generateXml(files), 'utf-8');
this.ctx.logger.log(`SonarQube report written to ${reportFile}`);
}
}
function resolveOutputfile(config: Vitest['config']) {
if (typeof config.outputFile === 'string') {
return config.outputFile;
}
if (config.outputFile['vitest-sonar-reporter']) {
return config.outputFile['vitest-sonar-reporter'];
}
throw new Error(
[
'Unable to resolve outputFile for vitest-sonar-reporter.',
'Define outputFile as string or add entry for it:',
JSON.stringify(
{
test: {
outputFile: {
'vitest-sonar-reporter': 'sonar-report.xml',
},
},
},
null,
2
),
].join('\n')
);
}