forked from stolostron/grafana
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathjest.config.codeowner.js
More file actions
197 lines (167 loc) · 6.1 KB
/
jest.config.codeowner.js
File metadata and controls
197 lines (167 loc) · 6.1 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
const fs = require('fs');
const open = require('open').default;
const path = require('path');
const baseConfig = require('./jest.config.js');
const { CODEOWNER_KIND, getCodeownerKind, createCodeownerSlug } = require('./scripts/codeowners-manifest/utils.js');
const CODEOWNERS_MANIFEST_FILENAMES_BY_TEAM_PATH = 'codeowners-manifest/filenames-by-team.json';
const codeownerName = process.env.CODEOWNER_NAME;
if (!codeownerName) {
console.error('ERROR: CODEOWNER_NAME environment variable is required');
process.exit(1);
}
const outputDir = `./coverage/by-team/${createCodeownerDirectory(codeownerName)}`;
const COVERAGE_SUMMARY_OUTPUT_PATH = './coverage-summary.json';
const codeownersFilePath = path.join(__dirname, CODEOWNERS_MANIFEST_FILENAMES_BY_TEAM_PATH);
if (!fs.existsSync(codeownersFilePath)) {
console.error(`Codeowners file not found at ${codeownersFilePath} ...`);
console.error('Please run: yarn codeowners-manifest first to generate the mapping file');
process.exit(1);
}
const codeownersData = JSON.parse(fs.readFileSync(codeownersFilePath, 'utf8'));
const teamFiles = codeownersData[codeownerName] || [];
if (teamFiles.length === 0) {
console.error(`ERROR: No files found for team "${codeownerName}"`);
console.error('Available teams:', Object.keys(codeownersData).join(', '));
process.exit(1);
}
const sourceFiles = teamFiles.filter((file) => {
const ext = path.extname(file);
return (
['.ts', '.tsx', '.js', '.jsx'].includes(ext) &&
// exclude all tests and mocks
!path.matchesGlob(file, '**/test/**/*') &&
!file.includes('.test.') &&
!file.includes('.spec.') &&
!path.matchesGlob(file, '**/__mocks__/**/*') &&
// and storybook stories
!file.includes('.story.') &&
// and generated files
!file.includes('.gen.ts') &&
// and type definitions
!file.includes('.d.ts') &&
!file.endsWith('/types.ts') &&
// and anything in graveyard
!path.matchesGlob(file, '**/graveyard/**/*') &&
// and scripts directory
!file.startsWith('scripts/') &&
// and jest config files
!path.matchesGlob(file, '**/jest.config*.js')
);
});
const testFiles = teamFiles.filter((file) => {
const ext = path.extname(file);
return ['.ts', '.tsx', '.js', '.jsx'].includes(ext) && (file.includes('.test.') || file.includes('.spec.'));
});
if (testFiles.length === 0) {
console.log(`No test files found for team ${codeownerName}`);
process.exit(0);
}
console.log(
`🧪 Collecting coverage for ${sourceFiles.length} testable files and running ${testFiles.length} test files of ${teamFiles.length} files owned by ${codeownerName}.`
);
module.exports = {
...baseConfig,
collectCoverage: true,
collectCoverageFrom: sourceFiles.map((file) => `<rootDir>/${file}`),
coverageReporters: ['none'],
coverageDirectory: '/tmp/jest-coverage-ignore',
coverageProvider: 'v8',
reporters: [
'default',
[
'jest-monocart-coverage',
{
name: `Coverage Report - ${codeownerName} owned files`,
outputDir: outputDir,
reports: ['console-summary', 'v8', 'json', 'lcov'],
sourceFilter: (coveredFile) => sourceFiles.includes(coveredFile),
all: {
dir: ['./packages', './public'],
filter: (filePath) => {
const relativePath = filePath.replace(process.cwd() + '/', '');
return sourceFiles.includes(relativePath);
},
},
cleanCache: true,
onEnd: (coverageResults) => {
const reportURL = `file://${path.resolve(outputDir)}/index.html`;
console.log(`📄 Coverage report saved to ${reportURL}`);
if (process.env.SHOULD_OPEN_COVERAGE_REPORT === 'true') {
openCoverageReport(reportURL);
}
writeCoverageSummaryArtifact(coverageResults);
// TODO: Emit coverage metrics https://github.com/grafana/grafana/issues/111208
},
},
],
],
testRegex: undefined,
testMatch: testFiles.map((file) => `<rootDir>/${file}`),
};
/**
* @typedef {Object} CoverageMetric
* @property {number} pct - Percentage value
*/
/**
* @typedef {Object} CoverageSummary
* @property {CoverageMetric} lines
* @property {CoverageMetric} statements
* @property {CoverageMetric} functions
* @property {CoverageMetric} branches
*/
/**
* @typedef {Object} CoverageResults
* @property {CoverageSummary} summary
*/
/**
* Writes coverage summary artifact for CI/CD consumption
* @param {CoverageResults} coverageResults - Coverage results from jest-monocart-coverage
*/
function writeCoverageSummaryArtifact(coverageResults) {
if (!coverageResults || !coverageResults.summary) {
return;
}
const summary = {
team: codeownerName,
commit: process.env.GITHUB_SHA || 'unknown',
timestamp: new Date().toISOString(),
summary: {
lines: { pct: coverageResults.summary.lines.pct },
statements: { pct: coverageResults.summary.statements.pct },
functions: { pct: coverageResults.summary.functions.pct },
branches: { pct: coverageResults.summary.branches.pct },
},
};
try {
fs.writeFileSync(COVERAGE_SUMMARY_OUTPUT_PATH, JSON.stringify(summary, null, 2));
console.log(`📊 Coverage summary written to ${COVERAGE_SUMMARY_OUTPUT_PATH}`);
} catch (err) {
console.error(`Failed to write coverage summary: ${err}`);
}
}
/**
* Creates a directory path for coverage reports grouped by codeowner kind
* @param {string} codeowner - CODEOWNERS codeowner
* @returns {string} Directory path relative to coverage/by-team/
*/
function createCodeownerDirectory(codeowner) {
const kind = getCodeownerKind(codeowner);
if (kind === CODEOWNER_KIND.UNKNOWN) {
throw new Error(
`Invalid codeowner format: "${codeowner}". Must be a GitHub team (@org/team), user (@username), or email (email@domain.tld)`
);
}
const slug = createCodeownerSlug(codeowner);
return `${kind}s/${slug}`;
}
/**
* Opens the coverage report in the default browser
* @param {string} reportURL - File URL to the coverage report HTML
*/
async function openCoverageReport(reportURL) {
try {
await open(reportURL);
} catch (err) {
console.error(`Failed to open coverage report: ${err}`);
}
}