Search code examples
gitgit-fetch

What use does the --append option in git fetch command?


While looking at the documentation for git fetch I noticed the --append option. The documentation says it does this:

Append ref names and object names of fetched refs to the existing contents of .git/FETCH_HEAD. Without this option old data in .git/FETCH_HEAD will be overwritten.

What use does this have? From what I understand, FETCH_HEAD keeps track of the tips of the remotes branche that were just fetched so that merge or rebase gets called on them.

Why would appending to the list matter? Why does keeping old fetch heads matter?


Solution

  • Sometimes you may need to fetch one branch at a time:

    $ git fetch origin master
    
    # FETCH_HEAD now points to origin/master
    $ cat .git/FETCH_HEAD
    1234567890abcdef        branch 'master' of https://git.example.com/someproject
    
    # Let's fetch another branch
    $ git fetch origin dev
    
    # FETCH_HEAD is overwritten and points to origin/dev
    $ cat .git/FETCH_HEAD
    fedcba0987654321        branch 'dev' of https://git.example.com/someproject
    
    # Fetch origin/master again, preserving the previous contents of .git/FETCH
    $ git fetch --append origin master
    
    # FETCH_HEAD now contains pointers to both origin/master and origin/dev
    $ cat .git/FETCH_HEAD
    fedcba0987654321        branch 'dev' of https://git.example.com/someproject
    1234567890abcdef        branch 'master' of https://git.example.com/someproject
    

    Similarly you can fetch from multiple remotes, accumulating the results in .git/FETCH_HEAD instead of having there only the results of the most recent git fetch.

    Then you can merge all branches registered in .git/FETCH_HEAD with a single git merge FETCH_HEAD operation1:

    When FETCH_HEAD (and no other commit) is specified, the branches recorded in the .git/FETCH_HEAD file by the previous invocation of git fetch for merging are merged to the current branch.


    1 Whether it is a good practice, compared to merging each branch separately, is outside of the scope of this answer.