Annuler des changements

Annuler les commits et les changements

In this section, we will discuss the available 'undo' Git strategies and commands. It is first important to note that Git does not have a traditional 'undo' system like those found in a word processing application. It will be beneficial to refrain from mapping Git operations to any traditional 'undo' mental model. Additionally, Git has its own nomenclature for 'undo' operations that it is best to leverage in a discussion. This nomenclature includes terms like reset, revert, checkout, clean, and more.

A fun metaphor is to think of Git as a timeline management utility. Commits are snapshots of a point in time or points of interest along the timeline of a project's history. Additionally, multiple timelines can be managed through the use of branches. When 'undoing' in Git, you are usually moving back in time, or to another timeline where mistakes didn't happen.

Ce tutoriel présente tous les outils nécessaires pour travailler avec les révisions précédentes d'un projet logiciel. Tout d'abord, nous verrons comment explorer d'anciens commits, puis nous parlerons de la différence entre le revert de commits publics dans l'historique du projet et le reset des changements non publiés en local, sur votre ordinateur.

Finding what is lost: Reviewing old commits

L'idée sous-jacente de tout système de contrôle de version est de stocker des copies sécurisées d'un projet afin que vous n'ayez plus à vous préoccuper de corrompre votre base de code. Une fois que vous avez créé un historique de projet pour les commits, vous pouvez passer en revue et revoir tous les commits de l'historique. La commande git log constitue l'un des meilleurs outils pour passer en revue l'historique d'un dépôt Git. Dans l'exemple ci-dessous, nous utilisons git log pour obtenir la liste des derniers commits effectués dans une bibliothèque graphique open source populaire.

git log --oneline
e2f9a78fe Replaced FlyControls with OrbitControls
d35ce0178 Editor: Shortcuts panel Safari support.
9dbe8d0cf Editor: Sidebar.Controls to Sidebar.Settings.Shortcuts. Clean up.
05c5288fc Merge pull request #12612 from TyLindberg/editor-controls-panel
0d8b6e74b Merge pull request #12805 from harto/patch-1
23b20c22e Merge pull request #12801 from gam0022/improve-raymarching-example-v2
fe78029f1 Fix typo in documentation
7ce43c448 Merge pull request #12794 from WestLangley/dev-x
17452bb93 Merge pull request #12778 from OndrejSpanel/unitTestFixes
b5c1b5c70 Merge pull request #12799 from dhritzkiv/patch-21
1b48ff4d2 Updated builds.
88adbcdf6 WebVRManager: Clean up.
2720fbb08 Merge pull request #12803 from dmarcos/parentPoseObject
9ed629301 Check parent of poseObject instead of camera
219f3eb13 Update GLTFLoader.js
15f13bb3c Update GLTFLoader.js
6d9c22a3b Update uniforms only when onWindowResize
881b25b58 Update ProjectionMatrix on change aspect

Each commit has a unique SHA-1 identifying hash. These IDs are used to travel through the committed timeline and revisit commits. By default, git log will only show commits for the currently selected branch. It is entirely possible that the commit you're looking for is on another branch. You can view all commits across all branches by executing git log --branches=*. The command git branch is used to view and visit other branches. Invoking the command, git branch -a will return a list of all known branch names. One of these branch names can then be logged using git log <branch_name>.

When you have found a commit reference to the point in history you want to visit, you can utilize the git checkout command to visit that commit. Git checkout is an easy way to “load” any of these saved snapshots onto your development machine. During the normal course of development, the HEAD usually points to master or some other local branch, but when you check out a previous commit, HEAD no longer points to a branch—it points directly to a commit. This is called a “detached HEAD” state, and it can be visualized as the following:

Git Tutorial: Checking out a previous commit

Lorsque vous faites le check-out d'un ancien fichier, vous ne déplacez pas le pointeur HEAD. Ce dernier reste sur la même branche et le même commit, à l'état « HEAD détaché ». Vous pouvez ensuite faire un commit de l'ancienne version du fichier dans un nouvel instantané comme vous le feriez pour tout autre changement. Utiliser git checkout dans un fichier permet donc de revenir à une ancienne version d'un fichier donné. Pour plus d'informations sur ces deux modes, consultez la page git checkout.

