90 lines · 3.5 KB
import { all, batch, first, run, stmt } from "./db";
import { loadIssue, setIssueState } from "./issues";
import type { IssueRow } from "./issues";
import { emitWebhook, publicUrl } from "./events/emit";
import { assertBelowCap } from "./limits";
import type { RepoRow } from "~/lib/types";

const CLOSING_KEYWORDS = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)\b/gi;
const MAX_KEYWORD_LINKS = 10;
export const MAX_LINKED_ISSUES = 20;

export type LinkedIssue = { number: number; title: string; state: "open" | "closed"; source: "manual" | "keyword" };

/** Re-derives keyword links ("fixes #12") from a pull request body; manual links are left untouched. */
export async function syncKeywordLinks(pullIssueId: string, repoId: string, body: string): Promise<void> {
  const numbers = [...new Set([...body.matchAll(CLOSING_KEYWORDS)].map((match) => Number(match[1])))].slice(
    0,
    MAX_KEYWORD_LINKS,
  );
  const issues = (await Promise.all(numbers.map((number) => loadIssue(repoId, number)))).filter(
    (issue): issue is IssueRow => issue !== null && issue.is_pull === 0,
  );
  const now = Date.now();
  await batch([
    stmt("DELETE FROM pull_issue_links WHERE pull_issue_id = ? AND source = 'keyword'", pullIssueId),
    ...issues.map((issue) =>
      stmt(
        `INSERT OR IGNORE INTO pull_issue_links (pull_issue_id, issue_id, source, created_by, created_at)
         VALUES (?, ?, 'keyword', NULL, ?)`,
        pullIssueId,
        issue.id,
        now,
      ),
    ),
  ]);
}

export async function linkIssue(pullIssueId: string, issueId: string, actorId: string): Promise<void> {
  const count = await first<{ count: number }>(
    "SELECT COUNT(*) AS count FROM pull_issue_links WHERE pull_issue_id = ?",