為什么要用版本控制?
假設你在的公司要上線一個新功能,你們開發團隊為實現這個新功能,寫了大約5000行代碼,上線沒2天,就發現這個功能用戶並不喜歡,你老板讓你去掉這個功能,你怎么辦?你說簡單,直接把5000行代碼去掉就行了,但是我的親,說的簡單,你的這個功能寫了3周時間,但你還能記得你是新增加了哪5000行代碼么?所以你急需要一個工具,能幫你記錄每次對代碼做了哪些修改,並且可以輕易的把代碼回滾到歷史上的某個狀態。 這個神奇的工具就叫做版本控制。
版本控制工具主要實現2個功能:
版本管理
在開發中,這是剛需,必須允許可以很容易對產品的版本進行任意回滾,版本控制工具實現這個功能的原理簡單來講,就是你每修改一次代碼,它就幫你做一次快照
協作開發
一個復雜點的軟件,往往不是一個開發人員可以搞定的,公司為加快產品開發速度,會招聘一堆跟你一樣的開發人員開發這個產品,拿微信來舉例,現在假設3個人一起開發微信,A開發聯系人功能,B開發發文字、圖片、語音通訊功能,C開發視頻通話功能, B和C的功能都是要基於通訊錄的,你說簡單,直接把A開發的代碼copy過來,在它的基礎上開發就好了,可以,但是你在他的代碼基礎上開發了2周后,這期間A沒閑着,對通訊錄代碼作了更新,此時怎么辦?你和他的代碼不一致了,此時我們知道,你肯定要再把A的新代碼拿過來替換掉你手上的舊通訊錄功能代碼, 現在人少,3個人之間溝通很簡單,但想想,如果團隊變成30個人呢?來回這樣copy代碼,很快就亂了, 所以此時亟需一個工具,能確保一直存儲最新的代碼庫,所有人的代碼應該和最新的代碼庫保持一致
常見版本管理工具介紹
1、VSS-- Visual Source Safe
此工具是Microsoft提供的,是使用的相當普遍的工具之一,他可以與VS.net進行無縫集成,成為了獨立開發人員和小型開發團隊所適合的工具,基本上Window平台上開發的中小型企業,當規模較大后,其性能通常是無法忍受的,對分支與並行開發支持的比較有限。
2、CVS--Concurrent Versions System,
此工具是一個開源工具,與后面提到的SVN是同一個廠家:Collab.Net提供的。
CVS是源於unix的版本控制工具,對於CVS的安裝和使用最好對unix的系統有所了解能更容易學習,CVS的服務器管理需要進行各種命令行操作。目前,CVS的客戶端有winCVS的圖形化界面,服務器端也有CVSNT的版本,易用性正在提高。
此工具是相當著名,使用得相當廣泛的版本控制工具之一,使用成熟的“Copy-Modify-Merge"開發模型,可以大大的提高開發效率,適合於項目比較大,產品發布頻繁,分支活動頻繁的中大型項目。
3、SVN --CollabNet Subversion
此工具是在CVS 的基礎上,由CollabNet提供開發的,也是開源工具,應用比較廣泛。
他修正cvs的一些局限性,適用范圍同cvs,目前有一些基於SVN的第三方工具,如TortoiseSVN,是其客戶端程序,使用的也相當廣泛。在權限管理,分支合並等方面做的很出色,他可以與Apache集成在一起進行用戶認證。
不過在權限管理方面目前還沒有個很好用的界面化工具,SVNManger對於已經使用SVN進行配置的項目來說,基本上是無法應用的,但對於從頭開始的項目是可以的,功能比較強大,但是搭建svnManger比較麻煩。
是一個跨平台的軟件,支持大多數常見的操作系統。作為一個開源的版本控制系統,Subversion 管理着隨時間改變的數據。 這些數據放置在一個中央資料檔案庫中。 這個檔案庫很像一個普通的文件服務器, 不過它會記住每一次文件的變動。 這樣你就可以把檔案恢復到舊的版本, 或是瀏覽文件的變動歷史。Subversion 是一個通用的系統, 可用來管理任何類型的文件, 其中包括了程序源碼。
4. GIT
因為最初是從Linux起家的,非常依賴文件系統的一些特性,這些在 Linux 下表現的很好,而 Windows 下特別糟糕Git 中文教程
Git是一個開源的分布式版本控制系統,用以有效、高速的處理從很小到非常大的項目版本管理.
Git 是 Linus Torvalds 為了幫助管理 Linux 內核開發而開發的一個開放源碼的版本控制軟件。
Torvalds 開始着手開發 Git 是為了作為一種過渡方案來替代 BitKeeper,后者之前一直是 Linux 內核開發人員在全球使用的主要源代碼工具。開放源碼社區中的有些人覺得 BitKeeper 的許可證並不適合開放源碼社區的工作,因此 Torvalds 決定着手研究許可證更為靈活的版本控制系統。盡管最初 Git 的開發是為了輔助 Linux 內核開發的過程,但是我們已經發現在很多其他自由軟件項目中也使用了 Git。例如 最近就遷移到 Git 上來了,很多 Freedesktop 的項目也遷移到了 Git 上。
5、BitKeeper
是由BitMover公司提供的,BitKeeper自稱是“分布式”可擴縮SCM系統。
不是采用C/S結構,而是采用P2P結構來實現的,同樣支持變更任務,所有變更集的操作都是原子的,與svn,cvs一致。
github介紹
很多人都知道,Linus在1991年創建了開源的Linux,從此,Linux系統不斷發展,已經成為最大的服務器系統軟件了。
Linus雖然創建了Linux,但Linux的壯大是靠全世界熱心的志願者參與的,這么多人在世界各地為Linux編寫代碼,那Linux的代碼是如何管理的呢?
事實是,在2002年以前,世界各地的志願者把源代碼文件通過diff的方式發給Linus,然后由Linus本人通過手工方式合並代碼!
你也許會想,為什么Linus不把Linux代碼放到版本控制系統里呢?不是有CVS、SVN這些免費的版本控制系統嗎?因為Linus堅定地反對CVS和SVN,這些集中式的版本控制系統不但速度慢,而且必須聯網才能使用。有一些商用的版本控制系統,雖然比CVS、SVN好用,但那是付費的,和Linux的開源精神不符。
不過,到了2002年,Linux系統已經發展了十年了,代碼庫之大讓Linus很難繼續通過手工方式管理了,社區的弟兄們也對這種方式表達了強烈不滿,於是Linus選擇了一個商業的版本控制系統BitKeeper,BitKeeper的東家BitMover公司出於人道主義精神,授權Linux社區免費使用這個版本控制系統。
安定團結的大好局面在2005年就被打破了,原因是Linux社區牛人聚集,不免沾染了一些梁山好漢的江湖習氣。開發Samba的Andrew試圖破解BitKeeper的協議(這么干的其實也不只他一個),被BitMover公司發現了(監控工作做得不錯!),於是BitMover公司怒了,要收回Linux社區的免費使用權。
Linus可以向BitMover公司道個歉,保證以后嚴格管教弟兄們,嗯,這是不可能的。實際情況是這樣的:
Linus花了兩周時間自己用C寫了一個分布式版本控制系統,這就是Git!一個月之內,Linux系統的源碼已經由Git管理了!牛是怎么定義的呢?大家可以體會一下。
Git迅速成為最流行的分布式版本控制系統,尤其是2008年,GitHub網站上線了(github是一個基於git的代碼托管平台,付費用戶可以建私人倉庫,我們一般的免費用戶只能使用公共倉庫,也就是代碼要公開。),它為開源項目免費提供Git存儲,無數開源項目開始遷移至GitHub,包括jQuery,PHP,Ruby等等。
歷史就是這么偶然,如果不是當年BitMover公司威脅Linux社區,可能現在我們就沒有免費而超級好用的Git了。
今天,GitHub已是:
- 一個擁有143萬開發者的社區。其中不乏Linux發明者Torvalds這樣的頂級黑客,以及Rails創始人DHH這樣的年輕極客。
- 這個星球上最流行的開源托管服務。目前已托管431萬git項目,不僅越來越多知名開源項目遷入GitHub,比如Ruby on Rails、jQuery、Ruby、Erlang/OTP;近三年流行的開源庫往往在GitHub首發,例如:BootStrap、Node.js、CoffeScript等。
- alexa全球排名414的網站。
git安裝
官網:https://git-scm.com/downloads
版本庫創建
什么是版本庫呢?版本庫又名倉庫,英文名repository,你可以簡單理解成一個目錄,這個目錄里面的所有文件都可以被Git管理起來,每個文件的修改、刪除,Git都能跟蹤,以便任何時刻都可以追蹤歷史,或者在將來某個時刻可以“還原”。
所以,創建一個版本庫非常簡單,首先,選擇一個合適的地方,創建一個空目錄:
shuais-MBP:~ dandyzhang$ mkdir git_test shuais-MBP:~ dandyzhang$ cd git_test shuais-MBP:git_test dandyzhang$ git init Initialized empty Git repository in /Users/dandyzhang/git_test/.git/
瞬間Git就把倉庫建好了,而且告訴你是一個空的倉庫(empty Git repository),細心的讀者可以發現當前目錄下多了一個.git
的目錄,這個目錄是Git來跟蹤管理版本庫的,沒事千萬不要手動修改這個目錄里面的文件,不然改亂了,就把Git倉庫給破壞了。
如果你沒有看到.git
目錄,那是因為這個目錄默認是隱藏的,用ls -ah
命令就可以看見。
shuais-MBP:git_test dandyzhang$ ls -ah . .. .git
把文件添加到版本庫
首先這里再明確一下,所有的版本控制系統,其實只能跟蹤文本文件的改動,比如TXT文件,網頁,所有的程序代碼等等,Git也不例外。版本控制系統可以告訴你每次的改動,比如在第5行加了一個單詞“Linux”,在第8行刪了一個單詞“Windows”。而圖片、視頻這些二進制文件,雖然也能由版本控制系統管理,但沒法跟蹤文件的變化,只能把二進制文件每次改動串起來,也就是只知道圖片從100KB改成了120KB,但到底改了啥,版本控制系統不知道,也沒法知道。
不幸的是,Microsoft的Word格式是二進制格式,因此,版本控制系統是沒法跟蹤Word文件的改動的,前面我們舉的例子只是為了演示,如果要真正使用版本控制系統,就要以純文本方式編寫文件。
因為文本是有編碼的,比如中文有常用的GBK編碼,日文有Shift_JIS編碼,如果沒有歷史遺留問題,強烈建議使用標准的UTF-8編碼,所有語言使用同一種編碼,既沒有沖突,又被所有平台所支持。
言歸正傳,現在我們編寫一個first_git_file.txt文件,內容如下:
shuais-MBP:git_test dandyzhang$ vim first_git_file.txt first time using git, hello git!
一定要放到git_trainning目錄下(子目錄也行),因為這是一個Git倉庫,放到其他地方Git再厲害也找不到這個文件。
和把大象放到冰箱需要3步相比,把一個文件放到Git倉庫只需要兩步。
第一步,用命令git add
告訴Git,把文件添加到倉庫:
shuais-MBP:git_test dandyzhang$ git add first_git_file.txt
執行上面的命令,沒有任何顯示,說明添加成功。
這時候我們再創建一個文件readme,不add到倉庫
shuais-MBP:git_test dandyzhang$ vim Readme this is readme file
此時使用status查看狀態:
shuais-MBP:git_test dandyzhang$ git status On branch master No commits yet Changes to be committed: (use "git rm --cached <file>..." to unstage) new file: first_git_file.txt Untracked files: (use "git add <file>..." to include in what will be committed) Readme
add后的文件first_git_file.txt被追蹤了,而沒有添加進git倉庫的則不會追蹤,空文件夾也不會顯示。
第二步,用命令git commit
告訴Git,把文件提交到倉庫,即上文被追蹤的文件已經被管理:
shuais-MBP:git_test dandyzhang$ git commit hint: Waiting for your editor to close the file... # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # # Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan> # # On branch master # # Initial commit # # Changes to be committed: # new file: first_git_file.txt # # Untracked files: # Readme # ~ ~ ~ ~ ~ ~ ~ "~/git_test/.git/COMMIT_EDITMSG" 16L, 321C
這里又進入到vim編輯模式,git在提示你寫入文件新建或更改的理由,原因或備注,加入備注在首行:
git first test... # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # # Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan> # # On branch master # # Initial commit # # Changes to be committed: # new file: first_git_file.txt # # Untracked files: # Readme #
保存:
shuais-MBP:git_test dandyzhang$ git commit [master (root-commit) 8dfa740] git first test... Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan> Your name and email address were configured automatically based on your username and hostname. Please check that they are accurate. You can suppress this message by setting them explicitly. Run the following command and follow the instructions in your editor to edit your configuration file: git config --global --edit After doing this, you may fix the identity used for this commit with: git commit --amend --reset-author 1 file changed, 1 insertion(+) create mode 100644 first_git_file.txt
此時查看status:
shuais-MBP:git_test dandyzhang$ git status On branch master Untracked files: (use "git add <file>..." to include in what will be committed) Readme nothing added to commit but untracked files present (use "git add" to track)
發現只有readme存在。
中間紅色部分的意思是,你在往git庫里提交代碼時,你需要告訴git你是誰,這樣git就會紀錄下來是誰改的代碼,其實就是為了日后查詢方便,你只需要提供一個名字和郵件地址就可以,這里我的git直接通過主機名自己創建了一個,但你可以通過git config --global --edit修改
簡單解釋一下git commit
命令,-m
后面輸入的是本次提交的說明,可以輸入任意內容,當然最好是有意義的,這樣你就能從歷史記錄里方便地找到改動記錄。
嫌麻煩不想輸入-m "xxx"
行不行?確實有辦法可以這么干,但是強烈不建議你這么干,因為輸入說明對自己對別人閱讀都很重要。
為什么Git添加文件需要add
,commit
一共兩步呢?因為commit
可以一次提交很多文件,所以你可以多次add
不同的文件,相當於修改了項目的多個地方的代碼最后統一commit,比如:
$ git add file1.txt $ git add file2.txt file3.txt $ git commit -m "add 3 files."
代碼回滾
1、代碼修改並提交
我們已經成功地添加並提交了一個first_git_file.txt文件,現在,是時候繼續工作了,於是,我們繼續修改first_git_file.txt文件,改成如下內容:
shuais-MBP:git_test dandyzhang$ vim first_git_file.txt first time using git, hello git! update(one) insert one line here....
現在,運行git status
命令看看結果:
shuais-MBP:git_test dandyzhang$ git status On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: first_git_file.txt Untracked files: (use "git add <file>..." to include in what will be committed) Readme no changes added to commit (use "git add" and/or "git commit -a")
雖然Git告訴我們first_git_file.txt被修改了,但如果能看看具體修改了什么內容,自然是很好的。比如你休假兩周從國外回來,第一天上班時,已經記不清上次怎么修改的readme.txt,所以,需要用git diff
這個命令看看:
shuais-MBP:git_test dandyzhang$ git diff first_git_file.txt diff --git a/first_git_file.txt b/first_git_file.txt index 5f48045..7581c01 100644 --- a/first_git_file.txt +++ b/first_git_file.txt @@ -1 +1,2 @@ -first time using git, hello git! +first time using git, hello git! update(one) +insert one line here....
輸出中+號綠色顯示的就是修改或新增的內容,-號紅色顯示的就是去掉或被修改的內容
知道了對first_git_file.txt 作了什么修改后,再把它提交到倉庫就放心多了,提交修改和提交新文件是一樣的兩步,第一步是git add:
shuais-MBP:git_test dandyzhang$ git add . # 代表把當前目錄下所有改動的文件都提交到代碼庫 shuais-MBP:git_test dandyzhang$ git commit -m 'commit changes 2' [master f31af7b] commit changes 2 Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan> Your name and email address were configured automatically based on your username and hostname. Please check that they are accurate. You can suppress this message by setting them explicitly. Run the following command and follow the instructions in your editor to edit your configuration file: git config --global --edit After doing this, you may fix the identity used for this commit with: git commit --amend --reset-author 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 Readme shuais-MBP:git_test dandyzhang$
如果上面的操作,add之后我們插入一個status操作,會得到提示,一個文件被修改另一個未被跟蹤。
commit之后再查看status:
shuais-MBP:git_test dandyzhang$ git status
On branch master
nothing to commit, working tree clean
shuais-MBP:git_test dandyzhang$
這時本地文件狀態就全部被清空了。Git告訴我們當前沒有需要提交的修改,而且,工作目錄是干凈(working directory clean)的。
此時,再修改下readme:
shuais-MBP:git_test dandyzhang$ vim Readme this is readme file insert one line...second times. shuais-MBP:git_test dandyzhang$ git add . shuais-MBP:git_test dandyzhang$ git commit -m 'second time modified readme.' [master f557e4f] second time modified readme. Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan> Your name and email address were configured automatically based on your username and hostname. Please check that they are accurate. You can suppress this message by setting them explicitly. Run the following command and follow the instructions in your editor to edit your configuration file: git config --global --edit After doing this, you may fix the identity used for this commit with: git commit --amend --reset-author 1 file changed, 1 insertion(+)
代碼回滾
上面已經又修改過文件了,有興趣的話可以多測試幾次
像這樣,你不斷對文件進行修改,然后不斷提交修改到版本庫里,就好比玩RPG游戲時,每通過一關就會自動把游戲狀態存盤,如果某一關沒過去,你還可以選擇讀取前一關的狀態。有些時候,在打Boss之前,你會手動存盤,以便萬一打Boss失敗了,可以從最近的地方重新開始。Git也是一樣,每當你覺得文件修改到一定程度的時候,就可以“保存一個快照”,這個快照在Git中被稱為commit
。一旦你把文件改亂了,或者誤刪了文件,還可以從最近的一個commit
恢復,然后繼續工作,而不是把幾個月的工作成果全部丟失。
現在,測試過幾次之后,大家應該也不會很清晰的記得文件的修改情況和版本明細了。並且在實際工作中,我們腦子里怎么也不可能記得一個幾千行的文件每次都改了什么內容,不然要版本控制系統干什么。版本控制系統肯定有某個命令可以告訴我們歷史記錄,在Git中,我們用git log
命令查看:
shuais-MBP:git_test dandyzhang$ git log commit f557e4fcd45978b358f21b75e87cfe2f80f381b7 (HEAD -> master) Author: 衰 Zzz <dandyzhang@shuais-MBP.lan> Date: Wed Jul 4 22:59:02 2018 +0800 second time modified readme. commit f31af7bf79a2b0114eb9d1adcac82b4fa7128a2b Author: 衰 Zzz <dandyzhang@shuais-MBP.lan> Date: Wed Jul 4 22:50:20 2018 +0800 commit changes 2 commit 8dfa74052ee22ef3f86b51424172df60c23778c6 Author: 衰 Zzz <dandyzhang@shuais-MBP.lan> Date: Wed Jul 4 22:27:56 2018 +0800 git first test...
git log
命令顯示從最近到最遠的提交日志,可以看到日志一共記錄了,第一次測試跟兩次修改;如果嫌輸出信息太多,看得眼花繚亂的,可以試試加上--pretty=oneline
參數:
shuais-MBP:git_test dandyzhang$ git log --pretty=oneline f557e4fcd45978b358f21b75e87cfe2f80f381b7 (HEAD -> master) second time modified readme. f31af7bf79a2b0114eb9d1adcac82b4fa7128a2b commit changes 2 8dfa74052ee22ef3f86b51424172df60c23778c6 git first test...
需要友情提示的是,你看到的一大串類似3628164...882e1e0
的是commit id
(版本號),和SVN不一樣,Git的commit id
不是1,2,3……遞增的數字,而是一個SHA1計算出來的一個非常大的數字,用十六進制表示,而且你看到的commit id
和我的肯定不一樣,以你自己的為准。為什么commit id
需要用這么一大串數字表示呢?因為Git是分布式的版本控制系統,后面我們還要研究多人在同一個版本庫里工作,如果大家都用1,2,3……作為版本號,那肯定就沖突了。
回滾!!!
好了,現在我們啟動時光穿梭機,准備把readme回退到上一個版本,即‘commit changes 2’版本,怎么做呢?
首先,Git必須知道當前版本是哪個版本,在Git中,用HEAD
表示當前版本,也就是最新的提交f557e4fcd45978b358f21b75e87cfe2f80f381b7(注意我的提交ID和你的肯定不一樣),上一個版本就是HEAD^
,上上一個版本就是HEAD^^
,當然往上100個版本寫100個^
比較容易數不過來,所以寫成HEAD~100
。
小插曲:
寫的太忘我,忘記添加global user.mail&user.name參數。目前,以我的測試,如果不設置話,文件是不會回滾的。 為什么設置? 很大程度上,一方面日志里記錄了,更新的用戶的名字郵箱,如果遇到問題或者不理解的地方,可以及時聯系開發者。
所以,別激動,先添加參數,添加好再修改一次文件:
shuais-MBP:git_test dandyzhang$ git config --global user.email 'wuzdandz@163.com'
shuais-MBP:git_test dandyzhang$ git config --global user.name 'dandy zhang'
shuais-MBP:git_test dandyzhang$ vim Readme # 這里就不再費勁記錄了,隨便加點東西就好了。
shuais-MBP:git_test dandyzhang$ git add .
shuais-MBP:git_test dandyzhang$ git commit # 忘記加備注了。。。。
[master b958914] update readme third times
1 file changed, 1 insertion(+)
這時候查看日志:
現在,我們要把當前版本“update readme third times”回退到上一個版本“second time modified readme.”,就可以使用git reset
命令:
shuais-MBP:git_test dandyzhang$ git reset --hard HEAD^
HEAD is now at f557e4f second time modified readme.
shuais-MBP:git_test dandyzhang$ vim Readme
this is readme file
insert one line...second times.
完美!
這時候,也許你會重新查看log:
shuais-MBP:git_test dandyzhang$ git log commit f557e4fcd45978b358f21b75e87cfe2f80f381b7 (HEAD -> master) Author: 衰 Zzz <dandyzhang@shuais-MBP.lan> Date: Wed Jul 4 22:59:02 2018 +0800 second time modified readme. commit f31af7bf79a2b0114eb9d1adcac82b4fa7128a2b Author: 衰 Zzz <dandyzhang@shuais-MBP.lan> Date: Wed Jul 4 22:50:20 2018 +0800 commit changes 2 commit 8dfa74052ee22ef3f86b51424172df60c23778c6 Author: 衰 Zzz <dandyzhang@shuais-MBP.lan> Date: Wed Jul 4 22:27:56 2018 +0800 git first test...
發現最新的一版已經不見了。假如是真的要回滾到對應的版本倒是還好,可是,如果是沒注意選錯了,就沒辦法更改了么?
辦法其實還是有的,只要上面的命令行窗口還沒有被關掉,你就可以順着往上找啊找啊,找到那個add new content的commit id是
b9589146dd0eeb4f6b6eb5347e7cb373a1c55533,於是就可以指定回到未來的某個版本:
shuais-MBP:git_test dandyzhang$ git reset --hard b95891
HEAD is now at b958914 update readme third times
版本號沒必要寫全,前幾位就可以了,Git會自動去找。當然也不能只寫前一兩位,因為Git可能會找到多個版本號,就無法確定是哪一個了。
這時候再,小心翼翼!!的查看一下readme的內容:
shuais-MBP:git_test dandyzhang$ vim Readme
this is readme file
insert one line...second times.
insert one line...third time.
發現版本真的改回來了。
Git的版本回退速度非常快,因為Git在內部有個指向當前版本的HEAD
指針,當你回退版本的時候,Git僅僅是把HEAD從指向update readme third times
現在,你總算是可以回退到了某個版本,開心的一毛,關掉了電腦,第二天早上就后悔了,想恢復到新版本怎么辦?找不到新版本的commit id怎么辦?
在Git中,總是有后悔葯可以吃的。當你用$ git reset --hard HEAD^回退到update again版本時,再想恢復到最新add new content的版本,就必須找到add new contentL的commit id。Git提供了一個命令git reflog用來記錄你的每一次命令:
shuais-MBP:git_test dandyzhang$ git reflog
b958914 (HEAD -> master) HEAD@{0}: reset: moving to b95891
f557e4f HEAD@{1}: reset: moving to HEAD^
b958914 (HEAD -> master) HEAD@{2}: commit: update readme third times
f557e4f HEAD@{3}: commit: second time modified readme.
f31af7b HEAD@{4}: commit: commit changes 2
8dfa740 HEAD@{5}: commit (initial): git first test...
這里,就不演示再回滾然后拿最前面的ID,再復原的過程了。記得reflog這個命令的作用即可,git的回滾的意義,在於將指針指向你所需要回到的某一個版本,但並不會刪掉其他的版本。
也許你還會問這樣一個問題,如果回滾代碼到過去,再在過去的代碼里修改了一些東西,commit之后,后面的版本還存在么?
就像鏈表一樣,鏈子斷開把新的加了進入?還是相當於時光機一般,我回到過去,修改或殺死了小時候的我,未來的我還在么?
其實這里需要解釋一下git的版本存儲機制:
如圖,如果回到二的版本階段,修改了代碼,git會重新定義一個版本。說的恐怖一點,這有點類似於你創造了一個平行宇宙。。
工作區和暫存區
Git和其他版本控制系統如SVN的一個不同之處就是有暫存區的概念。
先來看名詞解釋。
工作區(Working Directory)
就是你在電腦里能看到的目錄,比如我的git_test文件夾就是一個工作區:
shuais-MacBook-Pro:~ dandyzhang$ cd git_test/ shuais-MacBook-Pro:git_test dandyzhang$ ls Readme first_git_file.txt
版本庫(Repository)
工作區有一個隱藏目錄.git
,這個不算工作區,而是Git的版本庫。
Git的版本庫里存了很多東西,其中最重要的就是稱為stage(或者叫index)的暫存區,還有Git為我們自動創建的第一個分支master
,以及指向master
的一個指針叫HEAD
。
分支和HEAD
的概念我們以后再講。
前面講了我們把文件往Git版本庫里添加的時候,是分兩步執行的:
第一步是用git add
把文件添加進去,實際上就是把文件修改添加到暫存區;
第二步是用git commit
提交更改,實際上就是把暫存區的所有內容提交到當前分支。
因為我們創建Git版本庫時,Git自動為我們創建了唯一一個master
分支,所以,現在,git commit
就是往master
分支上提交更改。
你可以簡單理解為,需要提交的文件修改通通放到暫存區,然后,一次性提交暫存區的所有修改。
之前,我們先創建了一個git_first_file.txt並add&commit,然后進行了修改並add&commit,最后又建了一個新readme並add&commit。
當在工作區添加了一個readme文件,沒有加入stage的時候。status查看的時候,很明顯git在提示readme是untracked files
此時再將readme add到git的stage,status轉成了new file。
現在,暫存區的狀態就變成這樣了:
備注一下:盜的圖,這里readme.txt = first_git_file.txt , LICENSE = readme.md
所以,git add
命令實際上就是把要提交的所有修改放到暫存區(Stage),然后,執行git commit
就可以一次性把暫存區的所有修改提交到分支。
有點相當於,用鼠標選中了這么多文件,進行commit。
一旦提交后,如果你又沒有對工作區做任何修改,那么工作區就是“干凈”的:
$ git status
On branch master
nothing to commit, working directory clean
現在版本庫變成了這樣,暫存區就沒有任何內容了:
(備注一下,盜的圖, 這里readme.txt = first_git_file.txt , LICENSE = readme.md)
暫存區是Git非常重要的概念,弄明白了暫存區,就弄明白了Git的很多操作到底干了什么。
撤銷修改
某天,你在做某個boss的很奇怪的需求,各種奇葩,火大的很,直接在readme最后寫了句:
shuais-MacBook-Pro:git_test dandyzhang$ vim Readme this is readme file insert one line...second times. insert one line...third time. fuck IT Director.
在你准備提交前,一杯咖啡起了作用,你猛然發現了有點上頭,“fuck IT Director .”可能會讓你丟掉績效獎金
既然錯誤發現得很及時,就可以很容易地糾正它。你刪除了這句話,手動把文件恢復到上一個版本的狀態。如果用git status
查看一下:
shuais-MacBook-Pro:git_test dandyzhang$ git status On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: Readme no changes added to commit (use "git add" and/or "git commit -a")
你可以發現,Git會告訴你,git checkout -- file
可以丟棄工作區的修改:
shuais-MacBook-Pro:git_test dandyzhang$ git checkout -- Readme shuais-MacBook-Pro:git_test dandyzhang$ vim Readme this is readme file insert one line...second times. insert one line...third time.
你剛才添加的 一行罵老板的話就被撤銷了,
命令git checkout -- readme.md
意思就是,把readme.md
文件在工作區的修改全部撤銷,這里有兩種情況:
一種是readme.md
自修改后還沒有被放到暫存區,現在,撤銷修改就回到和版本庫一模一樣的狀態;
一種是readme.md
已經添加到暫存區后,又作了修改,現在,撤銷修改就回到添加到暫存區后的狀態。
總之,就是讓這個文件回到最近一次git commit
或git add
時的狀態。
git checkout -- file
命令中的--
很重要,沒有--
,就變成了“切換到另一個分支”的命令,我們在后面的分支管理中會再次遇到git checkout
命令。
現在假定是凌晨3點,你不但寫了一些胡話,還git add
到暫存區了:
shuais-MacBook-Pro:git_test dandyzhang$ vim Readme this is readme file insert one line...second times. insert one line...third time. Fuck manager's requirement. So stupid. shuais-MacBook-Pro:git_test dandyzhang$ git add Readme
慶幸的是,在commit
之前,你發現了這個問題。用git status
查看一下,修改只是添加到了暫存區,還沒有提交:
shuais-MacBook-Pro:git_test dandyzhang$ git status On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: Readme
Git同樣告訴我們,用命令git reset HEAD file
可以把暫存區的修改撤銷掉(unstage),重新放回工作區:
shuais-MacBook-Pro:git_test dandyzhang$ git reset HEAD Readme
Unstaged changes after reset:
M Readme
git reset
命令既可以回退版本,也可以把暫存區的修改回退到工作區。當我們用HEAD
時,表示最新的版本。
再用git status
查看一下,現在暫存區是干凈的,工作區有修改。
shuais-MacBook-Pro:git_test dandyzhang$ git status On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: Readme no changes added to commit (use "git add" and/or "git commit -a")
還記得如何丟棄工作區的修改嗎?
shuais-MacBook-Pro:git_test dandyzhang$ git checkout -- Readme shuais-MacBook-Pro:git_test dandyzhang$ git status On branch master nothing to commit, working tree clean
哈哈,這個世界終於清靜了!!
記得千萬別commit!!!commit完就已經被git進行版本控制了,再怎么刪除也會有記錄。除非刪除代碼庫。
em....... 這是個不錯的想法。可能你需要收拾下行李,找下一家了。
刪除操作
在Git中,刪除也是一個修改操作,我們實戰一下,先添加一個新文件test.txt到Git並且提交:
shuais-MacBook-Pro:git_test dandyzhang$ vim test.txt this is a test file. shuais-MacBook-Pro:git_test dandyzhang$ git add . shuais-MacBook-Pro:git_test dandyzhang$ git commit -m 'add a new test.txt file' [master f6afa4f] add a new test.txt file 1 file changed, 1 insertion(+) create mode 100644 test.txt
一般情況下,你通常直接在文件管理器中把沒用的文件刪了,或者用rm
命令刪了:
shuais-MacBook-Pro:git_test dandyzhang$ rm test.txt
這個時候,Git知道你刪除了文件,因此,工作區和版本庫就不一致了,git status
命令會立刻告訴你哪些文件被刪除了:
shuais-MacBook-Pro:git_test dandyzhang$ git status On branch master Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) deleted: test.txt no changes added to commit (use "git add" and/or "git commit -a")
現在你有兩個選擇,一是確實要從版本庫中刪除該文件,那就用命令git rm
刪掉,並且git commit
:
shuais-MacBook-Pro:git_test dandyzhang$ git rm test.txt rm 'test.txt' shuais-MacBook-Pro:git_test dandyzhang$ git commit -m 'delete test.txt file' [master b172a52] delete test.txt file 1 file changed, 1 deletion(-) delete mode 100644 test.txt
現在,文件就從版本庫中被刪除了。
另一種情況是刪錯了,因為版本庫里還有呢,所以可以很輕松地把誤刪的文件恢復到最新版本:
shuais-MacBook-Pro:git_test dandyzhang$ git checkout -- test.txt
git checkout
其實是用版本庫里的版本替換工作區的版本,無論工作區是修改還是刪除,都可以“一鍵還原”。
遠程倉庫
到目前為止,我們已經掌握了如何在Git倉庫里對一個文件進行時光穿梭,你再也不用擔心文件備份或者丟失的問題了。
可是有用過集中式版本控制系統SVN的童鞋會站出來說,這些功能在SVN里早就有了,沒看出Git有什么特別的地方。
沒錯,如果只是在一個倉庫里管理文件歷史,Git和SVN真沒啥區別。為了保證你現在所學的Git物超所值,將來絕對不會后悔,同時為了打擊已經不幸學了SVN的童鞋,本章開始介紹Git的殺手級功能之一(注意是之一,也就是后面還有之二,之三……):遠程倉庫。
Git是分布式版本控制系統,同一個Git倉庫,可以分布到不同的機器上。怎么分布呢?最早,肯定只有一台機器有一個原始版本庫,此后,別的機器可以“克隆”這個原始版本庫,而且每台機器的版本庫其實都是一樣的,並沒有主次之分。
你肯定會想,至少需要兩台機器才能玩遠程庫不是?但是我只有一台電腦,怎么玩?
其實一台電腦上也是可以克隆多個版本庫的,只要不在同一個目錄下。不過,現實生活中是不會有人這么傻的在一台電腦上搞幾個遠程庫玩,因為一台電腦上搞幾個遠程庫完全沒有意義,而且硬盤掛了會導致所有庫都掛掉,所以我也不告訴你在一台電腦上怎么克隆多個倉庫。
實際情況往往是這樣,找一台電腦充當服務器的角色,每天24小時開機,其他每個人都從這個“服務器”倉庫克隆一份到自己的電腦上,並且各自把各自的提交推送到服務器倉庫里,也從服務器倉庫中拉取別人的提交。
完全可以自己搭建一台運行Git的服務器,不過現階段,為了學Git先搭個服務器絕對是小題大作。好在這個世界上有個叫GitHub的神奇的網站,從名字就可以看出,這個網站就是提供Git倉庫托管服務的,所以,只要注冊一個GitHub賬號,就可以免費獲得Git遠程倉庫。
在繼續閱讀后續內容前,請自行注冊GitHub賬號。由於你的本地Git倉庫和GitHub倉庫之間的傳輸是通過SSH加密的,所以,需要一點設置:
第1步:創建SSH Key。在用戶主目錄下,看看有沒有.ssh目錄,如果有,再看看這個目錄下有沒有id_rsa
和id_rsa.pub
這兩個文件,如果已經有了,可直接跳到下一步。如果沒有,打開Shell(Windows下打開Git Bash),創建SSH Key:
shuais-MacBook-Pro:~ dandyzhang$ ssh-keygen -t rsa -C 'wuzdandz@163.com'
你需要把郵件地址換成你自己的郵件地址,然后一路回車,使用默認值即可,由於這個Key也不是用於什么機密,所以也無需設置密碼。
如果一切順利的話,可以在用戶主目錄里找到.ssh
目錄,里面有id_rsa
和id_rsa.pub
兩個文件,這兩個就是SSH Key的秘鑰對,id_rsa
是私鑰,不能泄露出去,id_rsa.pub
是公鑰,可以放心地告訴任何人。
Generating public/private rsa key pair. Enter file in which to save the key (/Users/dandyzhang/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /Users/dandyzhang/.ssh/id_rsa. Your public key has been saved in /Users/dandyzhang/.ssh/id_rsa.pub. The key fingerprint is: SHA256:sNFwTTqMGfE4VInYHtawiA3RVKta8su/zEONeJfvDe4 wuzdandz@163.com The key's randomart image is: +---[RSA 2048]----+ | o+.+B*o+. | | +oo=&o.. | | . ooX.* | | ..= . | | . o..oS. | | =. + + | | . .o . .. | | . +. ..o | | o.=o oE . | +----[SHA256]-----+
第2步:登陸GitHub,打開“Account settings”,“SSH Keys”頁面:
然后,點“Add SSH Key”,填上任意Title,在Key文本框里粘貼id_rsa.pub
文件的內容:
shuais-MacBook-Pro:~ dandyzhang$ ls -ah . .gitconfig Library .. .idlerc Movies .CFUserTextEncoding .python_history Music .DS_Store .ssh Pictures .Trash .viminfo Public .bash_history .wns PycharmProjects .bash_profile Applications git_test .bash_profile.pysave Desktop venv .bash_sessions Documents .downloader Downloads shuais-MacBook-Pro:~ dandyzhang$ cd .ssh shuais-MacBook-Pro:.ssh dandyzhang$ ls id_rsa id_rsa.pub known_hosts shuais-MacBook-Pro:.ssh dandyzhang$ vim id_rsa.pub
點“Add Key”,你就應該看到已經添加的Key
為什么GitHub需要SSH Key呢?因為GitHub需要識別出你推送的提交確實是你推送的,而不是別人冒充的,而Git支持SSH協議,所以,GitHub只要知道了你的公鑰,就可以確認只有你自己才能推送。
當然,GitHub允許你添加多個Key。假定你有若干電腦,你一會兒在公司提交,一會兒在家里提交,只要把每台電腦的Key都添加到GitHub,就可以在每台電腦上往GitHub推送了。
最后友情提示,在GitHub上免費托管的Git倉庫,任何人都可以看到喔(但只有你自己才能改)。所以,不要把敏感信息放進去。
如果你不想讓別人看到Git庫,有兩個辦法,一個是交點保護費,讓GitHub把公開的倉庫變成私有的,這樣別人就看不見了(不可讀更不可寫)。另一個辦法是自己動手,搭一個Git服務器,因為是你自己的Git服務器,所以別人也是看不見的。這個方法我們后面會講到的,相當簡單,公司內部開發必備。
確保你擁有一個GitHub賬號后,我們就即將開始遠程倉庫的學習。
創建遠程倉庫
現在的情景是,你已經在本地創建了一個Git倉庫后,又想在GitHub創建一個Git倉庫,並且讓這兩個倉庫進行遠程同步,這樣,GitHub上的倉庫既可以作為備份,又可以讓其他人通過該倉庫來協作,真是一舉多得。
首先,登陸GitHub,然后,點擊start a project:
藍色的箭頭代表個人的私密項目,需要付費的。
創建好的倉庫:
紅色框1:通過命令行在本地創建一個repo(代碼倉庫),並推到這個剛創建的遠程倉庫上來
紅色框2:把已經寫好代碼的本地倉庫推到遠程來。
紅色框3:從其他的代碼倉庫導入
藍色框是用來選擇鏈接方式。這里我們可以選擇ssh,因為已經建立了公鑰的認證。
目前,在GitHub上的這個Test1倉庫還是空的,GitHub告訴我們,可以從這個倉庫克隆出新的倉庫,也可以把一個已有的本地倉庫與之關聯,然后,把本地倉庫的內容推送到GitHub倉庫。
現在,我們根據GitHub的提示,在本地已有的git_trainning倉庫下運行命令:
shuais-MacBook-Pro:.ssh dandyzhang$ cd .. shuais-MacBook-Pro:~ dandyzhang$ cd git_test shuais-MacBook-Pro:git_test dandyzhang$ ls -af . first_git_file.txt .git .. Readme shuais-MacBook-Pro:git_test dandyzhang$ git remote add origin https://github.com/dandy-weeknd/Test1.git shuais-MacBook-Pro:git_test dandyzhang$ git push -u origin master fatal: unable to access 'https://github.com/dandy-weeknd/Test1.git/': Could not resolve host: github.com shuais-MacBook-Pro:git_test dandyzhang$ git push -u origin master Username for 'https://github.com': wuzdandz@163.com Password for 'https://wuzdandz@163.com@github.com': Enumerating objects: 17, done. Counting objects: 100% (17/17), done. Delta compression using up to 4 threads. Compressing objects: 100% (13/13), done. Writing objects: 100% (17/17), 1.51 KiB | 775.00 KiB/s, done. Total 17 (delta 3), reused 0 (delta 0) remote: Resolving deltas: 100% (3/3), done. To https://github.com/dandy-weeknd/Test1.git * [new branch] master -> master Branch 'master' set up to track remote branch 'master' from 'origin'.
這里先選用的是HTTPS的方式來提交代碼倉庫源代碼;此時刷新頁面;
從現在起,只本地做了提交,就可以通過命令:
git push origin master
直接提交到遠程源代碼倉庫:
shuais-MacBook-Pro:git_test dandyzhang$ vim index.html <html> <head></head> <body> github first index html ! </body> </html> shuais-MacBook-Pro:git_test dandyzhang$ git add . shuais-MacBook-Pro:git_test dandyzhang$ git commit [master 325453e] github first text file ! 1 file changed, 6 insertions(+) create mode 100644 index.html shuais-MacBook-Pro:git_test dandyzhang$ shuais-MacBook-Pro:git_test dandyzhang$ git push origin master Enumerating objects: 4, done. Counting objects: 100% (4/4), done. Delta compression using up to 4 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), 382 bytes | 382.00 KiB/s, done. Total 3 (delta 0), reused 0 (delta 0) To https://github.com/dandy-weeknd/Test1.git b172a52..325453e master -> master
刷新一下遠程倉庫:
可以看到文件已經更新過來,並且上面有個7commits。點進去看一下:
從遠程庫克隆
我們講了先有本地庫,后有遠程庫的時候,如何關聯遠程庫。
現在,假設我們從零開發,那么最好的方式是先創建遠程庫,然后,從遠程庫克隆。
首先,登陸GitHub,創建一個新的倉庫,名字叫Test2_From_Github:
:
我們勾選Initialize this repository with a README
,這樣GitHub會自動為我們創建一個README.md
文件。創建完畢后,可以看到README.md
文件:
現在,遠程庫已經准備好了,下一步是用命令git clone
克隆一個本地庫:
在本地找一個你想存放這個遠程倉庫的目錄,然后在本地命令行用git clone 命令來克隆這個遠程庫:
shuais-MacBook-Pro:~ dandyzhang$ mkdir git_test2 shuais-MacBook-Pro:~ dandyzhang$ cd git_test2 shuais-MacBook-Pro:git_test2 dandyzhang$ git clone https://github.com/dandy-weeknd/Test2_From_Github.git Cloning into 'Test2_From_Github'... remote: Counting objects: 3, done. remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0 Unpacking objects: 100% (3/3), done. shuais-MacBook-Pro:git_test2 dandyzhang$ ls Test2_From_Github shuais-MacBook-Pro:git_test2 dandyzhang$ ls -af . .. Test2_From_Github shuais-MacBook-Pro:git_test2 dandyzhang$ cd Test2_From_Github/ shuais-MacBook-Pro:Test2_From_Github dandyzhang$ ls -af . .. README.md .git
如果有多個人協作開發,那么每個人各自從遠程克隆一份就可以了。
你也許還注意到,GitHub給出的地址不止一個,還可以用https://github.com/triaquae/gitskills.git 這樣的地址。實際上,Git支持多種協議,默認的git://
使用ssh,但也可以使用https
等其他協議。
使用https
除了速度慢以外,還有個最大的麻煩是每次推送都必須輸入口令,但是在某些只開放http端口的公司內部就無法使用ssh
協議而只能用https
。
一些小操作
比如,你看到別人的項目代碼寫的很好,自己又有新的想法,就可以點擊fork復制到自己的代碼倉庫。然后拉取到本地進行更改。
上面我們提到了如何配置ssh,配置好ssh,如何通過ssh連接提交代碼到遠程代碼庫呢?
進入到本地代碼庫,修改隱藏文件夾.ssh下的config文件,把之前提到的藍框點到ssh,復制連接。
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github using ssh to test shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim .git/config # 編輯可配置文件,修改提交方式從https到ssh link [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ignorecase = true precomposeunicode = true [remote "origin"] url = git@github.com:dandy-weeknd/Test2_From_Github.git fetch = +refs/heads/*:refs/remotes/origin/* [branch "master"] remote = origin merge = refs/heads/master shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit [master e5cc600] using ssh in readme.md 1 file changed, 2 insertions(+), 1 deletion(-) shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin master # 提交到遠程代碼庫 The authenticity of host 'github.com (52.74.223.119)' can't be established. RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8. Are you sure you want to continue connecting (yes/no)? y Please type 'yes' or 'no': yes Warning: Permanently added 'github.com,52.74.223.119' (RSA) to the list of known hosts. Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Writing objects: 100% (3/3), 287 bytes | 287.00 KiB/s, done. Total 3 (delta 0), reused 0 (delta 0) To github.com:dandy-weeknd/Test2_From_Github.git cf545df..e5cc600 master -> master
已經上傳完成,檢查一下。
測試一下協作開發代碼合並的問題
既然是協同開發就需要先有個協同者下載代碼,這里起一台虛擬機模擬下:
dandy@ubuntu01:~$ git clone https://github.com/dandy-weeknd/Test2_From_Github.git Cloning into 'Test2_From_Github'... remote: Counting objects: 6, done. remote: Compressing objects: 100% (2/2), done. remote: Total 6 (delta 0), reused 3 (delta 0), pack-reused 0 Unpacking objects: 100% (6/6), done. Checking connectivity... done. dandy@ubuntu01:~$ ls Test2_From_Github
這時候,對源代碼進行修改,協作開發。
dandy@ubuntu01:~/Test2_From_Github$ vim main.py # 創建一個新文件 def sayhi(name): print('Hi,', name) dandy@ubuntu01:~/Test2_From_Github$ vim README.md # Test2_From_Github using ssh[ubuntu insert here] to test this line changed from ubuntu server.
修改完進行提交:
git add . dandy@ubuntu01:~/Test2_From_Github$ git commit -m 'changed from ubuntu server.' *** Please tell me who you are. Run git config --global user.email "you@example.com" git config --global user.name "Your Name" to set your account's default identity. Omit --global to set the identity only in this repository. fatal: unable to auto-detect email address (got 'dandy@ubuntu01.(none)') dandy@ubuntu01:~/Test2_From_Github$ git config --global user.email "dandy@ubuntu.com" dandy@ubuntu01:~/Test2_From_Github$ git config --global user.name "dandy.ubuntu" dandy@ubuntu01:~/Test2_From_Github$ git commit -m 'changed from ubuntu server.' [master de354d3] changed from ubuntu server. 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 main.py
dandy@ubuntu01:~/Test2_From_Github$ git push origin master # 因為需要賬號密碼,嫌麻煩,就再建立一個ssh Username for 'https://github.com': Password for 'https://github.com': remote: Anonymous access to dandy-weeknd/Test2_From_Github.git denied. fatal: Authentication failed for 'https://github.com/dandy-weeknd/Test2_From_Github.git/' dandy@ubuntu01:~/Test2_From_Github$ vim .git/config # 修改成ssh連接 dandy@ubuntu01:~/Test2_From_Github$ ls ~/ Test2_From_Github dandy@ubuntu01:~/Test2_From_Github$ ls ~/.ssh ls: cannot access '/home/dandy/.ssh': No such file or directory dandy@ubuntu01:~/Test2_From_Github$ sudo ls ~/.ssh [sudo] password for dandy: ls: cannot access '/home/dandy/.ssh': No such file or directory dandy@ubuntu01:~/Test2_From_Github$ ssh-keygen -t rsa -C "dandy@ubuntu.com" # 建立秘鑰 Generating public/private rsa key pair. Enter file in which to save the key (/home/dandy/.ssh/id_rsa): Created directory '/home/dandy/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/dandy/.ssh/id_rsa. Your public key has been saved in /home/dandy/.ssh/id_rsa.pub. The key fingerprint is: SHA256:4VzEuYG59R9y/CkHR9eNu+yMLV9Cl4tcBMRzR76MdrE dandy@ubuntu.com The key's randomart image is: +---[RSA 2048]----+ | +..oo o+| | o.= oo+=| | .o.+ .+++| | o.o. o.O.=| | S B+Eo| | ooB+o| | B+..| | o +o | | o. | +----[SHA256]-----+ dandy@ubuntu01:~/Test2_From_Github$ cd ~/.ssh dandy@ubuntu01:~/.ssh$ ls id_rsa id_rsa.pub dandy@ubuntu01:~/.ssh$ cd .. dandy@ubuntu01:~$ vim ~/.ssh/config dandy@ubuntu01:~$ vim ~/.ssh/id_rsa.pub # copy公鑰
復制出來,注意這一次,不能再像之前那樣粘貼在your profile的settings里面了,從作者本身的角度來講,加入公鑰,是為了以后通過電腦上傳任何代碼到遠程代碼庫都不必輸入賬號密碼,但是作為一個協同者,顯然是不能給它這樣的權限。所以應該添加到項目代碼倉庫的settings中;如圖中的deploy keys
現在我們重新提交一次虛擬機本地代碼庫到遠程github源代碼庫
dandy@ubuntu01:~$ ls Test2_From_Github dandy@ubuntu01:~$ cd Test2_From_Github/ dandy@ubuntu01:~/Test2_From_Github$ git push origin master The authenticity of host 'github.com (52.74.223.119)' can't be established. RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'github.com,52.74.223.119' (RSA) to the list of known hosts. Counting objects: 4, done. Delta compression using up to 2 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (4/4), 407 bytes | 0 bytes/s, done. Total 4 (delta 0), reused 0 (delta 0) To git@github.com:dandy-weeknd/Test2_From_Github.git e5cc600..de354d3 master -> master
效果圖:
這時,假定做為開發者中的另一個原作者,不知道遠程代碼庫代碼已經更新, 還是在本地修改clone的代碼:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # 修改了readme # Test2_From_Github using ssh to test I am also editing this project, but i forget to check it from github whether it is the newest or not? shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim setting.py # 新建了一個文件 import os Base_dir = os.path.join(__file__)
然后提交到github上:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'i am editing this project in macbook pro' [master 084fd50] i am editing this project in macbook pro 2 files changed, 5 insertions(+) create mode 100644 setting.py shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin master # 提交到github上 To github.com:dandy-weeknd/Test2_From_Github.git ! [rejected] master -> master (fetch first) error: failed to push some refs to 'git@github.com:dandy-weeknd/Test2_From_Github.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.
可以發現,這一次的代碼提交被拒絕了,github已經提示:遠程包含的工作文件本地不存在,這通常由於另一個代碼倉庫提交導致,在你提交到github前,需要整合,合並代碼。
這里再引入一個新的git命令:
git pull
用來將遠程新的代碼下載下來,但是有可能把本地修改過的文件覆蓋掉。先試一下:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git pull Warning: Permanently added the RSA host key for IP address '13.229.188.59' to the list of known hosts. remote: Counting objects: 4, done. remote: Compressing objects: 100% (3/3), done. remote: Total 4 (delta 0), reused 4 (delta 0), pack-reused 0 Unpacking objects: 100% (4/4), done. From github.com:dandy-weeknd/Test2_From_Github e5cc600..de354d3 master -> origin/master Auto-merging README.md CONFLICT (content): Merge conflict in README.md Automatic merge failed; fix conflicts and then commit the result.
解釋一下上面這段話:開始是計數、壓縮、巴拉巴拉。。然后發現有異常就自動合並代碼,發現有矛盾問題在readme中,自動合並失敗,需要自己解決矛盾並重新提交結果代碼。
查看下readme:
head指向的是本地的文件修改情況、=======分隔符后面github上被修改過的代碼,最后>>>>>>>后面的應該是雙方都有的代碼區。仔細一想,代碼肯定是上面的是新的,所以保留下面的代碼對其他協作本地git代碼庫不會產生影響(只需要pull),所以我們修改一下這個readme文件
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github using ssh to test I am also editing this project, but i forget to check it from github whether it is the newest or not? using ssh[ubuntu insert here] to test this line changed from ubuntu server.
重新再提交一次:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'fix two different version code' [master 775460f] fix two different version code shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin master Enumerating objects: 11, done. Counting objects: 100% (11/11), done. Delta compression using up to 4 threads. Compressing objects: 100% (6/6), done. Writing objects: 100% (7/7), 820 bytes | 410.00 KiB/s, done. Total 7 (delta 1), reused 0 (delta 0) remote: Resolving deltas: 100% (1/1), done. To github.com:dandy-weeknd/Test2_From_Github.git de354d3..775460f master -> master
完美解決。
這里詮釋的只是git對於版本矛盾的自主解決方案演示,但是在真正的生產環境下,顯然不可能會是這樣處理的。這方面的問題,之后再做探討!
分支管理
分支就是科幻電影里面的平行宇宙,當你正在電腦前努力學習Git的時候,另一個你正在另一個平行宇宙里努力學習SVN。
如果兩個平行宇宙互不干擾,那對現在的你也沒啥影響。不過,在某個時間點,兩個平行宇宙合並了,結果,你既學會了Git又學會了SVN!
分支在實際中有什么用呢?假設你准備開發一個新功能,但是需要兩周才能完成,第一周你寫了50%的代碼,如果立刻提交,由於代碼還沒寫完,不完整的代碼庫會導致別人不能干活了。如果等代碼全部寫完再一次提交,又存在丟失每天進度的巨大風險。
現在有了分支,就不用怕了。你創建了一個屬於你自己的分支,別人看不到,還繼續在原來的分支上正常工作,而你在自己的分支上干活,想提交就提交,直到開發完畢后,再一次性合並到原來的分支上,這樣,既安全,又不影響別人工作。
其他版本控制系統如SVN等都有分支管理,但是用過之后你會發現,這些版本控制系統創建和切換分支比蝸牛還慢,簡直讓人無法忍受,結果分支功能成了擺設,大家都不去用。
但Git的分支是與眾不同的,無論創建、切換和刪除分支,Git在1秒鍾之內就能完成!無論你的版本庫是1個文件還是1萬個文件。
1、創建與合並分支
在學習版本回退部分時,你已經知道,每次提交,Git都把它們串成一條時間線,這條時間線就是一個分支。截止到目前,只有一條時間線,在Git里,這個分支叫主分支,即master
分支。HEAD
嚴格來說不是指向提交,而是指向master
,master
才是指向提交的,所以,HEAD
指向的就是當前分支。
一開始的時候,master
分支是一條線,Git用master
指向最新的提交,再用HEAD
指向master
,就能確定當前分支,以及當前分支的提交點:
每次提交,master
分支都會向前移動一步,這樣,隨着你不斷提交,master
分支的線也越來越長, 當我們創建新的分支,例如dev
時,Git新建了一個指針叫dev
,指向master
相同的提交,再把HEAD
指向dev
,就表示當前分支在dev
上:
假如我們在dev
上的工作完成了,就可以把dev
合並到master
上。Git怎么合並呢?最簡單的方法,就是直接把master
指向dev
的當前提交,就完成了合並:
所以Git合並分支也很快!就改改指針,工作區內容也不變!
合並完分支后,甚至可以刪除dev
分支。刪除dev
分支就是把dev
指針給刪掉,刪掉后,我們就剩下了一條master
分支:
真是太神奇了,你看得出來有些提交是通過分支完成的嗎?
上面這張圖就詮釋了協作開發的分支與合並的大概流程圖。
下面開始實戰
首先,需要先創建dev分支:
shuais-MacBook-Pro:~ dandyzhang$ ls Applications Downloads Music PycharmProjects venv Desktop Library Pictures git_test Documents Movies Public git_test2 shuais-MacBook-Pro:~ dandyzhang$ cd git_test2 shuais-MacBook-Pro:git_test2 dandyzhang$ ls Test2_From_Github shuais-MacBook-Pro:git_test2 dandyzhang$ cd Test2_From_Github/ shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout -b dev Switched to a new branch 'dev'
git checkout命令加上-b參數表示創建並切換,相當於以下兩條命令:
git branch dev # 創建branch分支
git checkout dev # 轉換到分支dev上
然后,用git branch
命令查看當前分支:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch * dev master
git branch
命令會列出所有分支,當前分支前面會標一個*
號。
然后,我們就可以在dev
分支上正常提交,比如對readme做個修改,加上一行:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ ls README.md main.py setting.py shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github using ssh to test I am also editing this project, but i forget to check it from github whether it is the newest or not? using ssh[ubuntu insert here] to [dev add here] test this line changed from ubuntu server. here we are using dev to add a new line.
然后提交:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'from branch dev' [dev 524b382] from branch dev 1 file changed, 4 insertions(+), 1 deletion(-)
先切換回master分支:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout master Switched to branch 'master' Your branch is up to date with 'origin/master'. shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch dev * master
查看readme文件,剛才添加的內容不見了!
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github using ssh to test I am also editing this project, but i forget to check it from github whether it is the newest or not? using ssh[ubuntu insert here] to test this line changed from ubuntu server.
因為那個提交是在dev
分支上,而master
分支此刻的提交點並沒有變:
現在,我們把dev
分支的工作成果合並到master
分支上:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git merge dev Updating 775460f..524b382 Fast-forward README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
注意一下上面合並代碼到master主線的操作,需要先add到stage並commit到分支倉庫,然后切換到master主分支,最后merge 分支。git merge
命令用於合並指定分支到當前分支。合並后,再查看readme.txt的內容,就可以看到,和dev
分支的最新提交是完全一樣的。
注意到上面的Fast-forward
信息,Git告訴我們,這次合並是“快進模式”,也就是直接把master
指向dev
的當前提交,所以合並速度非常快。
當然,也不是每次合並都能Fast-forward
,我們后面會講其他方式的合並。
合並完成后,就可以放心地刪除dev
分支了:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch -d dev
Deleted branch dev (was 524b382).
刪除后,查看branch,就只剩下master分支了:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch
* master
因為創建、合並和刪除分支非常快,所以Git鼓勵你使用分支完成某個任務,合並后再刪掉分支,這和直接在master
分支上工作效果是一樣的,但過程更安全。
2、解決沖突
人生不如意之事十之八九,合並分支往往也不是一帆風順的。
准備新的feature1
分支,繼續我們的新分支開發:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout -b feature1 Switched to a new branch 'feature1' shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch * feature1 master
修改readme:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github using ssh to test I am also editing this project, but i forget to check it from github whether it is the newest or not? using ssh[ubuntu insert here] to [dev add here] test [feature1] this line changed from ubuntu server. here we are using dev to add a new line. another one line insert by feature1.
在feature1分支上提交:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'add by feature1' [feature1 7ba88de] add by feature1 1 file changed, 2 insertions(+), 1 deletion(-)
切換到master分支:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout master Switched to branch 'master' Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits)
Git自動的提示我們當前master分支比遠程的feature1落后一個提交。
在master分支上修改readme文件的最后一行:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github using ssh to test I am also editing this project, but i forget to check it from github whether it is the newest or not? using ssh[ubuntu insert here] to [dev add here] test this line changed from ubuntu server. here we are using dev to add a new line. add this line from master, do not care whether if exists new branch.
提交:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'master update' [master f3490d7] master update 1 file changed, 1 insertion(+), 1 deletion(-)
現在,master
分支和feature1
分支各自都分別有新的提交,變成了這樣:
這種情況下,Git無法執行“快速合並”,只能試圖把各自的修改合並起來,但這種合並就可能會有沖突,我們試試看:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git merge feature1 Auto-merging README.md CONFLICT (content): Merge conflict in README.md Automatic merge failed; fix conflicts and then commit the result. shuais-MacBook-Pro:Test2_From_Github dandyzhang$
不出所料,果然沖突了!Git告訴我們readme文件存在沖突,必須手動解決沖突后再提交。git status
也可以告訴我們沖突的文件:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git status On branch master Your branch is ahead of 'origin/master' by 2 commits. (use "git push" to publish your local commits) You have unmerged paths. (fix conflicts and run "git commit") (use "git merge --abort" to abort the merge) Unmerged paths: (use "git add <file>..." to mark resolution) both modified: README.md no changes added to commit (use "git add" and/or "git commit -a")
我們可以直接查看readme.txt的內容:
# Test2_From_Github using ssh to test I am also editing this project, but i forget to check it from github whether it is the newest or not? using ssh[ubuntu insert here] to [dev add here] test [feature1] this line changed from ubuntu server. here we are using dev to add a new line. <<<<<<< HEAD add this line from master, do not care whether if exists new branch. ======= another one line insert by feature1. >>>>>>> feature1
Git用<<<<<<<
,=======
,>>>>>>>
標記出不同分支的內容,我們修改如下后保存:
# Test2_From_Github using ssh to test I am also editing this project, but i forget to check it from github whether it is the newest or not? using ssh[ubuntu insert here] to [dev add here] test [feature1] this line changed from ubuntu server. here we are using dev to add a new line. add this line from master, do not care whether if exists new branch. another one line insert by feature1.
再提交:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'master and feature1 conflict fixed' [master 0497781] master and feature1 conflict fixed
現在,master
分支和feature1
分支變成了下圖所示:
用帶參數的git log
也可以看到分支的合並情況:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git log --graph --pretty=oneline * 0497781e6ce609ef7a9fa425769a11a5dc7847b9 (HEAD -> master) master and feature1 conflict fixed |\ | * 7ba88de0e18caca1681ae66db36fa513d8f5a38c (feature1) add by feature1 * | f3490d750855375bd3717b304ba517cebf987f2d master update |/ * 524b382d29793105eed5c0497fd3eb2587a0e3ba from branch dev * 775460fa81586121344553f09e9f62b58f5d3200 (origin/master, origin/HEAD) fix two different version code |\ | * de354d34ee8d5aeefd171d4ba638b0545678a374 changed from ubuntu server. * | 084fd50f4cdc3255bd26ab1fb8bbee4f020700c6 i am editing this project in macbook pro |/ * e5cc600986322beb77930cf428ab3b07f72bd7f7 using ssh in readme.md * cf545dfa993fcc8ecd43f117286f606922b7d0d1 Initial commit
3、分支策略
在實際開發中,我們應該按照幾個基本原則進行分支管理:
首先,master
分支應該是非常穩定的,也就是僅用來發布新版本,平時不能在上面干活;
那在哪干活呢?干活都在dev
分支上,也就是說,dev
分支是不穩定的,到某個時候,比如1.0版本發布時,再把dev
分支合並到master
上,在master
分支發布1.0版本;
你和你的小伙伴們每個人都在dev
分支上干活,每個人都有自己的分支,時不時地往dev
分支上合並就可以了。
所以,團隊合作的分支看起來就像這樣:
4、bug分支
軟件開發中,bug就像家常便飯一樣。有了bug就需要修復,在Git中,由於分支是如此的強大,所以,每個bug都可以通過一個新的臨時分支來修復,修復后,合並分支,然后將臨時分支刪除。
首先,模擬創立一個分支進行開發:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch * master shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout -b dev Switched to a new branch 'dev' shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch * dev master shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github using ssh to test I am also editing this project, but i forget to check it from github whether it is the newest or not? using ssh[ubuntu insert here] to [dev add here] test [feature1] this line changed from ubuntu server. here we are using dev to add a new line. add this line from master, do not care whether if exists new branch. another one line insert by feature1. ignore the lines in front of me, developing the new function now...from new dev and facing a bug101 need to fix..
當你接到一個修復一個代號101的bug的任務時,很自然地,你想創建一個分支bug101
來修復它,但是,等等,當前正在dev
上進行的工作還沒有提交:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git status On branch dev Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: README.md no changes added to commit (use "git add" and/or "git commit -a")
並不是你不想提交,而是工作只進行到一半,還沒法提交,預計完成還需1天時間。但是,必須在兩個小時內修復該bug,怎么辦?
幸好,Git還提供了一個stash
功能,可以把當前工作現場“儲藏”起來,等以后恢復現場后繼續工作:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git stash Saved working directory and index state WIP on dev: 0497781 master and feature1 conflict fixed
# 上面使用了stash命令,dev分支里面的文件現在已經被管理了,查詢一下dev工作區狀態 shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git status On branch dev nothing to commit, working tree clean
首先確定要在哪個分支上修復bug,假定需要在master
分支上修復,就從master
創建臨時分支:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout master Switched to branch 'master' Your branch is up to date with 'origin/master'. shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout -b bug101 Switched to a new branch 'bug101'
現在需要修復bug,假設bug操作為刪除掉readme內容,加上一句hello git stash,然后提交:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github hello git stash ! shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'fix bug101' [bug101 0fda0f9] fix bug101 1 file changed, 1 insertion(+), 13 deletions(-)
修復完成后,切換到master
分支,並完成合並,最后刪除bug101
分支:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout master Switched to branch 'master' Your branch is up to date with 'origin/master'. shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git merge -m "merge fixed bug101 " bug101 Updating 0497781..0fda0f9 Fast-forward (no commit created; -m option ignored) README.md | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github hello git stash ! shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch -d bug101 Deleted branch bug101 (was 0fda0f9).
太棒了,原計划兩個小時的bug修復只花了5分鍾!現在,是時候接着回到dev
分支干活了!
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout dev Switched to branch 'dev' shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git status On branch dev nothing to commit, working tree clean
工作區是干凈對的,剛才工作的工作現場到哪去了?用git stash list看看:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git stash list stash@{0}: WIP on dev: 0497781 master and feature1 conflict fixed
工作現場還在,Git把stash內容存在某個地方了,但是需要恢復一下,有兩個辦法:
一是用git stash apply
恢復,但是恢復后,stash內容並不刪除,你需要用git stash drop
來刪除;
另一種方式是用git stash pop
,恢復的同時把stash內容也刪了:(這一點跟python的list里面的pop很相似,刪除最后一個index,並返回)
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git stash pop On branch dev Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: README.md no changes added to commit (use "git add" and/or "git commit -a") Dropped refs/stash@{0} (f43222b3d7f574d3e42baaf83c0378de2ad68f49)
再用git stash list
查看,就看不到任何stash內容了.
你可以多次stash,恢復的時候,先用git stash list
查看,然后恢復指定的stash,用命令:
$ git stash apply stash@{0}
忽略特殊文件.gitignore
有些時候,你必須把某些文件放到Git工作目錄中,但又不能提交它們,比如保存了數據庫密碼的配置文件啦,等等,每次git status
都會顯示Untracked files ...
,有強迫症的童鞋心里肯定不爽。
好在Git考慮到了大家的感受,這個問題解決起來也很簡單,在Git工作區的根目錄下創建一個特殊的.gitignore
文件,然后把要忽略的文件名填進去,Git就會自動忽略這些文件。
不需要從頭寫.gitignore
文件,GitHub已經為我們准備了各種配置文件,只需要組合一下就可以使用了。所有配置文件可以直接在線瀏覽:https://github.com/github/gitignore
忽略文件的原則是:
- 忽略操作系統自動生成的文件,比如縮略圖等;
- 忽略編譯生成的中間文件、可執行文件等,也就是如果一個文件是通過另一個文件自動生成的,那自動生成的文件就沒必要放進版本庫,比如Java編譯產生的
.class
文件; - 忽略你自己的帶有敏感信息的配置文件,比如存放口令的配置文件。
舉個例子:
假設你在Windows下進行Python開發,Windows會自動在有圖片的目錄下生成隱藏的縮略圖文件,如果有自定義目錄,目錄下就會有Desktop.ini
文件,因此你需要忽略Windows自動生成的垃圾文件:
# Windows:
Thumbs.db
ehthumbs.db
Desktop.ini
然后,繼續忽略Python編譯產生的.pyc
、.pyo
、dist
等文件或目錄:
# Python: *.py[cod] *.so *.egg *.egg-info dist build
加上你自己定義的文件,最終得到一個完整的.gitignore
文件,內容如下:
# Windows: Thumbs.db ehthumbs.db Desktop.ini # Python: *.py[cod] *.so *.egg *.egg-info dist build # My configurations: db.ini deploy_key_rsa
最后一步就是把.gitignore
也提交到Git,就完成了!當然檢驗.gitignore
的標准是git status
命令是不是說working directory clean
。
使用Windows的童鞋注意了,如果你在資源管理器里新建一個.gitignore
文件,它會非常弱智地提示你必須輸入文件名,但是在文本編輯器里“保存”或者“另存為”就可以把文件保存為.gitignore
了。
首先根據上面的連接,下載一份python ignorefile。
首先,我們先在master分支建立一個文檔,放入一個文件:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ ls README.md main.py setting.py shuais-MacBook-Pro:Test2_From_Github dandyzhang$ mkdir core shuais-MacBook-Pro:Test2_From_Github dandyzhang$ ls README.md core main.py setting.py shuais-MacBook-Pro:Test2_From_Github dandyzhang$ cd core shuais-MacBook-Pro:core dandyzhang$ vim main.py def func1(): print('before ignore'
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'version before gitignore' [master 52a0beb] version before gitignore 1 file changed, 2 insertions(+) create mode 100644 core/main.py shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin master Enumerating objects: 9, done. Counting objects: 100% (9/9), done. Delta compression using up to 4 threads. Compressing objects: 100% (4/4), done. Writing objects: 100% (7/7), 644 bytes | 644.00 KiB/s, done. Total 7 (delta 1), reused 0 (delta 0) remote: Resolving deltas: 100% (1/1), done. To github.com:dandy-weeknd/Test2_From_Github.git 0497781..52a0beb master -> master
編輯gitignore 文件:
# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/
在最后加上一行:core/來測試一下忽略core文件夾
此時,再次編輯core下面的文件
1、修改main.py
def func1(): print('before ignore' def func2(): print('after ignore add this function')
2、在core下面創建新文件core.py
shuais-MacBook-Pro:core dandyzhang$ vim core.py # new file after add gitignore file.
3、提交測試
shuais-MacBook-Pro:core dandyzhang$ git add . shuais-MacBook-Pro:core dandyzhang$ git commit -m 'add gitignore' [master 1c9eba3] add gitignore 1 file changed, 3 insertions(+) shuais-MacBook-Pro:core dandyzhang$ git status On branch master Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits) Untracked files: (use "git add <file>..." to include in what will be committed) ../.gitignore nothing added to commit but untracked files present (use "git add" to track) shuais-MacBook-Pro:core dandyzhang$ git push origin master Enumerating objects: 7, done. Counting objects: 100% (7/7), done. Delta compression using up to 4 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (4/4), 450 bytes | 450.00 KiB/s, done. Total 4 (delta 0), reused 0 (delta 0) To github.com:dandy-weeknd/Test2_From_Github.git 52a0beb..1c9eba3 master -> master
4、結果
可以得出結論,之於gitignore文件定義之前加入的文件還是會被git繼續追蹤,而在gitignore文件定義之后加入的都不會被追蹤。
假設存在這樣一種情況呢?某個文件夾下,確實要屏蔽或忽視,但是僅有一個文件特殊,需要強制將它加入到Git中。
shuais-MacBook-Pro:core dandyzhang$ vim test.py def func(): print('can you ignore me ?') shuais-MacBook-Pro:core dandyzhang$ git add -f test.py shuais-MacBook-Pro:core dandyzhang$ git commit -m 'ignore or not for test.py' [master 843ce07] ignore or not for test.py 1 file changed, 2 insertions(+) create mode 100644 core/test.py shuais-MacBook-Pro:core dandyzhang$ git push origin master Enumerating objects: 6, done. Counting objects: 100% (6/6), done. Delta compression using up to 4 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (4/4), 465 bytes | 465.00 KiB/s, done. Total 4 (delta 0), reused 0 (delta 0) To github.com:dandy-weeknd/Test2_From_Github.git 1c9eba3..843ce07 master -> master
有沒有點小激動:
或者你發現,可能是.gitignore
寫得有問題,需要找出來到底哪個規則寫錯了,可以用git check-ignore
命令檢查:
shuais-MacBook-Pro:core dandyzhang$ git check-ignore -v core/test.py .gitignore:106:core/ core/test.py
Git會告訴我們,.gitignore
的第106行規則忽略了該文件,於是我們就可以知道應該修訂哪個規則。
小結
-
忽略某些文件時,需要編寫
.gitignore
; -
.gitignore
文件本身要放到版本庫里,並且可以對.gitignore
做版本管理!
多人協作
當你從遠程倉庫克隆時,實際上Git自動把本地的master
分支和遠程的master
分支對應起來了,並且,遠程倉庫的默認名稱是origin
。
要查看遠程庫的信息,用git remote
:
shuais-MacBook-Pro:core dandyzhang$ git remote
origin
或者,用git remote -v
顯示更詳細的信息:
shuais-MacBook-Pro:core dandyzhang$ git remote -v origin git@github.com:dandy-weeknd/Test2_From_Github.git (fetch) origin git@github.com:dandy-weeknd/Test2_From_Github.git (push)
上面顯示了可以抓取和推送的origin
的地址。如果沒有推送權限,就看不到push的地址。
1 、推送分支
推送分支,就是把該分支上的所有本地提交推送到遠程庫。推送時,要指定本地分支,這樣,Git就會把該分支推送到遠程庫對應的遠程分支上:
git push origin master
如果要推送其他分支,比如dev
,就改成:
git push origin dev
但是,並不是一定要把本地分支往遠程推送,那么,哪些分支需要推送,哪些不需要呢?
-
master
分支是主分支,因此要時刻與遠程同步; -
dev
分支是開發分支,團隊所有成員都需要在上面工作,所以也需要與遠程同步; -
bug分支只用於在本地修復bug,就沒必要推到遠程了,除非老板要看看你每周到底修復了幾個bug;
-
feature分支是否推到遠程,取決於你是否和你的小伙伴合作在上面開發。
總之,就是在Git中,分支完全可以在本地自己藏着玩,是否推送,視你的心情而定!
2 、抓取分支
多人協作時,大家都會往master
和dev
分支上推送各自的修改。
現在,模擬一個你的小伙伴,可以在另一台電腦(注意要把SSH Key添加到GitHub)或者同一台電腦的另一個目錄下克隆:
dandy@ubuntu01:~/git_test$ git clone git@github.com:dandy-weeknd/Test2_From_Github.git Cloning into 'Test2_From_Github'... Warning: Permanently added the RSA host key for IP address '13.250.177.223' to the list of known hosts. remote: Counting objects: 44, done. remote: Compressing objects: 100% (27/27), done. remote: Total 44 (delta 8), reused 39 (delta 6), pack-reused 0 Receiving objects: 100% (44/44), 4.54 KiB | 0 bytes/s, done. Resolving deltas: 100% (8/8), done. Checking connectivity... done.
當你的小伙伴從遠程庫clone時,默認情況下,你的小伙伴只能看到本地的master
分支。不信可以用git branch
命令看看:
dandy@ubuntu01:~/git_test$ cd Test2_From_Github/ dandy@ubuntu01:~/git_test/Test2_From_Github$ git branch * master
現在,你的小伙伴要在dev
分支上開發,就必須創建遠程origin
的dev
分支到本地,於是他用這個命令創建本地dev
分支:
dandy@ubuntu01:~/git_test/Test2_From_Github$ git checkout -b dev origin/dev Branch dev set up to track remote branch dev from origin. Switched to a new branch 'dev'
現在,他就可以在dev
上繼續修改,然后,時不時地把dev
分支push
到遠程:
dandy@ubuntu01:~/git_test/Test2_From_Github$ vim README.md # Test2_From_Github hello git stash ! ....origin/dev
dandy@ubuntu01:~/git_test/Test2_From_Github$ git add . dandy@ubuntu01:~/git_test/Test2_From_Github$ git commit -m 'dev change' [dev 6cb1d87] dev change 1 file changed, 1 insertion(+), 1 deletion(-) dandy@ubuntu01:~/git_test/Test2_From_Github$ git branch * dev master dandy@ubuntu01:~/git_test/Test2_From_Github$ git push origin dev Warning: Permanently added the RSA host key for IP address '13.229.188.59' to the list of known hosts. Counting objects: 3, done. Delta compression using up to 2 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), 383 bytes | 0 bytes/s, done. Total 3 (delta 0), reused 0 (delta 0) To git@github.com:dandy-weeknd/Test2_From_Github.git * [new branch] dev -> dev
查看:
你的小伙伴已經向origin/dev分支推送了他的提交,而碰巧你也對同樣的文件作了修改,並試圖推送:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md # Test2_From_Github hello git stash ! from another client git to modified this file. in dev branch
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'modified readme later' [dev 780d33e] modified readme later 1 file changed, 1 insertion(+) shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin dev To github.com:dandy-weeknd/Test2_From_Github.git ! [rejected] dev -> dev (fetch first) error: failed to push some refs to 'git@github.com:dandy-weeknd/Test2_From_Github.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.
推送失敗,因為你的小伙伴的最新提交和你試圖推送的提交有沖突,解決辦法也很簡單,Git已經提示我們,先用git pull
把最新的提交從origin/dev
抓下來,然后,在本地合並,解決沖突,再推
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git pull remote: Counting objects: 3, done. remote: Compressing objects: 100% (3/3), done. remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0 Unpacking objects: 100% (3/3), done. From github.com:dandy-weeknd/Test2_From_Github 8767de7..a4de972 dev -> origin/dev There is no tracking information for the current branch. Please specify which branch you want to merge with. See git-pull(1) for details. git pull <remote> <branch> If you wish to set tracking information for this branch you can do so with: git branch --set-upstream-to=origin/<branch> dev
git pull
也失敗了,原因是沒有指定本地dev
分支與遠程origin/dev
分支的鏈接,根據提示,設置dev
和origin/dev
的鏈接:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch --set-upstream-to=origin/dev dev Branch 'dev' set up to track remote branch 'dev' from 'origin'.
再pull:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git pull Auto-merging README.md CONFLICT (content): Merge conflict in README.md Automatic merge failed; fix conflicts and then commit the result.
這回git pull
成功,但是合並有沖突,需要手動解決,解決的方法和分支管理中的解決沖突完全一樣。解決后,提交,再push:
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add . shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'fix two person code' [dev 9c4e39b] fix two person code shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin dev Enumerating objects: 10, done. Counting objects: 100% (10/10), done. Delta compression using up to 4 threads. Compressing objects: 100% (6/6), done. Writing objects: 100% (6/6), 782 bytes | 391.00 KiB/s, done. Total 6 (delta 1), reused 0 (delta 0) remote: Resolving deltas: 100% (1/1), done. To github.com:dandy-weeknd/Test2_From_Github.git a4de972..9c4e39b dev -> dev
結果圖:
因此,多人協作的工作模式通常是這樣:
-
首先,可以試圖用
git push origin branch-name
推送自己的修改; -
如果推送失敗,則因為遠程分支比你的本地更新,需要先用
git pull
試圖合並; -
如果合並有沖突,則解決沖突,並在本地提交;
-
沒有沖突或者解決掉沖突后,再用
git push origin branch-name
推送就能成功!
如果git pull
提示“no tracking information”,則說明本地分支和遠程分支的鏈接關系沒有創建,用命令git branch --set-upstream branch-name origin/branch-name
。
這就是多人協作的工作模式,一旦熟悉了,就非常簡單。
github使用
我們一直用GitHub作為免費的遠程倉庫,如果是個人的開源項目,放到GitHub上是完全沒有問題的。其實GitHub還是一個開源協作社區,通過GitHub,既可以讓別人參與你的開源項目,也可以參與別人的開源項目。
在GitHub出現以前,開源項目開源容易,但讓廣大人民群眾參與進來比較困難,因為要參與,就要提交代碼,而給每個想提交代碼的群眾都開一個賬號那是不現實的,因此,群眾也僅限於報個bug,即使能改掉bug,也只能把diff文件用郵件發過去,很不方便。
但是在GitHub上,利用Git極其強大的克隆和分支功能,廣大人民群眾真正可以第一次自由參與各種開源項目了。
如何參與一個開源項目呢?比如人氣極高的bootstrap項目,這是一個非常強大的CSS框架,你可以訪問它的項目主頁https://github.com/twbs/bootstrap,點“Fork”就在自己的賬號下克隆了一個bootstrap倉庫,然后,從自己的賬號下clone:
git clone git@github.com:michaelliao/bootstrap.git
一定要從自己的賬號下clone倉庫,這樣你才能推送修改。如果從bootstrap的作者的倉庫地址git@github.com:twbs/bootstrap.git
克隆,因為沒有權限,你將不能推送修改。
Bootstrap的官方倉庫twbs/bootstrap
、你在GitHub上克隆的倉庫my/bootstrap
,以及你自己克隆到本地電腦的倉庫,他們的關系就像下圖顯示的那樣:
如果你想修復bootstrap的一個bug,或者新增一個功能,立刻就可以開始干活,干完后,往自己的倉庫推送。
如果你希望bootstrap的官方庫能接受你的修改,你就可以在GitHub上發起一個pull request。當然,對方是否接受你的pull request就不一定了。
如果沒有能力修改的話,可以自己測試。上傳代碼到github倉庫,另一個賬號區區fork,修改再提交。
小結
-
在GitHub上,可以任意Fork開源倉庫;
-
自己擁有Fork后的倉庫的讀寫權限;
-
可以推送pull request給官方倉庫來貢獻代碼。
參考:http://www.cnblogs.com/alex3714/articles/5930846.html