Search code examples
gitbranch

Copy state of another branch and commit them in git


I have two branches in Git, A and B. I want to be in branch B and ”checkout” the complete ”state” (not history) of A but still be in B, and then commit that as one single change of B.

So files that are present in B but not A are deleted in that commit, files are present in A but not B are created in the commit, and files that differ between A and B are modified in B. So the history of B is kept but the ”states” of A and B are identical.

How do I do that?


Solution

  • The old way of doing that would be (assuming you are on B already):

    git checkout A -- .
    git commit -m "single change to get to A's content"
    

    The new way is:

    git restore --worktree --staged --source=A -- .
    git commit -m "single commit to get to A's content"
    

    The longer but possible way would be:

    git checkout --detach A
    git reset --soft B # set the branch pointer (well, HEAD, actually) to where B points to
    git commit -m "single commit to get to A's content"
    # now you have this single revision after B that has the same content of A
    # set B over here and checkout
    git branch -f B
    git checkout B
    

    That would also work.