136 lines · 5.2 KB
import { all, first, run } from "../db";
import { randomId } from "../crypto";
import { HttpError } from "../errors";
import { loadRepoById } from "../repos";
import { ZERO_SHA } from "../git/store";
import { labelUrl, SITE_LIMITS } from "./config";
import { createSiteDeployment, loadSiteForRepo, removePreview } from "./deploy";
import { previewLabel } from "./naming";
import type { SiteDeployRequest } from "./deploy";
import type { SiteRow } from "./config";

async function tryDeploy(input: SiteDeployRequest): Promise<boolean> {
  try {
    await createSiteDeployment(input);
    return true;
  } catch (error) {
    if (error instanceof HttpError) {
      console.warn("Site deploy skipped", input.site.id, error.message);
      return false;
    }
    throw error;
  }
}

/** Comments the preview link once per pull request; the pusher is the author so no bot account is needed. */
async function commentPreview(site: SiteRow, branch: string, label: string, authorId: string | null): Promise<void> {
  const url = labelUrl(label);
  if (!url || !authorId || !site.repo_id) return;
  const pulls = await all<{ number: number; issue_id: string }>(
    `SELECT i.number, i.id AS issue_id FROM pull_requests p JOIN issues i ON i.id = p.issue_id
     WHERE p.repo_id = ? AND p.head_repo_id = ? AND p.head_ref = ? AND i.state = 'open' LIMIT ?`,
    site.repo_id,
    site.repo_id,
    branch,
    SITE_LIMITS.previewsPerPush,
  );
  for (const pull of pulls) {
    const now = Date.now();
    const inserted = await run(
      "INSERT OR IGNORE INTO site_preview_comments (site_id, pr_number, created_at) VALUES (?, ?, ?)",