2

I have an old commit, A. When I committed A, I changed 2 files: F1 and F2. I want to change A, so it only modifies file F1. I want to commit F2 separately. I do not want to delete F1 from my git repository.

I tried doing this by

git rebase -i HEAD~3 // The exact number doesn't matter, I just change "pick" to "edit" next to A
git reset HEAD^ // unstage all changes
git add F1 // don't add F2, we want to commit it separately
git rebase --continue

However, this gives the error

F2: needs update
You must edit all merge conflicts and then
mark them as resolved using git add

I solve the problem by doing git rebase --skip

However, this removes commit A from the git history completely.

What am I doing wrong?

I looked at other posts on SO, and tried the solutions, but they didn't work.

Foobar
  • 7,458
  • 16
  • 81
  • 161
  • Have you already pushed this branch to the remote, and is it already shared? If so, then you should probably _not_ be attempting to rewrite the branch history via git rebase. – Tim Biegeleisen Nov 11 '19 at 05:12
  • No one else has pulled this branch yet. Also, once I merge this branch, I can delete it, so I imagine there shouldn't be an issue? – Foobar Nov 11 '19 at 05:13
  • 1
    https://stackoverflow.com/questions/32315156/how-to-inject-a-commit-between-some-two-arbitrary-commits-in-the-past – Tim Biegeleisen Nov 11 '19 at 05:21

2 Answers2

3

Here is how I would do this:

git rebase -i HEAD~3 //Change "pick" to "edit" for commit to change
git reset HEAD^ -- F2 //reset F2 to previous version in staging area
git commit --amend //replace current commit with F1 change only
git add F2 // add new F2 back to staging area
git commit //commit F2 in a separate commit
git rebase --continue

Note that this, as all rebases, rewrites history, and so should only be done if the commits have not yet been pushed to a public repository.

David Sugar
  • 1,042
  • 6
  • 8
0

I almost did what @Tim's post suggested, except I had to add in 1 command. Here's what I did:

git rebase -i HEAD~3 // The exact number doesn't matter, I just change "pick" to "edit" next to A
git reset HEAD^ // unstage all changes
git add F2
git commit -m "Add F2"
git add F1
git commit -m "Add F1"
git rebase --continue

The git reset HEAD^ was not mentioned in the linked post.

Foobar
  • 7,458
  • 16
  • 81
  • 161