如何递归提取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_dictfunction 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()andstrftime(), we convert the Unix timestamp (commit.committed_date) to your desiredyy-mm-dd hh:mm:ssstring format. - Modern Iteration: Replaced
.next()withnext(...)since the former is deprecated in newer GitPython versions.
Notes
- Ensure you have GitPython installed: run
pip install gitpythonif 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 aStopIterationerror. You can add a try-except block to handle such cases if needed.
内容的提问来源于stack exchange,提问作者user3399495
相关产品推荐
相关产品推荐

