我克隆了一些git存储库,并做了"git branch abcd",将我转换为源自origin/abcd的分支.abcd不是默认的原始分支.然后,我从abcd创建了一个功能分支"my_feature".我想在一个脚本中将"git merge origin/abcd"写入my_feature中,无论所使用的原始分支的名称如何都适用(或者至少适用于其他一些答案中没有描述复杂分支结构的简单情况) GIT).
如何找到当前分支创建的"最近"/"父"原点分支?
这一点很难做好。在 git 中,分支只是指向提交的自动前进指针,并且提交上可以有任意数量的分支名称。考虑这种情况:
your master: y1---y2---y3
/
master: a---b---c---d---e
\
feature: f1---f2---f3---f4
Run Code Online (Sandbox Code Playgroud)
您在 处签出了分支“master” c,并提交了y1、y2、 和y3。您的历史看起来像这样a b c y1 y2 y3。同时 master 已经升级到d和e,但是有人创建了一个功能分支并f1基于. Git 无法确定您的分支来自而不是来自,因此您最多可以选择要合并的分支。f4cmasterfeature
如果您自动执行此操作,则必须应用启发式方法来选择最短的分支,或最长的分支,或具有最多/最少提交的分支,或其他类似的分支。当然,由于选项太多,对于git内置函数来说这并不是一个好的选择。但是,使用 git 的“管道”功能,您可以编写自己的:
#!/bin/bash
# Tries to determine a good merge base from among all local branches.
# Here used, a "good" merge base is the one sharing the most recent commit
# on this branch. This function will exit 1 if no branch is found,
# or exit 2 in a tie.
#
# Untested - use at your own risk.
MAX_SEARCH=20 # only search the last 20 commits on this branch
FOUND=0
LAST_BRANCH=
# iterate through the commits, most recent first
for COMMIT in $(git rev-list --max-count=$MAX_SEARCH HEAD); do
# check every local branch
for BRANCH in $(git for-each-ref --format="%(refname)" refs/heads); do
# look for the commit in that branch's history
if (git rev-list $BRANCH | fgrep -q COMMIT); then
echo $BRANCH
FOUND=$((FOUND + 1))
LAST_BRANCH="$BRANCH"
fi
done
if [ $FOUND -gt 1 ]; then
# more than one choice; exit
exit 2
elif [ $FOUND -eq 1 ]; then
git merge $LAST_BRANCH
exit 0
fi
done
exit 1 # could not find a parent
Run Code Online (Sandbox Code Playgroud)