-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbinding.ts
More file actions
266 lines (249 loc) · 7.32 KB
/
binding.ts
File metadata and controls
266 lines (249 loc) · 7.32 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import { readdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
import path from 'node:path';
import type {
CategoryConfig,
PluginAnswer,
PluginSetupBinding,
PluginSetupTree,
} from '@code-pushup/models';
import {
answerArray,
answerBoolean,
answerString,
hasDependency,
pluralize,
readJsonFile,
singleQuote,
} from '@code-pushup/utils';
import { addLcovReporter, hasLcovReporter } from './config-file.js';
import {
ALL_COVERAGE_TYPES,
COVERAGE_PLUGIN_SLUG,
COVERAGE_PLUGIN_TITLE,
} from './constants.js';
const { name: PACKAGE_NAME } = createRequire(import.meta.url)(
'../../package.json',
) as typeof import('../../package.json');
const CONFIG_EXT = '[mc]?[tj]s';
const VITEST_CONFIG = new RegExp(`^vi(test|te)\\.config\\.${CONFIG_EXT}$`);
const VITEST_WORKSPACE = new RegExp(`^vitest\\.workspace\\.${CONFIG_EXT}$`);
const JEST_CONFIG = new RegExp(`^jest\\.config\\.${CONFIG_EXT}$`);
const DEFAULT_REPORT_PATH = 'coverage/lcov.info';
const LCOV_COMMENT =
'// NOTE: Ensure your test config includes "lcov" in coverage reporters.';
const FRAMEWORKS = [
{ name: 'Jest', value: 'jest' },
{ name: 'Vitest', value: 'vitest' },
{ name: 'other', value: 'other' },
] as const;
type Framework = (typeof FRAMEWORKS)[number]['value'];
const CATEGORIES: CategoryConfig[] = [
{
slug: 'code-coverage',
title: 'Code coverage',
description: 'Measures how much of your code is **covered by tests**.',
refs: [
{
type: 'group',
plugin: COVERAGE_PLUGIN_SLUG,
slug: 'coverage',
weight: 1,
},
],
},
];
type CoverageOptions = {
framework: string;
configFile: string;
reportPath: string;
testCommand: string;
types: string[];
continueOnFail: boolean;
categories: boolean;
};
export const coverageSetupBinding = {
slug: COVERAGE_PLUGIN_SLUG,
title: COVERAGE_PLUGIN_TITLE,
packageName: PACKAGE_NAME,
isRecommended,
// eslint-disable-next-line max-lines-per-function
prompts: async (targetDir: string) => {
const framework = await detectFramework(targetDir);
const configFile = await detectConfigFile(targetDir, framework);
return [
{
key: 'coverage.framework',
message: 'Test framework',
type: 'select',
choices: [...FRAMEWORKS],
default: framework,
},
{
key: 'coverage.configFile',
message: 'Path to test config file',
type: 'input',
default: configFile ?? '',
},
{
key: 'coverage.reportPath',
message: 'Path to LCOV report file',
type: 'input',
default: framework === 'other' ? '' : DEFAULT_REPORT_PATH,
},
{
key: 'coverage.testCommand',
message: 'Command to run tests with coverage',
type: 'input',
default: defaultTestCommand(framework),
},
{
key: 'coverage.types',
message: 'Coverage types to measure',
type: 'checkbox',
choices: ALL_COVERAGE_TYPES.map(type => ({
name: pluralize(type),
value: type,
})),
default: [...ALL_COVERAGE_TYPES],
},
{
key: 'coverage.continueOnFail',
message: 'Continue if test command fails?',
type: 'confirm',
default: true,
},
{
key: 'coverage.categories',
message: 'Add Code coverage categories?',
type: 'confirm',
default: true,
},
];
},
generateConfig: async (
answers: Record<string, PluginAnswer>,
tree?: PluginSetupTree,
) => {
const options = parseAnswers(answers);
const lcovConfigured = await configureLcovReporter(options, tree);
return {
imports: [
{ moduleSpecifier: PACKAGE_NAME, defaultImport: 'coveragePlugin' },
],
pluginInit: formatPluginInit(options, lcovConfigured),
...(options.categories ? { categories: CATEGORIES } : {}),
};
},
} satisfies PluginSetupBinding;
function parseAnswers(answers: Record<string, PluginAnswer>): CoverageOptions {
return {
framework: answerString(answers, 'coverage.framework'),
configFile: answerString(answers, 'coverage.configFile'),
reportPath:
answerString(answers, 'coverage.reportPath') || DEFAULT_REPORT_PATH,
testCommand: answerString(answers, 'coverage.testCommand'),
types: answerArray(answers, 'coverage.types'),
continueOnFail: answerBoolean(answers, 'coverage.continueOnFail'),
categories: answerBoolean(answers, 'coverage.categories'),
};
}
/** Returns true if lcov reporter is already present or was successfully added. */
async function configureLcovReporter(
options: CoverageOptions,
tree?: PluginSetupTree,
): Promise<boolean> {
const { framework, configFile } = options;
if (framework === 'other' || !configFile || !tree) {
return false;
}
const content = await tree.read(configFile);
if (content == null) {
return false;
}
if (hasLcovReporter(content, framework)) {
return true;
}
const modified = addLcovReporter(content, framework);
if (modified === content) {
return false;
}
await tree.write(configFile, modified);
return true;
}
function formatPluginInit(
options: CoverageOptions,
lcovConfigured: boolean,
): string[] {
const { reportPath, testCommand, types, continueOnFail } = options;
const hasCustomTypes =
types.length > 0 && types.length < ALL_COVERAGE_TYPES.length;
const body = [
`reports: [${singleQuote(reportPath)}],`,
testCommand
? `coverageToolCommand: { command: ${singleQuote(testCommand)} },`
: '',
hasCustomTypes
? `coverageTypes: [${types.map(singleQuote).join(', ')}],`
: '',
continueOnFail ? '' : 'continueOnCommandFail: false,',
].filter(Boolean);
const init = [
'await coveragePlugin({',
...body.map(line => ` ${line}`),
'}),',
];
return lcovConfigured ? init : [LCOV_COMMENT, ...init];
}
async function isRecommended(targetDir: string): Promise<boolean> {
return (await detectFramework(targetDir)) !== 'other';
}
async function detectFramework(targetDir: string): Promise<Framework> {
const files = await readdir(targetDir, { encoding: 'utf8' });
const hasVitestConfig = files.some(
file => VITEST_CONFIG.test(file) || VITEST_WORKSPACE.test(file),
);
const hasJestConfig = files.some(file => JEST_CONFIG.test(file));
if (hasVitestConfig) {
return 'vitest';
}
if (hasJestConfig) {
return 'jest';
}
try {
const packageJson = await readJsonFile<{
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
}>(path.join(targetDir, 'package.json'));
if (hasDependency(packageJson, 'vitest')) {
return 'vitest';
}
if (hasDependency(packageJson, 'jest')) {
return 'jest';
}
} catch {
return 'other';
}
return 'other';
}
async function detectConfigFile(
targetDir: string,
framework: Framework,
): Promise<string | undefined> {
if (framework === 'other') {
return undefined;
}
const files = await readdir(targetDir, { encoding: 'utf8' });
const pattern = framework === 'vitest' ? VITEST_CONFIG : JEST_CONFIG;
return files.find(file => pattern.test(file));
}
function defaultTestCommand(framework: Framework): string {
switch (framework) {
case 'jest':
return 'npx jest --coverage';
case 'vitest':
return 'npx vitest run --coverage.enabled';
default:
return '';
}
}