import { existsSync } from "node:fs";
import { spawn } from "node:child_process";
import { ServiceMethodFactory } from "@ethicdevs/react-monolith";
import type { Repository } from "@prisma/client";
import { Env } from "../../env";
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(""));
});
});
const branches = gitBranchResult
.split("\n")
.map((branch) => branch.trim().replace(/^\* /i, ""))
.filter((x) => x != null && x.trim() !== "");
console.log("branches:", parentOrg.slug, repo.slug, branches);
return branches;
} catch (_) {
return [];
}
};
};
export default makeGetRepositoryBranches;