well actually
well actually

Reputation: 12360

Git undo changes to files which match regex in particular changeset

Say I have a bunch of files which were modified by changeset X. This changeset is currently HEAD. I want to separate all changes to files that match regex '*Test.java' into another changeset. If I do:

git diffstat HEAD^ HEAD

I would currently get something like:

M       a/b/c/ThisIsSomeClass.java
M       a/b/c/d/ThisIsSomeTest.java
M       a/JustAnotherClass.java
M       a/b/c/AnotherTest.java

What sequence of git commands can I do to separate the *Test.java files into another changeset?

Upvotes: 1

Views: 6543

Answers (1)

Brian Campbell
Brian Campbell

Reputation: 332736

Something like this should work. Make sure to run it in a copy of your Git repo at first to make sure that it works correctly; if you're not careful with running reset, it's possible to lose work. In general, when doing manipulation like this, you should make sure your directory is clean; everything should be committed, stashed, or ignored, so there aren't any important changes or uncommitted files lying around.

git reset --soft HEAD^
git reset $(git diff --cached --name-only -- '*Test.java')
git commit -m "This is the first commit, that does not contain the *Test.java"
git add -u .
git commit -m "This is the second commit, of just the *Test.java files"

The reset --soft will reset you to commit HEAD^, but with all of your changes from the last commit still staged, ready to be committed. The next git reset will unstage all of the changed files named *Test.java, leaving the other ones still staged. The commit will commit those changes that are still staged. Now you stage all of the other files again, with git add -u . (this will only stage files that are changed, it won't add new files, so this is safe to run even if you have other files that you don't want to add to your commit; if you do have new files that you unstaged in the process of doing this, then drop the -u or add them individually). And then you commit that second set of files.

Upvotes: 2

Related Questions