Splitting git commits into multiple commits

I fixed two errors in a piece of code and it modifies shared files. For example, bug 1, modified file A, B, C and bug fix 2, modified by B, C, and D are fixed. I have all the changes in one commit. For the purpose of code reviews, I need to split the changes into two commits (actually two branches).

I think from my current fix branch I am creating two branches like git branch fix-1 fix and git branch fix-2 fix . Both branches have all the changes. Now, in the fix-1 branch, I would like to save changes related only to fix 1, that is, all changes in file A and part of the changes in files B and C. Is it possible to do this in git? Which team is suitable for this?

I know that in git add I can do an interactive add where I can select the pieces of code to add, not just the file level. Is there something similar I can do here?

+4
source share
2 answers

If the commit was your last commit, here is the solution.

  • Check out the fix branch

     git checkout fix 
  • Reset return to fixes but save changes to working directory

     git reset HEAD^ 
  • Create branch for fix-1

     git checkout -b fix-1 
  • Add / commit fixes-1 fixes

     git add -p git commit 
  • Save the remaining changes.

     git stash 
  • Checkout / create a branch for fix-2

     git checkout -b fix-1 
  • Discard your hidden changes

     git stash pop 
  • Commit / add them

     git commit -a 
+5
source

From the state you are in (two branches, each with all changes), go to each branch and do git rebase -i fix^ and select "edit" to fix fix . Then, when it pauses commit editing for you, you use git reset HEAD^ , which discards the commit but leaves the changes in the working tree. Then use your usual git add -p strategy to split the commit into several git commits , and then git rebase --continue .

I think this is in the git rebase in the SPLITTING COMMITS section.

+3
source

All Articles