You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为基于私有GitHub仓库的网站实现“最后更新”指示器?

仓库文件最后更新时间指示器实现方案

方法一:GitHub API 实现(适配GitHub仓库)

  • 构造请求接口:针对目标文件,调用GitHub的提交记录接口,取最新一条提交的时间
  • 示例JS代码:
async function getLastUpdatedTime(owner, repo, filePath) {
  const apiUrl = `https://api.github.com/repos/${owner}/${repo}/commits?path=${encodeURIComponent(filePath)}&per_page=1`;
  const response = await fetch(apiUrl);
  if (!response.ok) throw new Error('请求失败');
  const commits = await response.json();
  if (commits.length === 0) return '无更新记录';
  const date = new Date(commits[0].commit.committer.date);
  return `Last Updated ${date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}`;
}
  • 注意事项:私有仓库需在请求头中携带个人访问令牌(PAT),避免API调用次数限制;之前的404问题大概率是仓库所有者、仓库名或文件路径拼写错误,核对参数即可解决。

方法二:本地Git命令获取(适配本地仓库)

直接在仓库目录下执行以下命令,替换{file_path}为目标文件路径:

git log -1 --format="Last Updated %ad" --date="format:%B %d, %Y" -- {file_path}

命令解释:-1取最近一次提交记录,%ad提取提交日期,--date指定日期输出格式,-- {file_path}锁定目标文件。

方法三:静态站点生成器集成(适配Jekyll、Hexo等)

  • Jekyll场景:启用jekyll-last-modified-at插件后,可在模板中直接调用内置变量:
Last Updated {{ page.last_modified_at | date: "%B %d, %Y" }}

内容的提问来源于stack exchange,提问作者vlone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:52:02