首页 > 解决方案 > 如何使用 git hook 停止“git push all”?

问题描述

正如标题所说,我该如何停止这个“git push all”命令。我的配置文件被更改为包含两个 url(如下所示),因此将在“git push all”时将 git push 到两个服务器。

部分配置文件:

[remote "all"]
    url = C:\\Users\\user1\\Desktop\\Machine1\\Server1
    url = C:\\Users\\user1\\Desktop\\Machine2\\Server2
    fetch = +refs/heads/*:refs/remotes/all/*

我创建了一个 pre-push git 挂钩,它基本上会在每个服务器中创建一个 lock.txt 文件,如果它检测到存在类似的锁定文件,一切都会撤回。收回后,我将返回一个退出代码“1”以阻止它进行 git 推送。一小部分代码如下所示。

git hook pre-push 文件的一部分:

LockFileExist = False
for serverpath in cleanurls:
    for file in os.listdir(str(serverpath)):
        if "lock.txt" in file:
            LockFileExist = True
    if LockFileExist == False:
        Create_Lock(serverpath)
    else:
        print ("Stopped pushing, starting revert process..")
        exitcode = Revert_Process(createdlockfiles)
        if exitcode == 0:
            print ("Revert process has failed. Nothing to revert.")
        else:
            print ("Revert process is successful")
        print("Stopping the whole git process..")
        exit(1)

因此,这就是显示的(下图),预推送文件运行了两次,因为 git push all 在推送到两个单独的服务器时被视为两个单独的命令。但是,我希望命令在第一个退出代码发出的那一刻结束。

结果

这甚至可能吗?我愿意接受任何建议。我能想到的另一种方法是停止整个命令行窗口,但我不确定这是否是正确的方法。如果您需要更多代码进行测试,请告诉我!预先感谢您的帮助。

标签: pythongitgithooks

解决方案


我还没有想出完整的解决方案,但我正在使用脚本来解决这个问题。这个想法是通过使用文本文件来记下 git 进程的当前状态。有了这些信息,我可以使用类似开关的 if 语句在它们之间切换。代码很长,所以这里是一个粗略的想法。

我正在使用三种状态:

1) Enabled - To allow git hook to run
2) Disabled - To stop all the other git push
3) Neutralized - To stop git hook but allow other git push to run

粗略的代码结构:

#reads from file
LockSystemToggle = 0
if "Disabled" in lockvariable:
    LockSystemToggle = 1
    f.close()
elif "Neutralized" in lockvariable:
    LockSystemToggle = 2
    f.close()
else:                                               
    f = open(lockdirectorypath, "w+")       #nothing much, just in case of empty file
    f.write("Locking System = Enabled")
    f.close()
if LockSystemToggle == 0:
    #runs initial git hook functions
    #file is "Neutralized" or "Disabled" here depending on situation
elif LockSystemToggle == 1:
    exit(1)   #skips initial git hook functions but blocks all git push
else:
    exit(0)   #skips initial git hook functions but continue git push

不必担心将下一个“git push all”的文件结构更改为“启用”,因为我将从另一个应用程序发送命令,我可以在推送之前更改它们。


推荐阅读