53 lines
1.8 KiB
JavaScript
53 lines
1.8 KiB
JavaScript
// Minimal GitHub REST API client: just the list/paginate calls this CLI
|
|
// needs. No dependencies, no auth required for public repos.
|
|
|
|
const API = "https://api.github.com";
|
|
|
|
function authHeaders(token) {
|
|
const headers = { "User-Agent": "github-backup-cli" };
|
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
return headers;
|
|
}
|
|
|
|
async function getJson(url, token) {
|
|
const res = await fetch(url, { headers: authHeaders(token) });
|
|
if (!res.ok) {
|
|
const body = await res.text().catch(() => "");
|
|
throw new Error(`GitHub API ${res.status} on ${url}: ${body.slice(0, 200)}`);
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
async function paginate(urlBase, token) {
|
|
const out = [];
|
|
let page = 1;
|
|
// 100 is GitHub's max per_page; stop once a page comes back short.
|
|
for (;;) {
|
|
const sep = urlBase.includes("?") ? "&" : "?";
|
|
const page_data = await getJson(`${urlBase}${sep}per_page=100&page=${page}`, token);
|
|
if (!Array.isArray(page_data) || page_data.length === 0) break;
|
|
out.push(...page_data);
|
|
if (page_data.length < 100) break;
|
|
page += 1;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// listRepos: public repos of `login` if no token, else the token owner's
|
|
// own repos (owner affiliation only — no org repos, matching the plain
|
|
// "back up MY stuff" promise; private repos included when token is set).
|
|
export async function listRepos({ login, token }) {
|
|
if (token) {
|
|
return paginate(`${API}/user/repos?affiliation=owner&sort=full_name`, token);
|
|
}
|
|
return paginate(`${API}/users/${login}/repos?sort=full_name`, token);
|
|
}
|
|
|
|
export async function listIssues(owner, repo, token) {
|
|
return paginate(`${API}/repos/${owner}/${repo}/issues?state=all`, token);
|
|
}
|
|
|
|
export async function listReleases(owner, repo, token) {
|
|
return paginate(`${API}/repos/${owner}/${repo}/releases`, token);
|
|
}
|