From c230ee83a10d017077bec15fdbffdf039eb3f7de Mon Sep 17 00:00:00 2001 From: Vasyl Ivanchuk Date: Wed, 11 Sep 2024 23:15:17 +0300 Subject: [PATCH] feat: add get latest commit hash function --- src/utils/git.ts | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/src/utils/git.ts b/src/utils/git.ts index abf2008d..df2933b7 100644 --- a/src/utils/git.ts +++ b/src/utils/git.ts @@ -29,22 +29,39 @@ export const cloneRepo = async (repoUrl: string, destination: string, options?: await executeCommand(command, options); }; -export const getLatestReleaseVersion = async (repo: string): Promise => { - const apiUrl = `https://api.github.com/repos/${repo}/releases/latest`; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const gitApiRequest = async (url: string): Promise => { try { - const response = await fetch(apiUrl); + const response = await fetch(url); if (!response.ok) { throw new Error(`GitHub API request failed with status: ${response.status}`); } - const releaseInfo = await response.json(); - if (typeof releaseInfo?.tag_name !== "string") { - throw new Error(`Failed to parse the latest release version: ${JSON.stringify(releaseInfo)}`); - } - return releaseInfo.tag_name; + return await response.json(); } catch (error) { if (error instanceof Error) { - throw new Error(`Failed to fetch the latest release version: ${error.message}`); + throw new Error(`Failed to make the GitHub API request: ${error.message}`); } throw error; } }; + +export const getLatestReleaseVersion = async (repo: string): Promise => { + const releaseInfo = await gitApiRequest(`https://api.github.com/repos/${repo}/releases/latest`); + if (typeof releaseInfo?.tag_name !== "string") { + throw new Error(`Failed to parse the latest release version: ${JSON.stringify(releaseInfo)}`); + } + return releaseInfo.tag_name; +}; + +export const getLatestCommitHash = async (repo: string): Promise => { + const commitsInfo = await gitApiRequest(`https://api.github.com/repos/${repo}/commits?per_page=1`); + if (!commitsInfo?.length) { + throw new Error( + `Unable to get the latest commit hash. Latest commit not found. The response: ${JSON.stringify(commitsInfo)}` + ); + } + if (typeof commitsInfo[0].sha !== "string") { + throw new Error(`Failed to parse the latest commit hash: ${JSON.stringify(commitsInfo)}`); + } + return commitsInfo[0].sha; +};