Prefer providing CodeQL via dependency injection

This commit is contained in:
Henry Mercer
2025-08-07 12:13:59 +01:00
parent c7884c6fd8
commit f8c2086872
42 changed files with 138 additions and 126 deletions

35
lib/codeql.js generated
View File

@@ -36,7 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
exports.setupCodeQL = setupCodeQL;
exports.getCodeQL = getCodeQL;
exports.setCodeQL = setCodeQL;
exports.getCachedCodeQL = getCachedCodeQL;
exports.createStubCodeQL = createStubCodeQL;
exports.getCodeQLForTesting = getCodeQLForTesting;
exports.getCodeQLForCmd = getCodeQLForCmd;
exports.getExtraOptions = getExtraOptions;
@@ -63,7 +63,6 @@ const util = __importStar(require("./util"));
const util_1 = require("./util");
/**
* Stores the CodeQL object, and is populated by `setupCodeQL` or `getCodeQL`.
* Can be overridden in tests using `setCodeQL`.
*/
let cachedCodeQL = undefined;
/**
@@ -150,6 +149,16 @@ async function getCodeQL(cmd) {
}
return cachedCodeQL;
}
/**
* Overrides the CodeQL object. Only for use in tests that cannot override
* CodeQL via dependency injection.
*
* Accepts a partial object. Any undefined methods will be implemented
* to immediately throw an exception indicating which method is missing.
*/
function setCodeQL(codeql) {
cachedCodeQL = createStubCodeQL(codeql);
}
function resolveFunction(partialCodeql, methodName, defaultImplementation) {
if (typeof partialCodeql[methodName] !== "function") {
if (defaultImplementation !== undefined) {
@@ -163,13 +172,13 @@ function resolveFunction(partialCodeql, methodName, defaultImplementation) {
return partialCodeql[methodName];
}
/**
* Set the functionality for CodeQL methods. Only for use in tests.
* Creates a stub CodeQL object. Only for use in tests.
*
* Accepts a partial object and any undefined methods will be implemented
* Accepts a partial object. Any undefined methods will be implemented
* to immediately throw an exception indicating which method is missing.
*/
function setCodeQL(partialCodeql) {
cachedCodeQL = {
function createStubCodeQL(partialCodeql) {
return {
getPath: resolveFunction(partialCodeql, "getPath", () => "/tmp/dummy-path"),
getVersion: resolveFunction(partialCodeql, "getVersion", async () => ({
version: "1.0.0",
@@ -200,20 +209,6 @@ function setCodeQL(partialCodeql) {
resolveExtractor: resolveFunction(partialCodeql, "resolveExtractor"),
mergeResults: resolveFunction(partialCodeql, "mergeResults"),
};
return cachedCodeQL;
}
/**
* Get the cached CodeQL object. Should only be used from tests.
*
* TODO: Work out a good way for tests to get this from the test context
* instead of having to have this method.
*/
function getCachedCodeQL() {
if (cachedCodeQL === undefined) {
// Should never happen as setCodeQL is called by testing-utils.setupTests
throw new Error("cachedCodeQL undefined");
}
return cachedCodeQL;
}
/**
* Get a real, newly created CodeQL instance for testing. The instance refers to