Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can changes in the same file be split to different commits in git?

Sorry if there is a duplicate for this somewhere, I drowned in a flood of tricks to change commit messages (which doesn't help me) when searching for a solution to this.

I have two sets of changes that should be part of one commit each. Unfortunately, I started the second changeset in the morning, not noticing that I had forgotten to commit the first one in the evening before.

In most cases, they affect different files. However, there is one file that contains changes for both changesets which break the build if pushed without the second changeset. Too bad I want to work on that on a separate branch until functional.

Sadly, I had already committed (not pushed) the first changeset and created the work branch on top of it when I noticed that there was a file containing changes for both.

Is there a way to edit my commit such that I can extract the changes affecting changeset 2?

In Mercurial, you could untangle commits by

  1. converting them to patches,
  2. opening them in a text editor and
  3. moving lines of diff between the patch files (if your Mercurial GUI was not open at the time).

When the GUI was reopened, the patches contained what they were supposed to, could be finalized and pushed.

That's actually the workflow I am aiming for. Is there anything similar for git?

Tools I am using: TortoiseGit and GitExtensions on Win10

Edit: solution as suggested in the answer

git checkout new_branch
git reset -p HEAD~1
git add -p
...
git commit -m "my changeset 1"
git add
git commit -m "my changeset 2"
git checkout old_branch
git reset --hard <new_branch>~1

Which gives me old_branch at changeset 1 and new_branch at changeset 2.

Thanks again!

like image 539
starturtle Avatar asked Feb 10 '17 08:02

starturtle


1 Answers

Use git add -p to selectively stage changes/hunks that you plan to commit. After you commit the first batch, you may be left with the second set of changes in which case you can just add the file as normal and commit.

Git will ask what you want to do with each commit. Type '?' for help. Press 'y' to stage the hunk and 'n' to disclude the hunk from your staging area.

In the case where git doesn't select a hunk at a fine enough grain, when it asks you what to do with the hunk, you can press 'e' and your editor will open and you can choose which parts of the hunk you want to include.

Learned about this recently and it's been incredibly useful.

like image 108
jbu Avatar answered Sep 30 '22 01:09

jbu