Files

148 lines
6.7 KiB
JavaScript

// Pull request drafts: a pull request into `dev` stays a draft until it can be reviewed.
//
// - Linked issue: a pull request that closes no issue ("Fixes #123" in the description, or an issue
// linked under Development) becomes a draft at once.
// - CLA: a pull request whose head commit has a failing "CLA" status 30 minutes or more after it
// was opened becomes a draft. A commit the CLA check has not seen yet counts as neither.
// - A pull request this script made a draft is marked ready again once both are met. One that its
// author marks ready before that becomes a draft again.
// - A draft is closed 7 days after it became a draft or was reopened, whoever made it a draft.
//
// Pull requests by maintainers and bots, and those into `main`, are left alone. Every run looks at
// all open pull requests. Run by the drafts job of pull-requests.yml.
module.exports = async ({ github, context, core }) => {
if (!process.env.DRAFTS_TOKEN) {
core.setFailed("The secret DRAFTS_TOKEN is not set; see the drafts job in pull-requests.yml.");
return;
}
// Makes a pull request a draft, or marks it ready, as the owner of DRAFTS_TOKEN.
const stage = async (mutation, id) => {
const response = await fetch("https://api.github.com/graphql", {
method: "POST",
headers: {
authorization: `bearer ${process.env.DRAFTS_TOKEN}`,
"content-type": "application/json",
},
body: JSON.stringify({
query: `mutation($id: ID!) { ${mutation}(input: { pullRequestId: $id }) { clientMutationId } }`,
variables: { id },
}),
});
const result = await response.json();
if (!response.ok || result.errors) {
throw new Error(`${mutation}: ${JSON.stringify(result.errors ?? result)}`);
}
};
// Keep in sync with ALLOWED in cla.js.
const MAINTAINERS = new Set(["chenyme"]);
const MARKER = "<!-- drafts -->";
// Present while the pull request waits as a draft that this workflow made.
const WAITING = "<!-- drafts: waiting -->";
const CLA_WAIT = 30 * 60 * 1000;
const DRAFT_DAYS = 7;
const { owner, repo } = context.repo;
const now = Date.now();
const guide = `https://github.com/${owner}/${repo}/blob/HEAD/.github/CONTRIBUTING.md#pull-request-review`;
const query = `query($owner: String!, $repo: String!, $cursor: String) {
repository(owner: $owner, name: $repo) {
pullRequests(states: OPEN, baseRefName: "dev", first: 50, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes {
id number isDraft createdAt
author { login __typename }
closingIssuesReferences(first: 1) { totalCount }
commits(last: 1) { nodes { commit { status { context(name: "CLA") { state } } } } }
timelineItems(itemTypes: [CONVERT_TO_DRAFT_EVENT, REOPENED_EVENT], last: 1) {
nodes {
... on ConvertToDraftEvent { createdAt }
... on ReopenedEvent { createdAt }
}
}
}
}
}
}`;
const pulls = [];
for (let cursor = null; ;) {
const page = (await github.graphql(query, { owner, repo, cursor })).repository.pullRequests;
pulls.push(...page.nodes);
if (!page.pageInfo.hasNextPage) break;
cursor = page.pageInfo.endCursor;
}
const botComment = async (number) => {
const comments = await github.paginate(github.rest.issues.listComments,
{ owner, repo, issue_number: number, per_page: 100 });
return comments.find((item) => item.user.type === "Bot" && item.body.includes(MARKER));
};
const say = async (number, previous, body) => {
if (previous?.body === body) return;
if (previous) await github.rest.issues.updateComment({ owner, repo, comment_id: previous.id, body });
else await github.rest.issues.createComment({ owner, repo, issue_number: number, body });
};
const waiting = (linked, signed) => [
MARKER,
WAITING,
"Thank you for your contribution. This pull request is a draft, and drafts are not reviewed, until both of these are done:",
"",
`- [${linked ? "x" : " "}] Link the issue it resolves: write \`Fixes #123\` in the description, or link the issue under Development. If there is no issue yet, open one first.`,
`- [${signed ? "x" : " "}] Every commit author signs the Contributor License Agreement, as the CLA comment explains.`,
"",
`It is marked ready for review once both are done. A draft is closed ${DRAFT_DAYS} days after it became a draft or was reopened. See [Pull Request Review](${guide}).`,
].join("\n");
const failed = [];
for (const pr of pulls) {
try {
const author = pr.author;
if (!author || author.__typename === "Bot" || MAINTAINERS.has(author.login.toLowerCase())) continue;
const linked = pr.closingIssuesReferences.totalCount > 0;
// Right after a push the CLA check has not reported on the new head commit yet.
const cla = pr.commits.nodes[0]?.commit.status?.context?.state;
const signed = cla === "SUCCESS";
const unsigned = cla === "FAILURE" || cla === "ERROR";
const late = now - Date.parse(pr.createdAt) >= CLA_WAIT;
if (!pr.isDraft) {
if (linked && !(unsigned && late)) continue;
await stage("convertPullRequestToDraft", pr.id);
await say(pr.number, await botComment(pr.number), waiting(linked, signed));
core.info(`#${pr.number}: made a draft.`);
continue;
}
const previous = await botComment(pr.number);
const ours = previous?.body.includes(WAITING);
if (ours) {
if (linked && signed) {
await stage("markPullRequestReadyForReview", pr.id);
await say(pr.number, previous, `${MARKER}\nThank you! This pull request is now ready for review.`);
core.info(`#${pr.number}: marked ready for review.`);
continue;
}
await say(pr.number, previous, waiting(linked, signed));
}
const since = Date.parse(pr.timelineItems.nodes[0]?.createdAt ?? pr.createdAt);
if (now - since < DRAFT_DAYS * 24 * 60 * 60 * 1000) continue;
// A draft this workflow made stays its own after closing, so it is marked ready once
// reopened and done.
await say(pr.number, previous, [
MARKER,
...(ours ? [WAITING] : []),
`Closing this pull request: it has been a draft for ${DRAFT_DAYS} days. Reopen it once it is ready for review.`,
].join("\n"));
await github.rest.pulls.update({ owner, repo, pull_number: pr.number, state: "closed" });
core.info(`#${pr.number}: closed after ${DRAFT_DAYS} days as a draft.`);
} catch (error) {
// One pull request that fails does not stop the others.
core.error(`#${pr.number}: ${error.message}`);
failed.push(pr.number);
}
}
if (failed.length) core.setFailed(`Failed on ${failed.map((n) => `#${n}`).join(", ")}.`);
};