/ opencodehub / src / lib / auto-merge-rules.ts
swadhinbiswas feat: OpenCodeHub v1.1.0 - Enterprise Features & Storage Adapters · 2/15/2026
719a1cb
250 lines · 7.8 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import { and, eq } from "drizzle-orm";
import { getDatabase, schema } from "@/db";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { logger } from "@/lib/logger";

function parseList(value: string | null | undefined): string[] {
  if (!value) return [];
  try {
    const parsed = JSON.parse(value);
    if (Array.isArray(parsed)) {
      return parsed.map((item) => String(item).trim()).filter(Boolean);
    }
  } catch (error) {}
  return value
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean);
}

function unique(values: string[]): string[] {
  return Array.from(new Set(values));
}

async function getCodeOwnerBlockers(
  db: NodePgDatabase<typeof schema>,
  repository: typeof schema.repositories.$inferSelect,
  repoDiskPath: string,
  prId: string,
  baseBranch: string,
  headBranch: string
): Promise<string[]> {
  const blockers: string[] = [];

  try {
    const { getChangedFiles } = await import("./git");
    const { parseCodeOwners, findOwnersForFile, expandOwnersToUsernames } = await import("./codeowners");
    const fs = await import("fs/promises");
    const path = await import("path");

    const changedFiles = await getChangedFiles(repoDiskPath, baseBranch, headBranch);
    if (changedFiles.length === 0) return blockers;

    const possiblePaths = ["CODEOWNERS", ".github/CODEOWNERS", "docs/CODEOWNERS"];
    let codeOwnersContent: string | null = null;

    for (const p of possiblePaths) {
      try {
        codeOwnersContent = await fs.readFile(path.join(repoDiskPath, p), "utf-8");
        break;
      } catch (error) {}
    }

    if (!codeOwnersContent) return blockers;

    const codeOwners = parseCodeOwners(codeOwnersContent);

    const approvals = await db.query.pullRequestReviews.findMany({
      where: and(
        eq(schema.pullRequestReviews.pullRequestId, prId),
        eq(schema.pullRequestReviews.state, "approved")
      ),
    });

    const approverUserIds = approvals.map((review) => review.reviewerId);
    const approverUsers = approverUserIds.length
      ? await db.query.users.findMany({
          where: (users, { inArray }) => inArray(users.id, approverUserIds),
        })
      : [];
    const approverUsernames = new Set(approverUsers.map((user) => user.username));

    for (const file of changedFiles) {
      const owners = findOwnersForFile(codeOwners, file);
      if (owners.length === 0) continue;

      const expandedOwners = await expandOwnersToUsernames({
        db,
        repository,
        owners,
      });

      const hasOwnerApproval = Array.from(expandedOwners).some((owner) =>
        approverUsernames.has(owner)
      );

      if (!hasOwnerApproval) {
        blockers.push(`Missing Code Owner approval for ${file} (requires: ${owners.join(", ")})`);
      }
    }
  } catch (error) {
    logger.error({ error, prId }, "Failed to check Code Owners for auto-merge rules");
  }

  return blockers;
}

