How to rollback commit git

How to rollback commit git

Git Rollback

Hey there! Hope you’re doing well.

The last blog was a cheat sheet for all the git commands we have covered till now. We saw how to track files, stage or un-stage them, commit the changes, amend commits, branches, and manage merge conflicts.

In this blog, we look at a significant topic in Git, which I personally believe is the whole point of the existence of Git (well, I may also be wrong here).

Every commit made is the latest version of the changes made to the files in that repo. This means the previous commit contains some changes, and the latest commits contain some new changes but are not limited to a feature update, bug fixes, etc.

Say you are working on a particular feature improvement of a website. The most recent commit, which is there, has all the features bug-free. After you finish improving the feature, you made the commit with the updated changes (feature improvement code) and released the website update. After some days, you find out that your code had some error that doesn’t work properly on a certain use case, like handling a string of more than 100 characters. But it was working properly in the previous version(before you made the changes).🙆‍♂️ So now what? You will need to identify the bug, rectify, test, and again update the website. This may usually take a lot of time, and you can’t bear losses during that time you put towards resolving the error. So Git lets you rollback to the previous commit where everything was working properly so that those instances of the code can be deployed for the website and users don’t face any problems. And during that time, you can fix the issue, and when it works properly, you can again deploy the new feature.

There are different ways to rollback in Git. Here, we will use the git revert command.

Revert doesn’t mean undoing the changes. I described the scenario above for ease of understanding that you rollback to the previous version. What revert does is create a new commit with the inverse of the changes you made in the latest commit, which means whatever lines were added will be removed, removed lines will be added, and a new commit will be made. So it cancels out the bad commit, and basically, the net effect is just like going back to the previous version before your feature improvement. Here, the history of changes is not modified, but it keeps a record of everything that happens, good commit, bad commit, and then the reverted commit. Revert is useful because it automatically reverses the changes, so you don’t need to do it manually.

I’ll use my repo from the merge demo.

We made lots of previous commits.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Commits are listed in chronological order.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

The latest commit is listed first, and as we go down, we see older commits. So you can see the second most recent commit was made in experiment_sort branch, which we merged into the main branch.

To demonstrate the revert, let’s create a file with some error💀 and commit it.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Create a file called user_greet.py in the folder and write some code.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

This script will simply print the message. So let’s commit it.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

All good👌 till here. Right?

Now, say you thought we could make the script more personalized by printing the user’s name with the message instead of just the user. So you update the script accordingly.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Now, let’s commit it.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Now obviously, I created a problem in the code. When we run it, the name variable will not contain anything. And as per the last version, we were at least getting a message, but now we are getting an error.

So now we will revert this version of the code to the previous version (previous commit).

Keep in mind the changes we are making, what lines are being added. It will help you compare with the code after we revert.

Use the following command:

Remember, HEAD is like an alias for the latest commit.

When you run the above command, an editor opens.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

So now I write the reason I’m reverting the changes.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Now save the changes and exit the editor. After exiting, the revert will be done and a new commit will be made.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

See from bottom to top. The last commit was made for the previous blog when we were learning how to resolve a git merge conflict. The third commit was made for this blog when we created the script to greet users. Then we thought to make the greeting more personalized, so we tried making some changes and committed it, which is included in the second commit. But that commit was not good, it had some bugs that needed to be fixed. So for the time being, we wanted to go back to the previous instance of code, so we reverted the changes and then a new commit was made, the first commit in the screenshot. You can also see the messages in the commit log.

The last two entries in the log:

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Now observe here carefully. In the second commit (starting with 3db911….), which is the commit before revert, see that one line is removed and two lines are added, which is from when we wanted to optimize the code for a personalized message. This had the error, that’s why we reverted, which created the new commit, see the first one in the screenshot. There it shows 2 lines are removed and 1 line is added. The removed lines were the optimized code for a personal message, and the line added by git was the one we originally wrote.

So you see that additions of the last are removed in revert, and removed lines are added back, so its effect is just like moving back to the old commit, while it’s actually making inverse of the bad commit.

Till now we saw what we will do if we had to revert the last commit. But what if we have to revert back to a different older commit, like say the 3rd last commit… If we want to revert back to other commits back in time, say we want to remove this user greeting feature entirely, we can use a specific commit id to target that.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

