git rebase 基本使用

1,167 阅读3分钟

适用情形

当我们需要实现下面功能,并且希望代码的提交记录整洁的话可以考虑使用 git rebase

  • 合并多条提交记录
  • 合并多次提交至另一分支
  • 分支合并

基本命令

git rebase -i commit_id		合并 (commit_id, HEAD] 提交记录
git rebase —abort	终止当前 rebase 操作
git rebase --edit-todo	如果你异常退出了 vi 窗口,使用该命令继续编辑
git rebase --continue	用于解决冲突以后,继续执行 rebase

一、合并多条提交记录

git rebase -i HEAD~4    合并最近四次提交记录
git rebase -i commit_id1 commit_id2	合并 (commit_id1 commit_id2] 之间的提交记录

有几个命令需要注意一下

p	pick = use commit
s	squash = use commit, but meld into previous commit
r	reword = use commit, but edit the commit message
e	edit = use commit, but stop for amending
f	fixup = like “squash”, but discard this commit’s log message
x	exec = run command (the rest of the line) using shell
d	drop = remove commit

翻译 =>

pick	保留该 commit(缩写:p)
squash	将该 commit 和前一个 commit 合并(缩写:s)
reword	保留该 commit,但我需要修改该commit的注释(缩写:r)
edit	保留该 commit, 但我要停下来修改该提交(不仅仅修改注释)(缩写:e)
fixup	将该 commit 和前一个 commit 合并,但我不要保留该提交的注释信息(缩写:f)
exec	执行 shell 命令(缩写:x)
drop	我要丢弃该 commit(缩写:d)

二、合并多次提交至另一分支

该场景也可以使用 cherry-pick 命令进行 commit 转移 cherry-pick 使用方法

将当前分支 (commit_id1, commit_id2] 提交记录添加至 branchName 分支

git rebase commit_id1 commit_id2 --onto  [branchName]

--onto 的意思是要将该指定的提交复制到哪个分支上

branchName 所指向的提交 id 设置为当前 HEAD 所指向的提交 commit_id

git checkout branchName
git reset --hard commit_id

三、分支合并

场景说明

项目开发主分支 master, 对应 master 分支切出多个 dev 分支 feature/*, 多人合作共同开发一个项目,dev 分支上开发功能完成后均合并到 master 分支

  1. 首先我们开发从 master 分支上切换一个开发分支 feature/test 出来切换到该分支
git checkout -b feature/test
  1. 同时,在此之后,其他人向 master 提交或并入了新的代码提交,此时我们feature/test 之前在 master 分支的内容是落后于当前 master 版本的

解决方法1:

在我们当前 feature/test 开发分支 merge 主分支, 使用 merge 会产生而外的 merge commit 记录

git merge master

解决方法2: 在我们当前 feature/test 开发分支 rebase 主分支,使用 rebase 不会产生额外的 commit 记录

git rebase master

rebase 内部操作简单说明:

  1. git 会把 feature/test 分支里面的提交的 commit 取消掉
  2. 把 1 中取消的 commit 临时保存成 patch 文件,存在 .git/rebase 目录下
  3. feature/test 分支更新到最新的 master 分支
  4. 把 2 中在 .git/rebase 目录下保存的 patch 文件应用到 feature/test 分支上
  1. 文件产生冲突 (conflict)

rebase 过程中出现 conflict 时候,rebase 操作会停止进行,需要我们手动去处理这些冲突的文件并保存;当文件冲突解决后,使用 git add . 命令去更新相应的内容

git add 后我们不需要执行 git commit,只要执行下面命令继续 rebase

git rebase --continue
  1. 无论什么时候,我们都可以使用下面命令终止当前 rebase 操作
git rebase —abort