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

如何使用GitPython遍历仓库树时获取文件blob的提交时间

纯GitPython实现方案

你可以通过倒序遍历提交记录批量查询所有文件的最后提交时间,完全不需要调用系统git命令,不会受运行环境的其他仓库影响,实现代码如下:

import git

repo = git.Repo('some_repo')
# 收集当前HEAD下所有非目录文件路径
target_files = set()
for blob in repo.tree().traverse():
    if blob.type == "blob":
        target_files.add(blob.path)

file_last_commit = {}
# 从最新提交开始倒序遍历
for commit in repo.iter_commits():
    # 遍历当前提交的所有文件
    for item in commit.tree.traverse():
        if item.type == "blob" and item.path in target_files and item.path not in file_last_commit:
            # committed_datetime.isoformat() 输出和 `%cI` 格式完全一致的ISO标准提交时间
            file_last_commit[item.path] = commit.committed_datetime.isoformat()
    # 所有文件都查询完成后提前终止遍历,提升效率
    if len(file_last_commit) == len(target_files):
        break

# 输出结果
for path, commit_time in file_last_commit.items():
    print(f"{path}: {commit_time}")

方案说明

  • 直接通过GitPython读取Git对象库实现,全程不调用系统git命令,不会出现环境仓库冲突问题
  • 批量遍历提交的效率远高于逐文件查询,适合大体积仓库使用
  • 用blob.type == "blob"判断文件类型,不需要依赖工作区实际文件存在,就算仅拉取了Git对象库也可正常运行
  • 如果需要匹配%aI(作者时间)格式,将committed_datetime替换为authored_datetime即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:24:00