git代碼庫回滾: 指的是將代碼庫某分支退回到以前的某個commit id
【本地代碼庫回滾】:
git reset --hard commit-id :回滾到commit-id,講commit-id之后提交的commit都去除
git reset --hard HEAD~3:將最近3次的提交回滾
【遠程代碼庫回滾】:
這個是重點要說的內容,過程比本地回滾要復雜
應用場景:自動部署系統發布后發現問題,需要回滾到某一個commit,再重新發布
原理:先將本地分支退回到某個commit,刪除遠程分支,再重新push本地分支
操作步驟:
1、git checkout the_branch
2、git pull
3、git branch the_branch_backup //備份一下這個分支當前的情況
4、git reset --hard the_commit_id //把the_branch本地回滾到the_commit_id
5、git push origin :the_branch //刪除遠程 the_branch
6、git push origin the_branch //用回滾后的本地分支重新建立遠程分支
7、git push origin :the_branch_backup //如果前面都成功了,刪除這個備份分支
如果使用了gerrit做遠程代碼中心庫和code review平台,需要確保操作git的用戶具備分支的push權限,並且選擇了 Force Push選項(在push權限設置里有這個選項)
另外,gerrit中心庫是個bare庫,將HEAD默認指向了master,因此master分支是不能進行刪除操作的,最好不要選擇刪除master分支的策略,換用其他分支。如果一定要這樣做,可以考慮到gerrit服務器上修改HEAD指針。。。不建議這樣搞
方法一:
1、新建backup分支 作為備份,以防萬一
- git branch backup
2、將本地的backup分支 推送到遠程的backup
- git push origin backup:backup
3、本地倉庫徹底回退到xxxxx版本,xxxxx版本之后的commit信息將丟失
- git reset --hard xxxxx
4、刪除遠程的master分支 (注意master前有個:)
- git push origin :master
主要遠程倉庫的master如果是保護分支將報錯,請去掉對分支的保護設置:
- remote: GitLab: You are allowed to deleted protected branches from this project. To http://gitlab.mogujie.org/shihao/afanty.git ! [remote rejected] master (pre-receive hook declined) error: failed to push some refs to 'http://gitlab.mogujie.org/xxxx/xxxx.git'
5、重新創建遠程master分支(這跟第1次提交本地代碼庫給遠程倉庫的命令一樣)
- git push origin master
方法二:
1、本地代碼回滾到上一版本(或者指定版本)
- git reset --hard HEAD~1
2、加入-f參數,強制提交,遠程端將強制跟新到reset版本
- git push -f origin master
注:方法二前建議如方法一一樣備份當前git中的數據,個人推薦方法二