开发经常会遇到代码提交后又想回到上一个提交的版本,但是不知道怎么操作,我也经常忘了需要百度才能搞定,现在写下这篇文章作为记录:
已经提交到git但是没有push的
1、回退到上一个版本,并保留修改记录,先查看提交历史:
$ git log
commit b69a4ced352ec9d5bd9dbf0036a052f9812854fb (HEAD -> master, origin/master) Author: zhuhualong Date: Thu Oct 12 18:29:53 2017 +0800 选择服务器控件修改 commit eb3378a32d36c03825e444002e541a2d12af274c Author: yangze Date: Wed Oct 11 10:01:05 2017 +0800 测试主机联通性工具类 commit bd2a381042868a331730ba549065ed8aaba817e9 Merge: 5c4a2ff f0d82fa Author: yangze Date: Wed Oct 11 10:00:18 2017 +0800 Merge branch 'master' of http://172.16.15.19/cop2/cop_task.git commit f0d82fa46a818525cf042a157e0fc889e0c813f6 Author: [email protected] Date: Tue Oct 10 20:48:56 2017 +0800
2、回退到指定的版本处:
$ git reset eb33
Unstaged changes after reset:
M cop.task.web/src/main/webapp/statics/api/assets/server/serverList.json
M cop.task.web/src/main/webapp/statics/css/app.css
M cop.task.web/src/main/webapp/statics/js/app/operation/tpl_task.js
M cop.task.web/src/main/webapp/statics/js/config.lazyload.js
M cop.task.web/src/main/webapp/statics/js/controllers/selectServerModal.js
M cop.task.web/src/main/webapp/statics/tpl/operation/template/selectServerModal.html
M cop.task.web/src/main/webapp/statics/tpl/operation/template/targetServer.html
3、或者回退所有内容到上一个版本
git reset HEAD^
这里写代码片
4、#回退test这个文件的版本到上一个版本
git reset HEAD^ test.py
这里写代码片
5、将本地的状态回退到和远程的一样
git reset –hard origin/master
6、回退到上一次提交的状态,按照某一次的commit完全反向的进行一次commit
git revert HEAD
7、将本地状态回退到某个指定版本,回退前所有的修改丢掉
$ git reset --hard eb33
HEAD is now at eb3378a 测试主机联通性工具类
已经提交到gitlab如何同步回退gitlab的代码
1、git本地回退到指定版本后,按以往的提交顺序进行提交时会出现这个问题
$ git push origin master
Username for 'http://172.16.15.19': lbp
To http://172.16.15.19/cop2/cop_task.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'http://172.16.15.19/cop2/cop_task.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.
2、这是因为gitlab已经在你提交历史前面了,你无法把push过的再次push进行覆盖,这个时候加个参数–force就行
$ git push origin master --force
Username for 'http://172.16.15.19': lbp
Total 0 (delta 0), reused 0 (delta 0)
remote: GitLab: You are not allowed to force push code to a protected branch on this project.
To http://172.16.15.19/cop2/cop_task.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'http://172.16.15.19/cop2/cop_task.git'
3、加完参数后发现gitlab不允许强行push到保护的分支上,解决方法是让项目的管理员暂时在gitlab上把你要提交的分支设置为不受保护的分支即可
$ git push origin master --force
Username for 'http://172.16.15.19': lbp
Total 0 (delta 0), reused 0 (delta 0)
To http://172.16.15.19/cop2/cop_task.git
+ b69a4ce...eb3378a master ->master (forced update)