临时分支法解决git提交代码冲突

在改动git仓库中的文件时,没有在变更前执行 git pull 而导致本地的代码在后续的改动后和线上的代码不一致,而在commit后准备提交时再执行 git pull 获取代码时却提示 rejected -- non-fast-forward 的错误。

相关


临时分支法

  1. 创建一个临时分支
  2. 将远端待提交分支拉取到本地的临时分支
  3. 手动将本地的待提交分支合并到临时分支上
  4. 将合并后的临时分支提交到远端的待提交分支
  5. 将远端分支拉取到本地,即将冲突合并后的代码更新到本地分支
  6. 删除临时分支

操作记录

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
37
38
39
40
41
42
43
44
45
46
47
48
49
➜ git pull origin hexo:hexo
From https://github.com/leafney/Leafney.github.io
! [rejected] hexo -> hexo (non-fast-forward)
➜ git branch
* hexo
master
➜ git fetch origin hexo:tmp
From https://github.com/leafney/Leafney.github.io
* [new branch] hexo -> tmp
➜ git checkout tmp
Switched to branch 'tmp'
➜ git merge hexo
Updating 5b4d8c0..4431abb
Fast-forward
.gitignore | 2 +-
...ent-environment-configuration.md => flutter-development-environment-configuration.md} | 10 ++++++----
2 files changed, 7 insertions(+), 5 deletions(-)
rename source/_posts/{flutter-devemopment-environment-configuration.md => flutter-development-environment-configuration.md} (97%)
➜ git push origin tmp:hexo
Enumerating objects: 10, done.
Counting objects: 100% (10/10), done.
Delta compression using up to 8 threads
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 10.98 KiB | 5.49 MiB/s, done.
Total 6 (delta 4), reused 0 (delta 0)
remote: Resolving deltas: 100% (4/4), completed with 4 local objects.
To https://github.com/leafney/Leafney.github.io.git
5b4d8c0..4431abb tmp -> hexo
➜ git checkout hexo
Switched to branch 'hexo'
Your branch is up to date with 'origin/hexo'.
➜ git pull origin hexo:hexo
Already up to date.
➜ git branch -D tmp
Deleted branch tmp (was 4431abb).
➜ git branch

命令整理

错误:

1
2
3
➜ git pull origin hexo:hexo
From https://github.com/leafney/Leafney.github.io
! [rejected] hexo -> hexo (non-fast-forward)

解决:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 将远端待提交分支hexo拉取到本地的一个临时分支tmp下
git fetch origin hexo:tmp
# 切换到临时分支tmp
git checkout tmp
# 将本地的待提交分支hexo合并到临时分支tmp,并解决冲突
git merge hexo
# 将临时分支tmp提交到远端的待提交分支hexo
git push origin tmp:hexo
# 切换到本地的待提交分支hexo
git checkout hexo
# 拉取远端的待提交分支hexo到本地的待提交分支hexo
git pull origin hexo:hexo
# 删除本地的临时分支tmp
git branch -D tmp

坚持原创技术分享,您的支持将鼓励我继续创作!
如有疑问或需要技术讨论,请留言或发邮件到 service@itfanr.cc