Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions design/github.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ also wake a Conversation or run an Event automation.
A PR whose base branch is the head of another open PR gets no merge ask
until that PR merges, because GitHub checks the merge only against the
base branch. A review ask can still come.
A PR in the merge queue gets no merge ask, because GitHub merges it. When
the queue removes it because its checks failed, it gets no merge ask until
a push.
- An issue that Junior opened is an Inbox item for its GitHub assignees who
have a linked account. Assigning a person on GitHub adds them, and
unassigning removes them. The item closes when the issue closes or nobody
Expand Down
6 changes: 6 additions & 0 deletions packages/junior-github/src/graphql-documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,12 @@ export const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
headRefOid
isDraft
isInMergeQueue
queueRemovalOrForcePush: timelineItems(last: 1, itemTypes: [REMOVED_FROM_MERGE_QUEUE_EVENT, HEAD_REF_FORCE_PUSHED_EVENT]) {
nodes {
__typename
... on RemovedFromMergeQueueEvent { createdAt reason }
}
}
mergeStateStatus
reviewDecision
state
Expand Down
365 changes: 0 additions & 365 deletions packages/junior-github/src/webhooks/installation-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ import {
ADD_REVIEW_REACTION,
OPEN_PULL_REQUEST_MERGEABILITY,
PULL_REQUEST_CONFLICT_HISTORY,
PULL_REQUEST_NEXT_ACTION,
PULL_REQUEST_REVIEWS_BEFORE,
pullRequestCards,
pullRequestHeadFacts,
pullRequestLifecycles,
Expand Down Expand Up @@ -629,366 +627,3 @@ export async function loadRepositoryMergeAccess(
const { permission } = await loadRepositoryPermission(env, cache, target);
return permission === "admin" || permission === "write";
}

const timestampSchema = z.iso.datetime({ offset: true });

// GitHub can return a null node for a deleted or hidden item, so the
// connection lists drop them.
function nodesSchema<T extends z.ZodType>(node: T) {
return z
.array(node.nullable())
.transform((items) =>
items.filter((item): item is NonNullable<typeof item> => item !== null),
);
}

const actorSchema = z
.object({ __typename: z.string(), login: z.string().min(1) })
.nullable();
const reviewsSchema = z.object({
pageInfo: z.object({
hasPreviousPage: z.boolean(),
startCursor: z.string().nullable(),
}),
nodes: nodesSchema(
z.object({
author: actorSchema,
state: z.string(),
submittedAt: timestampSchema.nullable(),
}),
),
});
const userLoginSchema = z
.object({ __typename: z.string(), login: z.string().min(1).optional() })
.nullable();

const nextActionSchema = z.object({
data: z.object({
repository: z.object({
defaultBranchRef: z.object({ name: z.string() }).nullable(),
pullRequest: z.object({
autoMergeRequest: z.object({}).nullable(),
// A deleted base branch has no ref.
baseRef: z
.object({
associatedPullRequests: z.object({ totalCount: z.number() }),
})
.nullable(),
baseRefName: z.string(),
commits: z.object({
nodes: nodesSchema(
z.object({ commit: z.object({ committedDate: timestampSchema }) }),
),
}),
headRefOid: z.string(),
isDraft: z.boolean(),
isInMergeQueue: z.boolean(),
mergeStateStatus: z.string(),
reviewDecision: z
.enum(["APPROVED", "CHANGES_REQUESTED", "REVIEW_REQUIRED"])
.nullish(),
reviewRequests: z.object({
nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })),
}),
reviews: reviewsSchema,
state: z.enum(["CLOSED", "MERGED", "OPEN"]),
timelineItems: z.object({
nodes: nodesSchema(
z.discriminatedUnion("__typename", [
z.object({
__typename: z.literal("IssueComment"),
author: actorSchema,
createdAt: timestampSchema,
}),
z.object({
__typename: z.literal("ReviewRequestedEvent"),
createdAt: timestampSchema,
requestedReviewer: userLoginSchema,
}),
z.object({
__typename: z.literal("ReviewRequestRemovedEvent"),
actor: actorSchema,
createdAt: timestampSchema,
requestedReviewer: userLoginSchema,
}),
]),
),
}),
title: z.string(),
updatedAt: timestampSchema,
url: z.string().url(),
}),
}),
}),
});

const reviewsPageSchema = z.object({
data: z.object({
repository: z.object({
pullRequest: z.object({ reviews: reviewsSchema }),
}),
}),
});