This commit id is not just jumbled text and numbers. It’s a hash calculated using the SHA-1 algorithm.

So we want to rollback to the commit where this feature didn’t exist at all. So let’s identify that commit from the git log and copy that commit id. That would be the fourth commit from the last in the git log output.

So use the command:

You can either paste the full commit id or use just a few starting characters of the commit id to let git automatically detect which id we are trying to refer to until there’s more id with similar starting characters.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

To rollback to this commit, use the same command, but now with this commit id instead of HEAD.

So after this similarly, you will get an editor, and then a new commit will be created. Aaaaand, done!🤜🤛

My name is Harsh Seksaria. I like to write about the topics simplifying them as much as possible for you to understand without unnecessary effort. Still, sometimes something may not be very clear. If you find any mistake, error, or you have a suggestion, just mail me. I’ll try to improve it asap.

Как это отменить?! Git-команды для исправления своих ошибок

Если вы ошиблись в Git’е, разобраться, что происходит и как это исправить, — непростая задача. Документация Git — это кроличья нора, из которой вы вылезете только зная конкретное название команды, которая решит вашу проблему.

Рассказываем о командах, которые помогут вам выбраться из проблемных ситуаций.

Вот блин, я сделал что-то не то… У Git ведь есть машина времени?!

Так вы можете восстановить то, что случайно удалили, и откатить слияние, после которого всё сломалось. reflog используется очень часто — давайте поблагодарим того, кто предложил добавить его в Git.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Я только что сделал коммит и заметил, что нужно кое-что поправить!

Внимание Никогда не изменяйте коммиты в публичной ветке. Используйте эту команду только для коммитов в локальной ветке, иначе вам конец.

Мне нужно изменить сообщение последнего коммита!

Тупые требования к оформлению сообщений…

Я случайно закоммитил что-то в мастер, хотя должен был в новую ветку!

Команды не сработают, если вы уже закоммитили в публичную ветку. В таком случае может помочь git reset HEAD@ <какое-то-количество-коммитов-назад>вместо HEAD

Ну отлично. Я закоммитил не в ту ветку!

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Я пытаюсь запустить diff, но ничего не происходит

Если вы знаете, что изменения были внесены, но diff пуст, то возможно вы индексировали изменения (через add ). Поэтому вам нужно использовать специальный флаг.

Конечно, «это не баг, а фича», но с первого взгляда это чертовски неоднозначно.

Мне нужно каким-то образом отменить коммит, который был сделан 5 коммитов назад

Помимо этого, откатить можно не целый коммит, а отдельный файл. Но следуя канону Git’а, это будут уже совсем другие команды…

Мне нужно отменить изменения в файле

Именно поэтому checkout — лучший инструмент для отката изменений в файлах.

Давай по новой, Миша, всё х**ня

Если вам нужно полностью откатиться до исходной версии (т. е. отменить все изменения), то можете попробовать сделать так.

Будьте осторожны, эти команды разрушительны и необратимы.

Эти команды Git нужны для экстренных ситуаций, но пригодиться могут не только они. Про другие команды с пояснениями писали тут:

How to Revert a Commit in Git

When working in Git, the need will arise from time to time to undo, or revert a particular commit, or a set of commits.

Why would you want to revert a commit in Git? Let’s say a commit introduces a problem in your repository’s codebase; the ability to undo a Git commit can save the day with the git revert command.

We’re going to go over how to revert a commit using the cross-platform GitKraken Git client, which includes a GUI and a CLI.

Whether you prefer to use a GUI or CLI, GitKraken offers the best of both worlds and makes reverting commits faster, easier, and safer by giving you more control.

How to Revert a Commit in GitKraken

Compared to how you revert a Git commit in the command line, reverting a commit takes only 2 clicks with the helpful visual context of GitKraken.

To revert a commit with GitKraken, simply right-click on any commit from the central graph and select Revert commit from the context menu.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

You will then be asked if you want to immediately commit the changes; from here you can choose to save the reverted commit, or select No to make additional code changes or change the Git commit message.

In this case, you don’t have to remember complicated commit shas or branch names.

GitKraken makes it very easy to make additional code changes or change your Git commit message if needed.

