0

I think this question is very general, so sorry for not being specific. When I modify some come code to try something new, whatever the project or language, I may have to revert back to previous Git commits if it all fails. But in the process of making these uncertain modifications (let's call them X), I also make some nice corrections or additions (let's call them Y) that I want to keep.

Is there a clever way to separate X and Y, so that at the end of the day I can keep Y and discard X?

Ben
  • 429
  • 4
  • 11
  • Are X and Y committed separately, or are they all lumped into the changes in the working directory? – Jeff Puckett Jun 15 '16 at 17:45
  • just to expand on #2 in [0x5453's answer](http://stackoverflow.com/a/37840868/4233593), if you have a lot of changes that need to be sorted for different commits, then you should create an interactive patch with `git add -p`. see [my answer](http://stackoverflow.com/a/37769129/4233593) about creating precision patches when splitting hunks isn't enough. – Jeff Puckett Jun 15 '16 at 17:51

2 Answers2

3

Here's what I do:

  1. Make a new branch for my "uncertain modifications".
  2. As I'm going, make small commits that can stand alone.
  3. If my commits aren't small enough to keep only the changes I need, I'll have to go back and split old commits. Interactive rebase to the commit in question, reset to HEAD~, and split the changes into relevant commits.
  4. Rebase/cherry-pick commits I want to keep back onto my original branch.
  5. Squash those small commits to keep history clean.
0x5453
  • 12,753
  • 1
  • 32
  • 61
0

Maybe this was implicit in 0x5453's answer, but I just want to add a precision which was central in my question. To make small standalone commits, a very nice feature is interactive adding/committing. I personally use git commit --interactive. This enables me to choose small portions of my modifications to gather in one, logically homogeneous commit. That way, I can organise several changes into different commits ex post and leave uncommitted uncertain changes (and potentially stash them if I need to push/pull). This comes very handy when I make many unrelated modifications in one shot.

That said, it is still very important to commit (interactively) often enough not to be lost in a huge amount of changes.

Ben
  • 429
  • 4
  • 11