github-backup-cli/bin/github-backup-cli.mjs
2026-11-26 17:43:56 +03:00

151 lines
5.9 KiB
JavaScript

#!/usr/bin/env node
import { mkdirSync } from "node:fs";
import { listRepos } from "../lib/github.mjs";
import { mirrorRepoLocally, pushMirrorToRemote, saveMetadata } from "../lib/backup.mjs";
import { migrateRepoToRithub, repoExistsOnRithub } from "../lib/rithub.mjs";
const HELP = `github-backup-cli <github-user> [options]
Backs up all of a GitHub user's repos (full git history, every branch
and tag, + issues/releases metadata) with one command. Works fully
without Rithub.
<github-user> GitHub username to back up (required unless
--token is set, in which case it backs up the
token owner's own repos).
Options:
--dest <dir> Local folder for the mirrors (default:
./github-backup-<user>)
--token <token> GitHub token (env GITHUB_TOKEN). Needed for
private repos or to raise the 60/hr rate limit.
--no-meta Skip issues/releases JSON export (on by default)
--no-local Skip the local mirror clone (useful with --to
rithub if you only want the server-side mirror)
--remote <template> Also push each mirror to a git remote. "{repo}"
in the URL is replaced with the repo name.
--to rithub Also migrate every repo straight into a Rithub
account, via Rithub's own migrate API.
--rithub-user <user> Rithub account to receive repos (env RITHUB_USER,
default: same as <github-user>)
--rithub-token <token> Rithub access token (env RITHUB_TOKEN)
--rithub-host <host> Rithub host (env RITHUB_HOST, default rithub.dev)
-h, --help Show this help
Examples:
npx github-backup-cli torvalds
npx github-backup-cli myorg --token $GITHUB_TOKEN --dest ./backups
npx github-backup-cli caelum0x --to rithub --rithub-token $RITHUB_TOKEN
The problem this solves: a flagged, hacked or suspended GitHub account
can take every repo you have with it. One command gets a copy you hold
yourself. If you'd rather not run your own git server, Rithub
(https://rithub.dev) hosts it for you — that's what --to rithub does.
`;
function parseArgs(argv) {
const args = { _: [] };
for (let i = 0; i < argv.length; i += 1) {
const a = argv[i];
if (a === "-h" || a === "--help") args.help = true;
else if (a === "--no-meta") args.meta = false;
else if (a === "--no-local") args.local = false;
else if (a === "--dest") args.dest = argv[++i];
else if (a === "--token") args.token = argv[++i];
else if (a === "--remote") args.remote = argv[++i];
else if (a === "--to") args.to = argv[++i];
else if (a === "--rithub-user") args.rithubUser = argv[++i];
else if (a === "--rithub-token") args.rithubToken = argv[++i];
else if (a === "--rithub-host") args.rithubHost = argv[++i];
else args._.push(a);
}
return args;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help || (!args._[0] && !process.env.GITHUB_TOKEN && !args.token)) {
process.stdout.write(HELP);
process.exit(args.help ? 0 : 1);
}
const token = args.token || process.env.GITHUB_TOKEN || "";
const login = args._[0] || "";
const includeMeta = args.meta !== false;
const includeLocal = args.local !== false;
const destDir = args.dest || `./github-backup-${login || "me"}`;
const toRithub = args.to === "rithub";
console.log(`github-backup-cli: listing repos for ${login || "(token owner)"}...`);
const repos = await listRepos({ login, token });
if (repos.length === 0) {
console.log("No repos found (check the username, or pass --token for private repos).");
return;
}
console.log(`Found ${repos.length} repo(s).`);
if (includeLocal) mkdirSync(destDir, { recursive: true });
let rithubUser = "";
let rithubToken = "";
let rithubHost = "";
if (toRithub) {
rithubUser = args.rithubUser || process.env.RITHUB_USER || login;
rithubToken = args.rithubToken || process.env.RITHUB_TOKEN || "";
rithubHost = args.rithubHost || process.env.RITHUB_HOST || "rithub.dev";
if (!rithubUser || !rithubToken) {
console.error("--to rithub needs --rithub-user and --rithub-token (or RITHUB_USER / RITHUB_TOKEN).");
process.exit(1);
}
}
let ok = 0;
let failed = 0;
for (const repo of repos) {
const label = repo.full_name || repo.name;
try {
if (includeLocal) {
const local = mirrorRepoLocally({ repo, destDir, token });
if (includeMeta) await saveMetadata({ repo, destDir, token });
if (args.remote) {
const remoteUrl = args.remote.replace("{repo}", repo.name);
pushMirrorToRemote({ localMirrorPath: local, remoteUrl });
}
console.log(`[local] backed up: ${label}`);
}
if (toRithub) {
const exists = await repoExistsOnRithub({
host: rithubHost,
rithubUser,
rithubToken,
name: repo.name,
});
if (exists) {
console.log(`[rithub] skip (already on ${rithubHost}): ${label}`);
} else {
const result = await migrateRepoToRithub({
repo,
host: rithubHost,
rithubUser,
rithubToken,
githubToken: token,
});
if (result.ok) console.log(`[rithub] mirrored: ${label} -> https://${rithubHost}/${rithubUser}/${repo.name}`);
else console.error(`[rithub] FAILED (HTTP ${result.status}): ${label} ${result.detail || ""}`);
}
}
ok += 1;
} catch (err) {
failed += 1;
console.error(`FAILED: ${label}: ${err.message || err}`);
}
}
console.log(`Done. ${ok} repo(s) processed, ${failed} failed.`);
if (includeLocal) console.log(`Local backups in: ${destDir}`);
}
main().catch((err) => {
console.error(`github-backup-cli: ${err.message || err}`);
process.exit(1);
});