首先介紹下情境
首先,一定要想清楚,自己想幹什麼。
找redis源碼作為例子,查看所在的分支git branch
取前5條commit看看
git log --pretty=format:"%h - %an, %ar : %s" -5
e9d861e - antirez, 27 hours ago : Clear child data when opening the pipes.e565632 - antirez, 27 hours ago : Child -> Parent pipe for COW info transferring.e1eccf9 - antirez, 31 hours ago : zmalloc: Make fp var non local to fix build.945a2f9 - antirez, 31 hours ago : zmalloc: zmalloc_get_smap_bytes_by_field() modified to work for any PID.b13759e - antirez, 31 hours ago : redis-cli: "allocator-stats" -> "malloc-stats".
臨時切換到某個commit
有可能你並不需要復原代碼,你只想將程式碼程式庫暫時切換到之前的某個版本,看看那個時候的實現,然後回來繼續寫之前沒有完成的任務。比如想看看945a2f9這個commit,執行操作
Note: checking out '945a2f9'.You are in 'detached HEAD' state. You can look around, make experimentalchanges and commit them, and you can discard any commits you make in thisstate without impacting any branches by performing another checkout.If you want to create a new branch to retain commits you create, you maydo so (now or later) by using -b with the checkout command again. Example: git checkout -b <new-branch-name>HEAD is now at 945a2f9... zmalloc: zmalloc_get_smap_bytes_by_field() modified to work for any PID.
再執行git branch
* (HEAD detached at 945a2f9) 3.0 3.2 unstable
可以看到處於一個臨時的分支上面,如果想以這個分支作為基礎開發新的功能,可以建立一個新的分支進行開發。
git checkout -b old-bottle 945a2f9
如果想回到之前的的分支,只要checkout回去就好了。
當然如果在切回以前的commit的之前已經改了一些代碼,可能不會那麼順利地切到之前的commit,可以
使用reset將修改了的代碼丟棄
stash->checkout->stash pop將修改的代碼找回來
產生一個新的分支用於儲存修改的代碼
刪除未發布的提交
如果確定要刪除某幾個commit,並且那幾個commit的代碼還沒有提交到遠程版本庫裡的話。
可以這樣
git reset --hard 945a2f9HEAD is now at 945a2f9 zmalloc: zmalloc_get_smap_bytes_by_field() modified to work for any PID.
再查看git log,就已經看不到945a2f9之前的commit記錄了。
當然如果想儲存當前沒有提交的代碼,可以和之前一樣使用stash
git stashgit reset --hard 945a2f9git stash pop
注意:
reset --hard 一定要慎用!!
這回讓你徹底丟失本地的代碼(除非有備份過)
刪除發行的提交
假設代碼已經提交到遠程版本庫了,這時應該使用revert命令,revert命令實際是提交一個新的commit來復原之前的commit。還是以945a2f9為例,現在想讓代碼會滾到945a2f9的狀態,那麼需要revert掉之前的commit
git revert e9d861e e565632 e1eccf9
或者可以這樣做,revert掉HEAD的前三個commit
之後就可以將現在的HEAD push到版本庫了。
如果發現之前revert操作錯了,可以再執行一次revert來取消上次的revert。
總結
以上就是這篇文章的全部內容了,本文只是簡單講了一些我個人的一些操作實踐。希望能對大家的學習或者工作帶來一定的協助,如果有疑問大家可以留言交流。