一篇文章,全面掌握Git
阿新 • • 發佈:2020-05-31
## 版本控制
**版本控制**就是記錄專案檔案的歷史變化。它為我們**查閱日誌**,**回退**,**協作**等方面提供了有力的幫助。
版本控制一般分為集中化版本控制和分散式版本控制。
![集中式](https://upload-images.jianshu.io/upload_images/19724385-e9ae0e66f0c693ea.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![分散式](https://upload-images.jianshu.io/upload_images/19724385-bb4f74594a8124d3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
集中化主要的版本資料都儲存服務端。
分散式版本資料分散在多端。
## Git
Git屬於分散式版本控制,也是現在比較流行的一種版本管理工具。
Git專案有三個區塊:工作區 / 暫存區 / 版本庫
- 工作區存放從版本庫提取出來的檔案,供我們編輯修改;
- 暫存區儲存了下一次要提交的目錄資訊;
- 版本庫儲存專案版本元資料和Objects資料,後文會詳解。
![Git工作流程](https://upload-images.jianshu.io/upload_images/19724385-f6fd498f7ca2ebfc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
Git工作流程
```bash
# 下載
<<==== clone
# 上傳
====>> add ====>> commit ====>> push
# 更新
<<==== merge|rebase <<===== fetch
```
#### 區分 Pull vs Fetch
我們將一個更新操作拆分為**資料更新+合併處理**兩部分,這樣來看 fetch 只是進行資料更新。而pull 其實是 ( fetch + (merge|rebase) )組合操作,它執行**資料更新**同時執行**合併處理**。pull 預設是fetch+merge 組合 ,也可以通過引數 --rebase 指定為 fetch + rebase。
#### 區分Merge vs Rebase
**合併處理**是Git很重要的一塊知識。兩個命令在工作中也經常使用,區分它們對我們很有用。
場景如下
專案有一個mywork分支。C2時間點我和小明各自下載專案進行功能開發,小明效率比較高,先推送了C3 C4 到遠端倉庫。我本地倉庫現在有C5 C6兩個提交,要推送到遠端倉庫,需先同步遠端倉庫版本。
![git](https://upload-images.jianshu.io/upload_images/19724385-a7659059cab50789.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
如果通過 fetch + merge 方式,Git會將遠端最新(C4)和本地最新(C6)進行合併併產生一個新的(C7)。
衝突處理步驟
```bash
git merge # 發生衝突會出現衝突標記
“<<<<<<< HEAD
40
=======
41
>>>>>>> 41”
# 手動處理衝突
git add .
git commit -m 'fix conflict'
git push origin HEAD
```
![git merge](https://upload-images.jianshu.io/upload_images/19724385-7c8fba26a4901ea4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
如果通過 fetch + rebase 方式,git會先將C5 C6儲存到.git/rebase零時目錄,合併成功後刪除。
衝突處理步驟
```bash
git rebase # 發生衝突會出現衝突標記
“<<<<<<< HEAD
40
=======
41
>>>>>>> 41”
# 手動處理衝突
git add .
git rebase --continue
git push origin HEAD
```
![git rebase](https://upload-images.jianshu.io/upload_images/19724385-dbd184aefc6b1c45.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![git rebase](https://upload-images.jianshu.io/upload_images/19724385-9e2a3fe48b566a19.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
#### 小結
git merge 會產生大量Merge日誌,可能會對檢視帶來不便。不過大家還是根據實際情況進行選取。
#### 關於撤銷回退幾種場景
提交後發現有檔案漏了,又不想提交兩次。此時通過 “git commit --amend” 可以合併為一個提交。
```bash
git commit -m 'initial commit'
git add .gitignore
git commit --amend
```
如果檔案想撤回且尚未提交,執行下面命令撤出暫存空間(index)
```bash
git res