Skip to main content
 首页 » 编程设计

python之我可以从 python git pre-receive hook 前缀错误 : instead of remote: 返回消息吗

2025年05月04日7bjzhanghao

我在 python 中编写了一个 git pre-receive Hook ,以在用户尝试推送到禁止目录时中止进程。

执行此操作的函数采用文件路径参数并遍历它们以查找顽皮的目录,如下所示;

for filename in changed: 
    pieces = filename.split('/') 
    if(len(pieces) >3 and pieces[0] == 'application' and pieces[1] == 'modules' and pieces[3] == 'core'): 
        # User is trying to push to application/modules/[MODULE_NAME]/core directory, they must be stopped! 
        msg = 'You are pushing code that will be over-written by framework updates: ' + filename + '. THIS IS NOT ALLOWED!' 
        print(msg) 
        exit(1) 

这行得通,并返回格式如下的消息;

远程:您正在推送将被覆盖的代码......等等

其后是

错误:无法推送某些引用...等

然而,我想做的是替换打印调用并将消息作为错误返回,所以它读取;

错误:您正在推送的代码将被覆盖......等等

我的理由是,我怀疑不同的 gui git 客户端会以不同的方式显示错误(即红色、带有 pop 窗口、感叹号等),并且它们更有可能被试图推送的人阅读。请问有人知道怎么做吗?

请您参考如下方法:

你不能,因为 git 的 hook 处理代码简单地获取返回的每个字符串(特别是在边带 channel 2 上;这是 hook 输出结束的地方)并在前面加上单词 remote:它的(参见 sideband.c 中的 recv_sideband())。您可以让它打印 remote: error: 并祈祷 gui 可能会将其识别为错误字符串。 :-)