3

The question could also be "Why using git fetch while git pull exists ?".

A reason of doing a git fetch could be that you want to see the logs of the fetch command to know what you will be merging, just before you run git merge.

git fetch then git merge being the classic workflow, are there other common stuffs you do after a git fetch that you can't do if you didn't run this command before ?

ThCollignon
  • 976
  • 3
  • 14
  • 31
  • If you want to see what's in the repo or maybe merge it manually? – JLev Nov 23 '17 at 07:39
  • 2
    My use case: I have local modifications in my working tree and want to get remote updates before I get offline during traveling. I can update my local branches later on the train when I finish my work and commit it to a feature branch. – Melebius Nov 23 '17 at 07:54

2 Answers2

5

The git fetch command is used to bring parts of history from other repositores into your local one.

So, that's the only use of this command in itself; it does not actually cares about what you can do with that history, and while merging that history is, indeed, arguably the most common use, you can do other stuff.

For instance, I routinely check out the fetched history (typically a remote branch updated by git fetch) for building an older release.

You can also merely perform history digging operations such as diffing and running git log.

You can also cherry-pick commits of interest.

You can run git filter-branch on the fetched line of history and git push it somewhere right away without merging anywhere.

TL;DR

Do not mentally connect git fetch with anything: it merely fetches the data; whatever you then do with that data is completely up to you.

kostix
  • 51,517
  • 14
  • 93
  • 176
4

git fetch gets some refs and their related objects that don't exist locally yet so that we can manipulate these refs and objects. By default, we can't fetch a single commit without any ref. But we can if the remote repository allows it with some config.

Besides git merge and git rebase, here are some more cases:

a)You'd like to reuse the commit message of a commit abc123, but you don't have the commit yet. The commit is reachable from a branch master of another remote repository.

git add .
git fetch <url_of_another_repository> master
git commit -c abc123 --reset-author

b)You'd like to have a quick look and find out what new commits you have made locally after you've made a mess.

git fetch origin master
git cherry FETCH_HEAD HEAD

c)You'd like to apply a commit from master of another remote repository to your local branch.

git fetch <url_of_another_repository> master
git cherry-pick abc123

d)Your colleague has made a commit to a ref refs/reviews/333 and asks you to have a review but you don't have a web service to do it online. So you fetch it and checks it out.

git fetch origin refs/reviews/333
git checkout FETCH_HEAD
ElpieKay
  • 27,194
  • 6
  • 32
  • 53