8

In git, I have a branch A. I create another branch B where I create few commits. Then I want to fast forward branch A to branch B.

I know that I can checkout A and do fast forward to the latest commit of B. This operation requires two modifications of working copy: the first to return to A and then revert working copy to B. If new commits on B contain a lot of changes, the operation could be quite slow.

Is it possible to do fast forward another branch without changing the working copy? (in other words, to move just the pointer of A)

Shep
  • 7,990
  • 8
  • 49
  • 71
TN.
  • 18,874
  • 30
  • 99
  • 157

2 Answers2

6

Git provides the update-ref command for this purpose

git update-ref A B

Note: This command is one of the lower-level Git commands and does not provide any safeguards for you to keep from screwing yourself up. If B is not a fast-forward of A it will still update A, potentially making commits unreachable and subject to garbage collection.

Andrew C
  • 13,845
  • 6
  • 50
  • 57
  • @Zeeker says that it no longer loses commits: http://stackoverflow.com/questions/26752567/is-it-better-to-use-git-branch-f-or-git-update-ref-to-fast-forware-existing-bra#comment42096589_26752567 – TN. Nov 05 '14 at 13:45
  • 2
    The aren't going to magically disappear the moment you do the `update-ref` or anything like that. But they can become unreachable, and once that happens are subject to the normal garbage collection policies. – Andrew C Nov 05 '14 at 16:32
  • Hmm.. I want do this, but not enough to use a naked update-ref. :-( – Thilo Dec 05 '14 at 00:54
  • @Thila You could use `git branch -f` if you wanted, or script something that did `git merge-base --is-ancestor` and then did the update only if it was true. – Andrew C Dec 05 '14 at 05:37
2

If you want to fast forward move another branch to the current HEAD, you can also:

git fetch . HEAD:another-branch

Unfortunately this doesn't work with commit IDs like:

git fetch . TARGET_ID:another-branch

But it works with branch or tag names.
So, my solution is to create a temporary target branch:

git branch target <your-target-ref-id>
git fetch . target:another-branch
git branch -d target

You could do this in one line:

git branch t <your-target-ref-id> && git fetch . t:another-branch && git branch -d t

<your-target-ref-id> could be a commit id, tag or branch name.

Finally you can put this in a script or git alias.

LaChRiZ
  • 29
  • 5