Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take last N commits of the current branch and apply them to another branch

This is my scenario:

  • I'm in the master branch
  • From the master branch, the branch feature1 was created
  • Several commits were added to feature1 and other commits were added to master
  • Now, I want to take ONLY the last N commits from feature1 and apply them to master.

I want to go from this:

                       (branch) feature1: f1 > f2 > f3 > f4
                      /
(branch) master: A > B > C > D

To this:

                       (branch) feature1:  f1 > f2 > f3 > f4
                      /
(branch) master: A > B > C > D > f3 > f4
like image 649
Jorge E. Hernández Avatar asked Jul 28 '17 21:07

Jorge E. Hernández


1 Answers

You can observe last hashes of your commits by running

git log -N where N is number of commit hashes you want to see.

and then you can do

git cherry-pick {firstHash}^..{lastHash} where {firstHash} and {secondHash} are starting point and ending point of your cherry-picking , its like closed interval [firstHash,lastHash] , so all commits in between will be taken as well.

Note: firstHash has to come before lastHash for obvious reasons.

if you don't want them to be commited and you only want the content of them you can do

git cherry-pick {firstHash}^..{lastHash} --no-commit

In your case if we consider (f1,f2..) are commit hashes, this should do the drill:

git checkout master
git cherry-pick f3^..f4

If there are any merge conflicts you gonna have to resolve them and call git cherry-pick --continue (sometimes git bash is stubborn about it and it doesn't show you that) to be able to continue onto the next commit.

In any case you should check the documentation of cherry pick as @Erhan mentioned - https://git-scm.com/docs/git-cherry-pick

like image 140
kuskmen Avatar answered Oct 12 '22 14:10

kuskmen