user2759617
user2759617

Reputation: 707

Working on the same branch, how to pull without losing changes?

I am working on the same branch as my colleagues. Now I have committed some files and sent for code review and so has some other co-worker. Now he pushes his code before I do. I now need to pull his changes back and then add my changes. But it's already committed.

How do I get his changes and then add my changes without the history looking bad and me having to jump hoops? I am very new to git.

Upvotes: 10

Views: 23988

Answers (3)

ckruczek
ckruczek

Reputation: 2410

As already stated you can do a git pull --rebase but there is also a different approach you go with: Imagine your history now look like this:

A -> B -> C -> D | | local master remote/master You can do the following:

$ git branch save_state $ git reset --hard C Basically this brings you to

A -> B -> C (remote/master) \ -> D (local save_state)

You know pull the changes from remote into your master

$ git pull origin master

Which will lead to a fast forward merge(history is clean up to here) And know you can do a

$ git checkout save_state $ git rebase master $ git checkout master && git merge save_state You can rebase this branch here without problems because it doesnt have been pushed to remote yet.

Upvotes: 2

crea1
crea1

Reputation: 12617

You can use git pull --rebase. This will fetch your collegues commits and then put your commits (that you haven't pushed) on top of them, keeping the history looking good as well.

Edit: Cyril CHAPON made some good points in his comment. Take a look at some of his links to fully understand the how rebase works and to avoid pitfalls.

Upvotes: 16

Ewan Mellor
Ewan Mellor

Reputation: 6857

git pull

That will get his changes from the remote server, bring them locally to your machine, and then merge his work in with yours. This will give a join in the history: one branch with your work, one with his, and then a join when the two are brought together. Git will give you the opportunity to fix any conflicts if that is necessary, but it does a great job of merging automatically.

I very strongly recommend that you read this: https://git-scm.com/book/en/v2

Upvotes: 0

Related Questions