prasad
prasad

Reputation: 229

git create branch with existing local commits

I have started working on a feature branch and made some changes and commit. But I have not pushed these changes to remote tracking branch. But now I want to create a separate bug fix branch so that I can create pull request. How can I create a new branch with all commit history i made on current branch without pushing.

I would like to add commit graph for more clarity. A---B---C---D---E---G

So I have made changes on branch where A was already on remote and made local commits BCDEG. Now I want new branch staring from A commit with all the local commit BCDEG so that for review I can create new pull request on existing feature branch commit A.

Upvotes: 2

Views: 1955

Answers (2)

Damon D
Damon D

Reputation: 196

Given that you want to change

A` <-- A <-- B <-- C <-- D <-- E <-- G
^origin/feature                      ^HEAD, feature

to

         -- B <-- C <-- D <-- E <-- G
        /                           ^HEAD, bug-fix
A' <-- A
^      ^feature
|
origin/feature

First, you need to create your branch

git branch bug-fix

This gives you the diagram

A' <-- A <-- B <-- C <-- D <-- E <-- G
^origin/feature                      ^ feature, bug-fix, HEAD

Note that you are still on the feature branch, you only need to make the bug-fix branch, don't checkout yet.

Next, you need to remove the commits on feature (B, C, D, E, G) with reset (A here is the SHA1 hash of the commit, you can also use relative HEAD position):

git reset --hard A

NOTE you will lose any uncommitted work on feature - please do understand the perils of the reset command before executing that command. All the reset does is "push" the pointer of feature to the commit A.

Then checkout your new branch and push your feature branch changes for a pull request:

git checkout bug-fix
git push

This gives you the desired diagram of:

         -- B <-- C <-- D <-- E <-- G
        /                           ^ HEAD, bug-fix
A' <-- A
       ^origin/feature, feature

Upvotes: 7

ilardm
ilardm

Reputation: 146

Assuming you are already on your feature branch and want to create new branch, starting from feature branch, just do:

git checkout -b <new_branch>

After that you can push it to origin and create pull request like:

git push origin <new_branch>

P.S. if I understood your question correctly.

Upvotes: 0

Related Questions