首页 > 解决方案 > 需要在 GitPython 中获取最新合并的提交 SHA id

问题描述

我在 git 中的默认分支是“开发”分支。

我想获得最新合并分支的提交 ID 到我的“开发”分支。git python 可以吗?

在命令行我可以做

git log | grep Merge

然后选择最新的。有没有办法用 gitpython 做到这一点?

谢谢。

标签: gitgitpython

解决方案


一旦你有了分支 HEAD commit ( headcommit = repo.head.commit),你可以:

  • 检查它的父母数量:len(headcommit.parents)
  • 如果是一个,则采用其唯一的父级:headcommit.parents[0]

重复直到你找到一个有多个父级的提交:这将是你的合并提交。
那会效仿git log --merges -n 1

OP建议:

headcommit = repo.head.commit 
while True: 
  headcommit = headcommit.parents[0] 
  if len(headcommit.parents) is not 1: break 
print (headcommit

推荐阅读