// The GitHub gateway: what Pilot asks of GitHub. It uses the Owner's `gh` authentication. // It grows with the steps that push branches and open pull requests. Daemon tests replace it with an in-memory fake. import { execFile } from "node:child_process"; import { promisify } from "node:util"; export type PullRequestState = "draft" | "ready" | "merged" | "closed"; export type PullRequest = { repo: string; number: number; branch: string; title: string; state: PullRequestState }; export interface GitHub { /** The URL to clone a repository ("owner/name") from, or null when GitHub has none by that name that the Owner can see. */ cloneUrl(repo: string): Promise; /** The pull requests of a repository ("owner/name"), open or not. */ pullRequests(repo: string): Promise; } /** GitHub through the `gh` command line tool. Its errors say what failed in plain words. */ export function ghGitHub(): GitHub { const exec = promisify(execFile); const run = (args: string[]) => exec("gh", args).catch((error: NodeJS.ErrnoException & { stderr?: string }) => { if (error.code === "ENOENT") throw new Error("Pilot could not run gh. Install the GitHub CLI, then try again."); throw Object.assign(new Error("GitHub did not answer, or gh is not signed in. gh said: " + firstStderrLine(error.stderr)), { stderr: error.stderr ?? "", }); }); return { async cloneUrl(repo) { try { const { stdout } = await run(["repo", "view", repo, "--json", "url,sshUrl"]); const urls = JSON.parse(stdout) as { url: string; sshUrl: string }; // The Owner picked a protocol for git when signing in to gh. Clone the same way, so git finds the same credentials. const protocol = (await run(["config", "get", "git_protocol", "--host", "github.com"])).stdout.trim(); return protocol === "ssh" ? urls.sshUrl : urls.url + ".git"; } catch (error) { if (/Could not resolve to a Repository/.test((error as { stderr?: string }).stderr ?? "")) return null; throw error; } }, async pullRequests(repo) { const { stdout } = await run(["pr", "list", "--repo", repo, "--state", "all", "--json", "number,headRefName,title,state,isDraft"]); const pulls = JSON.parse(stdout) as { number: number; headRefName: string; title: string; state: "OPEN" | "MERGED" | "CLOSED"; isDraft: boolean }[]; return pulls.map((pull) => ({ repo, number: pull.number, branch: pull.headRefName, title: pull.title, state: pull.state === "MERGED" ? "merged" : pull.state === "CLOSED" ? "closed" : pull.isDraft ? "draft" : "ready", })); }, }; } /** The first line gh wrote on stderr, or "nothing". */ const firstStderrLine = (text: string | undefined) => (text ?? "").trim().split("\n")[0] || "nothing";