如何在Python中将git log输出拆分为单个提交的列表?
提取Git Log到Python列表的解决方案
不用re.split,改用正则匹配完整提交块就能保留所有信息,以下是具体实现:
实现思路
通过正则表达式匹配每个完整的提交单元,直接捕获哈希、关联分支、作者、日期、提交信息等所有字段,再将每个提交整理为字典存入列表。
代码示例
import re git_log = """commit 19e0f017ac832238f5a800dd3ea7a5966b3c1343 (HEAD -> master, origin/master, origin/HEAD) Author: Slim Shady Date: Sun Sep 18 19:53:42 2022 -0700 ci: remove debugging line github action script commit body commit ef82c672d21d70c43f0454b0b4d6fa22ef4ad0a9 (fix_release_action) Author: Slim Shady Date: Sun Sep 18 19:41:20 2022 -0700 feat: read and write IDs commit 8ee8fcbebcab76a2fbf0ee096a0d216e51fe2874 Author: Slim Shady Date: Sun Sep 18 17:41:03 2022 -0700 feat: new hook to allow custom tags """ # 定义匹配提交的正则模式 commit_pattern = re.compile( r'commit (\w{40})(?: \((.*?)\))?\nAuthor: (.*?)\nDate: (.*?)\n\n(.*?)(?=\ncommit |\Z)', re.DOTALL ) commits = [] # 遍历所有匹配的提交 for match in commit_pattern.finditer(git_log): commit_hash, branches, author, date, message = match.groups() # 处理分支字段:有分支则拆分列表,无则设为None branches = branches.split(', ') if branches else None # 清理提交信息的首尾空白,保留内部换行格式 message = message.strip() # 将提交信息存入字典,再加入列表 commits.append({ 'hash': commit_hash, 'branches': branches, 'author': author, 'date': date, 'message': message }) # 验证结果(可选) for idx, commit in enumerate(commits, 1): print(f"=== 提交 {idx} ===") print(f"哈希: {commit['hash']}") print(f"关联分支: {commit['branches']}") print(f"作者: {commit['author']}") print(f"日期: {commit['date']}") print(f"提交内容:\n{commit['message']}\n")
正则说明
commit (\w{40}):捕获40位的提交哈希(?: \((.*?)\))?:可选捕获括号内的关联分支信息,非捕获组包裹避免干扰主匹配\nAuthor: (.*?):捕获作者名称\nDate: (.*?):捕获提交日期\n\n(.*?)(?=\ncommit |\Z):捕获提交标题和正文,直到下一个commit开头或文本结束,re.DOTALL让.匹配换行符
内容的提问来源于stack exchange,提问作者Jacob Pavlock
相关产品推荐
相关产品推荐

