Is it possible to fast forward another branch without checking it out?
Asked Answered
E

2

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)

Emphysema answered 4/11, 2014 at 14:29 Comment(2)
git update-ref. Use with caution.Glomeration
@AndrewC add it as an answer.Emphysema
G
5

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.

Glomeration answered 4/11, 2014 at 21:38 Comment(4)
@Zeeker says that it no longer loses commits: #26753067Emphysema
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.Glomeration
Hmm.. I want do this, but not enough to use a naked update-ref. :-(Shelleyshellfire
@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.Glomeration
R
3

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.

Refuse answered 10/2, 2020 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.