Git常见问题-推送被拒怎么办?

2024/04/21 | 字数748 | 阅读2分钟


原因

在push失败的时候,你通常看到的情况是这样的:

bash
1
2
3
4
5
6
7
8
9
git push
To /Users/ticktech/usr/playground/git/demo.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to '/Users/ticktech/usr/playground/git/demo.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

原因是,在你推送代码之前,已经有人先你一步,提前推送了代码到远端仓库。也就是说,你的本地仓库已经不是最新的版本了。

处理

拉取最新版本,并使用rebase的方式将本地修改重新提交。

bash
1
2
git pull --rebase
git push 

在rebase过程中,可能会出现冲突,如下面所示,可以使用git status -s命令查看哪些文件有冲突,手动修复:

bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
git pull --rebase
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), 254 bytes | 254.00 KiB/s, done.
From /Users/ticktech/usr/playground/git/demo
   32dbee4..39f0952  master     -> origin/master
Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
error: could not apply 5e6b2b6... new b
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
Recorded preimage for 'README.md'
Could not apply 5e6b2b6... new b

git status -s
UU README.md

可以采用下面的方式修复:

bash
1
2
3
4
vim your-conflict-file

git add .
git rebase --continue

上面的过程可能会出现多次,如果想要中断rebase的操作,可以在任何一次冲突后,执行git rebase --abort退出,Git会将本地仓库和工作区的状态回退到执行rebase之前的状态,是不是倍感贴心,感觉Git是懂程序员的~

上一篇:Git常见问题-提交了一个垃圾文件怎么办 下一篇:Git常见问题-如何解决冲突

【文章不错,鼓励一下】