Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git create branch from range of previous commits?

Tags:

git

I have a bunch of commits for an OS project and I want to pull out just the last say 20 commits into another branch so I can pull request.

How could I do this? The reason being is I have maybe 150 commits, but most of those are for a much larger contribute, which isn't ready yet. But the next version is being released soon.

Thanks!

like image 375
Steven Avatar asked Mar 24 '12 17:03

Steven


People also ask

How do I create a branch from a previous commit?

In order to create a Git branch from a commit, use the “git checkout” command with the “-b” option and specify the branch name as well as the commit to create your branch from. Alternatively, you can use the “git branch” command with the branch name and the commit SHA for the new branch.

Can I copy a commit to another branch?

git cherry-pick <commit-hash> will apply the changes made in an existing commit to another branch, while recording a new commit. Essentially, you can copy commits from branch to branch.


1 Answers

You can do this with cherry-pick. If your history of long_branch looks like this:

A-B  <-- master    \     C-D-E-F-G-H  <-- long_branch 

and you want to move the contents of, say, F through H to a different branch, say, short_branch, which is based off of master:

git checkout master -b short_branch 

which gives

A-B  <-- master, short_branch    \     C-D-E-F-G-H  <-- long_branch 

then... (note that the commit range is E..H; the left side is non-inclusive for the range)

git cherry-pick E..H 

which gives:

    F'-G'-H'  <-- short_branch    / A-B  <-- master    \     C-D-E-F-G-H  <-- long_branch 

Note that I'm referring to the new commits as F', G', H' - this is because while they will contain the same effective changes as F, G, and H, they won't be the actual same commits (due to different parents + commit times).

like image 59
Amber Avatar answered Oct 05 '22 19:10

Amber