如何使用 python 检查 git repo 中是否存在未暂存/未提交的更改或未推送的提交

Luk*_*ron 1 python python-3.x gitpython

如何使用 python 检查 git repo 中是否存在未暂存/未提交的更改或未推送的提交?

我只知道命令行

git status会告诉

  • 未分阶段的改变
  • 未承诺阶段
  • 以及当前分支是否在远程提交之后提交

如果我为函数提供一个根路径,例如(“C:/ ProgramFiles”),如果代码可以给出一个列表,其中每个元素都是

(path of this repos found under the root path, Unstaged/uncommited changes, Untracked files: , Latest commit is pushed)

Luk*_*rry 5

您可以使用GitPython包来提供帮助。

pip install GitPython

那么这个脚本可以为您提供一个起点:

from git import Repo

repo = Repo('.')

print(f"Unstaged/uncommited changes: {repo.is_dirty()}")
print(f"Untracked files: {len(repo.untracked_files)}")

remote = repo.remote('origin')
remote.fetch()
latest_remote_commit = remote.refs[repo.active_branch.name].commit
latest_local_commit = repo.head.commit

print(f"Latest commit is pushed: {latest_local_commit == latest_remote_commit}")

Run Code Online (Sandbox Code Playgroud)