If you’re reverting more than one commit in GitKraken, you will need to revert them one at a time and should do so in order of newest to oldest. This will decrease the chance of introducing a conflict.

Pretty easy right? If you’re ready, download GitKraken Client and open your repo to revert a commit.

How do revert a Git commit in GitLens?

If you’re a VS Code user, GitLens makes it easy to revert commits.

With GitLens installed, open your repo in VS Code and right-click on the commit from the Commits view in the sidebar to get the Revert Commit option.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

You can also access this option through the command palette by typing >GitLens: Git Revert or from the commit details’ quick pick menu.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Ready to give it a try? Install GitLens to stay organized and on track with your tasks and projects.

How do you revert a Git commit in the GitKraken CLI?

To undo a commit using the free GitKraken CLI, you will use the git revert command in this fashion:

The value of can be anything that meets the criteria of a gitrevision, as defined by Git.

Commonly, gitrevisions are part of the commit sha; you will need to include enough of the sha to identify the commit as unique among that Git repository.

Other common gitrevisions are Git branch names followed by

, followed by the number of commits behind the head commit your target commit is.

In the above example, the target commit is 2 commits behind the head commit on the currently checked out branch.

In the above example, the target commit is 2 commits behind the head commit on the master branch.

How do you change your Git commit message with the GitKraken CLI?

By default, the git revert command will open a prompt in the GitKraken CLI to edit your Git commit message.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

How do you revert multiple commits in the GitKraken CLI?

This will revert these two commits, plus every commit in between them.

Can I make additional code changes before committing the reverted changes?

This will modify your working tree and index without creating a commit, allowing you to make additional changes before you revert the Git commit.

When you revert a Git commit, the new commit is made up of exactly the opposite changes as the target commit you’re reverting; most of the time, you won’t need to make additional code changes.

Sometimes, you might need to make an edit, since reverting the commit completely might break something. For example, maybe you want to revert most of the commit, but there’s a line or two you need to keep.

How can you undo a Git commit?

Even the most diligent of developers run into mistakes from time to time when working with Git repositories. But the process of fixing these mistakes can differ depending on the circumstances of each case. Furthermore, if you aren’t careful with how you undo these errors, you could end up losing work.

Let’s imagine you’re an artist. You’ve been hard at work creating what will eventually be a beautiful masterpiece, but as you step back to admire your work, you notice you’ve added the wrong hue of grey to one of your clouds. Mistakes like this can make their way into commit history all the time.

Thankfully, Git offers several tools that allow you to undo mistakes introduced by a commit. As with any other toolbox, it’s important to understand the purpose, advantages, and related risks of every tool before using them.

Learn how to undo a Git commit, including how to undo your last Git commit, using GitKraken’s undo button and the GitKraken CLI.

Whether you prefer to undo in one-click, or use commands in the terminal, GitKraken gives you the flexibility and power to control your workflow at every step. Revert mistakes exactly how you want.

Git Revert

The philosophy behind Git revert is that we can undo past mistakes with “forward change”. In other words, rather than going back in time, we can introduce an “equal but opposite” action to neutralize the effect of our original action.

The git revert command follows this principle: it introduces a new commit to the commit history whose sole purpose is to undo the changes of a targeted commit. Importantly, this means that the existing commit history prior to the newly added “undo” commit, including the original error commit, is preserved.

The most common scenario for reverting a Git commit is that you’ve accidentally committed something and it was merged into a shared branch or repo that your teammates work from; Git revert can be particularly useful when you publish to and work off shared branches.

Another advantage is that the commit you target can be arbitrary; you can target any commit at any point in history. However, because of the freedom you have with targeting any commit, you can more easily introduce a conflict when attempting a Git revert.

Git Reset

While Git revert uses forward change to undo commits, the operation of Git reset is just the opposite.

Git reset is a way to move back in time to a particular commit, and to reset our active position to the chosen commit in a branch’s commit history.

However, just as science fiction movies depict, there are all sorts of side effects that can come from altering the course of history. For example, if you travel back to a commit with a reset, all the commits you passed may enter a dangling state where they exist but nothing references them. Furthermore, if you perform a “hard” reset, you can lose local work that wasn’t backed up properly.

