1

I have a commit that includes things that should be considered in another branch. So what I would like to do is cut out some portions of the commit and 'move' them into another branch. I looked at git cherry-pick and git revert but these commands seem to deal with the whole commit. Is it possible to pull out portions of a commit and move them to another branch as staged changes?

Kevin
  • 31
  • 4
  • undo the commit (`git reset`) and use `git add -p` – Ôrel Sep 27 '21 at 15:55
  • Is this the latest commit on the branch? – Schwern Sep 27 '21 at 15:56
  • Does this answer your question? [What's the difference between git reset --mixed, --soft, and --hard?](https://stackoverflow.com/questions/3528245/whats-the-difference-between-git-reset-mixed-soft-and-hard) See esp. my essay on "types of regret": https://stackoverflow.com/a/59675191/341994 – matt Sep 27 '21 at 15:57

2 Answers2

2

git cherry-pick -n will do the cherry pick but not commit it. Then you can alter the change as normal before committing.

Once that's done, remove the commit from the other branch as normal using git reset --hard or git rebase -i depending on whether it's the latest commit or if it's buried.

Schwern
  • 153,029
  • 25
  • 195
  • 336
  • `cherry-pick -n` and edit before committing is definitely appropriate ; regarding your second paragraph : re-reading the question, the OP doesn't ask to delete the original commit. – LeGEC Sep 28 '21 at 12:16
0

Assuming it's a single commit that you want to split up, this is what you can do:

git checkout -b temp the-feature # start a new branch from the feature you want to break up
git reset --soft HEAD~
# this will set the branch pointer on the parent revision
# all changes from the feature will be in the index
# take out all the changes that you would like to separate from the-feature
# when you are ready, add all files, commit
git add .
git commit -m "this is what I want to save apart from the-feature"
# here is where the magic happens:
git checkout the-feature # checkout the original feature
git reset --soft temp # make it point to the revision you created before
# now, all you should have in the index is all changes that are only relevant to the-feature
git commit -m "Changes for the-feature"
# and you can separate the branches:
git rebase --onto HEAD~2 the-feature~ the-feature
# now the two branches are separate
eftshift0
  • 26,375
  • 3
  • 36
  • 60