-
Notifications
You must be signed in to change notification settings - Fork 63
/
main.ts
356 lines (328 loc) · 11.6 KB
/
main.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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import { platform } from 'os';
import { chdir } from 'process';
import { debug, error, setFailed, warning, info } from '@actions/core';
import { exec } from '@actions/exec';
import { context } from '@actions/github';
import * as glob from '@actions/glob';
import {
downloadToFile,
getOptionalString,
verifyChecksum,
verifySignature,
} from './utils';
import type { ExecOptions } from '@actions/exec/lib/interfaces';
const DOWNLOAD_URL = `https://codeclimate.com/downloads/test-reporter/test-reporter-latest-${platform()}-amd64`;
const EXECUTABLE = './cc-reporter';
export const CODECLIMATE_GPG_PUBLIC_KEY_ID =
'9BD9E2DD46DA965A537E5B0A5CBF320243B6FD85' as const;
const CODECLIMATE_GPG_PUBLIC_KEY_URL =
`https://keys.openpgp.org/vks/v1/by-fingerprint/${CODECLIMATE_GPG_PUBLIC_KEY_ID}` as const;
const DEFAULT_COVERAGE_COMMAND = '';
const DEFAULT_WORKING_DIRECTORY = '';
const DEFAULT_CODECLIMATE_DEBUG = 'false';
const DEFAULT_COVERAGE_LOCATIONS = '';
const DEFAULT_VERIFY_DOWNLOAD = 'true';
function prepareEnv() {
const env = process.env as { [key: string]: string };
if (process.env.GITHUB_SHA !== undefined)
env.GIT_COMMIT_SHA = process.env.GITHUB_SHA;
if (process.env.GITHUB_REF !== undefined)
env.GIT_BRANCH = process.env.GITHUB_REF;
if (env.GIT_BRANCH)
env.GIT_BRANCH = env.GIT_BRANCH.replace(/^refs\/heads\//, ''); // Remove 'refs/heads/' prefix (See https://github.com/paambaati/codeclimate-action/issues/42)
if (process.env.GITHUB_EVENT_NAME === 'pull_request') {
env.GIT_BRANCH = process.env.GITHUB_HEAD_REF || env.GIT_BRANCH; // Report correct branch for PRs (See https://github.com/paambaati/codeclimate-action/issues/86)
env.GIT_COMMIT_SHA = context.payload.pull_request?.['head']?.['sha']; // Report correct SHA for the head branch (See https://github.com/paambaati/codeclimate-action/issues/140)
}
return env;
}
async function getLocationLines(
coverageLocationPatternsParam: string
): Promise<Array<string>> {
const coverageLocationPatternsLines = coverageLocationPatternsParam
.split(/\r?\n/)
.filter((pat) => pat)
.map((pat) => pat.trim());
const patternsAndFormats = coverageLocationPatternsLines.map((line) => {
const lineParts = line.split(':');
const format = lineParts.slice(-1)[0];
const pattern = lineParts.slice(0, -1)[0];
return { format, pattern };
});
const pathsWithFormat = await Promise.all(
patternsAndFormats.map(async ({ format, pattern }) => {
const globber = await glob.create(pattern);
const paths = await globber.glob();
const pathsWithFormat = paths.map(
(singlePath) => `${singlePath}:${format}`
);
return pathsWithFormat;
})
);
const coverageLocationLines = ([] as Array<string>).concat(
...pathsWithFormat
);
return coverageLocationLines;
}
export function run(
downloadUrl: string = DOWNLOAD_URL,
executable: string = EXECUTABLE,
coverageCommand: string = DEFAULT_COVERAGE_COMMAND,
workingDirectory: string = DEFAULT_WORKING_DIRECTORY,
codeClimateDebug: string = DEFAULT_CODECLIMATE_DEBUG,
coverageLocationsParam: string = DEFAULT_COVERAGE_LOCATIONS,
coveragePrefix?: string,
verifyDownload: string = DEFAULT_VERIFY_DOWNLOAD
): Promise<void> {
return new Promise(async (resolve, reject) => {
if (platform() === 'win32') {
const err = new Error('CC Reporter is not supported on Windows!');
error(err.message);
setFailed('🚨 CodeClimate Reporter will not run on Windows!');
return reject(err);
}
let lastExitCode = 1;
if (workingDirectory) {
debug(`Changing working directory to ${workingDirectory}`);
try {
chdir(workingDirectory);
lastExitCode = 0;
debug('✅ Changing working directory completed...');
} catch (err) {
error((err as Error).message);
setFailed('🚨 Changing working directory failed!');
return reject(err);
}
}
try {
debug(`ℹ️ Downloading CC Reporter from ${downloadUrl} ...`);
await downloadToFile(downloadUrl, executable);
debug('✅ CC Reporter downloaded...');
} catch (err) {
error((err as Error).message);
setFailed('🚨 CC Reporter download failed!');
warning(`Could not download ${downloadUrl}`);
warning(
`Please check if your platform is supported — see https://docs.codeclimate.com/docs/configuring-test-coverage#section-locations-of-pre-built-binaries`
);
return reject(err);
}
if (verifyDownload === 'true') {
const checksumUrl = `${downloadUrl}.sha256`;
const checksumFilePath = `${executable}.sha256`;
const signatureUrl = `${downloadUrl}.sha256.sig`;
const signatureFilePath = `${executable}.sha256.sig`;
const ccPublicKeyFilePath = 'public-key.asc';
try {
debug(`ℹ️ Verifying CC Reporter checksum...`);
await downloadToFile(checksumUrl, checksumFilePath);
const checksumVerified = await verifyChecksum(
executable,
checksumFilePath,
'sha256'
);
if (!checksumVerified)
throw new Error('CC Reporter checksum does not match!');
debug('✅ CC Reported checksum verification completed...');
} catch (err) {
error((err as Error).message);
setFailed('🚨 CC Reporter checksum verfication failed!');
return reject(err);
}
try {
debug(`ℹ️ Verifying CC Reporter GPG signature...`);
await downloadToFile(signatureUrl, signatureFilePath);
await downloadToFile(
CODECLIMATE_GPG_PUBLIC_KEY_URL,
ccPublicKeyFilePath
);
const signatureVerified = await verifySignature(
checksumFilePath,
signatureFilePath,
ccPublicKeyFilePath
);
if (!signatureVerified)
throw new Error('CC Reporter GPG signature is invalid!');
debug('✅ CC Reported GPG signature verification completed...');
} catch (err) {
error((err as Error).message);
setFailed('🚨 CC Reporter GPG signature verfication failed!');
return reject(err);
}
}
const execOpts: ExecOptions = {
env: prepareEnv(),
};
try {
lastExitCode = await exec(executable, ['before-build'], execOpts);
if (lastExitCode !== 0) {
throw new Error(
`Coverage after-build exited with code ${lastExitCode}`
);
}
debug('✅ CC Reporter before-build checkin completed...');
} catch (err) {
error((err as Error).message);
setFailed('🚨 CC Reporter before-build checkin failed!');
return reject(err);
}
if (coverageCommand) {
try {
lastExitCode = await exec(coverageCommand, undefined, execOpts);
if (lastExitCode !== 0) {
throw new Error(`Coverage run exited with code ${lastExitCode}`);
}
debug('✅ Coverage run completed...');
} catch (err) {
error((err as Error).message);
setFailed('🚨 Coverage run failed!');
return reject(err);
}
} else {
info(
`ℹ️ 'coverageCommand' not set, so skipping building coverage report!`
);
}
const coverageLocations = await getLocationLines(coverageLocationsParam);
if (coverageLocations.length > 0) {
debug(
`Parsing ${
coverageLocations.length
} coverage location(s) — ${coverageLocations} (${typeof coverageLocations})`
);
// Run format-coverage on each location.
const parts: Array<string> = [];
for (const i in coverageLocations) {
const [location, type] = coverageLocations[i].split(':');
if (!type) {
const err = new Error(`Invalid formatter type ${type}`);
debug(
`⚠️ Could not find coverage formatter type! Found ${
coverageLocations[i]
} (${typeof coverageLocations[i]})`
);
error(err.message);
setFailed(
'🚨 Coverage formatter type not set! Each coverage location should be of the format <file_path>:<coverage_format>'
);
return reject(err);
}
const commands = [
'format-coverage',
location,
'-t',
type,
'-o',
`codeclimate.${i}.json`,
];
if (codeClimateDebug === 'true') commands.push('--debug');
if (coveragePrefix) {
commands.push('--prefix', coveragePrefix);
}
parts.push(`codeclimate.${i}.json`);
try {
lastExitCode = await exec(executable, commands, execOpts);
if (lastExitCode !== 0) {
throw new Error(
`Coverage formatter exited with code ${lastExitCode}`
);
}
} catch (err) {
error((err as Error).message);
setFailed('🚨 CC Reporter coverage formatting failed!');
return reject(err);
}
}
// Run sum coverage.
const sumCommands = [
'sum-coverage',
...parts,
'-p',
`${coverageLocations.length}`,
'-o',
`coverage.total.json`,
];
if (codeClimateDebug === 'true') sumCommands.push('--debug');
try {
lastExitCode = await exec(executable, sumCommands, execOpts);
if (lastExitCode !== 0) {
throw new Error(
`Coverage sum process exited with code ${lastExitCode}`
);
}
} catch (err) {
error((err as Error).message);
setFailed('🚨 CC Reporter coverage sum failed!');
return reject(err);
}
// Upload to Code Climate.
const uploadCommands = ['upload-coverage', '-i', `coverage.total.json`];
if (codeClimateDebug === 'true') uploadCommands.push('--debug');
try {
lastExitCode = await exec(executable, uploadCommands, execOpts);
if (lastExitCode !== 0) {
throw new Error(`Coverage upload exited with code ${lastExitCode}`);
}
debug('✅ CC Reporter upload coverage completed!');
return resolve();
} catch (err) {
error((err as Error).message);
setFailed('🚨 CC Reporter coverage upload failed!');
return reject(err);
}
}
try {
const commands = ['after-build', '--exit-code', lastExitCode.toString()];
if (codeClimateDebug === 'true') commands.push('--debug');
if (coveragePrefix) {
commands.push('--prefix', coveragePrefix);
}
lastExitCode = await exec(executable, commands, execOpts);
if (lastExitCode !== 0) {
throw new Error(
`Coverage after-build exited with code ${lastExitCode}`
);
}
debug('✅ CC Reporter after-build checkin completed!');
return resolve();
} catch (err) {
error((err as Error).message);
setFailed('🚨 CC Reporter after-build checkin failed!');
return reject(err);
}
});
}
/* istanbul ignore next */
if (require.main === module) {
const coverageCommand = getOptionalString(
'coverageCommand',
DEFAULT_COVERAGE_COMMAND
);
const workingDirectory = getOptionalString(
'workingDirectory',
DEFAULT_WORKING_DIRECTORY
);
const codeClimateDebug = getOptionalString(
'debug',
DEFAULT_CODECLIMATE_DEBUG
);
const coverageLocations = getOptionalString(
'coverageLocations',
DEFAULT_COVERAGE_LOCATIONS
);
const coveragePrefix = getOptionalString('prefix');
const verifyDownload = getOptionalString(
'verifyDownload',
DEFAULT_VERIFY_DOWNLOAD
);
run(
DOWNLOAD_URL,
EXECUTABLE,
coverageCommand,
workingDirectory,
codeClimateDebug,
coverageLocations,
coveragePrefix,
verifyDownload
);
}