Home > Software design >  How to "git reset" to an old commit and add changes WITHOUT deleting the old commits in my
How to "git reset" to an old commit and add changes WITHOUT deleting the old commits in my

Time:11-15

I want to use an older commit and add different changes (but I do not want to delete my commit history). Currently, something like this will delete the last 3 commits in my GitHub pull request history and show a new commit with my new changes.

git reset HEAD~3
git add .
git commit -m "New changes"
git push --force

Is there a way to keep my last 3 commits and then have a 4th commit with "New changes"?

What I Tried:

git reset HEAD~3
git add .
git commit -m "New changes"
git push --force

What I Want to Happen: Add a new commit WITHOUT deleting the commit history

What Actually Resulted: A new commit, in place of the last three commits.

CodePudding user response:

A commit, once written, can never be changed again. But you can replace it with a new, similar commit.

If you have commits A-B-C-D-E and you want to change something in commit B, you need to create a new commit B' (and C'-D'-E'). The easiest to achieve this is doing an interactive rebase:

$ git rebase -i A
$ # now change the line "pick B" to "edit B" and save the file
$ # make your changes and stage (add) them
$ git commit --amend # create commit B'
$ git rebase --continue
$ # git will automatically create C'-D'-E'

If your new changes conflict with changes of C-D-E, Git will stop the rebase and ask you to resolve the conflicts.

Changing the "todo list" can be partially automated if your changes are independent of any existing changes in your subsequent commits by creating a "fixup commit" and then running rebase with autosqash:

$ # make your changes and stage them
$ git commit --fixup B
$ git rebase -i --autosquash
$ # fixup commit should be moved after "B" and changed to "fixup"
$ # save file and exit editor

Again, if there are any conflicts, Git will stop the rebase and ask you to resolve the conflicts, then continue with git rebase --continue.

CodePudding user response:

This is done these days like this:

git restore --staged --worktree --source=HEAD~3 -- .
git commit "reverting to blahblah"
  • Related