import { all, run } from "./db"; import { randomId } from "./crypto"; import { onCommitStatus } from "./merge-automation"; import type { StatusState } from "~/lib/types"; export type CommitStatusRow = { id: string; repo_id: string; sha: string; context: string; state: StatusState; description: string | null; target_url: string | null; created_at: number; updated_at: number; }; export async function setCommitStatus(input: { repoId: string; sha: string; context: string; state: StatusState; description: string | null; targetUrl: string | null; }): Promise { const now = Date.now(); await run( `INSERT INTO commit_statuses (id, repo_id, sha, context, state, description, target_url, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (repo_id, sha, context) DO UPDATE SET state = excluded.state, description = excluded.description, target_url = excluded.target_url, updated_at = excluded.updated_at`, randomId(), input.repoId, input.sha, input.context, input.state, input.description, input.targetUrl, now, now, ); if (input.state !== "pending") { await onCommitStatus(input.repoId, input.sha).catch((error) => console.error("Merge automation wake failed", error), ); } } export async function listCommitStatuses(repoId: string, sha: string): Promise { return all( "SELECT * FROM commit_statuses WHERE repo_id = ? AND sha = ? ORDER BY context", repoId, sha, ); } export function combinedState(statuses: Array<{ state: StatusState }>): StatusState | null { if (statuses.length === 0) return null; if (statuses.some((status) => status.state === "failure" || status.state === "error")) return "failure"; if (statuses.some((status) => status.state === "pending")) return "pending"; return "success"; }