Skip to content

Commit

Permalink
Merge PR when checks are ready (#13)
Browse files Browse the repository at this point in the history
There is an issue that you can not enable `auto-merge` when a PR is
ready to merge.

For this situation, I have added a try/catch block where it evaluates if
the error contains the message `Pull request is in clean status`. If so,
it will use the
[mergePullRequest](https://docs.github.com/en/graphql/reference/mutations#mergepullrequest)
mutation to merge the PR directly.

This fixes #12
  • Loading branch information
Bullrich committed Sep 28, 2023
1 parent e2f047c commit d7c5bf6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 8 deletions.
43 changes: 36 additions & 7 deletions src/github/merger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ mutation($prId: ID!) {
}
}`;

// https://docs.github.com/en/graphql/reference/mutations#mergepullrequest
export const MERGE_PULL_REQUEST = `
mutation($prId: ID!, $mergeMethod: PullRequestMergeMethod!) {
mergePullRequest(input: {pullRequestId: $prId, mergeMethod: $mergeMethod}) {
clientMutationId
}
}`;

export type MergeMethod = "SQUASH" | "MERGE" | "REBASE";

export class Merger {
Expand All @@ -30,13 +38,34 @@ export class Merger {
) {}

async enableAutoMerge(): Promise<void> {
await this.gql<{
enablePullRequestAutoMerge: { clientMutationId: unknown };
}>(ENABLE_AUTO_MERGE, {
prId: this.nodeId,
mergeMethod: this.mergeMethod,
});
this.logger.info("Succesfully enabled auto-merge");
try {
await this.gql<{
enablePullRequestAutoMerge: { clientMutationId: unknown };
}>(ENABLE_AUTO_MERGE, {
prId: this.nodeId,
mergeMethod: this.mergeMethod,
});
this.logger.info("Succesfully enabled auto-merge");
} catch (error) {
this.logger.warn(error as Error);
if (
error instanceof Error &&
error.message.includes("Pull request is in clean status")
) {
this.logger.warn(
"Pull Request is ready to merge. Running merge command instead",
);
await this.gql<{
mergePullRequest: { clientMutationId: unknown };
}>(MERGE_PULL_REQUEST, {
prId: this.nodeId,
mergeMethod: this.mergeMethod,
});
this.logger.info("Succesfully merged PR");
} else {
throw error;
}
}
}

async disableAutoMerge(): Promise<void> {
Expand Down
10 changes: 9 additions & 1 deletion src/test/queries.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { validate } from "@octokit/graphql-schema";

import { DISABLE_AUTO_MERGE, ENABLE_AUTO_MERGE } from "../github/merger";
import {
DISABLE_AUTO_MERGE,
ENABLE_AUTO_MERGE,
MERGE_PULL_REQUEST,
} from "../github/merger";

describe("Schemas", () => {
test("ENABLE_AUTO_MERGE", () => {
Expand All @@ -10,4 +14,8 @@ describe("Schemas", () => {
test("DISABLE_AUTO_MERGE", () => {
expect(validate(DISABLE_AUTO_MERGE)).toEqual([]);
});

test("MERGE_PULL_REQUEST", () => {
expect(validate(MERGE_PULL_REQUEST)).toEqual([]);
});
});

0 comments on commit d7c5bf6

Please sign in to comment.