Afficher une ancienne version

Pour cet exemple, partons du principe que vous avez commencé à développer quelque chose d'un peu fou, mais que vous hésitez encore à le conserver ou pas. Pour vous aider à prendre une décision, vous souhaitez examiner l'état du projet avant le début de votre test. Tout d'abord, vous devez rechercher l'ID de la révision que vous souhaitez afficher.

git log --oneline

Supposons que votre historique de projet ressemble à ceci :

b7119f2 Continue doing crazy things
872fa7e Try something crazy
a1e8fb5 Make some important changes to hello.txt
435b61d Create hello.txt
9773e52 Initial import

You can use git checkout to view the “Make some import changes to hello.txt” commit as follows:

git checkout a1e8fb5

This makes your working directory match the exact state of the a1e8fb5 commit. You can look at files, compile the project, run tests, and even edit files without worrying about losing the current state of the project. Nothing you do in here will be saved in your repository. To continue developing, you need to get back to the “current” state of your project:

git checkout master

Cet exemple part du principe que vous développez sur la branche master par défaut. Une fois que vous êtes revenu dans la branche master, vous pouvez utiliser git revert ou git reset pour annuler les changements indésirables.

Undoing a committed snapshot

Vous disposez de plusieurs stratégies différentes pour annuler un commit. Les exemples suivants partiront du principe que vous disposez d'un historique de commit comme le suivant :

git log --oneline
872fa7e Try something crazy
a1e8fb5 Make some important changes to hello.txt
435b61d Create hello.txt
9773e52 Initial import

We will focus on undoing the 872fa7e Try something crazy commit. Maybe things got a little too crazy.

How to undo a commit with git checkout

À l'aide de la commande git checkout, nous pouvons faire un check-out du commit précédent, a1e8fb5, pour rétablir le dépôt à un état antérieur au commit défaillant. Lorsque vous faites le check-out d'un commit donné, le dépôt est placé à l'état « HEAD détaché ». Cela signifie que vous ne travaillez plus sur une branche. À l'état détaché, tous les nouveaux commits que vous ferez seront orphelins lorsque repassez à une branche établie. Les commits orphelins seront supprimés par la commande garbage collection de Git. Cette dernière s'exécute à intervalles fixes et supprime les commits orphelins de façon permanente. Pour éviter leur suppression par la commande garbage collection, nous devons nous assurer de travailler sur une branche.

From the detached HEAD state, we can execute git checkout -b new_branch_without_crazy_commit. This will create a new branch named new_branch_without_crazy_commit and switch to that state. The repo is now on a new history timeline in which the 872fa7e commit no longer exists. At this point, we can continue work on this new branch in which the 872fa7e commit no longer exists and consider it 'undone'. Unfortunately, if you need the previous branch, maybe it was your master branch, this undo strategy is not appropriate. Let's look at some other 'undo' strategies. For more information and examples review our in-depth git checkout discussion.

How to undo a public commit with git revert

Revenons à notre exemple d'historique de commit d'origine. Celui qui inclut le commit 872fa7e. Cette fois, essayons de faire une annulation inversée. Si nous exécutons la commande git revert HEAD, Git crée un nouveau commit qui sera l'exact opposé du dernier commit. Un nouveau commit est donc ajouté à l'historique de branche actuel, et celui-ci ressemble à ce qui suit :

git log --oneline
e2f9a78 Revert "Try something crazy"
872fa7e Try something crazy
a1e8fb5 Make some important changes to hello.txt
435b61d Create hello.txt
9773e52 Initial import

At this point, we have again technically 'undone' the 872fa7e commit. Although 872fa7e still exists in the history, the new e2f9a78 commit is an inverse of the changes in 872fa7e. Unlike our previous checkout strategy, we can continue using the same branch. This solution is a satisfactory undo. This is the ideal 'undo' method for working with public shared repositories. If you have requirements of keeping a curated and minimal Git history this strategy may not be satisfactory.

