背景
- 代码commit 并且push到远程仓库,发现本次提交了多余的文件,比如不需要单容易冲突的配置文件等.
- 希望远程代码撤销本次commit 本地不变
- 重新commit 代码
操作
-
先git log 查看commit历史记录
如:
- 现在需要把修改文章包含修改文章的三次commit(f8e79f08731a1551c42cabfdedea820a6f01f68b)都取消掉,回退到上次别人的提交6fb15caa0c49840978e02eddb150c339598cbfb2
执行 reset命令
git reset 6fb15caa0c49840978e02eddb150c339598cbfb2
这时提示:
表明你之前commit的所有东西都已经reset了..
- 然后从新add 你需要提交的文件 然后commit
git commit -m "新增文章"
强推远程分支
git pull origin master
很多人这时候都会松了一口气,以为就这样大功告成了,然而离成功还查一部.你会发现你无法push
To git@192.168.1.100:zjc/HTML5.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'git@192.168.1.1000:zjc/HTML5.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
明显提示使用pull拉取一下,其实是不可以拉取的,如果拉取可能把自己之前push上去的错误信息拉取下来.这样就会回到革命前了.
- 这时候需要强制推到远程分支,那就执行强制名利吧.于是信心满满的敲出下面一行代码.
git push -f origin master
然后:
Counting objects: 53, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (53/53), done.
Writing objects: 100% (53/53), 1.15 MiB | 0 bytes/s, done.
Total 53 (delta 27), reused 0 (delta 0)
remote: GitLab: You are not allowed to force push code to a protected branch on this project.
To git@192.168.1.100:zjc/HTML5.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@192.168.2.100:zjc/HTML5.git'
Mac-mini:HTML5 wanggeng$ git push -f origin master
Counting objects: 53, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (53/53), done.
Writing objects: 100% (53/53), 1.15 MiB | 0 bytes/s, done.
Total 53 (delta 27), reused 0 (delta 0)
remote: GitLab: You are not allowed to force push code to a protected branch on this project.
To git@192.168.1.100:zjc/HTML5.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@192.168.1.100:zjc/HTML5.git'
刚开始的时候真的会以为成功了 .然后看到最后会发现有个error .没错,你没看错,确实有个error.又一次失败了,好像没路可走了. 客官.莫急.我们仔细看下错误信息,总会有办法的,我们可以看到这样一句提示** * remote: GitLab: You are not allowed to force push code to a protected branch on this project.* **
处理受保护分支
- 如果当前分支是 protecded 的受保护分支,则 git 服务器会拒绝强制推送,报错如下:
remote: GitLab: You are not allowed to force push code to a protected branch on this project.
此时,需要将当前分支的 Protected 属性暂时去掉。
- 对于 gitlab,可以进入当前仓库的设置中的 "Protected branches" 一项,将当前 branch 的 protected 临时去掉,等这次 push 完成,再重新设置回 protected 。
查看本地和服务器记录
去掉保护后执行
git push -f
Counting objects: 53, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (53/53), done.
Writing objects: 100% (53/53), 1.15 MiB | 0 bytes/s, done.
Total 53 (delta 27), reused 0 (delta 0)
To git@192.168.1.100:zjc/HTML5.git
+ a12aab9...0c95a9f master -> master (forced update)
可见已经成功提交
- 查看本地和远程记录:
本地的提交记录确实干净了,只剩下修改后的一次提交记录.这是后打开远程仓库,发现之前的错误提交信息也没有了.
到此结束!