If you need to make revisions to a commit that is not your last commit, the best solution is to create a new commit by reverting the old commit. As a Git best practice, you should avoid doing anything that will require you to force push, and rewrite history, of your main branch(es).

Git Interactive Rebase

Now, let’s say you want to undo a Git commit by going back in time, but you don’t want to completely reset history.

Rather than abandoning the commits after the erroneous commit, you want to apply them again and deal with the impacts of your changed history commit by commit.

For those who want a bit more manual control over the history revision process, Git provides the interactive rebase tool. With interactive rebase, you are presented with a list of commits up to a specified point on your branch’s history. From this point, you have various options for each commit:

Git Amend

In many cases, you catch your mistake right after you complete a commit. Perhaps you forgot to stage a file in the last commit, or had a typo in the commit message, or even made mistakes in the code, but you have not yet committed anything else on top of it.

If you want to modify the last commit in your history, you have the ability to amend the Git commit with changes. For example, you can amend the previous commit by changing the Git commit message or description, or you can even stage a file you forgot to include.

Similarly, if there is a mistake in your previous commit’s code, you can fix the mistake and even add more changes before you amend it. Git amend is a single-commit undo tool which only affects the last commit in the branch’s history.

As with Git reset and Git rebase, amending is a history-rewriting process, or a reverse change, rather than a forward change. Under the hood, Git amend creates a brand new commit and replaces your last commit with the new one. It should therefore receive the same level of caution; once you have pushed a commit into a shared branch, amending that commit and pushing the amended change can result in side effects for all of those working off of that commit.

GitKraken makes the process of reverting a commit in Git simple with far less risk. Do your workflow a favor and download the cross-platform GitKraken Git client for Windows, Mac, & Linux free today.

git revert

Можно сказать, что команда git revert представляет собой типичную команду отмены. Однако принцип ее действия отличается от привычной отмены изменений. Вместо удаления коммита из истории проекта эта команда отменяет внесенные в нем изменения и добавляет новый коммит с полученным содержимым. В результате история в Git не теряется, что важно для обеспечения целостной истории версий и надежной совместной работы.

Отмена с помощью команды revert необходима, когда нужно обратить изменения, внесенные в некоем коммите из истории проекта. Это может быть полезно, если баг появился в проекте из-за конкретного коммита. Вам не потребуется вручную переходить к этому коммиту, исправлять его и выполнять коммит нового снимка состояния — команда git revert сделает это автоматически.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Порядок действий

Для наглядности создадим тестовый репозиторий и напишем в командной строке следующее:

Обратите внимание, что после операции отмены третий коммит по-прежнему содержится в истории проекта. Вместо его удаления команда git revert добавила новый коммит для отмены изменений. В результате второй и четвертый коммиты представляют собой одну и ту же базу кода, а третий коммит хранится в истории на случай, если в дальнейшем нам понадобится к нему вернуться.

Распространенные опции

Это параметр по умолчанию, указывать его необязательно. Он открывает настроенный системный редактор, в котором вам будет предложено изменить комментарий к коммиту перед выполнением отмены

Разница между командами git reset и git revert

Важно понимать, что команда git revert отменяет одиночный коммит, но не возвращает проект в предшествовавшее состояние с удалением всех последующих коммитов. Такой результат в Git дает команда reset, а не revert.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

У команды revert есть два серьезных преимущества перед командой reset. Во-первых, она не изменяет историю проекта и, соответственно, безопасна для коммитов, которые уже опубликованы в общем репозитории. Подробнее о том, почему изменять общую историю опасно, см. на странице команды git reset.

Резюме

Готовы изучить команду git revert?

Ознакомьтесь с этим интерактивным обучающим руководством.

Команды reset, checkout и revert

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Переключение версий (команда checkout) перемещает указатель HEAD на указанный коммит. Покажем это на следующем примере.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Это обновление дерева «истории коммитов». Команду git checkout можно использовать на уровне коммита или файла. При переключении на уровне файла его содержимое будет отражать состояние при конкретном коммите.

Операция отмены (команда revert) принимает в качестве аргумента коммит и создает новый коммит, изменения в котором будут противоположны указанному. git revert действует только на уровне коммита и не работает на уровне файлов.

