@microsoft.azure/autorest.testserver
Version:
Autorest test server.
131 lines • 6.39 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.immediatePush = void 0;
/* eslint-disable no-console */
const child_process_1 = require("child_process");
const fs_1 = require("fs");
const path_1 = require("path");
const storage_blob_1 = require("@azure/storage-blob");
const github_1 = require("./github");
const GithubCommentHeader = "<!--AUTO-GENERATED PUBLISH JOB COMMENT-->\n";
const ReportHeader = "<!--AUTO-GENERATED TESTSERVER COVERAGE COMMENT-->\n";
async function collectCoverage(coverageFolder) {
// search for reports
const getMergedReport = (category) => {
const reports = (0, fs_1.readdirSync)(coverageFolder)
.filter((f) => f.startsWith(`report-${category}`) && f.endsWith(".json"))
.map((f) => require((0, path_1.join)(coverageFolder, f)));
const result = {};
for (const feature of reports.flatMap((r) => Object.keys(r))) {
result[feature] = Math.max(...reports.map((r) => r[feature] || 0));
}
return result;
};
const reports = {
General: getMergedReport("vanilla"),
Azure: getMergedReport("azure"),
Optional: getMergedReport("optional"),
DPG: getMergedReport("dpg"),
};
if (Object.keys(reports).every((cat) => Object.keys(reports[cat]).length === 0)) {
const cats = Object.keys(reports).join(", ");
throw new Error(`No report found in coverage folder '${coverageFolder}' for any of the categories: ${cats}`);
}
// post report
let comment = "";
const summary = {};
for (const category of Object.keys(reports)) {
const categoryObject = reports[category];
const features = Object.keys(categoryObject)
.sort()
.map((x) => [x, categoryObject[x] > 0]);
const countTotal = features.length;
const countCovered = features.filter((x) => x[1]).length;
const countMissing = countTotal - countCovered;
summary[category] = {
covered: countCovered,
total: countTotal,
};
const percentCoverage = ((countCovered / (countTotal || 1)) * 100) | 0;
comment += `## ${percentCoverage === 100 ? "✔️" : "❌️"} ${category}: ${percentCoverage}%\n\n`;
if (countMissing > 0) {
comment += `<details><summary>${countMissing} out of ${countTotal} features are not covered by tests</summary><p>\n\n`;
let first = true;
for (const feature of features.filter((x) => !x[1])) {
if (!first)
comment += `, `;
first = false;
const f = feature[0];
comment += `[\`${f}\`](https://github.com/Azure/autorest.testserver/search?q=${f})`;
}
comment += "</p></details>";
}
else if (countTotal === 0) {
comment += `no tests were run for this category\n`;
}
comment += "\n\n";
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const testServerVersion = require((0, path_1.join)(__dirname, "..", "..", "package.json")).version;
const report = `${ReportHeader}# 🤖 AutoRest automatic feature coverage report 🤖\n*feature set version ${testServerVersion}*\n\n${comment}`;
return {
summary,
report,
};
}
function getPublishedPackageVersion() {
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require((0, path_1.join)(__dirname, "..", "..", "..", "..", "..", "package.json")).version;
}
async function pushCoverage(repo, ref, azStorageAccount, azStorageAccessKey, comment, version) {
if (!version) {
version = getPublishedPackageVersion();
}
const blobSvc = new storage_blob_1.BlobServiceClient(`https://${azStorageAccount}.blob.core.windows.net`, new storage_blob_1.StorageSharedKeyCredential(azStorageAccount, azStorageAccessKey));
const containerClient = blobSvc.getContainerClient(`autorest-ci-coverage-report`);
await containerClient.createIfNotExists({
access: "blob",
});
const blockBlobClient = containerClient.getBlockBlobClient(`${repo.split("/")[1]}_${version}.md`);
const content = `<!-- Ref: ${ref}, Generated at ${new Date().toISOString()} -->\n` + comment;
blockBlobClient.upload(content, content.length, {
blobHTTPHeaders: {
blobContentType: "text/markdown; charset=utf-8",
},
});
}
async function immediatePush(repo, ref, githubToken, azStorageAccount, azStorageAccessKey, version, coverageFolder) {
const postComment = githubToken && githubToken !== "skip";
if (postComment) {
// try posting "published" comment on GitHub (IMPORTANT: this assumes that this script is only run after successful publish!)
try {
// try deriving PR associated with last commit
const lastCommitMessage = (0, child_process_1.execSync)("git log -1 --pretty=%B").toString();
const pr = +(/\(#(\d+)\)/g.exec(lastCommitMessage) || [])[1];
if (isNaN(pr))
throw `Could not deduce PR number from commit message ${JSON.stringify(lastCommitMessage)}`;
if (!version) {
version = getPublishedPackageVersion();
}
const ghClient = new github_1.GitHubCiClient(repo, githubToken);
await ghClient.createComment(pr, `${GithubCommentHeader}
# 🤖 AutoRest automatic publish job 🤖
## success (version: ${version})
<!--IMPORTANT: this assumes that this script is only run after successful publish via VSTS! So no "Continue on error" on the publish task!-->`);
}
catch (e) {
console.log("Posting 'published' comment to GitHub failed.");
console.log(e);
}
}
const { report, summary } = await collectCoverage(coverageFolder);
console.log("Uploading coverage report:");
for (const [category, categorySummary] of Object.entries(summary)) {
const percent = ((categorySummary.covered / categorySummary.total) * 100).toFixed(3);
console.log(` - ${category}: ${percent}% (${categorySummary.covered / categorySummary.total})`);
}
console.log("");
await pushCoverage(repo, ref, azStorageAccount, azStorageAccessKey, report, version);
}
exports.immediatePush = immediatePush;
//# sourceMappingURL=coverage.js.map