Remove unneeded apiDetails input to getApiClient

This commit is contained in:
Henry Mercer 2022-11-14 19:48:27 +00:00
parent dac8912e9f
commit 9df773d1a3
45 changed files with 128 additions and 180 deletions

View file

@ -411,7 +411,7 @@ async function getWorkflowPath(): Promise<string> {
const repo = repo_nwo[1];
const run_id = Number(getRequiredEnvParam("GITHUB_RUN_ID"));
const apiClient = api.getActionsApiClient();
const apiClient = api.getApiClient();
const runsResponse = await apiClient.request(
"GET /repos/:owner/:repo/actions/runs/:run_id?exclude_pull_requests=true",
{
@ -768,7 +768,7 @@ export async function sendStatusReport<S extends StatusReportBase>(
const nwo = getRequiredEnvParam("GITHUB_REPOSITORY");
const [owner, repo] = nwo.split("/");
const client = api.getActionsApiClient();
const client = api.getApiClient();
try {
await client.request(

View file

@ -226,12 +226,7 @@ async function run() {
const gitHubVersion = await getGitHubVersion();
const features = new Features(
gitHubVersion,
apiDetails,
repositoryNwo,
logger
);
const features = new Features(gitHubVersion, repositoryNwo, logger);
await runAutobuildIfLegacyGoWorkflow(config, features, logger);
@ -275,7 +270,6 @@ async function run() {
uploadResult = await upload_lib.uploadFromActions(
outputDir,
config.gitHubVersion,
apiDetails,
logger
);
core.setOutput("sarif-id", uploadResult.sarifID);
@ -302,7 +296,6 @@ async function run() {
await upload_lib.waitForProcessing(
parseRepositoryNwo(util.getRequiredEnvParam("GITHUB_REPOSITORY")),
uploadResult.sarifID,
apiDetails,
getActionsLogger()
);
}

View file

@ -1,10 +1,11 @@
import * as githubUtils from "@actions/github/lib/utils";
import test, { ExecutionContext } from "ava";
import test from "ava";
import * as sinon from "sinon";
import { getApiClient, GitHubApiCombinedDetails } from "./api-client";
import * as actionsUtil from "./actions-util";
import { getApiClient } from "./api-client";
import { setupTests } from "./testing-utils";
import { initializeEnvironment } from "./util";
import * as util from "./util";
// eslint-disable-next-line import/no-commonjs
const pkg = require("../package.json");
@ -18,36 +19,27 @@ test.beforeEach(() => {
pluginStub = sinon.stub(githubUtils.GitHub, "plugin");
githubStub = sinon.stub();
pluginStub.returns(githubStub);
initializeEnvironment(pkg.version);
util.initializeEnvironment(pkg.version);
});
test("Get the API with an API URL directly", async (t) => {
doTest(
t,
{
auth: "xyz",
url: "http://github.localhost",
apiURL: "http://api.github.localhost",
},
undefined,
{
test("getApiClient", async (t) => {
sinon.stub(actionsUtil, "getRequiredInput").withArgs("token").returns("xyz");
const requiredEnvParamStub = sinon.stub(util, "getRequiredEnvParam");
requiredEnvParamStub
.withArgs("GITHUB_SERVER_URL")
.returns("http://github.localhost");
requiredEnvParamStub
.withArgs("GITHUB_API_URL")
.returns("http://api.github.localhost");
getApiClient();
t.assert(
githubStub.calledOnceWithExactly({
auth: "token xyz",
baseUrl: "http://api.github.localhost",
log: sinon.match.any,
userAgent: `CodeQL-Action/${pkg.version}`,
}
})
);
});
function doTest(
t: ExecutionContext<unknown>,
clientArgs: GitHubApiCombinedDetails,
clientOptions: any,
expected: any
) {
getApiClient(clientArgs, clientOptions);
const firstCallArgs = githubStub.args[0];
// log is a function, so we don't need to test for equality of it
delete firstCallArgs[0].log;
t.deepEqual(firstCallArgs, [expected]);
}

View file

@ -29,7 +29,7 @@ export interface GitHubApiExternalRepoDetails {
apiURL: string | undefined;
}
export const getApiClient = function (
function createApiClientWithDetails(
apiDetails: GitHubApiCombinedDetails,
{ allowExternal = false } = {}
) {
@ -43,7 +43,7 @@ export const getApiClient = function (
log: consoleLogLevel({ level: "debug" }),
})
);
};
}
export function getApiDetails() {
return {
@ -53,11 +53,14 @@ export function getApiDetails() {
};
}
// Temporary function to aid in the transition to running on and off of github actions.
// Once all code has been converted this function should be removed or made canonical
// and called only from the action entrypoints.
export function getActionsApiClient() {
return getApiClient(getApiDetails());
export function getApiClient() {
return createApiClientWithDetails(getApiDetails());
}
export function getApiClientWithExternalAuth(
apiDetails: GitHubApiCombinedDetails
) {
return createApiClientWithDetails(apiDetails, { allowExternal: true });
}
let cachedGitHubVersion: GitHubVersion | undefined = undefined;

View file

@ -8,7 +8,7 @@ import {
sendStatusReport,
StatusReportBase,
} from "./actions-util";
import { getApiDetails, getGitHubVersion } from "./api-client";
import { getGitHubVersion } from "./api-client";
import { determineAutobuildLanguages, runAutobuild } from "./autobuild";
import * as configUtils from "./config-utils";
import { Features } from "./feature-flags";
@ -77,7 +77,6 @@ async function run() {
const features = new Features(
gitHubVersion,
getApiDetails(),
parseRepositoryNwo(getRequiredEnvParam("GITHUB_REPOSITORY")),
logger
);

View file

@ -350,14 +350,14 @@ async function getCodeQLBundleDownloadURL(
if (variant === util.GitHubVariant.GHAE) {
try {
const release = await api
.getApiClient(apiDetails)
.getApiClient()
.request("GET /enterprise/code-scanning/codeql-bundle/find/{tag}", {
tag: CODEQL_BUNDLE_VERSION,
});
const assetID = release.data.assets[codeQLBundleName];
if (assetID !== undefined) {
const download = await api
.getApiClient(apiDetails)
.getApiClient()
.request(
"GET /enterprise/code-scanning/codeql-bundle/download/{asset_id}",
{ asset_id: assetID }
@ -391,7 +391,7 @@ async function getCodeQLBundleDownloadURL(
}
const [repositoryOwner, repositoryName] = repository.split("/");
try {
const release = await api.getApiClient(apiDetails).repos.getReleaseByTag({
const release = await api.getApiClient().repos.getReleaseByTag({
owner: repositoryOwner,
repo: repositoryName,
tag: CODEQL_BUNDLE_VERSION,

View file

@ -48,6 +48,7 @@ function mockGetContents(
.stub(client.repos, "getContent")
.resolves(response as any);
sinon.stub(api, "getApiClient").value(() => client);
sinon.stub(api, "getApiClientWithExternalAuth").value(() => client);
return spyGetContents;
}

View file

@ -856,11 +856,10 @@ export function getUnknownLanguagesError(languages: string[]): string {
*/
async function getLanguagesInRepo(
repository: RepositoryNwo,
apiDetails: api.GitHubApiDetails,
logger: Logger
): Promise<Language[]> {
logger.debug(`GitHub repo ${repository.owner} ${repository.repo}`);
const response = await api.getApiClient(apiDetails).repos.listLanguages({
const response = await api.getApiClient().repos.listLanguages({
owner: repository.owner,
repo: repository.repo,
});
@ -895,7 +894,6 @@ async function getLanguages(
codeQL: CodeQL,
languagesInput: string | undefined,
repository: RepositoryNwo,
apiDetails: api.GitHubApiDetails,
logger: Logger
): Promise<Language[]> {
// Obtain from action input 'languages' if set
@ -907,7 +905,7 @@ async function getLanguages(
if (languages.length === 0) {
// Obtain languages as all languages in the repo that can be analysed
languages = await getLanguagesInRepo(repository, apiDetails, logger);
languages = await getLanguagesInRepo(repository, logger);
const availableLanguages = await codeQL.resolveLanguages();
languages = languages.filter((value) => value in availableLanguages);
logger.info(
@ -1012,7 +1010,6 @@ export async function getDefaultConfig(
codeQL,
languagesInput,
repository,
apiDetails,
logger
);
const queries: Queries = {};
@ -1142,7 +1139,6 @@ async function loadConfig(
codeQL,
languagesInput,
repository,
apiDetails,
logger
);
@ -1773,7 +1769,7 @@ async function getRemoteConfig(
}
const response = await api
.getApiClient(apiDetails, { allowExternal: true })
.getApiClientWithExternalAuth(apiDetails)
.repos.getContent({
owner: pieces.groups.owner,
repo: pieces.groups.repo,

View file

@ -32,7 +32,7 @@ export async function uploadDatabases(
return;
}
const client = getApiClient(apiDetails);
const client = getApiClient();
const codeql = await getCodeQL(config.codeQLCmd);
for (const language of config.languages) {

View file

@ -1,6 +1,5 @@
import test from "ava";
import { GitHubApiDetails } from "./api-client";
import {
Feature,
featureConfig,
@ -26,12 +25,6 @@ test.beforeEach(() => {
initializeEnvironment("1.2.3");
});
const testApiDetails: GitHubApiDetails = {
auth: "1234",
url: "https://github.com",
apiURL: undefined,
};
const testRepositoryNwo = parseRepositoryNwo("github/example");
const ALL_FEATURES_DISABLED_VARIANTS: Array<{
@ -319,7 +312,7 @@ function setUpTests(
): FeatureEnablement {
setupActionsVars(tmpDir, tmpDir);
return new Features(gitHubVersion, testApiDetails, testRepositoryNwo, logger);
return new Features(gitHubVersion, testRepositoryNwo, logger);
}
function includeCodeQlIfRequired(feature: string) {

View file

@ -1,4 +1,4 @@
import { getApiClient, GitHubApiDetails } from "./api-client";
import { getApiClient } from "./api-client";
import { CodeQL } from "./codeql";
import { Logger } from "./logging";
import { RepositoryNwo } from "./repository";
@ -65,13 +65,11 @@ export class Features implements FeatureEnablement {
constructor(
gitHubVersion: util.GitHubVersion,
apiDetails: GitHubApiDetails,
repositoryNwo: RepositoryNwo,
logger: Logger
) {
this.gitHubFeatureFlags = new GitHubFeatureFlags(
gitHubVersion,
apiDetails,
repositoryNwo,
logger
);
@ -133,7 +131,6 @@ class GitHubFeatureFlags implements FeatureEnablement {
constructor(
private gitHubVersion: util.GitHubVersion,
private apiDetails: GitHubApiDetails,
private repositoryNwo: RepositoryNwo,
private logger: Logger
) {
@ -173,9 +170,8 @@ class GitHubFeatureFlags implements FeatureEnablement {
);
return {};
}
const client = getApiClient(this.apiDetails);
try {
const response = await client.request(
const response = await getApiClient().request(
"GET /repos/:owner/:repo/code-scanning/codeql-action/features",
{
owner: this.repositoryNwo.owner,

View file

@ -157,12 +157,7 @@ async function run() {
getRequiredEnvParam("GITHUB_REPOSITORY")
);
const features = new Features(
gitHubVersion,
apiDetails,
repositoryNwo,
logger
);
const features = new Features(gitHubVersion, repositoryNwo, logger);
try {
const workflowErrors = await validateWorkflow();

View file

@ -89,7 +89,6 @@ function getAutomationID(
async function uploadPayload(
payload: any,
repositoryNwo: RepositoryNwo,
apiDetails: api.GitHubApiDetails,
logger: Logger
) {
logger.info("Uploading results");
@ -108,7 +107,7 @@ async function uploadPayload(
return;
}
const client = api.getApiClient(apiDetails);
const client = api.getApiClient();
const response = await client.request(
"PUT /repos/:owner/:repo/code-scanning/analysis",
@ -163,7 +162,6 @@ export function findSarifFilesInDir(sarifPath: string): string[] {
export async function uploadFromActions(
sarifPath: string,
gitHubVersion: util.GitHubVersion,
apiDetails: api.GitHubApiDetails,
logger: Logger
): Promise<UploadResult> {
return await uploadFiles(
@ -180,7 +178,6 @@ export async function uploadFromActions(
actionsUtil.getRequiredInput("checkout_path"),
actionsUtil.getRequiredInput("matrix"),
gitHubVersion,
apiDetails,
logger
);
}
@ -330,7 +327,6 @@ async function uploadFiles(
sourceRoot: string,
environment: string | undefined,
gitHubVersion: util.GitHubVersion,
apiDetails: api.GitHubApiDetails,
logger: Logger
): Promise<UploadResult> {
logger.startGroup("Uploading results");
@ -384,12 +380,7 @@ async function uploadFiles(
logger.debug(`Number of results in upload: ${numResultInSarif}`);
// Make the upload
const sarifID = await uploadPayload(
payload,
repositoryNwo,
apiDetails,
logger
);
const sarifID = await uploadPayload(payload, repositoryNwo, logger);
logger.endGroup();
@ -410,11 +401,10 @@ const STATUS_CHECK_TIMEOUT_MILLISECONDS = 2 * 60 * 1000;
export async function waitForProcessing(
repositoryNwo: RepositoryNwo,
sarifID: string,
apiDetails: api.GitHubApiDetails,
logger: Logger
): Promise<void> {
logger.startGroup("Waiting for processing to finish");
const client = api.getApiClient(apiDetails);
const client = api.getApiClient();
const statusCheckingStarted = Date.now();
// eslint-disable-next-line no-constant-condition

View file

@ -1,7 +1,7 @@
import * as core from "@actions/core";
import * as actionsUtil from "./actions-util";
import { getApiDetails, getGitHubVersion } from "./api-client";
import { getGitHubVersion } from "./api-client";
import { getActionsLogger } from "./logging";
import { parseRepositoryNwo } from "./repository";
import * as upload_lib from "./upload-lib";
@ -52,13 +52,11 @@ async function run() {
}
try {
const apiDetails = getApiDetails();
const gitHubVersion = await getGitHubVersion();
const uploadResult = await upload_lib.uploadFromActions(
actionsUtil.getRequiredInput("sarif_file"),
gitHubVersion,
apiDetails,
getActionsLogger()
);
core.setOutput("sarif-id", uploadResult.sarifID);
@ -70,7 +68,6 @@ async function run() {
await upload_lib.waitForProcessing(
parseRepositoryNwo(getRequiredEnvParam("GITHUB_REPOSITORY")),
uploadResult.sarifID,
apiDetails,
getActionsLogger()
);
}

View file

@ -328,7 +328,7 @@ export async function getGitHubVersion(
// Doesn't strictly have to be the meta endpoint as we're only
// using the response headers which are available on every request.
const apiClient = getApiClient(apiDetails);
const apiClient = getApiClient();
const response = await apiClient.meta.get();
// This happens on dotcom, although we expect to have already returned in that