如果我在以下情况下,
$ git log --oneline
* abcdef commit #b
* 123456 commit #a
我知道我可以一直跑下去
$ git reset HEAD~
$ git commit --amend
然而,我试着运行
$ git rebase -i HEAD~2
但是我得到了
fatal: Needed a single revision
invalid upstream HEAD~2
因此我的问题:是否有一种方法可以使用git rebase
来压制这两个提交?
您想要重基到master
分支的根提交。更具体地说,要压缩两个提交,您需要运行
git rebase -i --root
,然后在弹出的编辑器缓冲区的第二行用squash
代替pick
:
pick 123456 a
squash abcdef b
请参阅git-rebase
手册页,了解有关该标志的更多详细信息:
--root
将
<branch>
中所有可访问的提交重新设置为base用<upstream>
来限制它们。这允许您重新定位根在分支上提交。[…]
根目录
交互式重基示例# Set things up
$ mkdir testgit
$ cd testgit
$ git init
# Make two commits
$ touch README
$ git add README
$ git commit -m "add README"
$ printf "foon" > README
$ git commit -am "write 'foo' in README"
# Inspect the log
$ git log --oneline --decorate --graph
* 815b6ca (HEAD -> master) write 'foo' in README
* 630ede6 add README
# Rebase (interactively) the root of the current branch:
# - Substitute 'squash' for 'pick' on the second line; save and quit the editor.
# - Then write the commit message of the resulting commit; save and quit the editor.
$ git rebase -i --root
[detached HEAD c9003cd] add README; write 'foo' in README
Date: Sat May 16 17:38:43 2015 +0100
1 file changed, 1 insertion(+)
create mode 100644 README
Successfully rebased and updated refs/heads/master.
# Inspect the log again
$ git log --oneline --decorate --graph
* c9003cd (HEAD -> master) add README; write 'foo' in README
这个参数似乎有帮助:
--root
重新base所有从分支<可访问的提交,而不是用>
来限制它们。这允许您重新设置根目录在分支上提交。
这应该让你把(我猜你实际上想要修复)你的第二次提交压缩到第一次上:
git rebase --root -i
要注意理解——root选项的作用,因为在您的情况下,它可以满足您的需求,但在分支中使用时可能会很棘手,因为它将重置到历史中可到达的最远的祖先(即。树的根);因此rebase --root
将通过A-B-D-E-X-Y-Z
在a
上重新设置z
:
master A-B-C
upstream D-E
current branch X-Y-Z
我来到这个问题寻找答案的标题。在非常大的repo中,可接受的答案是为主分支(又名:master)中的每个提交生成交互式重基,而不是,只针对给定分支的。对于来到这里的其他人,替代方法是使用父分支名称(或提交):
git rebase -i <base_branch_name>
我在git文档中发现了这个(https://git-scm.com/docs/git-rebase#_interactive_mode):
)从你想保持原样的最后一次提交开始:
git rebase -i <after-this-commit>
一个编辑器将被启动,所有的提交选项之后的当前分支(忽略合并提交)鉴于提交。
假设你有一个从master分支出来的branch_a,你想在branch_a
上交互式地重基所有的提交。要做到这一点,你可以这样做:
git rebase -i master
或者,如果您想从中间开始(或在任何提交时),您可以这样做:
git rebase -i <some-commit-hash-in-the-middle>
另一种常见的形式是,如果你知道"我想从现在的位置重新提交5次"
git rebase -i HEAD~5
希望这可以帮助别人避免心脏病发作,当他们的git rebase打开一个编辑器与数千行提交。─=≡Σ((<><)