How to undo a commit with git reset

Pour cette stratégie d'annulation, nous allons poursuivre avec notre exemple. git reset est une commande étendue aux multiples usages et fonctions. Si nous appelons la commande git reset --hard a1e8fb5, l'historique de commit est réinitialisé sur ce commit donné. Lorsque nous examinons l'historique de commit avec la commande git log, nous obtenons les résultats suivants :

git log --oneline
a1e8fb5 Make some important changes to hello.txt
435b61d Create hello.txt
9773e52 Initial import

The log output shows the e2f9a78 and 872fa7e commits no longer exist in the commit history. At this point, we can continue working and creating new commits as if the 'crazy' commits never happened. This method of undoing changes has the cleanest effect on history. Doing a reset is great for local changes however it adds complications when working with a shared remote repository. If we have a shared remote repository that has the 872fa7e commit pushed to it, and we try to git push a branch where we have reset the history, Git will catch this and throw an error. Git will assume that the branch being pushed is not up to date because of it's missing commits. In these scenarios, git revert should be the preferred undo method.

Undoing the last commit

In the previous section, we discussed different strategies for undoing commits. These strategies are all applicable to the most recent commit as well. In some cases though, you might not need to remove or reset the last commit. Maybe it was just made prematurely. In this case you can amend the most recent commit. Once you have made more changes in the working directory and staged them for commit by using git add, you can execute git commit --amend. This will have Git open the configured system editor and let you modify the last commit message. The new changes will be added to the amended commit.

Undoing uncommitted changes

Before changes are committed to the repository history, they live in the staging index and the working directory. You may need to undo changes within these two areas. The staging index and working directory are internal Git state management mechanisms. For more detailed information on how these two mechanisms operate, visit the git reset page which explores them in depth.

The working directory

The working directory is generally in sync with the local file system. To undo changes in the working directory you can edit files like you normally would using your favorite editor. Git has a couple utilities that help manage the working directory. There is the git clean command which is a convenience utility for undoing changes to the working directory. Additionally, git reset can be invoked with the --mixed or --hard options and will apply a reset to the working directory.

The staging index

The git add command is used to add changes to the staging index. Git reset is primarily used to undo the staging index changes. A --mixed reset will move any pending changes from the staging index back into the working directory.

Undoing public changes

When working on a team with remote repositories, extra consideration needs to be made when undoing changes. Git reset should generally be considered a 'local' undo method. A reset should be used when undoing changes to a private branch. This safely isolates the removal of commits from other branches that may be in use by other developers. Problems arise when a reset is executed on a shared branch and that branch is then pushed remotely with git push. Git will block the push in this scenario complaining that the branch being pushed is out of date from the remote branch as it is missing commits.

git revert constitue la méthode privilégiée pour annuler un historique partagée. La commande revert est plus sûre que reset, car elle ne supprime pas de commits dans un historique partagé. Elle conserve les commits que vous souhaitez annuler et crée un nouveau commit qui inverse le commit indésirable. Cette méthode est plus sûre pour la collaboration à distance partagée, car un développeur hors site peut faire un pull de la branche et recevoir le nouveau commit inversé, lequel annule le commit indésirable.

Summary

We covered many high-level strategies for undoing things in Git. It's important to remember that there is more than one way to 'undo' in a Git project. Most of the discussion on this page touched on deeper topics that are more thoroughly explained on pages specific to the relevant Git commands. The most commonly used 'undo' tools are git checkout, git revert, and git reset. Some key points to remember are:

  • Une fois les changements commités, ils sont généralement permanents.
  • Utilisez git checkout pour déplacer et passer en revue l'historique de commit.
  • git revert is the best tool for undoing shared public changes
  • git reset is best used for undoing local private changes

Outre les commandes d'annulation principales, nous avons également examiné d'autres outils Git : git log pour trouver les commits perdus, git clean pour annuler les changements non commités et git add pour modifier l'index de staging.

Each of these commands has its own in-depth documentation. To learn more about a specific command mentioned here, visit the corresponding links.