|
| 1 | +import { exec as execCallback } from 'child_process'; |
| 2 | +import fs from 'fs'; |
| 3 | +import path from 'path'; |
| 4 | +import { promisify } from 'util'; |
| 5 | +import { context } from '@actions/github'; |
| 6 | +import * as core from '@actions/core'; |
| 7 | + |
| 8 | +const exec = promisify(execCallback); |
| 9 | + |
| 10 | +// Get PR number from GitHub Actions environment variables |
| 11 | +const PR_NUMBER = context.payload.pull_request?.number; |
| 12 | + |
| 13 | +const GITHUB_DEFAULT_BRANCH = 'main'; |
| 14 | +const SOURCE_BRANCH = PR_NUMBER ? `refs/pull/${PR_NUMBER}/head` : ''; |
| 15 | + |
| 16 | +const CHANGED_FILES_DIR = 'changed-files'; |
| 17 | + |
| 18 | +type PRInfo = { |
| 19 | + base: { |
| 20 | + ref: string; |
| 21 | + }; |
| 22 | + body: string; |
| 23 | + labels: { name: string }[]; |
| 24 | +}; |
| 25 | + |
| 26 | +/** |
| 27 | + * Get JSON info about the given pull request using Octokit |
| 28 | + * |
| 29 | + * @returns PR information from GitHub |
| 30 | + */ |
| 31 | +async function getPrInfo(): Promise<PRInfo | null> { |
| 32 | + if (!PR_NUMBER) { |
| 33 | + return null; |
| 34 | + } |
| 35 | + |
| 36 | + const { owner, repo } = context.repo; |
| 37 | + |
| 38 | + const response = await fetch( |
| 39 | + `https://api.github.com/repos/${owner}/${repo}/pulls/${PR_NUMBER}`, |
| 40 | + { |
| 41 | + headers: { |
| 42 | + Authorization: `token ${process.env.GITHUB_TOKEN}`, |
| 43 | + Accept: 'application/vnd.github.v3+json', |
| 44 | + }, |
| 45 | + }, |
| 46 | + ); |
| 47 | + |
| 48 | + return await response.json(); |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Fetches the git repository with a specified depth. |
| 53 | + * |
| 54 | + * @param depth - The depth to use for the fetch command. |
| 55 | + * @returns True if the fetch is successful, otherwise false. |
| 56 | + */ |
| 57 | +async function fetchWithDepth(depth: number): Promise<boolean> { |
| 58 | + try { |
| 59 | + await exec(`git fetch --depth ${depth} origin "${GITHUB_DEFAULT_BRANCH}"`); |
| 60 | + if (SOURCE_BRANCH) { |
| 61 | + await exec( |
| 62 | + `git fetch --depth ${depth} origin "${SOURCE_BRANCH}:${SOURCE_BRANCH}"`, |
| 63 | + ); |
| 64 | + } |
| 65 | + return true; |
| 66 | + } catch (error) { |
| 67 | + core.warning(`Failed to fetch with depth ${depth}:`, error); |
| 68 | + return false; |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +/** |
| 73 | + * Attempts to fetch the necessary commits until the merge base is found. |
| 74 | + * It tries different fetch depths and performs a full fetch if needed. |
| 75 | + * |
| 76 | + * @throws If an unexpected error occurs during the execution of git commands. |
| 77 | + */ |
| 78 | +async function fetchUntilMergeBaseFound() { |
| 79 | + const depths = [1, 10, 100]; |
| 80 | + for (const depth of depths) { |
| 81 | + core.info(`Attempting git diff with depth ${depth}...`); |
| 82 | + await fetchWithDepth(depth); |
| 83 | + |
| 84 | + try { |
| 85 | + await exec(`git merge-base origin/${GITHUB_DEFAULT_BRANCH} HEAD`); |
| 86 | + return; |
| 87 | + } catch (error: unknown) { |
| 88 | + if (error instanceof Error && 'code' in error) { |
| 89 | + core.warning( |
| 90 | + `Error 'no merge base' encountered with depth ${depth}. Incrementing depth...`, |
| 91 | + ); |
| 92 | + } else { |
| 93 | + throw error; |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + await exec(`git fetch --unshallow origin "${GITHUB_DEFAULT_BRANCH}"`); |
| 98 | +} |
| 99 | + |
| 100 | +/** |
| 101 | + * Performs a git diff command to get the list of files changed between the current branch and the origin. |
| 102 | + * It first ensures that the necessary commits are fetched until the merge base is found. |
| 103 | + * |
| 104 | + * @returns The output of the git diff command, listing the file paths with status (A, M, D). |
| 105 | + * @throws If unable to get the diff after fetching the merge base or if an unexpected error occurs. |
| 106 | + */ |
| 107 | +async function gitDiff(): Promise<string> { |
| 108 | + await fetchUntilMergeBaseFound(); |
| 109 | + const { stdout: diffResult } = await exec( |
| 110 | + `git diff --name-status "origin/${GITHUB_DEFAULT_BRANCH}...${ |
| 111 | + SOURCE_BRANCH || 'HEAD' |
| 112 | + }"`, |
| 113 | + ); |
| 114 | + if (!diffResult) { |
| 115 | + throw new Error('Unable to get diff after full checkout.'); |
| 116 | + } |
| 117 | + return diffResult; |
| 118 | +} |
| 119 | + |
| 120 | +function writePrBodyAndInfoToFile(prInfo: PRInfo) { |
| 121 | + const prBodyPath = path.resolve(CHANGED_FILES_DIR, 'pr-body.txt'); |
| 122 | + const labels = prInfo.labels.map((label) => label.name).join(', '); |
| 123 | + const updatedPrBody = `PR labels: {${labels}}\nPR base: {${ |
| 124 | + prInfo.base.ref |
| 125 | + }}\n${prInfo.body.trim()}`; |
| 126 | + fs.writeFileSync(prBodyPath, updatedPrBody); |
| 127 | + core.info(`PR body and info saved to ${prBodyPath}`); |
| 128 | +} |
| 129 | + |
| 130 | +/** |
| 131 | + * Main run function, stores the output of git diff and the body of the matching PR to a file. |
| 132 | + * |
| 133 | + * @returns Returns a promise that resolves when the git diff output and PR body is successfully stored. |
| 134 | + */ |
| 135 | +async function storeGitDiffOutputAndPrBody() { |
| 136 | + try { |
| 137 | + // Create the directory |
| 138 | + fs.mkdirSync(CHANGED_FILES_DIR, { recursive: true }); |
| 139 | + |
| 140 | + core.info(`Determining whether to run git diff...`); |
| 141 | + if (!PR_NUMBER) { |
| 142 | + core.info('Not a PR, skipping git diff'); |
| 143 | + return; |
| 144 | + } |
| 145 | + |
| 146 | + const prInfo = await getPrInfo(); |
| 147 | + |
| 148 | + const baseRef = prInfo?.base.ref; |
| 149 | + if (!baseRef) { |
| 150 | + core.info('Not a PR, skipping git diff'); |
| 151 | + return; |
| 152 | + } |
| 153 | + // We perform git diff even if the PR base is not main or skip-e2e-quality-gate label is applied |
| 154 | + // because we rely on the git diff results for other jobs |
| 155 | + core.info('Attempting to get git diff...'); |
| 156 | + const diffOutput = await gitDiff(); |
| 157 | + core.info(diffOutput); |
| 158 | + |
| 159 | + // Store the output of git diff |
| 160 | + const outputPath = path.resolve(CHANGED_FILES_DIR, 'changed-files.txt'); |
| 161 | + fs.writeFileSync(outputPath, diffOutput.trim()); |
| 162 | + core.info(`Git diff results saved to ${outputPath}`); |
| 163 | + |
| 164 | + writePrBodyAndInfoToFile(prInfo); |
| 165 | + |
| 166 | + core.info('success'); |
| 167 | + } catch (error: any) { |
| 168 | + core.setFailed(`Failed to process git diff: ${error.message}`); |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +// If main module (i.e. this is the TS file that was run directly) |
| 173 | +if (require.main === module) { |
| 174 | + storeGitDiffOutputAndPrBody(); |
| 175 | +} |
0 commit comments