52 lines
2.3 KiB
JavaScript
52 lines
2.3 KiB
JavaScript
import { spawnSync } from "node:child_process";
|
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { listIssues, listReleases } from "./github.mjs";
|
|
|
|
function run(cmd, args, opts = {}) {
|
|
const res = spawnSync(cmd, args, { stdio: "pipe", encoding: "utf8", ...opts });
|
|
if (res.status !== 0) {
|
|
const detail = (res.stderr || res.stdout || "").trim().slice(0, 400);
|
|
throw new Error(`${cmd} ${args.join(" ")} failed: ${detail}`);
|
|
}
|
|
return res;
|
|
}
|
|
|
|
// cloneUrlWithToken: embed a token for private repos without ever
|
|
// printing it (git itself never sees it on argv, only inside the URL
|
|
// passed straight to the clone/push subprocess).
|
|
function cloneUrlWithToken(httpsCloneUrl, token) {
|
|
if (!token) return httpsCloneUrl;
|
|
return httpsCloneUrl.replace("https://", `https://x-access-token:${token}@`);
|
|
}
|
|
|
|
// mirrorRepoLocally: `git clone --mirror` gets every branch, tag and ref
|
|
// in one shot — the same guarantee competing backup tools make. Returns
|
|
// the local bare-repo path.
|
|
export function mirrorRepoLocally({ repo, destDir, token }) {
|
|
const target = join(destDir, `${repo.name}.git`);
|
|
const url = cloneUrlWithToken(repo.clone_url, token);
|
|
run("git", ["clone", "--mirror", "--quiet", url, target]);
|
|
return target;
|
|
}
|
|
|
|
// pushMirrorToRemote: push every ref from the local bare mirror to an
|
|
// arbitrary git remote (another host, a second Rithub, a NAS, anything
|
|
// that accepts `git push --mirror`).
|
|
export function pushMirrorToRemote({ localMirrorPath, remoteUrl }) {
|
|
run("git", ["-C", localMirrorPath, "push", "--mirror", "--quiet", remoteUrl]);
|
|
}
|
|
|
|
// saveMetadata: issues + releases as plain JSON next to the mirror.
|
|
// Two API calls per repo — cheap, and skippable with --no-meta.
|
|
export async function saveMetadata({ repo, destDir, token }) {
|
|
const [issues, releases] = await Promise.all([
|
|
listIssues(repo.owner.login, repo.name, token).catch((err) => ({ error: String(err) })),
|
|
listReleases(repo.owner.login, repo.name, token).catch((err) => ({ error: String(err) })),
|
|
]);
|
|
const metaDir = join(destDir, `${repo.name}.git`, "github-meta");
|
|
mkdirSync(metaDir, { recursive: true });
|
|
writeFileSync(join(metaDir, "issues.json"), JSON.stringify(issues, null, 2));
|
|
writeFileSync(join(metaDir, "releases.json"), JSON.stringify(releases, null, 2));
|
|
}
|