export async function evaluateAutoMergeRules(prId: string): Promise<string[]> {
  const db = getDatabase() as NodePgDatabase<typeof schema>;

  const pr = await db.query.pullRequests.findFirst({
    where: eq(schema.pullRequests.id, prId),
    with: {
      checks: true,
      reviews: true,
      labels: { with: { label: true } },
    },
  });

  if (!pr) return ["Pull request not found"];

  const rules = await db.query.autoMergeRules.findMany({
    where: and(
      eq(schema.autoMergeRules.repositoryId, pr.repositoryId),
      eq(schema.autoMergeRules.isEnabled, true)
    ),
  });

  if (rules.length === 0) return [];

  const labelNames = unique((pr.labels || []).map((item) => item.label?.name).filter(Boolean) as string[]);
  const approvals = (pr.reviews || []).filter((review) => review.state === "approved");
  const approvalCount = unique(approvals.map((review) => review.reviewerId)).length;
  const failingChecks = (pr.checks || []).filter(
    (check) => check.status === "completed" && check.conclusion !== "success" && check.conclusion !== "neutral"
  );
  const pendingChecks = (pr.checks || []).filter((check) => check.status !== "completed");

  const blockers: string[] = [];

  for (const rule of rules) {
    const matchLabels = parseList(rule.matchLabels);
    const requiredLabels = parseList(rule.requiredLabels);
    const requiredChecks = parseList(rule.requiredChecks);

    if (matchLabels.length > 0 && !matchLabels.every((label) => labelNames.includes(label))) {
      continue;
    }

    const recordMismatch = async (reason: string) => {
      await db.update(schema.autoMergeRules)
        .set({
          lastMismatchReason: reason,
          updatedAt: new Date(),
        })
        .where(eq(schema.autoMergeRules.id, rule.id));
    };

    if (!rule.allowDraft && pr.isDraft) {
      const reason = `Auto-merge rule "${rule.name}" blocks drafts`;
      blockers.push(reason);
      await recordMismatch(reason);
      continue;
    }

    if (requiredLabels.length > 0) {
      const missingLabels = requiredLabels.filter((label) => !labelNames.includes(label));
      if (missingLabels.length > 0) {
        const reason = `Rule "${rule.name}" missing labels: ${missingLabels.join(", ")}`;
        blockers.push(reason);
        await recordMismatch(reason);
        continue;
      }
    }

    if (requiredChecks.length > 0) {
      const checkNames = (pr.checks || []).map((check) => check.name);
      const missingChecks = requiredChecks.filter((check) => !checkNames.includes(check));
      if (missingChecks.length > 0) {
        const reason = `Rule "${rule.name}" missing checks: ${missingChecks.join(", ")}`;
        blockers.push(reason);
        await recordMismatch(reason);
        continue;
      }

      if (failingChecks.length > 0) {
        const reason = `Rule "${rule.name}" has failing checks`;
        blockers.push(reason);
        await recordMismatch(reason);
        continue;
      }

      if (pendingChecks.length > 0) {
        const reason = `Rule "${rule.name}" has pending checks`;
        blockers.push(reason);
        await recordMismatch(reason);
        continue;
      }
    }

    if ((rule.minApprovals || 0) > approvalCount) {
      const reason = `Rule "${rule.name}" needs ${rule.minApprovals} approvals (has ${approvalCount})`;
      blockers.push(reason);
      await recordMismatch(reason);
      continue;
    }

    if ((rule.minTimeInQueueMinutes || 0) > 0) {
      if (!pr.autoMergeEnabledAt) {
        const reason = `Rule "${rule.name}" requires auto-merge delay before merge`;
        blockers.push(reason);
        await recordMismatch(reason);
        continue;
      }

      const elapsedMinutes = Math.floor(
        (Date.now() - new Date(pr.autoMergeEnabledAt).getTime()) / 60000
      );
      if (elapsedMinutes < (rule.minTimeInQueueMinutes || 0)) {
        const reason = `Rule "${rule.name}" requires ${rule.minTimeInQueueMinutes} minute delay (elapsed ${elapsedMinutes})`;
        blockers.push(reason);
        await recordMismatch(reason);
        continue;
      }
    }

    if (rule.requireCodeOwner) {
      const repo = await db.query.repositories.findFirst({
        where: eq(schema.repositories.id, pr.repositoryId),
      });
      if (repo?.diskPath) {
        const codeOwnerBlockers = await getCodeOwnerBlockers(
          db,
          repo,
          repo.diskPath,
          pr.id,
          pr.baseBranch,
          pr.headBranch
        );
        if (codeOwnerBlockers.length > 0) {
          const reasons = codeOwnerBlockers.map((message) => `Rule "${rule.name}": ${message}`);
          blockers.push(...reasons);
          await recordMismatch(reasons[0]);
          continue;
        }
      }
    }

    await db.update(schema.autoMergeRules)
      .set({
        matchCount: (rule.matchCount || 0) + 1,
        lastMatchedAt: new Date(),
        lastMismatchReason: null,
        updatedAt: new Date(),
      })
      .where(eq(schema.autoMergeRules.id, rule.id));
  }

  return blockers;
}