我正在编写一个 Python 脚本来获取即将由 git pull
操作应用的提交列表。优秀GitPython library是一个很好的起点,但 git 微妙的内部运作让我很不舒服。现在,这是我目前拥有的(简化和注释版本):
repo = git.Repo(path) # get the local repo
local_commit = repo.commit() # latest local commit
remote = git.remote.Remote(repo, 'origin') # remote repo
info = remote.fetch()[0] # fetch changes
remote_commit = info.commit # latest remote commit
if local_commit.hexsha == remote_commit.hexsha: # local is updated; end
return
# for every remote commit
while remote_commit.hexsha != local_commit.hexsha:
authors.append(remote_commit.author.email) # note the author
remote_commit = remote_commit.parents[0] # navigate up to the parent
本质上,它获取将在下一个 git pull
中应用的所有提交的作者。这运行良好,但存在以下问题:
- 当本地提交领先于远程时,我的代码只打印所有提交到第一个。
- 远程提交可以有多个父项,本地提交可以是第二个父项。这意味着我的代码永远不会在远程存储库中找到本地提交。
我可以处理位于本地存储库后面的远程存储库:只需同时从另一个方向(本地到远程)查看,代码会变得困惑但它可以工作。但是最后一个问题让我很痛苦:现在我需要导航一棵(可能是无限的)树来找到本地提交的匹配项。这不仅仅是理论上的:我最近的更改是一个 repo merge ,它提出了这个问题,所以我的脚本不工作。
在远程存储库中获取有序的提交列表,例如 repo.iter_commits()
为本地 Repo 所做的,将是一个很大的帮助。但是我在documentation里面没有找到怎么做。我可以只为远程存储库获取一个 Repo 对象吗?
是否有另一种方法可以让我到达那里,我正在使用锤子钉螺丝?
最佳答案
我知道这已经年龄了,但我只是为了一个项目而不得不这样做......
head = repo.head.ref
tracking = head.tracking_branch()
return tracking.commit.iter_items(repo, f'{head.path}..{tracking.path}')
(相反,要知道有多少本地提交待推送,只需反转它:head.commit.iter_items(repo, f'{tracking.path}..{head.path}')
)
关于python - GitPython:获取尚未应用的远程提交列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8290233/