Address comments from review

- Change error messages.
- Use logger instead of core
- throw Error instead of write error message
This commit is contained in:
Andrew Eisenberg 2023-11-15 12:47:51 -08:00
parent 04451e072f
commit df9b50ee5f
6 changed files with 68 additions and 52 deletions

View file

@ -24,7 +24,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = exports.tryUploadSarifIfRunFailed = void 0;
const core = __importStar(require("@actions/core"));
const actionsUtil = __importStar(require("./actions-util"));
const api_client_1 = require("./api-client");
const codeql_1 = require("./codeql");
@ -75,7 +74,7 @@ async function maybeUploadFailedSarif(config, repositoryNwo, features, logger) {
// We call 'database export-diagnostics' to find any per-database diagnostics.
await codeql.databaseExportDiagnostics(databasePath, sarifFile, category, config.tempDir, logger);
}
core.info(`Uploading failed SARIF file ${sarifFile}`);
logger.info(`Uploading failed SARIF file ${sarifFile}`);
const uploadResult = await uploadLib.uploadFromActions(sarifFile, checkoutPath, category, logger, { considerInvalidRequestUserError: false });
await uploadLib.waitForProcessing(repositoryNwo, uploadResult.sarifID, logger, { isUnsuccessfulExecution: true });
return uploadResult
@ -119,11 +118,11 @@ async function run(uploadDatabaseBundleDebugArtifact, uploadLogsDebugArtifact, p
`but the result was instead ${error}.`);
}
if (process.env["CODEQL_ACTION_EXPECT_UPLOAD_FAILED_SARIF"] === "true") {
await removeUploadedSarif(uploadFailedSarifResult);
await removeUploadedSarif(uploadFailedSarifResult, logger);
}
// Upload appropriate Actions artifacts for debugging
if (config.debugMode) {
core.info("Debug mode is on. Uploading available database bundles and logs as Actions debugging artifacts...");
logger.info("Debug mode is on. Uploading available database bundles and logs as Actions debugging artifacts...");
await uploadDatabaseBundleDebugArtifact(config, logger);
await uploadLogsDebugArtifact(config);
await printDebugLogs(config);
@ -131,14 +130,16 @@ async function run(uploadDatabaseBundleDebugArtifact, uploadLogsDebugArtifact, p
return uploadFailedSarifResult;
}
exports.run = run;
async function removeUploadedSarif(uploadFailedSarifResult) {
async function removeUploadedSarif(uploadFailedSarifResult, logger) {
const sarifID = uploadFailedSarifResult.sarifID;
if (sarifID) {
core.startGroup("Deleting failed SARIF upload");
core.info(`Uploaded failed SARIF file with ID ${sarifID}. Because this is a test, the analysis associated with it will now be deleted.`);
logger.startGroup("Deleting failed SARIF upload");
logger.info(`In test mode, therefore deleting the failed analysis to avoid impacting tool status for the Action repository. SARIF ID to delete: ${sarifID}.`);
const client = (0, api_client_1.getApiClient)();
try {
const repositoryNwo = (0, repository_1.parseRepositoryNwo)((0, util_1.getRequiredEnvParam)("GITHUB_REPOSITORY"));
// Wait to make sure the analysis is ready for download before requesting it.
await (0, util_1.wait)(5000);
// Get the analysis associated with the uploaded sarif
const analysisInfo = await client.request("GET /repos/:owner/:repo/code-scanning/analyses?sarif_id=:sarif_id", {
owner: repositoryNwo.owner,
@ -148,40 +149,36 @@ async function removeUploadedSarif(uploadFailedSarifResult) {
// Delete the analysis.
if (analysisInfo.data.length === 1) {
const analysis = analysisInfo.data[0];
core.info(`Deleting analysis ${analysis.id}`);
logger.info(`Analysis ID to delete: ${analysis.id}.`);
try {
await client.request("DELETE /repos/:owner/:repo/code-scanning/analyses/:analysis_id?confirm_delete", {
owner: repositoryNwo.owner,
repo: repositoryNwo.repo,
analysis_id: analysis.id,
});
logger.info(`Analysis deleted.`);
}
catch (e) {
if (e instanceof Error &&
e.message.includes("No analysis found for analysis ID")) {
core.info(`Analysis ${analysis.id} does not exist. It was likely already deleted.`);
}
else {
throw e;
}
const origMessage = (0, util_1.getErrorMessage)(e);
const newMessage = origMessage.includes("No analysis found for analysis ID")
? `Analysis ${analysis.id} does not exist. It was likely already deleted.`
: origMessage;
throw new Error(newMessage);
}
}
else {
core.warning(`Expected to find exactly one analysis with sarif_id ${sarifID}. Found ${analysisInfo.data.length}.`);
throw new Error(`Expected to find exactly one analysis with sarif_id ${sarifID}. Found ${analysisInfo.data.length}.`);
}
core.endGroup();
}
catch (e) {
// Fail the test if we can't delete the analysis.
core.error("Failed to delete uploaded SARIF analysis.");
throw e;
throw new Error(`Failed to delete uploaded SARIF analysis. Reason: ${(0, util_1.getErrorMessage)(e)}`);
}
finally {
core.endGroup();
logger.endGroup();
}
}
else {
core.warning("Could not delete uploaded SARIF analysis because no sarifID was returned.");
logger.warning("Could not delete the uploaded SARIF analysis because a SARIF ID wasn't provided by the API when uploading the SARIF file.");
}
}
//# sourceMappingURL=init-action-post-helper.js.map

File diff suppressed because one or more lines are too long

10
lib/util.js generated
View file

@ -26,7 +26,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkDiskUsage = exports.prettyPrintPack = exports.wrapError = exports.fixInvalidNotificationsInFile = exports.fixInvalidNotifications = exports.parseMatrixInput = exports.isHostedRunner = exports.checkForTimeout = exports.withTimeout = exports.tryGetFolderBytes = exports.listFolder = exports.doesDirectoryExist = exports.isInTestMode = exports.supportExpectDiscardedCache = exports.isGoodVersion = exports.delay = exports.bundleDb = exports.codeQlVersionAbove = exports.getCachedCodeQlVersion = exports.cacheCodeQlVersion = exports.isHTTPError = exports.UserError = exports.HTTPError = exports.getRequiredEnvParam = exports.initializeEnvironment = exports.assertNever = exports.apiVersionInRange = exports.DisallowedAPIVersionReason = exports.checkGitHubVersionInRange = exports.GitHubVariant = exports.parseGitHubUrl = exports.getCodeQLDatabasePath = exports.getThreadsFlag = exports.getThreadsFlagValue = exports.getAddSnippetsFlag = exports.getMemoryFlag = exports.getMemoryFlagValue = exports.getMemoryFlagValueForPlatform = exports.withTmpDir = exports.getToolNames = exports.getExtraOptionsEnvParam = exports.DEFAULT_DEBUG_DATABASE_NAME = exports.DEFAULT_DEBUG_ARTIFACT_NAME = exports.GITHUB_DOTCOM_URL = void 0;
exports.checkDiskUsage = exports.prettyPrintPack = exports.wait = exports.getErrorMessage = exports.wrapError = exports.fixInvalidNotificationsInFile = exports.fixInvalidNotifications = exports.parseMatrixInput = exports.isHostedRunner = exports.checkForTimeout = exports.withTimeout = exports.tryGetFolderBytes = exports.listFolder = exports.doesDirectoryExist = exports.isInTestMode = exports.supportExpectDiscardedCache = exports.isGoodVersion = exports.delay = exports.bundleDb = exports.codeQlVersionAbove = exports.getCachedCodeQlVersion = exports.cacheCodeQlVersion = exports.isHTTPError = exports.UserError = exports.HTTPError = exports.getRequiredEnvParam = exports.initializeEnvironment = exports.assertNever = exports.apiVersionInRange = exports.DisallowedAPIVersionReason = exports.checkGitHubVersionInRange = exports.GitHubVariant = exports.parseGitHubUrl = exports.getCodeQLDatabasePath = exports.getThreadsFlag = exports.getThreadsFlagValue = exports.getAddSnippetsFlag = exports.getMemoryFlag = exports.getMemoryFlagValue = exports.getMemoryFlagValueForPlatform = exports.withTmpDir = exports.getToolNames = exports.getExtraOptionsEnvParam = exports.DEFAULT_DEBUG_DATABASE_NAME = exports.DEFAULT_DEBUG_ARTIFACT_NAME = exports.GITHUB_DOTCOM_URL = void 0;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
@ -719,6 +719,14 @@ function wrapError(error) {
return error instanceof Error ? error : new Error(String(error));
}
exports.wrapError = wrapError;
function getErrorMessage(error) {
return error instanceof Error ? error.toString() : String(error);
}
exports.getErrorMessage = getErrorMessage;
async function wait(ms) {
await new Promise((resolve) => setTimeout(resolve, ms));
}
exports.wait = wait;
function prettyPrintPack(pack) {
return `${pack.name}${pack.version ? `@${pack.version}` : ""}${pack.path ? `:${pack.path}` : ""}`;
}

File diff suppressed because one or more lines are too long

View file

@ -1,5 +1,3 @@
import * as core from "@actions/core";
import * as actionsUtil from "./actions-util";
import { getApiClient } from "./api-client";
import { CODEQL_VERSION_EXPORT_FAILED_SARIF, getCodeQL } from "./codeql";
@ -11,9 +9,11 @@ import { RepositoryNwo, parseRepositoryNwo } from "./repository";
import * as uploadLib from "./upload-lib";
import {
codeQlVersionAbove,
getErrorMessage,
getRequiredEnvParam,
isInTestMode,
parseMatrixInput,
wait,
wrapError,
} from "./util";
import {
@ -97,7 +97,7 @@ async function maybeUploadFailedSarif(
);
}
core.info(`Uploading failed SARIF file ${sarifFile}`);
logger.info(`Uploading failed SARIF file ${sarifFile}`);
const uploadResult = await uploadLib.uploadFromActions(
sarifFile,
checkoutPath,
@ -187,12 +187,12 @@ export async function run(
}
if (process.env["CODEQL_ACTION_EXPECT_UPLOAD_FAILED_SARIF"] === "true") {
await removeUploadedSarif(uploadFailedSarifResult);
await removeUploadedSarif(uploadFailedSarifResult, logger);
}
// Upload appropriate Actions artifacts for debugging
if (config.debugMode) {
core.info(
logger.info(
"Debug mode is on. Uploading available database bundles and logs as Actions debugging artifacts...",
);
await uploadDatabaseBundleDebugArtifact(config, logger);
@ -206,12 +206,13 @@ export async function run(
async function removeUploadedSarif(
uploadFailedSarifResult: UploadFailedSarifResult,
logger: Logger,
) {
const sarifID = uploadFailedSarifResult.sarifID;
if (sarifID) {
core.startGroup("Deleting failed SARIF upload");
core.info(
`Uploaded failed SARIF file with ID ${sarifID}. Because this is a test, the analysis associated with it will now be deleted.`,
logger.startGroup("Deleting failed SARIF upload");
logger.info(
`In test mode, therefore deleting the failed analysis to avoid impacting tool status for the Action repository. SARIF ID to delete: ${sarifID}.`,
);
const client = getApiClient();
@ -220,6 +221,9 @@ async function removeUploadedSarif(
getRequiredEnvParam("GITHUB_REPOSITORY"),
);
// Wait to make sure the analysis is ready for download before requesting it.
await wait(5000);
// Get the analysis associated with the uploaded sarif
const analysisInfo = await client.request(
"GET /repos/:owner/:repo/code-scanning/analyses?sarif_id=:sarif_id",
@ -233,7 +237,7 @@ async function removeUploadedSarif(
// Delete the analysis.
if (analysisInfo.data.length === 1) {
const analysis = analysisInfo.data[0];
core.info(`Deleting analysis ${analysis.id}`);
logger.info(`Analysis ID to delete: ${analysis.id}.`);
try {
await client.request(
"DELETE /repos/:owner/:repo/code-scanning/analyses/:analysis_id?confirm_delete",
@ -243,34 +247,33 @@ async function removeUploadedSarif(
analysis_id: analysis.id,
},
);
logger.info(`Analysis deleted.`);
} catch (e) {
if (
e instanceof Error &&
e.message.includes("No analysis found for analysis ID")
) {
core.info(
`Analysis ${analysis.id} does not exist. It was likely already deleted.`,
);
} else {
throw e;
}
const origMessage = getErrorMessage(e);
const newMessage = origMessage.includes(
"No analysis found for analysis ID",
)
? `Analysis ${analysis.id} does not exist. It was likely already deleted.`
: origMessage;
throw new Error(newMessage);
}
} else {
core.warning(
throw new Error(
`Expected to find exactly one analysis with sarif_id ${sarifID}. Found ${analysisInfo.data.length}.`,
);
}
core.endGroup();
} catch (e) {
// Fail the test if we can't delete the analysis.
core.error("Failed to delete uploaded SARIF analysis.");
throw e;
throw new Error(
`Failed to delete uploaded SARIF analysis. Reason: ${getErrorMessage(
e,
)}`,
);
} finally {
core.endGroup();
logger.endGroup();
}
} else {
core.warning(
"Could not delete uploaded SARIF analysis because no sarifID was returned.",
logger.warning(
"Could not delete the uploaded SARIF analysis because a SARIF ID wasn't provided by the API when uploading the SARIF file.",
);
}
}

View file

@ -909,6 +909,14 @@ export function wrapError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error));
}
export function getErrorMessage(error: unknown): string {
return error instanceof Error ? error.toString() : String(error);
}
export async function wait(ms: number) {
await new Promise((resolve) => setTimeout(resolve, ms));
}
export function prettyPrintPack(pack: Pack) {
return `${pack.name}${pack.version ? `@${pack.version}` : ""}${
pack.path ? `:${pack.path}` : ""