Purpose
You’ve done some work in your repository and you realize the newest version of some third-party code, say a Ruby gem for instance, isn’t working out. But you’ve based some good changes off of this “broken” branch of your project, say some features for your next release that aren’t dependent on that broken third-party code. Now, you want to revert previous changes while keeping 1 or more other non-dependent changes.
Overview
To accomplish this, we need to do a few things:
- Commit all changes in separate feature-specific commits.
- Check out a stable version of our project
git checkout [BRANCH/COMMIT]
- Create a patch and apply it to our stable branch
Step 3 can be repeated as much as needed.
Example
Let’s say all of our commits that we need to revert to and pull from are in our same branch. This is a more common use case, but one that is harder to accomplish.
git commit -A -m "awesome changes we'll need later" git checkout 12c9c2d70dcfcb1d2 # previous commit's hash code git diff HEAD d72f601e8efcf7248fd
After running the diff, if everything looks good, progress on to applying the patch. If you only want to apply a certain file or subdirectory, you’ll need a new diff:
git diff HEAD d72f601e8efcf7248fd -- app/controllers/my_controller.rb
Once you find the exact diff you need, you can apply the patch to your current branch.
git diff HEAD d72f601e8efcf7248fd -- app/controllers/my_controller.rb | git apply