繁体   English   中英

在 Windows 上执行 Git 钩子

[英]Executing Git hooks on Windows

我在 Windows 上执行 Git 挂钩时遇到问题。 我有一个裸仓库,在它的“hooks”文件夹中,我将以下内容放入“更新”和“预推送”文件中,但从未执行 PHP 脚本:

"c:/Programs/PHP/php.exe" c:/Data/Scripts/git-pre-push.phpcli %1

关于为什么不执行 PHP 脚本的任何想法?

在 Git 控制台窗口中,当我尝试将某些内容推送到裸存储库时,会看到以下内容:

POST git-receive-pack (437 bytes)
remote: error: hook declined to update refs/heads/master
To https://myuser@mydomain/samplerepo
! [remote rejected] master -> master (hook declined)
error: failed to push some refs to 'https://myuser@mydomain/samplerepo'

...所以我知道“更新”正在以某种方式被执行。 当我删除该文件时,推送工作正常。

默认情况下,Git for Windows 使用自己的bash shell 的 Windows 端口执行钩子脚本。 当然,Unix shell 不知道%1 据说,Windows 版 Git 有额外的技巧来检测“常见”文件扩展名——例如.bat并在这种情况下采取替代路线。

我认为您对自己的程序的修复是最好的,但另一种方法是重写您的脚本以读取

#!/bin/sh
c:/Programs/PHP/php.exe c:/Data/Scripts/git-pre-push.phpcli "$@"

(shebang 行在 Windows 下没有真正的特殊意义,除了提示下一个人编辑脚本内容的含义外)。

#!/bin/sh
echo "executing pre-commit"

# Instructions:

# Put this file into your .git/hooks folder and set as executable 

 #- for Windows (attrib +x pre-commit)
 #- for ubuntu (chmod +x pre-commit)

# If you want to skip the hook just add the --no-verify: git commit --no-verify

# ---------------------------------------------

# Modify this
# LIST='list\|of\|words\|splitted\|by\|slash\|and\|pipe'
LIST="puts\|debugger;\|binding.pry\|alert(\|console.log("

if git rev-parse --verify HEAD >/dev/null 2>&1; then
    against=HEAD
else
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

for FILE in `git diff-index --name-status --cached $against -- | cut -c3-` ; do
    # Check if the file contains one of the words in LIST
    if grep -w $LIST $FILE; then
      echo $FILE." has unwanted word. Please remove it. If you want to skip that then run git commit -m '"your comment"' --no-verify"
      exit 1
    fi
      done
exit

在 Windows 上,通常是特殊的“#!” (称为shebang)PHP 脚本中的第一行无效。 但是,Windows 上的 Git 能够识别 shebang 第一行。 您可以使用 PHP 编写如下的 commit-msg 钩子,它将在 Windows 上正常运行。

#!D:/php/php.exe

<?php
echo 'commit-msg';
exit( 0 );    

在 Windows上查看更多关于git 钩子的信息

我相信秘密在于shebang部分 - 在Windows上,您需要像这样提供sh.exe的完整路径:

#!/bin/sh; C:/path/to/Git/bin/sh.exe

如果您安装了 cygwin,您还可以指向位于 cygwin/bin 中的 sh.exe 或 bash.exe 您甚至可以使用 cyqwin 支持的其他脚本语言 - 例如 ruby​​:

#!/usr/bin/env ruby; C:/path/to/cygwin/bin/ruby.exe
puts "RUBY HOOK RUNNING"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM