Home > database >  Best practice for undoing changes you made many commits ago?
Best practice for undoing changes you made many commits ago?

Time:09-05

Situations like the following happen quite often when I'm using Github and I'm not sure I'm going about them the right way.

Example. A few days ago, I added some libraries to requirements.txt file, committed and pushed the changes. Then I did a few days work and made more commits and pushes to other files. I didn't change requirements.txt at all.

Today, I realise I don't actually need the libraries I added to requirements.txt and want to remove them.

The easy thing would be to delete the unneeded libraries, make a commit, and push. But this feels too linear. Is there a more 'proper' way to do it? Should I go back in time and take the old file instead? Perhaps branch at that commit and move all the other work onto this branch? I feel like by adding a new commit that just undoes my previous one, it could clutter up the commit history?

CodePudding user response:

It really depends on what you would like to get as the history of the project... and if you will mess up other people's work.

If you are working with more people and they have already picked up that work (it's part of a shared branch, for example), then you should not rewrite history. Just commit the changes on the file (perhaps with a revert of that original revision) and move forward. You could still rewrite history of the project if you reeeeeeeeally needed/wanted to, but it creates additional work and synchronization effort to not mess it up once you have rewritten history of the branch.

If you are on your own or working on a feature branch that no one else is working on, you could consider rewriting history of the branch (with a git rebase -i is good enough) so that it looks like the change on the file never happened.

CodePudding user response:

It depends on your overall workflow. If you are still working on a feature branch or changes were only made locally you could use

  1. git revert {ID}
  2. git rebase -i {ID-Before-Commit}

For work I haven't shared yet I would probably go with option 2. It is usable for many scenarios and is worth to be familiar with. Read more

However, if you've already shared your changes with others it might be better just to add another commit with a proper message. In this case git revert {Id} can be used to 'undo' a complete commit.

  • Related