git post-commit hook - script on committed files

点点圈 提交于 2019-11-30 20:24:32

Assuming the script you execute on each file can't be set up to fail immediately when it fails on one argument, you can't use that xargs setup. You'll could do something like this:

#!/bin/bash

# for a pre-commit hook, use --cached instead of HEAD^ HEAD
IFS=$'\n'
git diff --name-only HEAD^ HEAD | grep '\.php$' |
while read file; do
    # exit immediately if the script fails
    my_script "$file" || exit $?
done

But perhaps phpmd will do this for you already? Couldn't quite understand from your question, but if it does, all you have to do is make sure it's the last command in the hook. The exit status of a pipeline is the exit status of the last command in it (phpmd), and the exit status of a shell script is the exit status of the last command it ran - so if phpmd exits with error status, the hook script will, and if it's a pre-commit hook, this will cause git to abort the commit.

As for an option to git-commit to control invocation of this hook, you're kind of out of luck, unless you consider --no-verify (which suppresses all commit hooks) good enough. An alias... the cleanest way to do that would be to set an environment variable in the alias, probably:

# gitconfig
[alias]
    commitx = "!run_my_hook=1; git commit"

# your script
#!/bin/bash
# if the variable's empty, exit immediately
if [ -z "$run_my_hook" ]; then
    exit 0;
fi
# rest of script here...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!