Skip to content

Instantly share code, notes, and snippets.

@mjdominus
Created February 7, 2012 21:14
Show Gist options
  • Save mjdominus/1761992 to your computer and use it in GitHub Desktop.
Save mjdominus/1761992 to your computer and use it in GitHub Desktop.
Separating two sets of changes into two branches

Say you want to separate commits to two sets of files, and you want to do this on the branch that starts at commit start and ends at commit end, so that if there are n of these commits, you'll end up with two new branches, each with n commits, one branch with just to the changes in the files in group X and the other with just the changes to the files in group Y.

First, we will create branch branch-X, for just the changes to files in group X:

git checkout -b branch-X start^
for commit in $(git rev-list --reverse start..endpoint); do
  git checkout $commit -- ((list of files and directories in X))
  git commit -C $commit
done

Now we'll do the same for Y, exactly the same but with Y instead of X:

git checkout -b branch-Y start^
for commit in $(git rev-list --reverse start..endpoint); do
  git checkout $commit -- ((list of files and directories in Y))
  git commit -C $commit
done

I hope this is something like what you wanted.

@alexpcoleman
Copy link

for anyone else who runs across this, i had to modify it slightly in order to handle the case where all the files in your list are not contained in all commits – git checkout throws an error if you pass it any files not found in a designated commit.

replace:

  • new-branch-name - name of the new branch you want these changes to go into
  • startcommithash - hash of the last commit in question
  • endcommithash - hash of the last commit in question
  • list.js of.txt your.md files.ts with a space-delimited list of all of the files you want to be a part of new-branch-name
git checkout -b new-branch-name startcommithash
for commit in $(git rev-list --reverse startcommithash..endcommithash); do
  for file in list.js of.txt your.md files.ts
  do
    git checkout $commit -- $file
  done
  git commit -C $commit
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment