我有一个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
我应该如何处理合并冲突,以便我的钩子可以按需运行?
您不能从钩子上执行此操作,因为-如您所见-钩子永远不会运行。
您需要做的是让用户在运行git merge
的情况下调用您自己的命令代替。让您的命令运行git merge
并检查结果(包括退出状态),以确定合并是否成功。
((顺便说一句,似乎似乎很有必要检查package.json
是否需要合并之前开始git merge
:自己找到合并基础,然后使用git rev-parse
提取三个哈希ID,用于HEAD:package.json
,<merge-base>:package.json
和<theirs>:package.json
如果匹配的哈希ID不匹配,您甚至可以使用git show
或git cat-file -p
提取文件本身,以进行合并前检查如果需要的话,如果所有三个哈希ID都匹配,则合并是微不足道的:所有三个文件都相同,Git将按原样保留package.json
;如果merge-base和它们的匹配,但HEAD
不同,则Git将保留HEAD
版本。如果merge-base和HEAD匹配,但它们不同,则Git将采用其版本。如果所有三个do n't匹配,Git将尝试合并json数据,就好像它是面向行的纯文本一样-text,这很可能会产生废话。)