Skip to content

Instantly share code, notes, and snippets.

@jiffle
Created August 26, 2018 11:07
Show Gist options
  • Save jiffle/ff53feb5531994e722a5b8ee639f2b06 to your computer and use it in GitHub Desktop.
Save jiffle/ff53feb5531994e722a5b8ee639f2b06 to your computer and use it in GitHub Desktop.
Git History Rewriting Tricks

Git History Rewriting Tricks

Removing incorrectly committed files from the last commit

This uses a Soft Reset to revert the commit, leaving the commit modifications as local working copy changes:

git reset --soft HEAD^ or git reset --soft HEAD~1

Then reset the unwanted files in order to leave them out from the commit:

git reset HEAD path/to/unwanted_file

Now commit again, you can even re-use the same commit message:

git commit -c ORIG_HEAD

Spliting a commit that contains changes from multiple features

(From Rebase section of Git Manual on Splitting Commits)

In interactive mode, you can mark commits with the action "edit". However, this does not necessarily mean that git rebase expects the result of this edit to be exactly one commit. Indeed, you can undo the commit, or you can add other commits. This can be used to split a commit into two:

Start an interactive rebase with

git rebase -i <commit>^

where <commit> is the commit you want to split. In fact, any commit range will do, as long as it contains that commit.

Mark the commit you want to split with the action "edit".

When it comes to editing that commit, execute

git reset HEAD^

The effect is that the HEAD is rewound by one, and the index follows suit. However, the working tree stays the same.

Now add the changes to the index that you want to have in the first commit. You can use git add (possibly interactively) or git gui (or both) to do that.

Commit the now-current index with whatever commit message is appropriate now.

Repeat the last two steps until your working tree is clean.

Continue the rebase with git rebase --continue.

If you are not absolutely sure that the intermediate revisions are consistent (they compile, pass the testsuite, etc.) you should use git stash to stash away the not-yet-committed changes after each commit, test, and amend the commit if fixes are necessary.

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