DonQuijote
DonQuijote

Reputation: 57

How to "git reset" to an old commit and add changes WITHOUT deleting the old commits in my GitHub pull request

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 Want to Happen: Add a new commit WITHOUT removing the last three commits in history

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

Upvotes: 0

Views: 346

Answers (2)

eftshift0
eftshift0

Reputation: 30156

This is done these days like this:

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

Upvotes: 3

knittl
knittl

Reputation: 265141

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.

Upvotes: 1

Related Questions