36 Reverting Commits

Sometimes we make mistakes. A commit that wasn’t supposed to be shared gets pushed to a public repository, a commit has a bug that can’t be fixed and needs to be undone, or maybe you just don’t need that code any longer. These cases all call for git revert.

The git revert command does just what you might expect. It reverts a single commit by applying a reverse commit to the history.

You can call git revert with just a commit ID. Git launches the editor with the commit message already filled out. It follows this pattern:

 
Revert "some commit message"
 
 
This reverts commit <some commit hash>.

You can edit this message to be whatever you want. You can use the --no-edit parameter to tell Git to use the default message without passing it through the editor if the default is sufficient.

Sometimes you need to revert several commits to completely undo a change. You can use --no-commit, or you can use -n to tell Git to perform the revert but stop short of committing the change. This lets you combine all the revert commits into one commit, which is useful if you need to revert a feature that spans several commits. Make sure that you revert commits in reverse order—the newest commit first. Otherwise, you might confuse Git by trying to revert code that doesn’t exist yet.

You can use git revert to undo commits that you don’t want or need any longer, but it does leave a trace. In most cases, you don’t want commits “disappearing” from your repository. For those instances where you don’t want a record of your commit at all, see Task 38, Erasing Commits.

What To Do...
  • Revert a particular commit.
     
    prompt>​ git revert <commit id>
     
    ...​ example ...
     
    prompt>​ git revert de3245fa
     
    Finished one revert.
     
    ...​ launches editor ...
     
    [master 743d2ef] Revert "simplify this code a bit"
     
    1 files changed, 1 insertions(+), 1 deletions(-)
  • Revert a particular commit, and use the default message.
     
    prompt>​ git revert --no-edit <commit id>
     
    ...​ example ...
     
    prompt>​ git revert --no-edit de3245fa
     
    Finished one revert.
     
    [master 3a26b89] Revert "simplify this code a bit"
     
    1 files changed, 1 insertions(+), 1 deletions(-)
  • Revert a commit, but don’t commit the change.
     
    prompt>​ git revert --no-commit <commit id>
     
    Finished one revert.
     
    ...​ or ...
     
    prompt>​ git revert -n <commit id>
     
    Finished one revert.

Related Tasks

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.187