/**
* One thing that a person or an App did on a pull request: `author` wrote a
* comment or review, and `reviewRequest` asked `login` for a review. `login`
* is the REST login, so a bot ends in `[bot]`.
*/
export interface GitHubPullRequestActivity {
at: Date;
/**
* `author`: a comment or a review by `login`. `reviewRequest`: GitHub
* asked `login` for a review. `reviewRequestRemoved`: `login` removed
* their own review request.
*/
kind: "author" | "reviewRequest" | "reviewRequestRemoved";
login: string;
/** The state of an `author` review, such as `COMMENTED`. */
review?: string;
}

/** The pull request facts that decide its next action. */
export interface GitHubPullRequestMergeState {
/**
* The latest comments, reviews, and review requests, in no order. GitHub
* returns the latest 100 comments and review requests.
*/
activity: GitHubPullRequestActivity[];
/** A person turned on auto-merge, so GitHub merges it without them. */
autoMerge: boolean;
/**
* The base branch is the head branch of another open pull request, so
* this one can merge only after that one. GitHub's merge state checks it
* only against the base branch. A pull request from the default branch,
* such as a sync into a long-lived branch, does not count.
*/
baseOpen: boolean;
draft: boolean;
/** When the head commit was made, as the time of the last push. */
headCommittedAt?: Date;
headSha: string;
/** A person added it to the merge queue, so GitHub merges it. */
inMergeQueue: boolean;
/**
* The requester's latest review that approves or requests changes
* approves it. Read for drafts too, from the last 100 reviews, because the
* requester marks an approved draft ready.
*/
requesterApproved: boolean;
/**
* GitHub's merge state, such as `clean` or `blocked`. `clean` means that
* the required reviews and every check and status passed, and there are
* no conflicts. Undefined when GitHub has not computed it yet.
*/
mergeableState?: string;
/** Logins of the people whose review GitHub still requests. */
requestedReviewers: string[];
/** Logins of the people and Apps whose review GitHub requests. */
reviewRequestLogins: string[];
/**
* GitHub still requests a review from a person or a team. A team that
* the App cannot read has no login, so `requestedReviewers` misses it.
*/
reviewPending: boolean;
/**
* Logins of the people whose latest submitted review was not dismissed,
* including a comment-only review. Read only when the pull request is open
* and not a draft.
*/
reviewedBy: string[];
/**
* `approved` with at least one approval and no reviewer who still
* requests changes. `changesRequested` while a reviewer still requests
* changes. Undefined with neither. Read only when the pull request is
* open and not a draft.
*/
reviewOutcome?: "approved" | "changesRequested";
/** GitHub's review decision, which a repository with no rule lacks. */
reviewDecision?: "APPROVED" | "CHANGES_REQUESTED" | "REVIEW_REQUIRED";
state: "closed" | "merged" | "open";
title: string;
updatedAt: string;
url: string;
}

// GraphQL gives a bot's login without the `[bot]` that REST and webhooks add.
function restLogin(actor: { __typename: string; login: string }): string {
return actor.__typename === "Bot" ? `${actor.login}[bot]` : actor.login;
}

type Review = z.output<typeof reviewsSchema>["nodes"][number];

