Home > OS >  Can you revert a single file from an old commit? (Git, bitbucket)
Can you revert a single file from an old commit? (Git, bitbucket)

Time:01-22

I have an issue regarding a recent PR that I created on Bitbucket. I accidentally copy pasted the content of the file, in a way that the whole content appears to be written by me, which ruins the Git history, which is important. This commit got pushed and several commits were followed after that, so undoing the commit is not the solution here, since every commit has a lot of changes.

I was wondering if there's a way to revert only an old file from an old commit, make only the necessary changes and commit this specific file.

I have read some articles about it but haven't come up with a safe solution yet.

Thank you in advance :)

CodePudding user response:

you can do it by reset your local after a checkout to the needed commit

git checkout 0d1d7fc32
git reset --soft HEAD~1
git restore {yourFile}

-- recommit and repush the commit 

CodePudding user response:

My preferred method of doing a partial revert is this:

git revert --no-commit <commid-id-to-revert>

At this point the changes from that revert will all be staged. You can unstage any files you don't wish to revert, and modify/re-stage any files you wish to tweak. (In your specific case you would unstage all files except the one you wish to revert.) Note it's possible you'll have conflicts. You can just "keep current" for any conflicts on files you don't wish to revert, but for conflicts on those that you wish to keep you'll need to resolve them the same way you normally would.

When you're finished making changes, continue the revert from the command line so the commit message is auto-populated:

git revert --continue

Tip: By default, when you revert a commit, the commit message will look something like:

Revert "Title of commit message being reverted"

This reverts commit <some-commit-id-here>.

My recommendation is to change that message, specifically for partial reverts, to something like this:

Revert (Partial) "Title of commit message being reverted"

This (partially) reverts commit <some-commit-id-here>.

A custom explanation of which parts of the commit are being reverted,
and why.
  •  Tags:  
  • Related