Search code examples
gitversion-controlmerge

Git workflow: Merge existing branch to new branch and delete old one


Scenario: being on master branch

  1. git checkout target_branch

  2. git checkout new_branch

  3. git commit -m: "TARGET BRANCH TASK NUMBER,NEW BRANCH TASK NUMBER: Message"

  4. git push origin new_branch

  5. git checkout target_branch

  6. git push origin target_branch

merge request (target - target_branch)

As I understand my new_branch isn't created from target_branch because firstly I made push from new_branch and only then I pushed target_branch (just forgot it).

So help me please do properly the next:

I'm going to work in target_branch with my friend, and we will create our branches from it.

I need now make my new_branch to be created from target_branch and delete old new_branch (that, I suppose, now seems to be created from master not from target_branch).

How can I do this properly (for Git history)?


Solution

  • To change new_branch checked out from target_branch (or master you can use same method):

    git checkout target_branch
    git cherry-pick target_branch..new_branch
    git branch -f new_branch
    git checkout new_branch
    

    Note:

    -If there has cherry-pick conflicts, you can modify and save the conflict files, then use git add . and git cherry-pick --continue. -If you don’t want to rebase new_branch on the top of target_branch, you can use git checkout <an history commit of target_branch>, and then use above commands to rebase new_branch. As below graphs, if you use git checkout B, and after above commands, the branches will look like:

    # Original branch structure
    
        A---B---C target_branch
    
        D---E---F new_branch
    
    # After rebase new_branch from commit B
    
        A---B---C target_branch
             \
              D'---E'---F' new_branch