Forgot to create new branch. How to transfer changes to new branch

前端 未结 6 2044
闹比i
闹比i 2021-02-19 13:45

this happens to every developer time-to-time. You start coding a new feature and forget to branch first locally.

So if that happens is there a way I can say hey, transf

6条回答
  •  抹茶落季
    2021-02-19 14:05

    1. In case you have committed the changes already!

    In the following case you started off with "Hello world" at the very beginning and after a commit your head was at C4, now, you stayed on master and made commits till C0 but forgot to create different branch at C4 itself

    Now in this case what you can do is

    -- Make a patch of commits from C3 to C0 so that you would have changes made in respective commits saved in files like C3.patch....C0.patch in the directory of your repo itself

    -- Reset your HEAD to C4

    -- And checkout all the unstaged changes so that you can create a new branch

    -- And apply those changes back on the newly created branch

    Basically you do

    -- git format-patch HEAD ~ {n} (n is 4 in this case)
    -- git reset HEAD~{n} (reached master or parent branch) 
    -- git checkout -- .
    -- git checkout -b 
    -- git am (or git am *.patch) (which is git apply -r C*.patch in this case)
    
    1. In case where you have not committed changes

    -- If they are staged, unstage by resetting head to the previous commit where you started of with making these changes

    -- Make a patch of these changes so that you have them stored on local repo directory

    -- Checkout those changes and make a new branch

    -- Apply that created patch to have those changes back on a new branch

    Basically you do

    -- git reset HEAD~1
    -- git diff > unstaged_changes.patch
    -- git branch -b 
    -- git am unstaged_changes.patch
    

提交回复
热议问题