@actions/github#context TypeScript Examples
The following examples show how to use
@actions/github#context.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: github.ts From EIP-Bot with Creative Commons Zero v1.0 Universal | 6 votes |
getPullRequestFromNumber = (pullNumber: number) => {
const github = getOctokit(GITHUB_TOKEN).rest;
return github.pulls
.get({
repo: context.repo.repo,
owner: context.repo.owner,
pull_number: pullNumber
})
.then((res) => {
return res.data;
});
}
Example #2
Source File: action.ts From jest-github-action with MIT License | 6 votes |
function getCheckPayload(results: FormattedTestResults, cwd: string) {
const payload: Octokit.ChecksCreateParams = {
...context.repo,
head_sha: getSha(),
name: core.getInput("check-name", { required: false }) || ACTION_NAME,
status: "completed",
conclusion: results.success ? "success" : "failure",
output: {
title: results.success ? "Jest tests passed" : "Jest tests failed",
text: getOutputText(results),
summary: results.success
? `${results.numPassedTests} tests passing in ${
results.numPassedTestSuites
} suite${results.numPassedTestSuites > 1 ? "s" : ""}.`
: `Failed tests: ${results.numFailedTests}/${results.numTotalTests}. Failed suites: ${results.numFailedTests}/${results.numTotalTestSuites}.`,
annotations: getAnnotations(results, cwd),
},
}
console.debug("Check payload: %j", payload)
return payload
}
Example #3
Source File: github.ts From EIP-Bot with Creative Commons Zero v1.0 Universal | 6 votes |
removeLabels = async (labels: string[]) => {
const Github = getOctokit(GITHUB_TOKEN).rest;
// makes it easy to maintain the integration tests and the
// responses from this are not used
if (isMock() || isTest()) return;
await Promise.all(
// this will submit a max of three requests which is not enough to
// rate limit
labels.map((label) =>
Github.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
name: label
})
)
);
}
Example #4
Source File: pullRequestComment.ts From github-action with Apache License 2.0 | 6 votes |
async function getComment() {
try {
const response = await octokit.issues.listComments({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number })
//TODO: check the below regex
// using a `string` true or false purposely as github action input cannot have a boolean value
if (getUseDcoFlag() === 'true') {
return response.data.find(comment => comment.body.match(/.*DCO Assistant Lite bot.*/))
} else if (getUseDcoFlag() === 'false') {
return response.data.find(comment => comment.body.match(/.*CLA Assistant Lite bot.*/))
}
} catch (error) {
throw new Error(`Error occured when getting all the comments of the pull request: ${error.message}`)
}
}
Example #5
Source File: action.ts From jest-github-action with MIT License | 6 votes |
async function deletePreviousComments(octokit: GitHub) {
const { data } = await octokit.issues.listComments({
...context.repo,
per_page: 100,
issue_number: getPullId(),
})
return Promise.all(
data
.filter(
(c) =>
c.user.login === "github-actions[bot]" && c.body.startsWith(COVERAGE_HEADER),
)
.map((c) => octokit.issues.deleteComment({ ...context.repo, comment_id: c.id })),
)
}
Example #6
Source File: setupClaCheck.ts From github-action with Apache License 2.0 | 6 votes |
export async function setupClaCheck() {
let committerMap = getInitialCommittersMap()
if (!isPersonalAccessTokenPresent()) {
core.setFailed('Please enter a personal access token as a environment variable in the CLA workflow file as described in the https://github.com/cla-assistant/github-action documentation')
return
}
let committers = await getCommitters()
committers = checkAllowList(committers)
const { claFileContent, sha } = await getCLAFileContentandSHA(committers, committerMap) as ClafileContentAndSha
committerMap = prepareCommiterMap(committers, claFileContent) as CommitterMap
try {
const reactedCommitters = await prCommentSetup(committerMap, committers) as ReactedCommitterMap
if (reactedCommitters?.newSigned.length) {
/* pushing the recently signed contributors to the CLA Json File */
await updateFile(sha, claFileContent, reactedCommitters)
}
if (reactedCommitters?.allSignedFlag || (committerMap?.notSigned === undefined || committerMap.notSigned.length === 0)) {
core.info(`All contributors have signed the CLA ? ✅ `)
return reRunLastWorkFlowIfRequired()
} else {
core.setFailed(`committers of Pull Request number ${context.issue.number} have to sign the CLA ?`)
}
} catch (err) {
core.setFailed(`Could not update the JSON file: ${err.message}`)
}
}
Example #7
Source File: main.ts From github-actions-pr-to-work-item with MIT License | 6 votes |
// prettier-ignore
function getWebHookPayLoad(): Payload {
const body: WebhookPayload = (context !== undefined && !local_debug) ? context.payload : sampleWebHookPayload
const payload: Payload = new Payload()
payload.action = body.action !== undefined ? body.action : ''
payload.number = body.pull_request?.number !== undefined ? body.pull_request?.number : -1
payload.title = body.pull_request !== undefined ? body.pull_request['title'] : ''
payload.url = body.pull_request?.html_url !== undefined ? body.pull_request.html_url : ''
payload.merged = body['merged'] !== undefined ? body['merged'] : false
payload.repo_name = body.repository?.name !== undefined ? body.repository.name : ''
payload.repo_url = body.repository?.html_url !== undefined ? body.repository.html_url : ''
payload.repo_fullname = body.repository?.full_name !== undefined ? body.repository.full_name : ''
payload.repo_owner = body.repository?.owner !== undefined ? body.repository.owner.login : ''
payload.sender_login = body.sender?.login !== undefined ? body.sender.login : ''
payload.body = body.pull_request != undefined && body.pull_request.body != undefined ? body.pull_request.body : ''
return payload
}
Example #8
Source File: github.ts From EIP-Bot with Creative Commons Zero v1.0 Universal | 6 votes |
addLabels = async (labels: string[]): Promise<void> => {
const Github = getOctokit(GITHUB_TOKEN).rest;
// makes it easy to maintain the integration tests and the
// responses from this are not used
if (isMock() || isTest()) return;
// because of a weird type issue
const { addLabels: _addLabels } = Github.issues;
await _addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
labels
});
}
Example #9
Source File: main.ts From hans-landa with MIT License | 6 votes |
async function buildOnCommit(props: ActionProps): Promise<void> {
let branchName = context.ref.slice(11)
let commitHash = context.sha
if (context.payload.pull_request) {
console.log('>>Triggered by commit on PR')
branchName = context.payload.pull_request.head.ref
commitHash = context.payload.pull_request.head.sha
} else {
console.log('>>Triggered by commit')
}
console.log(JSON.stringify(context.payload, null, 2))
triggerBuild({
...props,
branchName,
commitHash,
commitMessage: context.payload.pull_request?.body,
pullRequestId: context.payload.pull_request?.number,
branchDestName: context.payload.pull_request?.base.ref,
})
}
Example #10
Source File: pullRerunRunner.ts From github-action with Apache License 2.0 | 6 votes |
async function checkIfLastWorkFlowFailed(run: number): Promise<boolean> {
const response: any = await octokit.actions.getWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: run
})
return response.data.conclusion == 'failure'
}
Example #11
Source File: github.ts From EIP-Bot with Creative Commons Zero v1.0 Universal | 6 votes |
getPullRequestReviews = async (
pullNumber: number,
page = 1
): Promise<Review[]> => {
const Github = getOctokit(GITHUB_TOKEN).rest;
const { data: reviews }: { data: Review[] } = await Github.pulls.listReviews({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pullNumber,
per_page: 100,
page
});
if (_.isEmpty(reviews)) {
return reviews;
}
return getPullRequestReviews(pullNumber, page + 1).then((res) =>
reviews.concat(res)
);
}
Example #12
Source File: action.ts From jest-github-action with MIT License | 6 votes |
function getJestCommand(resultsFile: string) {
let cmd = core.getInput("test-command", { required: false })
const jestOptions = `--testLocationInResults --json ${
shouldCommentCoverage() ? "--coverage" : ""
} ${
shouldRunOnlyChangedFiles() && context.payload.pull_request?.base.ref
? "--changedSince=" + context.payload.pull_request?.base.ref
: ""
} --outputFile=${resultsFile}`
const shouldAddHyphen = cmd.startsWith("npm") || cmd.startsWith("npx") || cmd.startsWith("pnpm") || cmd.startsWith("pnpx")
cmd += (shouldAddHyphen ? " -- " : " ") + jestOptions
core.debug("Final test command: " + cmd)
return cmd
}
Example #13
Source File: get-changed-files.ts From action-eslint with MIT License | 6 votes |
getChangedFiles = async (token: string): Promise<FileNamesList> => {
const octokit = getOctokit(token);
const pullRequest = context.payload.pull_request;
let filenames: FileNamesList = [];
if (!pullRequest?.number) {
const getCommitEndpointOptions = octokit.rest.repos.getCommit.endpoint.merge({
owner: context.repo.owner,
repo: context.repo.repo,
ref: context.sha,
});
type ReposGetCommitResponse = GetResponseDataTypeFromEndpointMethod<typeof octokit.rest.repos.getCommit>;
const response: ReposGetCommitResponse[] = await octokit.paginate(getCommitEndpointOptions);
const filesArr = response.map((data) => data.files);
const filesChangedInCommit = filesArr.reduce((acc, val) => acc?.concat(val || []), []);
filenames = getFileNames(filesChangedInCommit as File[]);
} else {
const listFilesEndpointOptions = octokit.rest.pulls.listFiles.endpoint.merge({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pullRequest.number,
});
type PullsListFilesResponse = GetResponseDataTypeFromEndpointMethod<typeof octokit.rest.pulls.listFiles>;
const filesChangedInPR: PullsListFilesResponse = await octokit.paginate(listFilesEndpointOptions);
filenames = getFileNames(filesChangedInPR as File[]);
}
return filenames;
}
Example #14
Source File: delete.ts From action-deploy with MIT License | 6 votes |
export async function deleteDeployment (
client: GitHub,
deploymentId: number
): Promise<void> {
// invalidate deployment first
// since we can't delete active deployment
console.log(`invalidate deployment: ${deploymentId}`)
const status = await client.repos.createDeploymentStatus({
...context.repo,
deployment_id: deploymentId,
state: 'failure'
})
// then delete it
const deploymentUrl = status.data.deployment_url
console.log(`delete deployment: ${deploymentUrl}`)
await client.request(deploymentUrl, { method: 'DELETE' })
}
Example #15
Source File: pub.ts From vscode-drawio with GNU General Public License v3.0 | 6 votes |
export async function run(): Promise<void> {
const version = getChangelog().latestVersion;
if (version.kind === "unreleased") {
return;
}
await exec("yarn", [
"vsce",
"publish",
"--packagePath",
"./vscode-drawio.vsix",
"--pat",
process.env.MARKETPLACE_TOKEN!,
]);
const gitTag = `v${version.version}`;
console.log(`Creating a version tag "${gitTag}".`);
const api = new GitHub(process.env.GH_TOKEN!);
await api.git.createRef({
...context.repo,
ref: `refs/tags/${gitTag}`,
sha: context.sha,
});
console.log("Uploading to open-vsx...");
await exec("yarn", [
"ovsx",
"publish",
"./vscode-drawio.vsix",
"-p",
process.env.OPEN_VSX_TOKEN!,
]);
}
Example #16
Source File: complete.ts From action-deploy with MIT License | 6 votes |
export async function complete (
client: GitHub,
deploymentId: number,
status: DeploymentStatus
): Promise<void> {
const statuses = await client.repos.listDeploymentStatuses({
...context.repo,
deployment_id: deploymentId
})
const lastStatus = statuses.data.sort((a, b) => a.id - b.id).slice(-1)[0]
console.log(
`last status for deployment_id '${deploymentId}': ${JSON.stringify(
lastStatus,
null,
2
)}`
)
const statusResult = await client.repos.createDeploymentStatus({
...context.repo,
deployment_id: deploymentId,
state: status,
environment_url: lastStatus.environment_url,
log_url: lastStatus.log_url
})
console.log(`created deployment status: ${JSON.stringify(statusResult.data, null, 2)}`)
}
Example #17
Source File: main.ts From hans-landa with MIT License | 6 votes |
async function run(): Promise<void> {
try {
const props = getActionProps()
console.log(props)
if (isCommentOnPr(context) && shouldTriggerMessageBuild(props.triggerOn)) {
await buildOnComment(props)
} else if (shouldTriggerCommitBuild(props.triggerOn)) {
await buildOnCommit(props)
}
} catch (error) {
core.setFailed(error.message)
}
}
Example #18
Source File: main.ts From action-wait-for-check with MIT License | 6 votes |
async function run(): Promise<void> {
try {
const token = core.getInput('token', {required: true})
const result = await poll({
client: new GitHub(token),
log: msg => core.info(msg),
checkName: core.getInput('checkName', {required: true}),
owner: core.getInput('owner') || context.repo.owner,
repo: core.getInput('repo') || context.repo.repo,
ref: core.getInput('ref') || context.sha,
timeoutSeconds: parseInt(core.getInput('timeoutSeconds') || '600'),
intervalSeconds: parseInt(core.getInput('intervalSeconds') || '10')
})
core.setOutput('conclusion', result)
} catch (error) {
core.setFailed(error.message)
}
}
Example #19
Source File: main.ts From github-action with Apache License 2.0 | 6 votes |
export async function run() {
try {
core.info(`CLA Assistant GitHub Action bot has started the process`)
/*
* using a `string` true or false purposely as github action input cannot have a boolean value
*/
if (context.payload.action === 'closed' && input.lockPullRequestAfterMerge() == 'true') {
return lockPullRequest()
} else {
await setupClaCheck()
}
} catch (error) {
core.setFailed(error.message)
}
}
Example #20
Source File: main.ts From spotbugs-github-action with MIT License | 5 votes |
async function createCheck(
name: string,
title: string,
annotations: Annotation[],
numErrors: number
): Promise<void> {
const octokit = getOctokit(core.getInput(Inputs.Token))
let sha = context.sha
if (context.payload.pull_request) {
sha = context.payload.pull_request.head.sha
}
const req = {
...context.repo,
ref: sha
}
const res = await octokit.checks.listForRef(req)
const existingCheckRun = res.data.check_runs.find(
check => check.name === name
)
if (!existingCheckRun) {
const createRequest = {
...context.repo,
head_sha: sha,
name,
status: <const>'completed',
conclusion: numErrors === 0 ? <const>'success' : <const>'neutral',
output: {
title,
summary: `${numErrors} violation(s) found`,
annotations
}
}
await octokit.checks.create(createRequest)
} else {
const check_run_id = existingCheckRun.id
const update_req = {
...context.repo,
check_run_id,
status: <const>'completed',
conclusion: <const>'neutral',
output: {
title,
summary: `${numErrors} violation(s) found`,
annotations
}
}
await octokit.checks.update(update_req)
}
}
Example #21
Source File: InputHelper.ts From file-changes-action with MIT License | 5 votes |
/**
* @function inferInput
* @param before BASE commit sha to compare
* @param after HEAD commit sha to compare
* @param pr pr number to get changed files for
* @returns {Inferred} object of inferred input for the action
*/
export function inferInput(
before: string,
after: string,
pr: number
): Inferred {
const event = context.eventName
const weirdInput = `Received event from ${event}, but also received a before(${before}) or after(${after}) value.\n I am assuming you want to use a Push event but forgot something, so I'm giving you a message.`
const allInput = `Received event from ${event}, but received a before(${before}), after(${after}), and PR(${pr}).\n I am assuming you want to use one or the other but I am giving you Push.`
if (event === 'pull_request') {
if (
before &&
after &&
(before !== context.payload.before || after !== context.payload.after)
)
return {before, after} // PR(push) - pull_request event with push inputs | PUSH
if (before || after) coreWarning(weirdInput) // PR(push) - pull_request event with single push input | PR*
return {pr} // PR - pull_request event with no push inputs | PR
}
if (event === 'push') {
if (pr) return {pr} // Push(PR) - push event with pr inputs | PR
return {before, after} // Push - push event with no pr inputs | PUSH
}
if (pr) {
if (before && after) {
coreWarning(allInput) // Not PR or Push - all inputs | PUSH*
if (event === 'issue_comment') return {before, after} // If you explicitly set a before/after in an issue comment it will return those
return {pr} // Not PR or Push - pr inputs | PR if a PR before and after assume its a synchronize and return the whole PR
}
if (before || after) coreWarning(weirdInput) // Not PR or Push - pull_request event with single push input | PR*
return {pr} // Not PR or Push - pr inputs | PR
}
if (before || after) {
if (!(before && after)) {
const eString = `Received event from ${event}, but only received a before(${before}) or after(${after}).\n I need both of these if you want to use a Push event.`
throw new Error(
getErrorString('inferInput Error', 500, inferInput.name, eString)
)
}
return {before, after} // Not PR or Push - push inputs | PUSH
}
const eString = `Received event from ${event}, but received no inputs. {event_name:${event}, pr: ${+pr}, before:${before}, after:${after}}`
throw new Error(
getErrorString('inferInput Error', 500, inferInput.name, eString)
)
}
Example #22
Source File: main.ts From hans-landa with MIT License | 5 votes |
async function buildOnComment(props: ActionProps): Promise<void> {
console.log('>>Triggered by comment on PR')
console.log(JSON.stringify(context.payload, null, 2))
const client = new GitHub(props.githubToken)
const prNumber = context.payload.issue?.number
const repo = context.payload.repository?.name
const owner = context.payload.repository?.owner.login
console.log({
prNumber,
repo,
owner,
})
if (!prNumber || !repo || !owner) {
console.log('Unable to find PR info', {
prNumber,
repo,
owner,
})
return
}
const pr = await client.pulls.get({ pull_number: prNumber, owner, repo })
const branchName = pr.data.head.ref
const commitHash = pr.data.head.sha
const branchDestName = pr.data.base.ref
const { command, workflow } = parseComment(context.payload.comment.body)
console.log({
command,
workflow,
COMMAND_TRIGGER,
})
console.log(`command === COMMAND_TRIGGER: ${command === COMMAND_TRIGGER}`)
console.log(
`workflow === props.bitriseWorkflow : ${workflow ===
props.bitriseWorkflow}`,
)
console.log(
`workflow === props.commandAlias : ${workflow === props.commandAlias}`,
)
if (
command === COMMAND_TRIGGER &&
(workflow === props.bitriseWorkflow || workflow === props.commandAlias)
) {
triggerBuild({
...props,
branchName,
commitHash,
commitMessage: '',
pullRequestId: prNumber,
branchDestName,
})
}
}
Example #23
Source File: action.ts From jest-github-action with MIT License | 5 votes |
function getCommentPayload(body: string) {
const payload: Octokit.IssuesCreateCommentParams = {
...context.repo,
body,
issue_number: getPullId(),
}
return payload
}
Example #24
Source File: create.ts From action-deploy with MIT License | 5 votes |
async function invalidatePreviousDeployments (
client: GitHub,
environment: string
): Promise<void> {
const deployments = await client.repos.listDeployments({
...context.repo,
ref: context.ref,
environment
})
await Promise.all(
deployments.data.map(async deployment => {
const statuses = await client.repos.listDeploymentStatuses({
...context.repo,
deployment_id: deployment.id
})
const lastStatus = statuses.data.sort((a, b) => a.id - b.id).slice(-1)[0]
console.log(
`last status for deployment_id '${deployment.id}': ${JSON.stringify(
lastStatus,
null,
2
)}`
)
// invalidate the deployment
if (lastStatus?.state === 'success') {
console.log(`invalidating deployment: ${JSON.stringify(deployment, null, 2)}`)
await client.repos.createDeploymentStatus({
...context.repo,
deployment_id: deployment.id,
state: 'inactive',
environment_url: lastStatus.environment_url,
log_url: lastStatus.log_url
})
}
})
)
}
Example #25
Source File: InputHelper.ts From file-changes-action with MIT License | 5 votes |
/**
* @function getInputs
* @description reads the inputs to the action with core.getInput and returns object
* @returns {Inputs} object of inputs for the github action
*/
export function getInputs(): Inputs {
try {
const githubToken =
coreGetInput('githubToken') || process.env.GITHUB_TOKEN || false
if (!githubToken)
throw new Error(
getErrorString(
'getInputs Error',
500,
getInputs.name,
'Received no token, a token is a requirement.'
)
)
let prNumber
if (typeof context.issue.number !== 'undefined') {
if (
+coreGetInput('prNumber') !== context.issue.number &&
coreGetInput('prNumber')
) {
prNumber = +coreGetInput('prNumber')
} else {
prNumber = context.issue.number
}
} else {
prNumber = +coreGetInput('prNumber') || NaN
}
return {
githubRepo:
coreGetInput('githubRepo') ||
`${context.repo.owner}/${context.repo.repo}`,
githubToken,
pushBefore:
coreGetInput('pushBefore') ||
(context.payload.before === undefined ? false : context.payload.before),
pushAfter:
coreGetInput('pushAfter') ||
(context.payload.after === undefined ? false : context.payload.after),
prNumber,
output: coreGetInput('output') || ' ',
fileOutput: coreGetInput('fileOutput') || ' ',
event: context.eventName
} as Inputs
} catch (error) {
const eString = `Received an issue getting action inputs.`
const retVars = Object.fromEntries(
Object.entries(process.env).filter(
key =>
key[0].includes('GITHUB') ||
key[0].includes('INPUT_') ||
key[0] === 'HOME'
)
)
throw new Error(
getErrorString('getInputs Error', 500, getInputs.name, eString, retVars)
)
}
}
Example #26
Source File: main.ts From checkstyle-github-action with MIT License | 5 votes |
async function createCheck(
name: string,
title: string,
annotations: Annotation[],
numErrors: number,
conclusion: 'success' | 'failure' | 'neutral'
): Promise<void> {
core.info(
`Uploading ${annotations.length} / ${numErrors} annotations to GitHub as ${name} with conclusion ${conclusion}`
)
const octokit = getOctokit(core.getInput(Inputs.Token))
let sha = context.sha
if (context.payload.pull_request) {
sha = context.payload.pull_request.head.sha
}
const req = {
...context.repo,
ref: sha
}
const res = await octokit.checks.listForRef(req)
const existingCheckRun = res.data.check_runs.find(
check => check.name === name
)
if (!existingCheckRun) {
const createRequest = {
...context.repo,
head_sha: sha,
conclusion,
name,
status: <const>'completed',
output: {
title,
summary: `${numErrors} violation(s) found`,
annotations
}
}
await octokit.checks.create(createRequest)
} else {
const check_run_id = existingCheckRun.id
const update_req = {
...context.repo,
conclusion,
check_run_id,
status: <const>'completed',
output: {
title,
summary: `${numErrors} violation(s) found`,
annotations
}
}
await octokit.checks.update(update_req)
}
}
Example #27
Source File: main.ts From nunit-reporter with MIT License | 5 votes |
async function run(): Promise<void> {
try {
const path = getInput("path");
const numFailures = parseInt(getInput("numFailures"));
const accessToken = getInput("access-token");
const title = getInput("reportTitle");
const results = await readResults(path);
const octokit = new GitHub(accessToken);
const summary =
results.failed > 0
? `${results.failed} tests failed`
: `${results.passed} tests passed`;
let details =
results.failed === 0
? `** ${results.passed} tests passed**`
: `
**${results.passed} tests passed**
**${results.failed} tests failed**
`;
for (const ann of results.annotations) {
const annStr = generateSummary(ann);
const newDetails = `${details}\n${annStr}`;
if (newDetails.length > 65000) {
details = `${details}\n\n ... and more.`;
break;
} else {
details = newDetails;
}
}
const pr = context.payload.pull_request;
await octokit.checks.create({
head_sha: (pr && pr["head"] && pr["head"].sha) || context.sha,
name: `Tests Report: ${title}`,
owner: context.repo.owner,
repo: context.repo.repo,
status: "completed",
conclusion:
results.failed > 0 || results.passed === 0 ? "failure" : "success",
output: {
title,
summary,
annotations: results.annotations.slice(0, numFailures),
text: details,
},
});
} catch (error) {
setFailed(error.message);
}
}
Example #28
Source File: github.ts From EIP-Bot with Creative Commons Zero v1.0 Universal | 5 votes |
getPullNumber = () => {
return context.payload?.pull_request?.number;
}
Example #29
Source File: signatureComment.ts From github-action with Apache License 2.0 | 5 votes |
export default async function signatureWithPRComment(committerMap: CommitterMap, committers): Promise<ReactedCommitterMap> {
let repoId = context.payload.repository!.id
let prResponse = await octokit.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number
})
let listOfPRComments = [] as CommittersDetails[]
let filteredListOfPRComments = [] as CommittersDetails[]
prResponse?.data.map((prComment) => {
listOfPRComments.push({
name: prComment.user.login,
id: prComment.user.id,
comment_id: prComment.id,
body: prComment.body.trim().toLowerCase(),
created_at: prComment.created_at,
repoId: repoId,
pullRequestNo: context.issue.number
})
})
listOfPRComments.map(comment => {
if (isCommentSignedByUser(comment.body || "", comment.name)) {
filteredListOfPRComments.push(comment)
}
})
for (var i = 0; i < filteredListOfPRComments.length; i++) {
delete filteredListOfPRComments[i].body
}
/*
*checking if the reacted committers are not the signed committers(not in the storage file) and filtering only the unsigned committers
*/
const newSigned = filteredListOfPRComments.filter(commentedCommitter => committerMap.notSigned!.some(notSignedCommitter => commentedCommitter.id === notSignedCommitter.id))
/*
* checking if the commented users are only the contributors who has committed in the same PR (This is needed for the PR Comment and changing the status to success when all the contributors has reacted to the PR)
*/
const onlyCommitters = committers.filter(committer => filteredListOfPRComments.some(commentedCommitter => committer.id == commentedCommitter.id))
const commentedCommitterMap: ReactedCommitterMap = {
newSigned,
onlyCommitters,
allSignedFlag: false
}
return commentedCommitterMap
}