.ts
TypeScript
(application/typescript)
// std
import { existsSync } from "node:fs";
import { spawn } from "node:child_process";
// 1st-party
import { ServiceMethodFactory } from "@ethicdevs/react-monolith";
// generated via script[generate:prisma]
import type { Repository } from "@prisma/client";
// app
import { Env } from "../../env";
// service
import { RepositoryServiceDeps } from "./types";

const makeGetRepositoryBranches: ServiceMethodFactory<
  RepositoryServiceDeps,
  [Repository],
  Promise<string[]>
> = ({ request }) => {
  return async (repo) => {
    const parentOrg = await request.prisma.organization.findUnique({
      where: {
        id: repo.organizationId,
      },
    });

    if (parentOrg == null) {
      throw new Error(
        `Could not find the parent organization for project "${repo.slug}".`
      );
    }

    try {
      const repoPath = `${Env.GIT_REPOSITORIES_ROOT}/${parentOrg.slug}/${repo.slug}.git`;
      if (existsSync(repoPath) === false) {
        throw new Error(
          `Could not find a valid git repository at: ${repoPath}`
        );
      }

      const gitBranchProcess = spawn("git", ["branch", "-a"], {
        cwd: repoPath,
      });

      const gitBranchResult = await new Promise<string>((resolve, reject) => {
        let buffer = [] as string[];
        gitBranchProcess.stdout.on("data", (data) => buffer.push(data));
        gitBranchProcess.stderr.on("data", (data) => {
          reject(new Error(Buffer.from(data).toString("utf-8")));
        });
        gitBranchProcess.stdout.on("close", () => {
          resolve(buffer.join(""));
        });
      });

      return gitBranchResult
        .split("\n")
        .map((branch) => branch.trim().replace(/^\* /i, ""))
        .filter((x) => x != null && x.trim() !== "");
    } catch (_) {
      return [];
    }
  };
};

export default makeGetRepositoryBranches;