Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move some changes from a Git commit into a separate commit

Tags:

git

I'm on a feature branch with a single commit (as a result of an interactive rebase which squashed all of my commits).

I've decided, prior to pushing to origin and creating a pull request that I'd like to take a subset of the changes (at the file level) in that commit and make a second commit out of them since they're logically separate issues. How can I do this?

The change I'd like to break out was never in it's own commit, it just got bundled up into the first commit I did as part of the work on my feature branch.

like image 875
Scott Avatar asked Dec 24 '22 06:12

Scott


2 Answers

Move some changes from a Git commit into a separate commit

In a nutshell: reset the last commit and make 2 new commits

If I understand correctly, you want to keep most of the changes in the original commit, and put a smaller subset of changes in a second commit. If this is the case, then first you want to soft reset the last commit (thanks @hvd for the tip):

git reset --soft HEAD^

This will remove the last commit, but not the changes, as if the commit never happened, and the changes are all staged. At this point, you want to unstage the files that you don't want in the first commit. You can unstage file by file or directory by directory, like this:

git reset -- path/to/file-or-dir

Now you can do a commit for a majority of changes (already staged), and then a second commit for the rest.

If you have files where you want some of the changes in the first commit and other changes in the second commit, then you can reset the entire file first, and stage the changes selectively using git add -p, like this:

git reset -- path/to/file
git add -p path/to/file

The -p option of git add will let you select the hunks to stage. Note that you can split hunks and have a fine control of the lines to stage.

After the first commit, you can proceed with adding the still pending (not staged) changes.

like image 189
janos Avatar answered Mar 24 '23 14:03

janos


First, make sure that your working directory is free from any pending changes. Use git stash if you have changes you want to preserve.

Use git reset to move the repository "backwards" to the previous commit:

$ git reset HEAD^

This won't make any changes to your work files, but it roles back the repository state so that anything that was part of that commit will now show up as modified.

Now, add those changes that you want to be part of a separate commit, using git add. Once you have your changes staged, commit those changes with git commit.

Now, add all other remaining changes, and then commit those as well.

Now you have split your previous single commit into two separate commits.

like image 33
larsks Avatar answered Mar 24 '23 14:03

larsks