摘要
在当前分支中查找也包含在任何其他分支中的最新提交的最快方法是什么?
奖励:该技术是否可以允许上述问题中的“任何其他分支”成为“任何其他远程分支”或“任何其他本地分支”?
背景
我喜欢使用git rebase -i
。我的主要用例是在推送到远程之前重新组织提交。因此,我经常做 git rebase -i origin/master 。因此,我为该操作设置了一个名为 git rewrite
的别名。
问题是我并不总是想针对 origin/master
进行 rebase 。例如,我可能正在一个分支上工作,而希望 git rewrite 执行 git rebase -i origin/branch 。或者我可能正在本地分支工作并希望 git rewrite 执行 git rebase -i localbranch。
因此,实际上,我试图让我的 git rewrite 脚本执行类似以下操作:“从任何其他分支中包含的最后一次提交执行交互式 rebase ”。我想出的是:(仅适用于查找远程分支)
#!/bin/bash
# Do a git rebase -i from the most recent common point between the
# current branch and any other remote branch.
# We go backwards in the branch's history and for each commit check if
# that commit is present in one of the remote branches. As soon as we
# find one that is, we stop and rebase on that.
commit=$(git rev-parse HEAD)
while [ true ]; do
branch=$(git branch -r --contains $commit)
if [ -n "$branch" ]; then
# This commit exists in another remote branch!
break
fi
# OK, let's try the previous commit
commit=$(git log --pretty=%P -n 1 $commit)
# Stupid heuristic, take only first commit if multiple parents
commit=${commit%% *}
done
git rebase -i $commit
此方法的问题是它慢。它也有点不准确,因为当提交有多个父项时,它只跟随其中一个父项。
有人知道更好/更快/更干净的方法吗?
最佳答案
重写脚本可能如下所示(bash):
#!/bin/bash
count=0
for rev in $(git rev-list HEAD); do
num=$(git branch --all --contains ${rev} | wc | awk '{print $1}')
[ ${num} -eq 1 ] || break
count=$(( count + 1 ))
done
if [ ${count} -gt 0 ]; then
git rebase -i HEAD~${count}
fi
我经常做的是(从上游点 rebase ):
git rebase -i @{u}
但是,@{u}
技术无法捕获其他分支。
关于git rebase -i 快捷方式 - 找到最佳的 rebase 提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21815197/