Python git 包获取标签并提交

Python git package get tag and commit

我想在我的 Python 代码中打印一个 git commit 和标签。 我如何使用 git 包来做到这一点?

当我去我的 Bitbucket 时,我看到

tag: 73-2-g46b9856

commit checksum: 46b9856

如何从 git 包裹中检索此信息?

我做了以下事情:

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha

所以我假设您已经在 sha 变量中有了您想要的校验和。

此时,post 介绍了如何获取标签以及如何在 link 中查找与该 sha 关联的特定标签:

# Example code for clarity

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha
tagmap = {}
for t in repo.tags:
  tagmap.setdefault(repo.commit(t), []).append(t)
tags = tagmap[repo.commit(sha)] # Warning: Your latest commit might not have a tag associated with it so this will throw an error right now.
print(tags)

这是解决我的问题的方法:

repo = git.Repo(search_parent_directories = True)
sha = repo.head.object.hexsha

commit_chksum = repo.git.rev_parse(sha, short = 7)
tag = subprocess.check_output(["git", "describe", "--always"]).strip().decode()