When collaborating with other developers using Git, a simple workflow would be something like:
1. Clone entire project into your local machine
2. Work on local copy
3. Add and commit changes
4. Push commits back to remote repo
Every time before we start working on our local copy, we would probably want to ensure we have the latest live copy of the project.
One of the ways to accomplish this is to use a combination of
git fetch and
git fetch does is that it connects to the remote repo and pulls the changes (if any) into our local repo but it doesn’t merge them. After the fetch is done, you can use the
git diff command to view the changes. Doing a
git status will also show you that your local branch is out of sync with the remote repo, which makes sense because the remote repo has been updated but your local repo hasn’t.
Let’s do a simple example to demonstrate how
git fetch and
git merge works!
In my remote repo, I added a new commit –Edit file from remote (Do note that for actual projects, it is unlikely for developers to edit the remote repo directly since it’s usually the ‘production’ copy. All changes will be done in their local system first, and then pushed to the remote repo after testing is done)
Back in my local repo, doing a
git status will show that it is up to date with the remote repo. But if we run
git log, we only see the ‘Initial commit of myfile.txt’ commit. This is because, at this point, our local repo is unaware of any changes that is being done to the remote repo.
In order for the changes to be ‘made known’ to the local repo, we run:
And now when we run
git status, we will see that our local repo is 1 commit behind our remote repo.
To see what was done on the remote repo after using
git fetch, we can run
git log master..origin/master. From the output, we can see that only 1 new commit has been fetched in.
(More info on the git log command can be found here – https://git-scm.com/docs/gitrevisions)
It’s important to note that at this point, no changes have been made to our working files. git fetch only pulls in the commits from the remote repo; it doesn’t update any of our local branches.
This is why
git fetch is considered the ‘safe’ approach when attempting to sync our local with the remote repo. We can slowly browse through the commits pulled in and decide if we want to merge them into our working files.
Let us now run a
git merge and update our working files!
The command to do this is
git merge origin/master
. Since we are in our local repo and would like to merge the changes from our remote repo, the ‘origin/master’ option tells git to merge changes from that branch into the branch we are currently in.
The output will show us how many files have been changed as well as the type of changes (insertions/deletions).
Now if we run
git log from our local repo, we will see the ‘Edit file from remote‘ commit!