6

I have the following in my .git/hooks/pre-commit file

#!/bin/sh
exec c:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -ExecutionPolicy RemoteSigned -Command " Get-Location | % { '$_\pre-commit-hook.ps1'} | % { & $_ }"
exit

This successfully executes the code in the pre-commit-hook.ps1 file in the same directory, but does not capture the exit code. According to tldp.org the last exit code will be returned if only exit is specified. Git hooks will fail if the exit code is non-zero, but even though my powershell script returns a status code of 1, it always succeeds. What can I do to capture the exit code from the powershell script so the hook will function correctly?

Matt Phillips
  • 11,249
  • 10
  • 46
  • 71
  • In your script try adding `[environment]::Exit(1)` to return the non-zero code to the caller. If this works i'll make it my answer :-) – Andy Arismendi Feb 18 '12 at 03:04
  • nope doesn't work. I already had just `exit 1` in my script but that didn't work either – Matt Phillips Feb 18 '12 at 03:09
  • I figured you might of... Because sometimes it [doesn't work](http://stackoverflow.com/questions/8902004/powershell-fails-to-return-proper-exit-code/8902329#8902329). – Andy Arismendi Feb 18 '12 at 03:14
  • If you try just `exec c:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -ExecutionPolicy RemoteSigned -Command "[environment]::Exit(1)"` does it work? – Andy Arismendi Feb 18 '12 at 03:18
  • yeah that does work, but doesn't solve the problem lol. Would you mind going to chat? http://chat.stackoverflow.com/rooms/info/7875/matt?tab=general – Matt Phillips Feb 18 '12 at 03:22

1 Answers1

8

Keep the invocation of the ps1 script simple and you should have it working. The following works for me:

#!/bin/sh
echo 
exec powershell.exe -ExecutionPolicy RemoteSigned -File '.\.git\hooks\pre-commit-hook.ps1'
exit

The ps1 script just had an exit 1 and the commit did not happen.

When you are doing stuff like -command, Powershell is not known to work properly and you might have to do something like -command {& .\test.ps1; exit $lastexitcode}

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • 1
    Yup that works. I think the key here is that even though "pre-commit" itself is already running in .git/hooks, the current directory is the root of your project. That is definitely NOT in the docs ;) – Matt Phillips Feb 18 '12 at 03:40