對 Git 分支 master 和 origin/master 的一些認識

weixin_34075268發表於2017-03-24

首先要明確一點,對 Git 的操作是圍繞 3 個大的步驟來展開的(其實幾乎所有的 SCM 都是這樣)

  1. 從 git 取資料(git clone
  2. 改動程式碼
  3. 將改動傳回 git(git push

這 3 個步驟又涉及到兩個 repository,一個是 remote repository,在遠端伺服器上,一個是 local repository,在自己工作區上。其中 1, 3 兩個步驟涉及到 remote server/remote repository/remote branch,2 涉及到 local repository/local branch。git clone 會根據你指定的 remote server/repository/branch,拷貝一個副本到你本地,在 git push 之前,你對所有檔案的改動都是在你自己本地的 local repository 來做的,你的改動 local branch 和 remote branch 是獨立(並行)的。Gitk 顯示的就是 local repository。

在 clone 完成之後,Git 會自動為你將此遠端倉庫命名為 origin(origin 只相當於一個別名,執行 git remote –v 或者檢視 .git/config 可以看到 origin 的含義),並下載其中所有的資料,建立一個指向它的 master 分支的指標,我們用 (遠端倉庫名)/(分支名) 這樣的形式表示遠端分支,所以 origin/master 指向的是一個 remote branch(從那個 branch 我們 clone 資料到本地),但你無法在本地更改其資料。

同時,Git 會建立一個屬於你自己的本地 master 分支,它指向的是你剛剛從 remote server 傳到你本地的副本。隨著你不斷的改動檔案,git add , git commit,master 的指向會自動移動,你也可以通過merge(fast forward)來移動 master 的指向。

檢視所有分支:

$ git branch -a (to show all the branches git knows about)

* master
remotes/origin/HEAD -> origin/master
remotes/origin/master

檢視遠端分支:

$ git branch -r (to show remote branches git knows about)

origin/HEAD -> origin/master
origin/master

可以發現,master 就是 local branch,origin/master 是 remote branch(master is a branch in the local repository. remotes/origin/master is a branch named master on the remote named origin)。

$ git diff origin/master master

=> show me the changes between the remote master branch and my master branch

需要注意的是,remotes/origin/master 和 origin/master 的指向是相同的,可以執行以下命令看效果:

$ git diff origin/master remotes/origin/master

 

$ git push origin master

origin 指定了你要 push 到哪個 remote。

master 其實是一個“refspec”,正常的“refspec”的形式為“+<src>:<dst>”,冒號前表示 local branch 的名字,冒號後表示 remote repository 下 branch 的名字。注意,如果你省略了<dst>,git就認為你想 push 到 remote repository 下和 local branch 相同名字的 branch。聽起來有點拗口,再解釋下,push 是怎麼個 push 法,就是把本地 branch 指向的 commit push 到 remote repository 下的 branch,比如:

$ git push origin master:master

=> 在 local repository 中找到名字為 master 的 branch,使用它去更新 remote repository 下名字為 master 的 branch,如果 remote repository 下不存在名字是 master 的 branch,那麼新建一個。

$ git push origin master

=> 省略了<dst>,等價於“git push origin master:master”。

$ git push origin master:refs/for/mybranch

=> 在 local repository 中找到名字為 master 的 branch,用它去更新 remote repository 下面名字為 mybranch 的 branch。

$ git push origin HEAD:refs/for/mybranch

=> HEAD 指向當前工作的 branch,master 不一定指向當前工作的 branch,所以我覺得用 HEAD 還比 master 好些。

$ git push origin :mybranch

=> 在 origin repository 裡面查詢 mybranch,刪除它。用一個空的去更新它,就相當於刪除了。

相關文章