使用git rebase --interactive 编辑之前的提交,运行git reset HEAD~,然后运行git add -p 添加一些,然后进行提交,然后再添加一些并再次提交,次数不限。完成后,运行 git rebase --continue,您将在堆栈中较早地获得所有拆分提交。
重要提示:请注意,您可以随意尝试并进行所有您想要的更改,而不必担心丢失旧的更改,因为您可以随时运行git reflog 来找到您的要点包含您想要的更改的项目,(我们称之为a8c4ab),然后是git reset a8c4ab。
这里有一系列命令来展示它是如何工作的:
mkdir git-test; cd git-test; git init
现在添加一个文件A
vi A
添加这一行:
one
git commit -am one
然后将此行添加到A:
two
git commit -am two
然后将此行添加到A:
three
git commit -am three
现在文件 A 看起来像这样:
one
two
three
我们的git log 如下所示(好吧,我使用git log --pretty=oneline --pretty="%h %cn %cr ---- %s"
bfb8e46 Rose Perrone 4 seconds ago ---- three
2b613bc Rose Perrone 14 seconds ago ---- two
9aac58f Rose Perrone 24 seconds ago ---- one
假设我们要拆分第二个提交,two。
git rebase --interactive HEAD~2
这会显示如下所示的消息:
pick 2b613bc two
pick bfb8e46 three
将第一个 pick 更改为 e 以编辑该提交。
git reset HEAD~
git diff 向我们展示了我们刚刚取消了我们为第二次提交所做的提交:
diff --git a/A b/A
index 5626abf..814f4a4 100644
--- a/A
+++ b/A
@@ -1 +1,2 @@
one
+two
让我们暂存该更改,并在文件 A 中的该行中添加“和第三个”。
git add .
这通常是在交互式 rebase 期间我们将运行 git rebase --continue 的点,因为我们通常只想返回我们的提交堆栈以编辑较早的提交。但是这一次,我们想要创建一个新的提交。所以我们将运行git commit -am 'two and a third'。现在我们编辑文件A 并添加行two and two thirds。
git add .
git commit -am 'two and two thirds'
git rebase --continue
我们与我们的提交有冲突,three,所以让我们解决它:
我们会改变
one
<<<<<<< HEAD
two and a third
two and two thirds
=======
two
three
>>>>>>> bfb8e46... three
到
one
two and a third
two and two thirds
three
git add .; git rebase --continue
现在我们的git log -p 看起来像这样:
commit e59ca35bae8360439823d66d459238779e5b4892
Author: Rose Perrone <roseperrone@fake.com>
Date: Sun Jul 7 13:57:00 2013 -0700
three
diff --git a/A b/A
index 5aef867..dd8fb63 100644
--- a/A
+++ b/A
@@ -1,3 +1,4 @@
one
two and a third
two and two thirds
+three
commit 4a283ba9bf83ef664541b467acdd0bb4d770ab8e
Author: Rose Perrone <roseperrone@fake.com>
Date: Sun Jul 7 14:07:07 2013 -0700
two and two thirds
diff --git a/A b/A
index 575010a..5aef867 100644
--- a/A
+++ b/A
@@ -1,2 +1,3 @@
one
two and a third
+two and two thirds
commit 704d323ca1bc7c45ed8b1714d924adcdc83dfa44
Author: Rose Perrone <roseperrone@fake.com>
Date: Sun Jul 7 14:06:40 2013 -0700
two and a third
diff --git a/A b/A
index 5626abf..575010a 100644
--- a/A
+++ b/A
@@ -1 +1,2 @@
one
+two and a third
commit 9aac58f3893488ec643fecab3c85f5a2f481586f
Author: Rose Perrone <roseperrone@fake.com>
Date: Sun Jul 7 13:56:40 2013 -0700
one
diff --git a/A b/A
new file mode 100644
index 0000000..5626abf
--- /dev/null
+++ b/A
@@ -0,0 +1 @@
+one