Executing Git hooks on Windows

2020-02-21 08:39发布

I'm having trouble executing Git hooks on Windows. I have a bare repo and in it's "hooks" folder I put the following into both the "update" and "pre-push" files but the PHP script is never being executed:

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

Any ideas as to why the PHP script isn't executed?

In the Git console window I see the following when I try to push something to the bare repo:

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'

...so I know that the "update" is somehow being executed. When I remove that file the push works just fine.

3条回答
该账号已被封号
2楼-- · 2020-02-21 08:47
#!/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
查看更多
虎瘦雄心在
3楼-- · 2020-02-21 08:55

I believe the secret is in the shebang part - on windows you will need to give the full path to your sh.exe like this:

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

If you have cygwin installed you can also point to sh.exe or bash.exe located in cygwin/bin You can even utilize other scripting languages supported via cyqwin - e.g. ruby:

#!/usr/bin/env ruby; C:/path/to/cygwin/bin/ruby.exe
puts "RUBY HOOK RUNNING"
查看更多
forever°为你锁心
4楼-- · 2020-02-21 09:03

By default, Git for Windows executes hook scripts using its own Windows port of the bash shell. Certainly, a Unix shell has no idea about %1. Supposedly, Git for Windows has extra hacks in place to detect "common" filename extensions — such as .bat — and take an alternate route in such a case.

I think your fix to your own program is the best, but another approach would be to rewrite your script to read

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

(the shebang line has no real special sense under Windows other than hinting the next person to edit the script about the meaning of its content).

查看更多
登录 后发表回答