隐藏

git fetch拉取他人分支

发布:2022/4/21 14:44:42作者:管理员 来源:本站 浏览次数:780

有时候我们需要得到其它人的代码仓库,将别人(未push到远程仓库上的)修改与自己的修改进行合并,或者查看别人某个分支下的代码(而不真正切换别人的分支),本文介绍了相关的操作方法。

git remote

git remote用来管理本地工作目录对应的远程代码仓库,在一般的工作目录下,执行git remote结果如下:

> git remote
origin
> git remote -v
origin  git@remoteRepo (fetch)
origin  git@remoteRepo (push) 

我们可以使用git remote add命令来增加一个远程仓库,这个远程仓库可以是ssh地址(如上面这种),可以是本地目录,也可以是git协议或者http协议的地址。
例如,我要把liming的仓库作为我的远程仓库之一,可以执行git remote add 来增加仓库,例如:

> git remote add liming /home/liming/repo
> git remote
liming
origin
> git remote -v
liming  /home/liming/repo (fetch)
liming  /home/liming/repo (push)
origin  git@remoteRepo (fetch)
origin  git@remoteRepo (push) 

这样就将/home/liming/repo作为我的远程仓库之一了。

相应的,可以使用git remote rm或者git remote rename对远程代码仓库的名称进行修改(本地的,不会影响到对方的目录)

git fetch

git fetch用来得到远程代码仓库中本地没有的内容,git fetch 即可,例如:

> git fetch liming
remote: Counting objects: 20, done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 11 (delta 7), reused 4 (delta 2)
Unpacking objects: 100% (11/11), done.
From /home/liming/repo
 * [new branch]      card       -> liming/card
 * [new branch]      master     -> liming/master
 * [new branch]      test1      -> liming/test1
 * [new branch]      ziti       -> liming/ziti 

这样正在开发的代码就被抓取到本地了。

git checkout

可以使用git checkout切换到其它人的代码分支,git checkout /,例如:

> git checkout liming/card
Note: checking out 'liming/card'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
 git checkout -b new_branch_name
HEAD is now at 20831f6... 自动充值 

这样就可以看到已经commit过的代码了。

git checkout -b

checkout到别人的分支之后,处于detached HEAD状态,也就是说,这时候所作的commit都会被丢弃。要在别人代码的基础上进行修改,可以新建一个本地分支,例如:

# (在liming/card分支中)
> git checkout -b newcard
Switched to a new branch 'newcard' 

这样就建立了一个名为newcard的本地分支

修改gitconfig文件

有了本地分支之后,就可以在分支上修改和commit了,对于别人的改动,可以使用:

# (在newcard分支中)
git fetch liming
git merge liming/master 

和本地代码进行合并,但这样每次要运行两条命令。其实平常经常运行的git pull与上面两条命令功能相同,只要在配置文件中设置一下,就可以让git pull帮我们代劳:

在.gitconfig中[branch "newcard"]段(没有的话可以自己加上)增加:

remote = liming
merge = refs/heads/master 

如此一来,每次远程更新后,便可以用git pull得到远程的代码。

git push

在本地分支修改并提交后,可以将这些改动提交到远程分支,格式为git push :, src代表本地分支,dst代表远程分支,例如:

$git push liming newcard:card 

这样就可以把本地newcard的修改提交到liming下的card分支中。注意:只有在本地已merge远程分支最新代码,且对方不在此分支下才能操作成功。