Git Merge and Rebase

之前其实很少用到git merge and git rebase,一般都是通过Github UI Pull Request merges feature branch’s updates into master.

也可在CLI 中merge feature branch into master,但这样master中的git history不是线性的,并且会制造一个merge commit:

1
2
3
4
5
6
7
8
9
10
11
12
# merge feature to master, first go to master
git checkout master
# squash will summary all commits in feature branch into merge commit
git merge --squash feature
# or 不用fast-forward merge, 用普通的recursive merge
# by default is --ff (try fast-forward first, not create merge commit)
git merge --no-ff feature

# need to commit this merge
git commit -m "feature and master merged"
# then push to master
git push origin master

Highlight:

  • fast-forward merge: less commits, no merge commit will be generated.
  • recusive merge: has merge commit, can do revert, clear what was done on a branch.

关于rebase的使用,可以参考这篇文章,它构造了一个线性的git history,方便以后查看: https://www.jianshu.com/p/6960811ac89c 注意,这篇文章的例子是将dev branch 本地合并到master 再提交,并不是merge request的方式。

  1. 先将本地master 更新, git pull origin master
  2. 进入需要rebase的分支, git checkout dev
  3. 执行rebase, git rebase master. 这样就把master的commits 线性的合并到dev 分支了
  4. rebase可能遇到conflicts, 参考这里去修复Resolving merge conflicts after a Git rebase
  5. dev 中rebase 完成后,切换到master执行merge, git checkout master, git merge dev (github/gitlab UI就是做了这一步)

这样就把dev合并到master中了,实际上还是先rebase 再 merge.

这个文章讲了更多的rebase 特性: https://baijiahao.baidu.com/s?id=1633418495146592435

  1. git pull --rebase (will not use merge)
  2. 修改commit 历史
  3. 合并commit
  4. 分解commit
  5. 重新排序commit

Git Interactive Rebase, Squash, Amend and Other Ways of Rewriting History 实际遇到一个要求,存在多次的commits在dev branch中,需要squash multiple commits into one, 解决办法: 在本地rebase 然后再提交, for example I use dev branch:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 如果dev branch不干净
# later can run `git stash pop`
git stash

# 可以先在dev中squash一下多个commits
# HEAD~5: rebase HEAD 向下的5个commits
# HEAD 可以用git log看一下位置
git checkout dev
git rebase -i HEAD~5

# pull latest to master branch
# because it may be updated by others
git checkout master
git pull origin master

# current in dev branch, reword commits on top of master history
git checkout dev
# rebase against master,这样之后create pull/merge request就不会产生冲突了
# -i: interactively
git rebase -i master


# may have conflicts, fix conflicts as prompted
git add <fixed files>
git rebase --continue

# abort rebase
git rebase --abort

# after rebase (squash), check commit log changes
git log -n 5

# update merge request on github
# 之前的merge request就会被重写
# -f: force override merge request on remote
git push -f origin dev

Other GitHub tutorials:

GitHub.com Help Documentation: https://docs.github.com/en/github

0%