Skip to content

Instantly share code, notes, and snippets.

@StarpTech
Last active September 25, 2021 09:58
Show Gist options
  • Save StarpTech/6b72780bb8152d63847a819044f329f4 to your computer and use it in GitHub Desktop.
Save StarpTech/6b72780bb8152d63847a819044f329f4 to your computer and use it in GitHub Desktop.
ZX script to prefix the PR title with the linear ticket from the branch name or PR description. Can only run in GitHub CI.
#!/usr/bin/env zx
let token = process.env.GITHUB_TOKEN;
let branchName = process.env.GITHUB_HEAD_REF;
let pullNumber = process.env.PULL_NUMBER;
let apiUrl = process.env.GITHUB_API_URL;
let repo = process.env.GITHUB_REPOSITORY;
let issuePrefix = process.env.ISSUE_PREFIX
let allowFailure = process.env.ALLOW_FAILURE
console.log("Branch name:", branchName);
console.log("Pull number:", pullNumber);
console.log("Github api url:", apiUrl);
console.log("Repo:", repo);
let pr = `${apiUrl}/repos/${repo}/pulls/${pullNumber}`;
let requestHeaders = {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${token}`,
}
let resp = await fetch(pr, {
method: "GET",
headers: requestHeaders,
});
if (!resp.ok) {
console.error("Could not get PR: %s", resp.statusText);
process.exit(1)
}
let data = await resp.json();
let prTitle = data.title
let prBody = data.body
console.log("Current PR title: %s", prTitle);
const regex = new RegExp(`(${issuePrefix}[0-9]+)`, "igm")
const matchFromTitle = prTitle.match(regex);
const matchFromBranch = branchName.match(regex);
const matchFromBody = prBody.match(regex);
let ticket = ''
if (matchFromTitle !== null && matchFromTitle.length > 0) {
console.log("PR title already contains issue");
process.exit(0)
}
if (matchFromBody !== null && matchFromBody.length > 0) {
ticket = matchFromBody[0]
} else if (matchFromBranch !== null && matchFromBranch.length > 0) {
ticket = matchFromBranch[0]
}
if (!ticket) {
console.error("Could not extract issue from branch name");
process.exit(allowFailure ? 0 : 1)
}
const newPRTitle = ticket.toUpperCase() + ": " + prTitle.trim()
console.error("PR title updated: %s", newPRTitle);
resp = await fetch(pr, {
method: "PATCH",
body: JSON.stringify({ title: newPRTitle }),
headers: requestHeaders,
});
if (!resp.ok) {
console.error("Could not update PR title to: %s, error: %s", resp.statusText, newPRTitle);
process.exit(allowFailure ? 0 : 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment