/ opencodehub / src / lib / pull-requests.ts
Swadhin Biswas Feature/ai code reviewer (#79) · 8/16/2026
cfd400d
80 lines · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { getDatabase, schema } from "@/db";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { evaluateGates } from "./ci-gates";
import { mergeBranch } from "./git";
import { resolveRepoPath } from "./git-storage";
import { closeLinkedIssuesOnMerge } from "./pr-issue-linking";

export async function mergePullRequest(
  pullRequestId: string,
  mergedById: string,
  mergeMethod: "merge" | "squash" | "rebase" = "merge",
) {
  const db = getDatabase() as NodePgDatabase<typeof schema>;

  const pr = await db.query.pullRequests.findFirst({
    where: eq(schema.pullRequests.id, pullRequestId),
  });

  if (!pr) {
    throw new Error("Pull request not found");
  }

  if (pr.state !== "open") {
    throw new Error("Pull request is not open");
  }

  const gateResult = await evaluateGates(pr.id);
  if (!gateResult.canMerge) {
    const failed = gateResult.results
      .filter((result) => !result.passed)
      .map((result) => result.message)
      .join("; ");
    throw new Error(`Merge blocked: ${failed}`);
  }

  const repo = await db.query.repositories.findFirst({
    where: eq(schema.repositories.id, pr.repositoryId),
  });

  if (!repo) {
    throw new Error("Repository not found");
  }

  const repoPath = await resolveRepoPath(repo.diskPath);
  const commitTitle = `Merge pull request #${pr.number} from ${pr.headBranch}`;
  const mergeResult = await mergeBranch(
    repoPath,
    pr.baseBranch,
    pr.headBranch,
    commitTitle,
    mergeMethod,
  );

  if (!mergeResult.success) {
    throw new Error(mergeResult.message || "Merge failed");
  }

  const now = new Date();
  await db
    .update(schema.pullRequests)
    .set({
      state: "merged",
      isMerged: true,
      mergedAt: now,
      mergedById,
      mergeCommitSha: mergeResult.sha || null,
      mergeSha: mergeResult.sha || null,
      mergeMethod,
      updatedAt: now,
    })
    .where(eq(schema.pullRequests.id, pullRequestId));

  await closeLinkedIssuesOnMerge(pr.id, mergedById);

  return db.query.pullRequests.findFirst({
    where: eq(schema.pullRequests.id, pullRequestId),
  });
}