32 lines · 1.1 KB
import { branchSha, listRefs } from "./git/refs";
import { withStore } from "./git/store";
import type { RepoRow } from "~/lib/types";

const TEMPLATE_PATHS = [
  ".github/pull_request_template.md",
  ".github/PULL_REQUEST_TEMPLATE.md",
  "pull_request_template.md",
  "PULL_REQUEST_TEMPLATE.md",
  "docs/pull_request_template.md",
  "docs/PULL_REQUEST_TEMPLATE.md",
];
const MAX_TEMPLATE_BYTES = 16 * 1024;

/** Reads the pull request template from the base branch, if the repository has one. */
export async function readPullTemplate(repo: RepoRow, base: string): Promise<string | null> {
  const sha = branchSha(await listRefs(repo), base);
  if (!sha) return null;
  return withStore(repo.artifacts_name, async (store) => {
    const commit = await store.commit(sha);
    if (!commit) return null;
    for (const path of TEMPLATE_PATHS) {
      const entry = await store.entryAtPath(commit.treeSha, path);
      if (!entry || entry.type !== "blob") continue;
      const bytes = await store.blob(entry.sha);
      if (!bytes || bytes.byteLength > MAX_TEMPLATE_BYTES) return null;
      return new TextDecoder().decode(bytes);
    }
    return null;
  });
}