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

如何递归提取Git仓库所有文件及子文件夹的时间戳并生成字典

Recursively Traverse Git Repository to Get File Commit Dates

To create a dictionary mapping every file in your Git repository (including those in subfolders) to their latest commit date in the yy-mm-dd hh:mm:ss format, you'll need to recursively traverse tree objects (which represent folders) in addition to processing blob objects (files). Here's how to modify your code:

Step-by-Step Modified Code

import git
from datetime import datetime

def build_file_date_dict(repo, tree, parent_path="", file_dict=None):
    if file_dict is None:
        file_dict = {}
    
    for entry in tree:
        # Build the full path of the current entry
        full_path = f"{parent_path}/{entry.name}" if parent_path else entry.name
        
        if isinstance(entry, git.objects.tree.Tree):
            # Recursively process subfolders
            build_file_date_dict(repo, entry, full_path, file_dict)
        elif isinstance(entry, git.objects.blob.Blob):
            # Get the latest commit for this file
            commit = next(repo.iter_commits(paths=full_path, max_count=1))
            # Convert timestamp to the desired string format
            formatted_date = datetime.fromtimestamp(commit.committed_date).strftime('%y-%m-%d %H:%M:%S')
            # Add to the dictionary
            file_dict[full_path] = formatted_date
    
    return file_dict

# Initialize the repo and build the dictionary
repo = git.Repo("./repo")
root_tree = repo.tree()
file_date_dict = build_file_date_dict(repo, root_tree)

# Example: Print the result
for filename, date in file_date_dict.items():
    print(f"{filename}: {date}")

Key Changes Explained

  • Recursive Function: The build_file_date_dict function handles both files (blobs) and folders (trees). When it encounters a tree, it calls itself with the subfolder's tree and updated parent path.
  • Full Path Construction: We track the parent path to generate the complete relative path for each file, ensuring subfolder files are correctly identified.
  • Timestamp Formatting: Using datetime.fromtimestamp() and strftime(), we convert the Unix timestamp (commit.committed_date) to your desired yy-mm-dd hh:mm:ss string format.
  • Modern Iteration: Replaced .next() with next(...) since the former is deprecated in newer GitPython versions.

Notes

  • Ensure you have GitPython installed: run pip install gitpython if you haven't already.
  • This code assumes your repository is located at ./repo; adjust the path to match your actual repo location.
  • If a file has no commits (uncommon in a valid repo), next() will throw a StopIteration error. You can add a try-except block to handle such cases if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:46:16