Chapter 8. Recovering from Mistakes

In this chapter, we will cover the following topics:

  • Undo – remove a commit completely
  • Undo – remove a commit and retain the changes to files
  • Undo – remove a commit and retain the changes in the staging area
  • Undo – working with a dirty area
  • Redo – recreate the latest commit with new changes
  • Revert – undo the changes introduced by a commit
  • Reverting a merge
  • Viewing past Git actions with git reflog
  • Finding lost changes with git fsck

Introduction

It is possible to correct mistakes made in Git the with git push context (without exposing them if the mistake is found before sharing or publishing the change). If the mistake is already pushed, it is still possible to undo the changes made to the commit that introduced the mistake.

We'll also look at the reflog command and how we can use that and git fsck to recover lost information.

There is no git undo command in core Git. One of the reasons being ambiguity on what needs to be undone, for example, the last commit, the added file, and so on. If you want to undo the last commit, how should that be done? Should the changes introduced to the files by the commit be deleted? For instance, just roll back to the last known good commit, or should they be kept so that could be changed for a better commit or should the commit message simply be reworded?. In this chapter, we'll explore the possibilities to undo a commit in several ways depending on what we want to achieve. We'll explore four ways to undo a commit:

  • Undo everything; just remove the last commit like it never happened
  • Undo the commit and unstage the files; this takes us back to where we were before we started to add the files
  • Undo the commit, but keep the files in the index or staging area so we can just perform some minor modifications and then complete the commit
  • Undo the commit with the dirty work area

Note

The undo and redo commands in this chapter are performed on commits that are already published in the example repository. You should usually not perform the undo and redo commands on commits that are already published in a public repository, as you will be rewriting history. However, in the following recipes, we'll use an example repository and execute the operations on published commits so that everyone can have the same experience.

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

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