3
0
Fork 0
mirror of https://github.com/tj-actions/changed-files synced 2025-03-01 09:30:30 +00:00

feat: add support for passing branch name to the base_sha and sha inputs (#1742)

This commit is contained in:
Tonye Jack 2023-11-27 00:11:43 -07:00 committed by GitHub
parent 6784c9e1ee
commit 2139fa1b6f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 131 additions and 19 deletions

View file

@ -286,11 +286,15 @@ jobs:
shell:
bash
test-unset-github-output-env:
name: Test unset GITHUB_OUTPUT env
test-using-branch-names-for-base-sha-and-sha-inputs:
name: Test using branch names for base_sha and sha inputs
runs-on: ubuntu-latest
needs: build
if: needs.build.outputs.files_changed != 'true'
if: |
(
github.event_name == 'push' ||
github.event_name == 'pull_request'
) && needs.build.outputs.files_changed != 'true'
steps:
- name: Checkout branch
@ -304,12 +308,11 @@ jobs:
with:
name: build-assets
- name: Run changed-files with unset GITHUB_OUTPUT env
- name: Run changed-files with main as the base_sha
id: changed-files
continue-on-error: true
uses: ./
env:
GITHUB_OUTPUT: ""
with:
base_sha: main
- name: Show output
run: |

59
dist/index.js generated vendored
View file

@ -867,7 +867,11 @@ const github = __importStar(__nccwpck_require__(5438));
const utils_1 = __nccwpck_require__(918);
const getCurrentSHA = ({ inputs, workingDirectory }) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b, _c, _d, _e, _f, _g;
let currentSha = inputs.sha;
let currentSha = yield (0, utils_1.cleanShaInput)({
sha: inputs.sha,
cwd: workingDirectory,
token: inputs.token
});
core.debug('Getting current SHA...');
if (inputs.until) {
core.debug(`Getting base SHA for '${inputs.until}'...`);
@ -980,7 +984,11 @@ const getSHAForNonPullRequestEvent = (inputs, env, workingDirectory, isShallow,
}
}
const currentSha = yield getCurrentSHA({ inputs, workingDirectory });
let previousSha = inputs.baseSha;
let previousSha = yield (0, utils_1.cleanShaInput)({
sha: inputs.baseSha,
cwd: workingDirectory,
token: inputs.token
});
const diff = '..';
const currentBranchName = yield (0, utils_1.getCurrentBranchName)({ cwd: workingDirectory });
if (currentBranchName &&
@ -995,7 +1003,6 @@ const getSHAForNonPullRequestEvent = (inputs, env, workingDirectory, isShallow,
core.error(`Please verify that both commits are valid, and increase the fetch_depth to a number higher than ${inputs.fetchDepth}.`);
throw new Error('Similar commit hashes detected.');
}
yield (0, utils_1.verifyCommitSha)({ sha: previousSha, cwd: workingDirectory });
core.debug(`Previous SHA: ${previousSha}`);
return {
previousSha,
@ -1167,7 +1174,11 @@ const getSHAForPullRequestEvent = (inputs, env, workingDirectory, isShallow, has
core.info('Completed fetching more history.');
}
const currentSha = yield getCurrentSHA({ inputs, workingDirectory });
let previousSha = inputs.baseSha;
let previousSha = yield (0, utils_1.cleanShaInput)({
sha: inputs.baseSha,
cwd: workingDirectory,
token: inputs.token
});
let diff = '...';
if (previousSha && currentSha && currentBranch && targetBranch) {
if (previousSha === currentSha) {
@ -1175,7 +1186,6 @@ const getSHAForPullRequestEvent = (inputs, env, workingDirectory, isShallow, has
core.error(`Please verify that both commits are valid, and increase the fetch_depth to a number higher than ${inputs.fetchDepth}.`);
throw new Error('Similar commit hashes detected.');
}
yield (0, utils_1.verifyCommitSha)({ sha: previousSha, cwd: workingDirectory });
core.debug(`Previous SHA: ${previousSha}`);
return {
previousSha,
@ -1908,10 +1918,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.hasLocalGitDirectory = exports.recoverDeletedFiles = exports.setOutput = exports.setArrayOutput = exports.getOutputKey = exports.getRecoverFilePatterns = exports.getYamlFilePatterns = exports.getFilePatterns = exports.getDirNamesIncludeFilesPattern = exports.jsonOutput = exports.getDirnameMaxDepth = exports.canDiffCommits = exports.getPreviousGitTag = exports.verifyCommitSha = exports.getParentSha = exports.getCurrentBranchName = exports.getRemoteBranchHeadSha = exports.isInsideWorkTree = exports.getHeadSha = exports.gitLog = exports.getFilteredChangedFiles = exports.getAllChangedFiles = exports.gitRenamedFiles = exports.gitSubmoduleDiffSHA = exports.getSubmodulePath = exports.gitFetchSubmodules = exports.gitFetch = exports.submoduleExists = exports.isRepoShallow = exports.updateGitGlobalConfig = exports.exists = exports.verifyMinimumGitVersion = exports.getDirname = exports.normalizeSeparators = exports.isWindows = void 0;
exports.hasLocalGitDirectory = exports.recoverDeletedFiles = exports.setOutput = exports.setArrayOutput = exports.getOutputKey = exports.getRecoverFilePatterns = exports.getYamlFilePatterns = exports.getFilePatterns = exports.getDirNamesIncludeFilesPattern = exports.jsonOutput = exports.getDirnameMaxDepth = exports.canDiffCommits = exports.getPreviousGitTag = exports.cleanShaInput = exports.verifyCommitSha = exports.getParentSha = exports.getCurrentBranchName = exports.getRemoteBranchHeadSha = exports.isInsideWorkTree = exports.getHeadSha = exports.gitLog = exports.getFilteredChangedFiles = exports.getAllChangedFiles = exports.gitRenamedFiles = exports.gitSubmoduleDiffSHA = exports.getSubmodulePath = exports.gitFetchSubmodules = exports.gitFetch = exports.submoduleExists = exports.isRepoShallow = exports.updateGitGlobalConfig = exports.exists = exports.verifyMinimumGitVersion = exports.getDirname = exports.normalizeSeparators = exports.isWindows = void 0;
/*global AsyncIterableIterator*/
const core = __importStar(__nccwpck_require__(2186));
const exec = __importStar(__nccwpck_require__(1514));
const github = __importStar(__nccwpck_require__(5438));
const fs_1 = __nccwpck_require__(7147);
const promises_1 = __nccwpck_require__(3292);
const lodash_1 = __nccwpck_require__(250);
@ -2460,6 +2471,42 @@ const verifyCommitSha = ({ sha, cwd, showAsErrorMessage = true }) => __awaiter(v
return exitCode;
});
exports.verifyCommitSha = verifyCommitSha;
/**
* Clean the sha from the input which could be a branch name or a commit sha.
*
* If the input is a valid commit sha, return it as is.
*
* If the input is a branch name, get the HEAD sha of that branch and return it.
*
* @param sha The input string, which could be a branch name or a commit sha.
* @param cwd The working directory.
* @param token The GitHub token.
* @returns The cleaned SHA string.
*/
const cleanShaInput = ({ sha, cwd, token }) => __awaiter(void 0, void 0, void 0, function* () {
// Check if the input is a valid commit sha
if (!sha) {
return sha;
}
// Check if the input is a valid commit sha
const { stdout, exitCode } = yield exec.getExecOutput('git', ['rev-parse', '--verify', `${sha}^{commit}`], {
cwd,
ignoreReturnCode: true,
silent: !core.isDebug()
});
if (exitCode !== 0) {
const octokit = github.getOctokit(token);
// If it's not a valid commit sha, assume it's a branch name and get the HEAD sha
const { data: refData } = yield octokit.rest.git.getRef({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
ref: `heads/${sha}`
});
return refData.object.sha;
}
return stdout.trim();
});
exports.cleanShaInput = cleanShaInput;
const getPreviousGitTag = ({ cwd }) => __awaiter(void 0, void 0, void 0, function* () {
const { stdout } = yield exec.getExecOutput('git', ['tag', '--sort=-creatordate'], {
cwd,

2
dist/index.js.map generated vendored

File diff suppressed because one or more lines are too long

View file

@ -5,6 +5,7 @@ import {Env} from './env'
import {Inputs} from './inputs'
import {
canDiffCommits,
cleanShaInput,
getCurrentBranchName,
getHeadSha,
getParentSha,
@ -23,7 +24,11 @@ const getCurrentSHA = async ({
inputs: Inputs
workingDirectory: string
}): Promise<string> => {
let currentSha = inputs.sha
let currentSha = await cleanShaInput({
sha: inputs.sha,
cwd: workingDirectory,
token: inputs.token
})
core.debug('Getting current SHA...')
if (inputs.until) {
@ -162,7 +167,11 @@ export const getSHAForNonPullRequestEvent = async (
}
const currentSha = await getCurrentSHA({inputs, workingDirectory})
let previousSha = inputs.baseSha
let previousSha = await cleanShaInput({
sha: inputs.baseSha,
cwd: workingDirectory,
token: inputs.token
})
const diff = '..'
const currentBranchName = await getCurrentBranchName({cwd: workingDirectory})
@ -186,7 +195,6 @@ export const getSHAForNonPullRequestEvent = async (
throw new Error('Similar commit hashes detected.')
}
await verifyCommitSha({sha: previousSha, cwd: workingDirectory})
core.debug(`Previous SHA: ${previousSha}`)
return {
@ -390,7 +398,11 @@ export const getSHAForPullRequestEvent = async (
}
const currentSha = await getCurrentSHA({inputs, workingDirectory})
let previousSha = inputs.baseSha
let previousSha = await cleanShaInput({
sha: inputs.baseSha,
cwd: workingDirectory,
token: inputs.token
})
let diff = '...'
if (previousSha && currentSha && currentBranch && targetBranch) {
@ -404,7 +416,6 @@ export const getSHAForPullRequestEvent = async (
throw new Error('Similar commit hashes detected.')
}
await verifyCommitSha({sha: previousSha, cwd: workingDirectory})
core.debug(`Previous SHA: ${previousSha}`)
return {

View file

@ -1,6 +1,7 @@
/*global AsyncIterableIterator*/
import * as core from '@actions/core'
import * as exec from '@actions/exec'
import * as github from '@actions/github'
import {createReadStream, promises as fs} from 'fs'
import {readFile} from 'fs/promises'
import {flattenDeep} from 'lodash'
@ -771,6 +772,56 @@ export const verifyCommitSha = async ({
return exitCode
}
/**
* Clean the sha from the input which could be a branch name or a commit sha.
*
* If the input is a valid commit sha, return it as is.
*
* If the input is a branch name, get the HEAD sha of that branch and return it.
*
* @param sha The input string, which could be a branch name or a commit sha.
* @param cwd The working directory.
* @param token The GitHub token.
* @returns The cleaned SHA string.
*/
export const cleanShaInput = async ({
sha,
cwd,
token
}: {
sha: string
cwd: string
token: string
}): Promise<string> => {
// Check if the input is a valid commit sha
if (!sha) {
return sha
}
// Check if the input is a valid commit sha
const {stdout, exitCode} = await exec.getExecOutput(
'git',
['rev-parse', '--verify', `${sha}^{commit}`],
{
cwd,
ignoreReturnCode: true,
silent: !core.isDebug()
}
)
if (exitCode !== 0) {
const octokit = github.getOctokit(token)
// If it's not a valid commit sha, assume it's a branch name and get the HEAD sha
const {data: refData} = await octokit.rest.git.getRef({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
ref: `heads/${sha}`
})
return refData.object.sha
}
return stdout.trim()
}
export const getPreviousGitTag = async ({
cwd
}: {