Операция сброса (команда reset) принимает в качестве аргумента коммит и сбрасывает «три дерева» до состояния репозитория при указанном коммите. Ее можно выполнить в трех разных режимах, соответствующих трем деревьям.

Команды checkout и reset обычно используются для локальных или частных отмен. Эти команды изменяют историю репозитория, что может вызвать конфликты при отправке в удаленные общие репозитории. Команда revert считается безопасной операцией для публичных отмен, поскольку добавляет в историю новые данные, которыми можно делиться удаленно, а не перезаписывает старые, от которых могут зависеть участники команды.

Справка по различиям git reset, git revert и git checkout

В таблице ниже приведены наиболее распространенные сценарии использования всех этих команд. Обязательно держите ее под рукой для справки, поскольку вам, несомненно, придется использовать хотя бы некоторые из этих сценариев при работе с Git.

КомандаОбласть действияПримеры использования
git resetНа уровне коммитаОтмена коммитов в частной ветке или сброс изменений, не попавших в коммиты
git resetНа уровне файлаУдаление файла из индекса
Git checkoutНа уровне коммитаПереключение между ветками или проверка старых снимков состояния
Git checkoutНа уровне файлаОтмена изменений в рабочем каталоге
git revertНа уровне коммитаОтмена коммитов в публичной ветке
git revertНа уровне файла(Н/Д)

Операции на уровне коммитов

Сброс до конкретного коммита

На уровне коммитов команда reset позволяет перенести конец ветки на другой коммит. Таким образом можно удалить коммиты из текущей ветки. Например, следующая команда перемещает ветку hotfix на два коммита назад.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Команда git reset — это простой способ отменить изменения, которые еще никто не получал. Она прекрасно подойдет в случае, когда вы начали работать над функцией и вдруг подумали: «Ой, ну что я делаю? Лучше начать все сначала».

Помимо перемещения текущей ветки, с помощью команды git reset можно также изменить снимок состояния индекса и (или) рабочий каталог, передав ей один из следующих флагов:

Переключение на старые коммиты

Команду git checkout используют, чтобы обновлять состояние репозитория до определенной точки в истории проектов. Когда ей передают имя ветки, она позволяет переключиться на нее.

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Кроме того, можно переключиться на конкретный коммит, передав в качестве аргумента ссылку на коммит, а не ветку. При этом происходит то же самое, что и при переключении на ветку: команда перемещает ссылку HEAD на указанный коммит. Например, следующая команда переключит версию на два уровня до текущего коммита:

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Отмена публичных коммитов с помощью команды revert

При использовании команды revert коммит отменяется путем создания нового коммита. Это безопасный способ отменить изменения, поскольку при нем невозможно перезаписать историю коммитов. Например, следующая команда определит изменения, содержащиеся во втором с конца коммите, создаст новый коммит, в котором эти изменения будут отменены, и добавит его к проекту.

Выглядит это следующим образом:

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Или можно рассматривать git revert как инструмент для отмены изменений, попавших в коммиты, в то время как команда git reset HEAD предназначена для отмены изменений, не попавших в коммиты.

Операции на уровне файлов

Команды git reset и git checkout также могут принимать путь к файлу в качестве необязательного параметра. Это резко меняет их поведение. Вместо того чтобы действовать на снимки состояния целиком, их работа будет ограничена одним файлом.

git reset для определенного файла

При вызове с указанием пути к файлу команда git reset обновляет снимок состояния индекса, чтобы он соответствовал версии из указанного коммита. Например, следующая команда получит версию foo.py во втором с конца коммите и занесет ее в индекс для следующего коммита:

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

git checkout для файла

How to rollback commit git. Смотреть фото How to rollback commit git. Смотреть картинку How to rollback commit git. Картинка про How to rollback commit git. Фото How to rollback commit git

Например, после выполнения следующей команды файл foo.py в рабочем каталоге будет совпадать с его версией из второго коммита с конца:

Как и вызов git checkout на уровне коммита, эту команду можно использовать для проверки старых версий проекта, только область действия будет ограничена указанным файлом.

Если вы выполните индексирование и коммит для файла, на который переключились, это приведет к восстановлению старой версии файла. Обратите внимание, что при этом удаляются все последующие изменения в файле, тогда как команда git revert отменяет только изменения, внесенные указанным коммитом.

Резюме

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *