GitPython 如何检查 git pull 是否更改了本地文件

6
使用GitPython,我想在本地文件进行了拉取操作后仅在更改后调用某个函数。例如,如果我在另一台计算机上进行推送,然后在第一台计算机上进行拉取操作,则可以按预期工作,但不提供任何输出。理想的输出是更改的文件列表。或者,仅告诉我如果拉取出现错误,因为分支已经是最新的,或者一个布尔值表示是否发生了更改。我相信我可以爬取repo.git.status(),但这似乎很粗糙。在查找时,看起来我也可以比较分支以获取更改,但这似乎需要大量额外的代码和远程调用。是否有正确的方法只使用pull调用?
while True:
    repo = git.Repo()
    o = repo.remotes.origin
    o.pull()
    changed = NOT_SURE
    if changed:
        do_something()
    print(repo.git.status())
    time.sleep(POLLING_RATE)

更新:这确实可以用于检查是否进行了更改,但没有额外的远程调用,无法提供文件更改信息。
while True:
    print(str(time.ctime())+": Checking for updates")
    repo = git.Repo()
    current_hash = repo.head.object.hexsha
    o = repo.remotes.origin
    o.pull()
    pull_hash = repo.head.object.hexsha
    if current_hash != pull_hash:
        print("files have changed")
    else:
        print("no changes")

    time.sleep(config.GIT_POLL_RATE)

要确定最新提交(拉取后)和早期提交之间的差异,您可以使用 git diff。但是,我无法告诉您如何在 GitPython 中执行此操作。 - mkrieger1
比较哈希值可以告诉你通过拉取是否收到了新的提交。然而,两个提交之间的文件可能没有任何差异。 - mkrieger1
2个回答

5

我很感激您的回复,尽管已经晚了两年,但我仍希望这能对您有所帮助。

我刚刚编写了pullcheck,这是一个简单的脚本,用于从仓库中拉取,检查更改并在发现更改时重新启动目标。我发现这种方法能够识别出从拉取中的更改。

def git_pull_change(path):
    repo = git.Repo(path)
    current = repo.head.commit

    repo.remotes.origin.pull()

    if current == repo.head.commit:
        print("Repo not changed. Sleep mode activated.")
        return False
    else:
        print("Repo changed! Activated.")
        return True

0

如果您只想检查远程端有哪些更改,您也可以使用git-fetch

如果您想要打印更改,您可能需要尝试使用git-diff,例如:


POLLING_RATE = 10
REM_BRANCH = 'master'

def pretty_diff(diff):
    for cht in diff.change_type:
        changes = list(diff.iter_change_type(cht))
        if len(changes) == 0:
            continue
        print("Changes type:", cht)
        for d in changes:
            print(d.b_path)


while True:
    repo = git.Repo('.')
    current_hash = repo.head.object.hexsha
    o = repo.remotes.origin
    o.fetch()
    changed = o.refs[REM_BRANCH].object.hexsha != current_hash
    if changed:
        # do_something()
        diff = repo.head.commit.diff(o.refs[REM_BRANCH].object.hexsha)
        pretty_diff(diff)
    time.sleep(POLLING_RATE)

git-diff 支持不同的更改类型:

print(diff.change_type)
#('A', 'C', 'D', 'R', 'M', 'T')

对于不同的更改类型,您可以执行不同的操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接