Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git cherry-pick or merge specific directory from another branch

Tags:

git

I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example git checkout A -- X Y doesn't tell me much.

Basically I want this:

  • Create new branch featureA off of master
  • Merge directory /tools/my-tool from branch dev into featureA
like image 935
daleyjem Avatar asked Nov 06 '13 20:11

daleyjem


People also ask

Can you cherry pick a merge?

Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.


2 Answers

To answer the original question about how to cherry-pick some directories (as commits instead of a brute-force checkout), this is possible. Imagine that featureA has diverged from master and you want to bring over the tools/my-tool commits.

Assuming that you never made any commits that contain both stuff from /tools/my-tool and stuff from other directories

This will get you the list of commits to master in tools/my-tool (that are not already in featureA), in reverse-chronological order:

git log --no-merges featureA...master tools/my-tool 

To say it another way:

git log --no-merges source_branch...dest_branch my/firstpath my/secondpath [...] 

To get just the commits you need in chronological order, you need to first reverse the order of the input lines (such as with tail -r or tac), then isolate the column for the commit hash (such as with cut):

git log --format=oneline --no-merges featureA...master tools/my-tool \     | tail -r \     | cut -d " " -f 1 

And to do the whole operation at once, do this:

git cherry-pick $(git log --format=oneline --no-merges featureA...master tools/my-tool | tail -r | cut -d " " -f 1) 
like image 131
Ian Avatar answered Sep 17 '22 13:09

Ian


Here is the right way to cherry-pick commits from another branch for one folder:

git format-patch -k --stdout master...featureA -- tools/mytool | git am -3 -k

This will apply the patches to the "tools/mytool" files only, in order.

If you have a merge conflict on any commit, it will pause for you to fix it. git am --continue will resume where it left off.

like image 22
Sean Dunlap Avatar answered Sep 19 '22 13:09

Sean Dunlap