我有一个php项目,当我从另一个存储库中取出并且composer.lock文件被更改时,我应该运行composer.phar install --dev
。 git如何自动警告我/问我是否要运行此命令?我想某种钩子可以解决这个问题,但是我怎样才能获得有关拉入之前和之后发生了什么变化的信息?
答案 0 :(得分:20)
取决于您在拉动时使用的选项:
您可以自己编写post-merge git hook:
这个钩子是由git merge调用的,当在本地存储库上完成git pull时会发生这种情况。钩子接受一个参数,一个状态标志,指定合并是否是一个压缩合并。这个钩子 如果合并因冲突而失败,则不会影响git merge的结果,也不会执行。
此挂钩应该适合您(将其保存为可执行文件.git/hooks/post-merge
):
#!/bin/sh
CHANGED=`git diff HEAD@{1} --stat -- $GIT_DIR/../composer.lock | wc -l`
if [ $CHANGED -gt 0 ];
then
echo "composer.lock has changed!"
composer.phar install --dev
fi
您可以自己编写post-checkout git hook:
在更新工作树之后运行git checkout时会调用此挂钩。钩子有三个参数:前一个HEAD的ref,新HEAD的ref和一个表示结账是分支结账还是文件结账的标志
此挂钩应该适合您(将其保存为可执行文件.git/hooks/post-checkout
):
#!/bin/sh
CHANGED=`git diff $1 $2 --stat -- $GIT_DIR/../composer.lock | wc -l`
if [ $CHANGED -gt 0 ];
then
echo "composer.lock has changed!"
composer.phar install --dev
fi
答案 1 :(得分:2)
这是一个有趣的要点:https://gist.github.com/sindresorhus/7996717我已根据你的问题对其进行了调整。
合并后的git hook在合并分支或执行git pull
时执行。
合并后挂钩(read docs)
#/usr/bin/env bash
# MIT © Sindre Sorhus - sindresorhus.com
# forked by naXa! - naxa.by
# Git hook to run a command after `git merge` / `git pull` if a specified file was changed.
# Run `chmod +x post-merge` to make it executable then put it into `.git/hooks/`.
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
check_run() {
echo "$changed_files" | egrep --quiet "$1" && echo "$2"
}
# In this example it's used to print a warning if composer.lock has been changed
check_run composer.lock "Run `composer.phar install --dev`"
在分支机构之间切换或执行git rebase
时执行post-checkout git hook。
结帐后挂钩(read docs)
#/usr/bin/env bash
# MIT © Sindre Sorhus - sindresorhus.com
# forked by naXa! - naxa.by
# Git hook to run a command after `git checkout` if a specified file was changed.
# Run `chmod +x post-merge` to make it executable then put it into `.git/hooks/`.
# terminate gracefully on a file checkout (retrieving a file from the index)
# uncomment the below line if you don't want to run this hook on a file checkout (for example on git->revert in IntelliJ IDEA)
# [ $3 -eq 0 ] && { exit 0; }
changed_files="$(git diff-tree -r --name-only --no-commit-id $1 $2)"
check_run() {
echo "$changed_files" | egrep --quiet "$1" && echo "$2"
}
# In this example it's used to print a warning if composer.lock has been changed
check_run composer.lock "Run `composer.phar install --dev`"
exit 0;
您可能会注意到我已将grep
更改为egrep
。这样做是为了能够使用花哨的表达式进行搜索。例如"file1.txt|file2.txt"
其中|
用作OR运算符。