Alexander Mills
Alexander Mills

Reputation: 100486

Pulling in different Git branch

Say I create a repo and it has one branch called master. If someone else forks the repo and pushes to a new branch B, what is the best way for me to pull in B locally without overwriting my local master branch? Do I switch to branch B locally and then pull in the changes? My guess is if I don't explicitly switch branches locally then if I pull in the changes from the remote branch B then I will overwrite my local master branch with B. What is the best option here?

Upvotes: 0

Views: 83

Answers (4)

Gauthier
Gauthier

Reputation: 42035

I suppose that when you write "[someone] pushes to a new branch B", you mean that they push to their fork repo, not to the original repo origin.

Rather than fetching B from origin, you need to fetch from their fork:

git fetch <url/to/their/fork/repo> B

You will get a copy of the commits in their branch B, and you can see the remote branch with git branch -a. You can checkout the remote branch to make your working files reflect branch B.

If you want, you can create a local branch at the same time you are fetching. The name of the created local branch comes after a : :

git fetch <url/to/their/fork/repo> B:B

Now instead of running git checkout on a rather long branch name, you can just git checkout B.

Remember that pull is just fetch + merge, and that merge happens with the branch that is currently checked out. Your guess is kind of correct in that if you run git pull while master is checked out, you will merge the content of the pulled branch into master. This is not really overwriting though, rather adding a commit to master.


If you are going to use their fork repo more times, you can add it as a remote:

git remote add their_fork <url/to/their/fork/repo>

After this you do not need to write their whole URL, you can use the remote name instead:

git fetch their_fork B:B

Upvotes: 0

SJMan
SJMan

Reputation: 1607

You can do a git fetch origin branchname . By doing a git pull origin branchname you can merge the changes of both the branches. install a mergetool like kdiff3. You can integrate the two, follow this link

Upvotes: 3

Alex Pan
Alex Pan

Reputation: 4621

git fetch origin
git checkout --track origin/<remote_branch_name>

Upvotes: 2

siegi
siegi

Reputation: 5996

You can use git fetch origin branchB to get all commits from branchB without modifying your master or your working directory.

If you want to apply the changes to your master, you can merge them using git merge FETCH_HEAD while you are on your master branch. This creates a new commit with all the changes from master and from branchB. FETCH_HEAD is the last commit that was fetched.

Upvotes: 1

Related Questions