Search code examples
gitgit-stashgit-index

Making clean commits from a mess of changes in the working tree


Sometimes I end up with a working tree with a lot of changes, mainly after coding in a hurry - the changes are so many that could fit in 20 commits, spread across 2 or three branches. To clean up the working tree and commit everything nicely, I follow this unpleasant workflow:

  1. Use git add -p to inspect all the hunks in the working tree, without saving anything to the index (i.e. answer "no, don't stage this" to every hunk). Meanwhile, I try to mentally group the hunks into commits, and take some notes (in a text file) of the commits I should build with the hunks I'm seeing.

  2. After I've assigned every hunk to a commit (in my notes), then I start git add -p again, and answer "yes, stage this" only to the hunks that go into the first commit. After going over all the hunks and picking the ones I want, I actually do the commit.

  3. Repeat at step 2 as long as there are hunks left in git add -p. This means that I go over all the hunks, for every commit I have in my notes.

This is obviously a very silly way of dealing with many changes at once. Is there a good way of starting with many changes, sorting them out and then ending up with a nice set of commits, in their right branches?

Maybe there is a way to incrementally build multiple commits, simultaneously, in multiple indexes. Or maybe I should commit all the changes into one big commit, then split it into multiple ones somehow? Or maybe there's a way to (ab)use git stash to help in grouping changes together?


Solution

  • Not much of an improvement, but you could start adding files to the first commit during step one, even if that does not end up to be the first commit you really want to have, since you can finish by reordering your commits with an interactive rebase.