How to use git to remove a large feature I might want back later

Let’s say you have a large feature or chunk of code that you want to remove. But you might want to get it back later. How can you use Git to make it as easy as possible later to get your code back?

Removing a large feature or bit of code

Here’s how to use Git to make this easy for you:

  • Remove all the code for the entire feature in a single commit. That includes specs, config examples, documentation, and anything else that is only relevant to the feature at hand
  • Use a high level commit message like, “Remove XYZ feature”
  • Add more details to the extended commit message about why you are doing this, and why you might want to undo it later
  • Also include details in the extended commit message about any hurdles (data migrations, etc.) that might be needed when restoring later, if you need to do it

Restoring a large feature or bit of code from a commit that removed it

Restoring your changes later is probably one of the best and only reasons for using git revert. This is also straightforward if you used the advice above and kept your removal in a single commit.

  • Find the commit where you removed the feature, make note of the commit id.
  • Run git revert <my-commit-id> to revert the commit.
  • If conflicts arise, fix them, and then run git revert --continue.
  • (Optionally) Run git reset HEAD^ if you don’t want to commit yet, but just rather want the reverted changes to be present and unstaged in your working branch.
  • In any case, don’t use the default commit message Git prompts you with (Revert "ORIG_COMMIT_MESSAGE_HERE"). Instead, write a meaningful commit message with a title like “Restore XYZ Feature” that explains why this feature or code came back, and what the side-effects (if any) might be.
What if I didn't keep my changes in a single commit?
If you didn’t think ahead and keep your changes to remove your feature in a single commit, fear not! You can still use the steps above to restore. Just be sure you revert the commits in reverse order (revert the newest commit first), and follow the steps as you revert each commit. Afterwards, you may have a handful of “restore” commits. At that point, you can rebase interactively to squash your changes into one happy commit that reads something like, “Restore XYZ feature” with all your notes in the commit message.