如何用JavaScript获取GitHub所有仓库的总提交数?
实现GitHub全仓库总提交数统计(JavaScript方案)
可以实现,核心思路是通过遍历用户所有仓库,逐个获取每个仓库的提交数后累加,以下是具体实现方案:
核心逻辑
GitHub API没有直接返回用户所有仓库总提交数的接口,因此需要分两步:
- 获取用户名下所有仓库的列表
- 对每个仓库单独请求提交数,最后汇总总和
示例代码
// 替换为你的GitHub用户名 const githubUsername = "your-github-username"; // 可选:添加个人访问令牌提升API请求限额 const githubToken = "your-personal-access-token"; let totalCommitCount = 0; // 封装带授权的fetch请求 async function authFetch(url) { const headers = {}; if (githubToken) { headers["Authorization"] = `token ${githubToken}`; } return fetch(url, { headers }); } // 获取用户所有仓库(处理分页) async function getAllUserRepos() { const repos = []; let currentPage = 1; while (true) { const res = await authFetch( `https://api.github.com/users/${githubUsername}/repos?page=${currentPage}&per_page=100&type=owner` ); const pageRepos = await res.json(); if (pageRepos.length === 0) break; repos.push(...pageRepos); currentPage++; } return repos; } // 获取单个仓库的个人提交数 async function getRepoUserCommits(repoFullName) { // 搜索该仓库下当前用户的所有提交 const res = await authFetch( `https://api.github.com/search/commits?q=repo:${repoFullName}+author:${githubUsername}` ); const data = await res.json(); return data.total_count || 0; } // 计算并展示总提交数 async function calculateTotalCommits() { try { const repos = await getAllUserRepos(); // 并行请求提升效率,控制并发数避免触发限额 const commitCounts = await Promise.all( repos.map(repo => getRepoUserCommits(repo.full_name)) ); totalCommitCount = commitCounts.reduce((sum, count) => sum + count, 0); // 将结果渲染到页面元素 document.getElementById("total-commits-display").textContent = `总提交数:${totalCommitCount}`; } catch (err) { console.error("统计失败:", err); document.getElementById("total-commits-display").textContent = "统计失败,请稍后重试"; } } // 页面加载后执行 window.addEventListener("load", calculateTotalCommits);
关键注意事项
- API限额问题:未授权请求每小时仅60次,仓库数量多的话必然超限。建议创建GitHub个人访问令牌(PAT),授权后限额提升至每小时5000次。
- 过滤仓库类型:代码中通过
type=owner参数只统计自己创建的仓库,若需包含fork仓库可移除该参数。 - 提交范围控制:示例统计的是当前用户在各仓库的提交数,若需统计仓库所有提交(含其他贡献者),可改用
/repos/{repoFullName}/commits接口,通过响应头的Link字段解析总页数,再计算总提交数(或直接取接口返回的total_count)。
内容的提问来源于stack exchange,提问作者FoxDev
相关产品推荐
相关产品推荐

