1. 程式人生 > >git reset用法 一 重置引用(版本切換)

git reset用法 一 重置引用(版本切換)

               

reset命令讓我們可以在歷史版本中切換。每次commit都會有一個commit id。

比如看看我的倉庫的日誌:

[email protected]:~/work/189/appengine$ git logcommit f9fae00840b97ca9ab4e782c9581fb6cb35b0ff4Author: shuchen <[email protected]>Date:   Tue Sep 18 13:15:11 2012 +0800    update common/tool.sh        Change-Id: Ib4f0a3f1bc9d9033d72194d6340f87e03c43ec85commit 7e5aad74c76c2f2d540d7b3f3efaf9948f964de7Merge: 3ab3ff0 f03c6c1Author: Yongfeng Wu <
[email protected]
>Date:   Tue Sep 18 10:19:03 2012 +0800    Merge branch 'master' of ssh://10.112.18.189:29418/appenginecommit 3ab3ff03aece1ef9e62af3a613823f1a2bcd5e84Author: Yongfeng Wu <[email protected]>Date:   Tue Sep 18 10:13:40 2012 +0800    Design and implement file API for local file system.

再看看我的HEAD,指向的是refs/heads/master檔案,該檔案是引用檔案,reset命令主要就是修改refs/heads/master檔案。

內容如下:

cat .git/refs/heads/master f9fae00840b97ca9ab4e782c9581fb6cb35b0ff4
也就是當前是master branch,並且當前版本就是最後一次commit id。

要在清楚理解的前提下使用reset命令,一旦你切換到某個歷史版本,之後的歷史版本資訊就沒有了。

使用reset之前,首先確認是否配置了

core.logallrefupdates=true
可以通過git config core.logallrefupdates檢查。

結合reflog,可以安全的使用reset命令。比如新增一個x檔案做為測試。

[email protected]:~/work/myproject$ touch [email protected]:~/work/myproject$ git add [email protected]:~/work/myproject$ git commit -m'add test file x'[master 1aea8d9] add test file x 0 files changed create mode 100644 [email protected]:~/work/189/myproject$ git reflog1aea8d9 [email protected]{0}: commit: add test file xf9fae00 [email protected]{1}: commit: update common/tool.sh

現在用reset切換到上一個提交

$ git reset --hard f9fae00HEAD is now at f9fae00 update common/tool.sh
這是時候看一下目錄,x檔案已經被刪除。

在看一下reflog:

$ git reflogf9fae00 [email protected]{0}: reset: moving to f9fae001aea8d9 [email protected]{1}: commit: add test file xf9fae00 [email protected]{2}: commit: update common/tool.sh
但是如果用git log看,你會發現最近一次提交程式設計了f9fae00,後面的歷史記錄消失了。

再切回過去的版本呢?

$ git reset --hard [email protected]{1}HEAD is now at 1aea8d9 add test file x
x檔案回來了。

現在來看一下引數--hard,其實還有其他選項,預設選項是--mixed, 第三個選項是--soft.

--hard是最強的選項,將當前版本設定為某個歷史版本後(通過修改引用檔案/refs/heads/master來實現),staging和working area的內容也和那個歷史版本完全一致。這就意味著你的某些檔案可能就失蹤了,像x檔案一樣。

--mixed是預設選項,它修改引用檔案,不改變working area的檔案,但是staging 內容已經和歷史版本一致。

--soft是最弱選項,它只修改引用檔案,不改變staging和working area的檔案。

所以如果看到這個命令:

git reset --hard HEAD

意思是將staging和working area的檔案恢復到HEAD指向的引用檔案包含的commit id對應的那個版本。

這個命令git stash內部會呼叫。

push的時候會遇到問題,需要加上--force選項強制push

git push --force