我有一个post-merge
git钩子,该钩子部分基于https://gist.github.com/sindresorhus/7996717。如预期的那样,如果请求引入合并冲突,则挂钩无法运行。
我该如何处理合并冲突,以便我的钩子可以按需运行?我的钩子依靠差异。如果我手动解决冲突并提交更新,那么我将不再有任何差异,因此挂钩中的逻辑不再相关。
这是钩子(尽管我想如果有冲突开始,这里的内容并不重要)
#!/bin/sh
echo "[post-merge] Commit done."
DIFFS="$(git diff-tree -r --name-only --no-commit-id HEAD@{1} HEAD)"
BLUE='\033[0;34m'
GRN='\033[0;32m'
NC='\033[0m' # No Color
# Git hooks are not designed to be interactive. By default they don't have access to $stdin.
# which meant that normal use of `read` was not working when used within the context of a git hook.
# This line restores keyboard access to stdin so that the dev can respond to the prompt that appears while the hook
# is running.
# Alternatively, we could forgo the confirmation and make package installation automatic,
# though it seems better to allow dev to decide.
exec < /dev/tty
check_incoming() {
# $1 is package.json
# $2 is handle_package_json
echo "$DIFFS" | grep --quiet "$1" && eval "$2"
exit 0
}
handle_package_json() {
while true; do
echo -e "${BLUE}[post-merge] PACKAGE.JSON UPDATED:${NC}"
read -p "[post-merge] File may contain dependency updates. Run yarn install? (y/n) " yn
if [ "$yn" = "" ]; then
yn='Y'
fi
case $yn in
[Yy] ) yarn install; break;;
[Nn] ) echo "[post-merge] Installation deferred. You may need to manually update dependencies at a later point."; exit;;
* ) echo "[post-merge] Please answer y or n for yes or no.";;
esac
done
}
if [[ -n "$DIFFS" ]]; then
check_incoming package.json handle_package_json;
fi
答案 0 :(得分:0)
我该如何处理合并冲突,以便我的钩子可以按需运行?
您不能从钩子上执行此操作,因为-如您所见-钩子永远不会运行。
您需要做的是让用户调用自己的命令而不是运行git merge
。让命令运行git merge
并检查结果(包括退出状态),以确定合并是否成功。
(请注意,这意味着它们也无法运行git pull
,因为git pull
会运行git fetch
后跟git merge
。您可能需要向他们提供一个命令来代替git pull
,如果他们是喜欢git pull
命令的人。)
(顺便说一句,在开始package.json
之前检查git merge
是否需要合并 似乎很有意义:自己找到合并基础,然后使用git rev-parse
提取三个HEAD:package.json
,<merge-base>:package.json
和<theirs>:package.json
的哈希ID,如果匹配的哈希ID不匹配,您甚至可以提取文件本身(如果需要,使用git show
或git cat-file -p
进行合并前检查。如果所有三个哈希ID都匹配,则合并是微不足道的:所有三个文件都相同,Git只会保留{{1}如果合并基数和它们的匹配,但是package.json
不同,则Git将保留HEAD
版本;如果合并基数和HEAD匹配,但是它们不同,则Git将采用它们的版本。这三个不都匹配,Git将尝试合并json数据,就好像它是面向行的纯文本一样,这很可能会产生废话。)