/**
* Read whether a pull request is ready to merge, whether the requester
* changed their review, and who acted on it last, with a read-only token
* and one GraphQL query. GitHub computes the merge state after a change,
* so an unknown state is read once more. A pull request with more than 100
* reviews reads the older pages too. Each reviewer counts by their latest
* approval, change request, or dismissal. Comments do not change the
* result.
*/
export async function loadPullRequestMergeState(
env: GitHubInstallationEnv,
pullRequest: { number: number; repositoryFullName: string },
requesterLogin: string | undefined,
): Promise<GitHubPullRequestMergeState> {
const { owner, name } = splitRepository(
pullRequest.repositoryFullName,
"pull request merge state",
);
const token = await issueInstallationToken({
...env,
permissions: { pull_requests: "read" },
repositories: [name],
});
const variables = { name, number: pullRequest.number, owner };
const query = async (
document: typeof PULL_REQUEST_NEXT_ACTION,
extra?: { before: string },
) =>
await githubGraphqlRequest({
body: { ...document, variables: { ...variables, ...extra } },
token: token.token,
});
const readRepository = async () =>
nextActionSchema.parse(await query(PULL_REQUEST_NEXT_ACTION)).data
.repository;
const repository = await readRepository();
let pull = repository.pullRequest;
const open = pull.state === "OPEN" && !pull.isDraft;
const unknown = (status: string) => status === "UNKNOWN";
if (open && !pull.autoMergeRequest && unknown(pull.mergeStateStatus)) {
pull = (await readRepository()).pullRequest;
}
const reviews: Review[] = [...pull.reviews.nodes];
let page = pull.reviews.pageInfo;
// Older pages can hold a reviewer's latest change request.
while (open && page.hasPreviousPage && page.startCursor) {
const older = reviewsPageSchema.parse(
// oxlint-disable-next-line no-await-in-loop -- Each page starts at the cursor of the page after it.
await query(PULL_REQUEST_REVIEWS_BEFORE, { before: page.startCursor }),
).data.repository.pullRequest.reviews;
reviews.unshift(...older.nodes);
page = older.pageInfo;
}

const activity: GitHubPullRequestActivity[] = [];
for (const item of pull.timelineItems.nodes) {
if (item.__typename === "IssueComment" && item.author) {
activity.push({
at: new Date(item.createdAt),
kind: "author",
login: restLogin(item.author),
});
} else if (
item.__typename === "ReviewRequestedEvent" &&
item.requestedReviewer?.login
) {
activity.push({
at: new Date(item.createdAt),
kind: "reviewRequest",
login: item.requestedReviewer.login,
});
} else if (
item.__typename === "ReviewRequestRemovedEvent" &&
item.requestedReviewer?.login &&
item.actor &&
restLogin(item.actor).toLowerCase() ===
item.requestedReviewer.login.toLowerCase()
) {
activity.push({
at: new Date(item.createdAt),
kind: "reviewRequestRemoved",
login: item.requestedReviewer.login,
});
}
}
for (const review of reviews) {
if (review.author && review.submittedAt) {
activity.push({
at: new Date(review.submittedAt),
kind: "author",
login: restLogin(review.author),
review: review.state,
});
}
}

const mergeableState = unknown(pull.mergeStateStatus)
? undefined
: pull.mergeStateStatus.toLowerCase();
const headCommittedAt = pull.commits.nodes[0]?.commit.committedDate;
const state: GitHubPullRequestMergeState = {
activity,
autoMerge: Boolean(pull.autoMergeRequest),
baseOpen:
pull.baseRefName !== repository.defaultBranchRef?.name &&
(pull.baseRef?.associatedPullRequests.totalCount ?? 0) > 0,
draft: pull.isDraft,
...(headCommittedAt
? { headCommittedAt: new Date(headCommittedAt) }
: undefined),
headSha: pull.headRefOid,
inMergeQueue: pull.isInMergeQueue,
...(mergeableState ? { mergeableState } : undefined),
requesterApproved: false,
requestedReviewers: pull.reviewRequests.nodes.flatMap((request) =>
request.requestedReviewer?.__typename === "User" &&
request.requestedReviewer.login
? [request.requestedReviewer.login]
: [],
),
...(pull.reviewDecision
? { reviewDecision: pull.reviewDecision }
: undefined),
reviewPending: pull.reviewRequests.nodes.length > 0,
reviewRequestLogins: pull.reviewRequests.nodes.flatMap((request) =>
request.requestedReviewer?.login ? [request.requestedReviewer.login] : [],
),
reviewedBy: [],
state:
pull.state === "MERGED"
? "merged"
: pull.state === "OPEN"
? "open"
: "closed",
title: pull.title,
updatedAt: pull.updatedAt,
url: pull.url,
};
// GitHub lists reviews oldest first, so a later one replaces an earlier.
const latest = new Map<string, Review>();
for (const review of reviews) {
if (
review.author &&
review.state !== "COMMENTED" &&
review.state !== "PENDING"
) {
latest.set(review.author.login.toLowerCase(), review);
}
}
const login = requesterLogin?.toLowerCase();
const requesterReview = login ? latest.get(login) : undefined;
state.requesterApproved = requesterReview?.state === "APPROVED";
if (!open) return state;

// A dismissed review counts only when it is the person's latest review.
// GitHub keeps their earlier reviews, such as a comment before it.
const latestSubmitted = new Map<string, string>();
for (const review of reviews) {
if (review.author && review.submittedAt && review.state !== "PENDING") {
latestSubmitted.set(review.author.login.toLowerCase(), review.state);
}
}
state.reviewedBy = [...latestSubmitted].flatMap(([login, reviewState]) =>
reviewState === "DISMISSED" ? [] : [login],
);
const reviewStates = [...latest.values()].map((review) => review.state);
if (reviewStates.includes("CHANGES_REQUESTED")) {
state.reviewOutcome = "changesRequested";
} else if (reviewStates.includes("APPROVED")) {
state.reviewOutcome = "approved";
}
return state;
}
Loading
Loading