Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting git commit into a few commits

Tags:

git

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

What I am thinking is that from my current branch fix, I create two branches like git branch fix-1 fix and git branch fix-2 fix. Both branches have all changes. Now, in branch fix-1, I would like to keep the changes relevant to fix 1 only, that is, all changes in file A, and parts of changes in files B and C. Is it possible to do it in git? What command is relevant for this?

I know that in git add, I can do interactive add where I can select hunks of code for adding, not just at file level. Is there something similar I can do here?

like image 904
Yogeshwer Sharma Avatar asked Feb 24 '23 08:02

Yogeshwer Sharma


1 Answers

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

  1. Checkout the branch with the fix

    git checkout fix
    
  2. Reset back to before the fixes, but keep the changes in your working dir

    git reset HEAD^
    
  3. Create branch for fix-1

    git checkout -b fix-1
    
  4. Add/commit fix-1 fixes

    git add -p
    git commit
    
  5. Stash the remaining changes

    git stash
    
  6. Checkout/create branch for fix-2

    git checkout -b fix-1
    
  7. Pop off your stashed changes

    git stash pop
    
  8. Commit/add them

    git commit -a
    
like image 80
Andy Avatar answered Feb 26 '23 20:02

Andy