顯示具有 git 標籤的文章。 顯示所有文章
顯示具有 git 標籤的文章。 顯示所有文章

星期五, 9月 16, 2016

Git Reset, Checkout, and Revert



REF:
https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/summary


* Git Checkout
Q: 寫程式常常會覺得某一個版本寫的code是比較好,想從某個commit再重寫新版本,要如何做?

1. 可以用git checkout把某個commit 的code調出來檢視,由於此時HEAD指向該commit,不屬於任何branch,如果從這版本有修改新的程式碼,會造成不屬於任何branch,這些修改就算有commit,之後切到其它branch,所有改的內容也會遺失。
2. 解決方式: 1. 可以用git checkout把某個commit 的code調出來檢視,接著建立新的branch,check out到這branch後,再開始修改 code,把新的code套用commit在這新的branch後,就可以解決這問題。

Moving `HEAD` to an arbitrary commit
ref: https://www.atlassian.com/git/images/tutorials/advanced/resetting-checking-out-and-reverting/05.svg


* Git Reset
1. 有時候改的程式碼不小心commit或加到staged,用這指令可以把staged及commit的檔案全部變成unstaged,還原原始狀態。git reset --hard會把所有的檔案還原到最近一次commit的狀態,使用者任何修改過的檔案及狀態都會被移除。
2. 可以用來把某commit的程式碼全部移除掉,會造成該commit之後的其它commit也會被移除救不回,要小心使用。


Resetting the hotfix branch to HEAD~2
REF:https://www.atlassian.com/git/images/tutorials/advanced/resetting-checking-out-and-reverting/02.svg

*Git Revert
1. 有時候過了很久才發現某改commit的程式碼改錯了,某個function不能用,但是之後的程式碼改很多,又不想重寫,可以用revert指令。
2. Git Revert指令有點像先刪除某個commit所作的動作,再套用該commit之後其它commits的變更,然後建立新commit。




Reverting the 2nd to last commit
REF: https://www.atlassian.com/git/images/tutorials/advanced/resetting-checking-out-and-reverting/06.svg









星期日, 5月 29, 2016

Git 使用心得及記錄

0. 本地Commit有誤時,如何處理?
=>用reset
解法:
1. git reset --mixed (預設),  repo的commit會取消,目前workspace己修改的檔案內容會保留,(就是好像退回到連add都沒做的狀態,好像什麼事都沒發生)

git reset HEAD file ( which by default is using the --mixed flag) is different in that in the case where the file is already in the repo, it replaces the index version of the file with the one from repo (HEAD), effectively unstaging the modifications to it.


2. git reset --soft, repo的commit會取消,stage中會保持該取消的commit中的變更資料,(就是好像退回到原add的動作)。
3. git reset --hard, repo的commit會取消,會把workspace目前修改的檔案刪除,worksapce中的檔案會回到前一次commit的內容,所有這次改的資料都會不見。


可參考影片: https://www.youtube.com/watch?v=gVByWjwetVc

1. 如果不小心把本地端檔案殺掉了,但是reposity之前有儲存,要如何救回來?很簡單,就再從reposity checkout就好了。

2. Check out 會不會把目前目錄下的資料全部清除?
 答案是會全把舊的資料全殺光,所以checkout之前要記得先commit或備份,以免損失慘重。

3. 把檔案用git add加到stage後,在workspace再修改,此時再commit時,檔案會用那個版本的?

Ans: 檔案會用staged的版本。workspace修改的版本或資料並不會commit進去。
(If I modify a file that is added, and retry the commit, the changes aren't recognized, so the commit will fail again.)

解決方法1: 再用git add重做一次就好
解決方法2: 先用預設 reset的命令(--mixed),取消stage的動作(此時不會覆蓋workspace的版本),再重新commit就好。

注意: 千萬不要亂下git reset -hard,會把workspace目前修改的檔案刪除 

https://stackoverflow.com/questions/27776588/modifying-a-file-after-git-add

http://lib.csdn.net/article/git/28621