Thursday, 27 December 2018

GIT: Updating your remote-tracking branches with git fetch

34.1. Fetch

The git fetch command updates your remote-tracking branches, i.e., it updates the local copy of branches stored in a remote repository. The following command updates the remote-tracking branches from the repository called origin.
git fetch origin
The fetch command only updates the remote-tracking branches and none of the local branches. It also does not change the working tree of the Git repository. Therefore, you can run the git fetch command at any point in time.
After reviewing the changes in the remote tracking branchm you can merge the changes into your local branches or rebase your local branches onto the remote-tracking branch.
Alternatively you can also use the git cherry-pick commit_id command to take over only selected commits.
34.2. Fetch from all remote repositories
The git fetch command updates only the remote-tracking branches for one remote repository. In case you want to update the remote-tracking branches of all your remote repositories you can use the following command.
# simplification of the fetch command
# this runs git fetch for every remote repository
git remote update

# the same but remove all stale branches which
# are not in the remote anymore
git remote update --prune

34.3. Compare remote-tracking branch with local branch

The following code shows a few options how you can compare your branches.
# show the log entries between the last local commit and the
# remote branch
git log HEAD..origin/master

# show the diff for each patch
git log -p HEAD..origin/master

# show a single diff
git diff HEAD...origin/master

# instead of using HEAD you can also
# specify the branches directly
git diff master origin/master
The above commands show the changes introduced in HEAD compared to origin. If you want to see the changes in origin compared to HEAD, you can switch the arguments or use the -R parameter.

34.4. Rebase your local branch onto the remote-tracking branch

You can rebase your current local branch onto a remote-tracking branch. The following commands demonstrate that.
# assume you want to rebase master based on the latest fetch
# therefore check it out
git checkout master

# update your remote-tracking branch
git fetch

# rebase your master onto origin/master
git rebase origin/master
More information on the rebase command can be found in Rebasing branches.

34.5. Fetch compared with pull

The git pull command performs a git fetch and git merge (or git rebase based on your Git settings). The git fetch does not perform any operations on your local branches. You can always run the fetch command and review the incoming changes.

0 comments:

Post a Comment