Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ The **Zoosh Bitbucket Code Insights** is designed for uploading reports to Bitbu

For more details, please refer to the [Zoosh Bitbucket Code Insights README](packages/bitbucket-code-insights/README.md)

## Zoosh bitbucket-eslint-report

The **Zoosh bitbucket-eslint-report** is designed to facilitate the upload of an eslint report to Bitbucket. It provides functions to automate the process of uploading reports generated during build processes.

For more details, please refer to the [Zoosh bitbucket-eslint-report README](packages/bitbucket-eslint-report/README.md).

## Zoosh bitbucket-v8-coverage-report

The **Zoosh bitbucket-v8-coverage-report** is designed to facilitate the upload of V8 test coverage reports to Bitbucket. It provides functions to automate the process of uploading reports generated during build processes.
Expand All @@ -18,4 +24,4 @@ For more details, please refer to the [Zoosh bitbucket-v8-coverage-report README

Projects are licensed under the **GNU General Public License v3.0.** See the LICENSE file for details.

Thank you for using these tools to streamline your Bitbucket report management. For more information, visit the respective repository READMEs.
Thank you for using these tools to streamline your Bitbucket report management. For more information, visit the respective repository READMEs.
1 change: 1 addition & 0 deletions packages/bitbucket-code-insights/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ The project offers the following function to easily upload metadata to our commi
- `uploadReportToBitbucket`: Creates a "report" with the given metrics. This is best used for attaching useful information to a pull requests (for example coverage metrics).
- `uploadAnnotationsToBitbucket`: Attaches "annotations" to a report created by the previous command (these annotations can be shown in the diff view of the pull request)
- `createBuildOnBitbucket`: Creates a "build" with the given details. This is useful to show the result of a specific build or test step explicitly in the list of builds, besides the main pipeline build.
- `createCommentOnBitbucket`: Creates a simple "comment" with the given text on a pull request. This is useful to highlight something important explicitly and also trigger sending an email to reviewers.

More details can be found in the Bitbucket API documentation [here](https://developer.atlassian.com/cloud/bitbucket/rest/api-group-reports/#api-repositories-workspace-repo-slug-commit-commit-reports-reportid-put).

Expand Down
2 changes: 1 addition & 1 deletion packages/bitbucket-code-insights/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zooshdigital/bitbucket-code-insights",
"version": "1.2.2",
"version": "1.3.0",
"packageManager": "yarn@3.6.3",
"description": "Function to upload reports to Bitbucket",
"author": {
Expand Down
16 changes: 15 additions & 1 deletion packages/bitbucket-code-insights/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fetch from 'node-fetch';

import { createLogger } from 'utils/logger';
import { BitbucketAnnotation, BitbucketBuildBody, BitbucketReportBody } from './types';
import { BitbucketAnnotation, BitbucketBuildBody, BitbucketReportBody, BitbucketPrCommentBody } from './types';

const logger = createLogger('Bitbucket Code Insights');

Expand Down Expand Up @@ -91,3 +91,17 @@ export async function createBuildOnBitbucket(body: BitbucketBuildBody) {
logger.log(`Build created successfully.`);
}
}

export async function createCommentOnBitbucket(body: BitbucketPrCommentBody) {
assertEnvVars();
const repoFullName = process.env.BITBUCKET_REPO_FULL_NAME ?? '';
const pullRequestId = process.env.BITBUCKET_PR_ID ?? '';
const token = process.env.BITBUCKET_BUILD_TOKEN ?? '';

const url = `https://api.bitbucket.org/2.0/repositories/${repoFullName}/pullrequests/${pullRequestId}/comments`;

const response = await callApi(url, 'POST', body, token);
if (response.ok) {
logger.log(`Build created successfully.`);
}
}
6 changes: 6 additions & 0 deletions packages/bitbucket-code-insights/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,9 @@ export interface BitbucketBuildBody {
description: string;
url: string;
}

export interface BitbucketPrCommentBody {
content: {
raw: string;
};
}
4 changes: 4 additions & 0 deletions packages/bitbucket-v8-coverage-report/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ It takes the following arguments:
- `-f [percentage]` or `--min-functions-coverage [percentage]` (optional): Optional threshold for the functions coverage value.
- `-b [percentage]` or `--min-branches-coverage [percentage]` (optional): Optional threshold for the branches coverage value.
- `-a` or `--add-build` (optional): Create a success/failed "build" as well besides the report.
- `-j [path]` or `junit-path [path]`: (required for the `failed-test-comment` flag): The path to a junit XML file with unit test results.
- `-t` or `--failed-test-comment`: Create a comment on a PR in case there are failed unit tests in the junit XML file.

Ensure that the specified path leads to a V8 coverage report that can be passed to the Bitbucket API.

Expand All @@ -77,6 +79,8 @@ While some requests could be automatically authenticated running in a pipeline,

Since information is attached to a commit (even in case of a pull request), the library needs the BITBUCKET_REPO_FULL_NAME and BITBUCKET_COMMIT environment variables to do that. These two are standard Bitbucket pipeline variables, so there is no need to set them explicitly if running the script in a pipeline.

The tool uses BITBUCKET_PR_ID for the `failed-test-comment` functionality.

## License

This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.
51 changes: 49 additions & 2 deletions packages/bitbucket-v8-coverage-report/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@

import fs from 'fs/promises';
import commandLineArgs from 'command-line-args';
import { createBuildOnBitbucket, uploadReportToBitbucket } from '@zooshdigital/bitbucket-code-insights';
import { parse as parseJUnit, TestCase, TestSuites } from 'junit2json';
import {
createBuildOnBitbucket,
createCommentOnBitbucket,
uploadReportToBitbucket,
} from '@zooshdigital/bitbucket-code-insights';
import { BitbucketReportBody } from '@zooshdigital/bitbucket-code-insights/dist/types';

import { createLogger } from 'utils/logger';
Expand All @@ -22,6 +27,8 @@ const optionDefinitions = [
{ name: 'min-functions-coverage', alias: 'f', type: Number },
{ name: 'min-branches-coverage', alias: 'b', type: Number },
{ name: 'add-build', alias: 'a', type: Boolean },
{ name: 'junit-path', alias: 'j', type: String },
{ name: 'failed-test-comment', alias: 't', type: Boolean },
];

const args = commandLineArgs(optionDefinitions);
Expand All @@ -47,6 +54,26 @@ function getReportResult(
return true;
}

const getTestFailureText = (testCase: TestCase): string =>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the index file is getting quite long. Maybe functions like getTestFailureText, getTestCaseText, and getTestCasesText could be moved to a separate utils file?

testCase.failure
?.map(
(failure) => `\`\`\`
${failure.inner}
\`\`\`
`,
)
.join('\n') ?? '';

const getTestCaseText = (testCase: TestCase): string =>
`## ${testCase.name}

${getTestFailureText(testCase)}`;

const getTestCasesText = (testCases: TestCase[]): string =>
`# ${testCases.length} test case(s) failed!

${testCases.map(getTestCaseText).join('\n\n')}`;

async function uploadReport() {
try {
const {
Expand All @@ -58,6 +85,8 @@ async function uploadReport() {
'min-functions-coverage': minFunctionsCoverage,
'min-branches-coverage': minBranchesCoverage,
'add-build': addBuild,
'junit-path': junitPath,
'failed-test-comment': failedTestComment,
} = args;

if (!name || !reportPath) {
Expand All @@ -68,7 +97,7 @@ async function uploadReport() {

const coverageResults = JSON.parse(await fs.readFile(reportPath, 'utf8'));

const coverageResultPercentage = {
const coverageResultPercentage: CoverageResult = {
statements: coverageResults.total.statements.pct,
lines: coverageResults.total.lines.pct,
functions: coverageResults.total.functions.pct,
Expand Down Expand Up @@ -136,6 +165,24 @@ async function uploadReport() {
});
}

if (failedTestComment && junitPath) {
const jUnitResult = (await parseJUnit(await fs.readFile(junitPath, 'utf8'))) as TestSuites;
if (jUnitResult) {
const failedTestCases =
jUnitResult.testsuite?.flatMap(
(testSuite) => testSuite.testcase?.filter((testCase) => !!testCase.failure) ?? [],
) ?? [];
if (failedTestCases.length) {
const comment = getTestCasesText(failedTestCases);
await createCommentOnBitbucket({
content: {
raw: comment,
},
});
}
}
}

logger.log('Report uploaded successfully', name);
} catch (error) {
logger.log(`Error uploading report: ${error}`);
Expand Down
7 changes: 4 additions & 3 deletions packages/bitbucket-v8-coverage-report/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zooshdigital/bitbucket-v8-coverage-report",
"version": "1.2.9",
"version": "1.3.1",
"packageManager": "yarn@3.6.3",
"description": "Command-line tool to upload coverage reports to Bitbucket",
"keywords": [
Expand Down Expand Up @@ -34,8 +34,9 @@
"license": "GPL-3.0",
"homepage": "https://github.com/zooshgroup/bitbucket-tools",
"dependencies": {
"@zooshdigital/bitbucket-code-insights": "1.2.2",
"command-line-args": "5.2.1"
"@zooshdigital/bitbucket-code-insights": "1.3.0",
"command-line-args": "5.2.1",
"junit2json": "3.1.12"
},
"devDependencies": {
"@types/command-line-args": "5.2.3",
Expand Down
Loading