56 lines
1.6 KiB
JavaScript
56 lines
1.6 KiB
JavaScript
import { spawnSync } from "node:child_process";
|
|
import { mkdtempSync, rmSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
|
|
/**
|
|
* Bare-clone any public git repo (GitHub, GitLab, Rithub, or any other host
|
|
* that speaks the plain git protocol over http(s)/ssh) into a temp dir.
|
|
*
|
|
* Uses --filter=blob:none where the server supports it (git protocol v2) so
|
|
* file *contents* are not downloaded, only commit/tree metadata - this keeps
|
|
* the clone fast even for large repos. Hosts that don't support the filter
|
|
* just ignore it and git falls back to a normal clone; nothing breaks.
|
|
*
|
|
* @param {string} repoUrl
|
|
* @returns {string} path to the temporary bare repo
|
|
*/
|
|
export function cloneBare(repoUrl) {
|
|
const dir = mkdtempSync(join(tmpdir(), "git-year-wrapped-"));
|
|
|
|
const result = spawnSync(
|
|
"git",
|
|
["clone", "--bare", "--filter=blob:none", "--no-tags", "--quiet", repoUrl, dir],
|
|
{ stdio: ["ignore", "pipe", "pipe"], encoding: "utf8" }
|
|
);
|
|
|
|
if (result.error) {
|
|
cleanup(dir);
|
|
if (result.error.code === "ENOENT") {
|
|
throw new Error("git-year-wrapped needs the git CLI installed and on your PATH.");
|
|
}
|
|
throw result.error;
|
|
}
|
|
|
|
if (result.status !== 0) {
|
|
cleanup(dir);
|
|
const stderr = (result.stderr || "").trim();
|
|
throw new Error(
|
|
`Could not clone "${repoUrl}". Is the repo public and the URL correct?${stderr ? `\n${stderr}` : ""}`
|
|
);
|
|
}
|
|
|
|
return dir;
|
|
}
|
|
|
|
/**
|
|
* @param {string} dir
|
|
*/
|
|
export function cleanup(dir) {
|
|
try {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
} catch {
|
|
// best effort; a leftover temp dir is not worth failing the run over
|
|
}
|
|
}
|