Visual studio отменить commit
When undoing changes in Git, first decide what type of changes you are looking to undo. These changes fall into three categories:
- Discard uncommitted changes to a file, bringing the file back to the version in the last commit.
- Reset your local branch to a previous commit.
- Revert changes pushed to a remote branch and shared with others.
If you just need to make small updates such as to fix a typo or small problem introduced in your last commit, consider amending your previous commit or fixing the change in a new commit instead of any of these other steps.
In this tutorial you learn how to:
- Discard uncommitted changes to a single file
- Revert changes in shared commits
- Reset a branch to a previous state
Discard uncommitted changes to a single file
Restore file contents back to a known good version, removing unwanted changes.
These commands will overwrite your existing file changes. If you think you might want these changes later, consider stashing them instead.
Visual Studio 2019 version 16.8 and later versions provide a new Git menu for managing the Git workflow with less context switching than Team Explorer. Procedures provided in this article under the Visual Studio 2019 tab provide information for using the Git experience as well as Team Explorer. To learn more, see Side-by-side comparison of Git and Team Explorer.
Visual Studio 2015 & 2017
Open up the Changes view in Team Explorer.
Under the Changes section, find the file that you want to restore to the previous version. If your change is staged, remove it from the Staged Changes section by right-clicking and selecting Unstage.
Right-click that file and select Undo Changes.
You can use the checkout command and give it the filename(s) to change. Use wildcards for undoing changes to multiple files.
You can revert the file to the version in a specific commit by providing the commit ID:
This differs from the earlier use of the checkout command used to swap to a different branch. Git will tell you if it is changing a file or swapping between branches in the output, and complain if it's not clear which one you are trying to do.
Revert changes in shared commits
Use revert to undo the changes made in your commits pushed to shared branches. The revert command creates a new commit that undoes the changes on a previous commit. No history is rewritten in a revert , making it safe to use when working with others.
Visual Studio 2019 version 16.8 and later versions provide a new Git menu for managing the Git workflow with less context switching than Team Explorer. Procedures provided in this article under the Visual Studio 2019 tab provide information for using the Git experience as well as Team Explorer. To learn more, see Side-by-side comparison of Git and Team Explorer.
Open up the Changes view in Team Explorer. Select Actions and choose View History from the drop-down. In the history window that appears, right-click the commit to undo and select Revert from the context menu.
These commands will undo the changes made in commit 8437fbaf and create a new commit on the branch. The original commit at commit_id is still in the Git history. Revert is flexible but it requires a branch history and commit identifiers to use. Review your history to find the commits you want to revert.
Reset a branch to a previous state
Use reset to bring a branch in your local repository back to the contents of a previous commit. The most common use of the reset command is to simply discard all changed files since the last commit and return the files to the state they were in at the most recent commit.
Don't use reset on branches shared with others. Use revert instead.
Open up the Changes view in Team Explorer.
Select Actions and choose View History from the drop-down.
In the history window that appears, right-click the commit to reset the repo to and select Reset from the context menu.
Choose Reset and delete changes. .
The --hard part of the command tells Git to reset the files to the state of the previous commit and discard any staged changes. The HEAD argument tells Git to reset the local repository to the most recent commit. If you want to reset the repo to a different commit, provide the ID instead of HEAD.
A reset affects all files in the current branch on the repository, not just those in your current directory. Reset only discards changes that haven't been committed yet.
При отмене изменений в Git сначала определите тип изменений, которые требуется отменить. Эти изменения делятся на три категории:
- Отмена незафиксированных изменений в файле, приведя файл обратно к версии в последней фиксации.
- Сбросьте локальную ветвь до предыдущей фиксации.
- Отмена изменений, отправленных в удаленную ветвь и доступ к которой предоставлен другим пользователям.
Из этого руководства вы узнаете, как выполнить следующие задачи:
- Отмена незафиксированных изменений в одном файле
- Отмена изменений в общих фиксациях
- Сброс ветви до предыдущего состояния
Отмена незафиксированных изменений в одном файле
Восстановите содержимое файла обратно в известную хорошую версию, удалив нежелательные изменения.
Эти команды перезаписывают существующие изменения файла. Если вы считаете, что эти изменения могут потребоваться позже, рассмотрите возможность их скрытия .
Visual Studio 2019 версии 16.8 и более поздних версий предоставляют новое меню Git для управления рабочим процессом Git с меньшим переключением контекста, чем Team Explorer. Процедуры, описанные в этой статье на вкладке Visual Studio 2019, содержат сведения об использовании интерфейса Git, а также Team Explorer. Дополнительные сведения см. в статье о параллельном сравнении Git и Team Explorer.
Visual Studio 2015 & 2017 г.
Откройте представление изменений в Team Explorer.
В разделе "Изменения" найдите файл, который требуется восстановить до предыдущей версии. Если изменение выполняется поэтапно, удалите его из раздела "Промежуточные изменения ", щелкнув правой кнопкой мыши и выбрав "Отменить этап".
Щелкните этот файл правой кнопкой мыши и выберите команду "Отменить изменения".
Вы можете использовать checkout команду и присвоить ей имя файла для изменения. Используйте подстановочные знаки для отмены изменений в нескольких файлах.
Вы можете вернуть файл к версии в определенной фиксации, указав идентификатор фиксации:
Это отличается от предыдущего использования команды, используемой checkout для переключения на другую ветвь. Git сообщит вам, изменяет ли он файл или переключается между ветвями в выходных данных, и жалуется, если это не ясно, какой из них вы пытаетесь сделать.
Отмена изменений в общих фиксациях
Используется revert для отмены изменений, внесенных в фиксации, отправленных в общие ветви. Команда revert создает новую фиксацию, которая отменяет изменения предыдущей фиксации. Журнал не переписывается в , revert что делает его безопасным для использования при работе с другими пользователями.
Visual Studio 2019 версии 16.8 и более поздних версий предоставляют новое меню Git для управления рабочим процессом Git с меньшим переключением контекста, чем Team Explorer. Процедуры, описанные в этой статье на вкладке Visual Studio 2019, содержат сведения об использовании интерфейса Git, а также Team Explorer. Дополнительные сведения см. в статье о параллельном сравнении Git и Team Explorer.
Откройте представление изменений в Team Explorer. Выберите "Действия" и выберите "Просмотреть журнал " в раскрывающемся списке. В появившемся окне журнала щелкните правой кнопкой мыши фиксацию, чтобы отменить и выберите "Вернуться " в контекстном меню.
Эти команды отменят изменения, внесенные в фиксацию 8437fbafbaf, и создадут новую фиксацию в ветви. Исходная фиксация commit_id по-прежнему находится в журнале Git. Revert является гибким, но для этого требуется журнал ветвей и идентификаторы фиксации. Просмотрите журнал , чтобы найти фиксации, которые вы хотите вернуть.
Сброс ветви до предыдущего состояния
Используется reset для возврата ветви в локальном репозитории к содержимому предыдущей фиксации. Наиболее распространенное использование reset команды заключается в том, чтобы просто отменить все измененные файлы с момента последней фиксации и вернуть файлы в состояние, в которое они находились в последней фиксации.
Не используйте reset ветвях, к которым предоставлен доступ другим пользователям. Вместо этого используйте возврат .
Откройте представление изменений в Team Explorer.
Выберите "Действия" и выберите "Просмотреть журнал " в раскрывающемся списке.
В появившемся окне журнала щелкните правой кнопкой мыши фиксацию, чтобы сбросить репозиторий и выберите "Сбросить" в контекстном меню.
Часть --hard команды сообщает Git, что Git сбрасывает файлы в состояние предыдущей фиксации и отменяет все промежуточные изменения. Аргумент HEAD сообщает Git о сбросе локального репозитория до последней фиксации. Если вы хотите сбросить репозиторий на другую фиксацию, укажите идентификатор вместо HEAD.
Это reset влияет на все файлы в текущей ветви в репозитории, а не только на файлы в текущем каталоге. Reset Отменяет только изменения, которые еще не были зафиксированы.
The Git Repository window provides a full-screen Git experience that helps you manage your Git repository and stay up to date with your team's projects. For example, you might need to reset, revert, or cherry-pick commits, or just clean your commit history. The Git Repository window is also a great place to visualize and manage your branches.
Version control with Visual Studio is easy with Git. And, you can work remotely with the Git provider of your choice, such as GitHub or Azure DevOps. Or, you can work locally with no provider at all.
Change the last commit (amend)
Updating the last commit is called amending in Git, and it's a common use case. Sometimes you just need to update your commit message, or you might need to include a last-minute change.
You can amend a commit on the command line by using the following command:
The Git Repository window makes it easy to update your commit message. Open the commit details of the last commit by double-clicking it, and then select the Edit option next to the commit message.
When you finish editing your commit message, select Amend.
If you need to include code changes to your last commit, you can do that in the Git Changes window. Select the Amend checkbox and then commit your changes.
To learn more about amending, see Git Tools - Rewriting History on the Git website.
Merge commits (squash)
To merge a series of commits, Git provides an option to squash commits down into a single commit. This option can be helpful if you make frequent commits and end up with a long list of commits that you want to clean up before pushing to a remote repository.
You can squash two commits on the command line by using the following command:
Then update pick to squash , save, and update the commit message.
To merge commits in Visual Studio, use the Ctrl key to select multiple commits that you want to merge. Then right-click and select Squash Commits. Visual Studio automatically combines your commit messages, but sometimes it's better to provide an updated message. After you review and update your commit message, select the Squash button.
To learn more about squashing, see Git Tools - Rewriting History on the Git website.
Merge and rebase branches
If you're using Git branches to work on different features, at some point you'll need to include updates introduced to other branches. This can happen while you're still working on your feature branch. It can also happen when you're done working on your feature branch and need to keep your changes by adding them to a different branch. In Git, you can include these updates by merging or rebasing branches.
The following instructions use New_Feature as an example name for a feature branch. Replace it with the name of your own branch.
To merge the main branch into your feature branch on the command line, use the following commands:
To do the same in Visual Studio, check out the feature branch by double-clicking it in the branch list. Then right-click main and select Merge 'main' into 'New_Feature'.
To rebase the main branch into your feature branch on the command line, use the following commands:
To do the same in Visual Studio, check out the feature branch by double-clicking it in the branch list. Then right-click main and select Rebase 'New_Feature' onto 'main'.
To learn more about merging, rebasing, and branching in general, see Git Branching on the Git website.
Copy commits (cherry-pick)
Copy commits from one branch to another by using the cherry-pick option. Unlike a merge or rebase, cherry-picking brings only the changes from the commits that you select, instead of all the changes in a branch. Cherry-picking is a great way to tackle these common problems:
- Accidentally committing in the wrong branch. Cherry-pick the changes over to the correct branch and then reset the original branch to the previous commit.
- Pulling out a set of commits made in a feature branch, so you merge them back to your main branch sooner.
- Porting in specific commits from the main branch without rebasing your branch.
To copy changes from a commit to your current branch by using the command line, use the following command:
To do the same in Visual Studio, preview the branch that you want to cherry-pick a commit from by selecting it with a single click. Then right-click the targeted commit and select Cherry-Pick.
When the operation is complete, Visual Studio shows a success message. The commit that you cherry-picked appears in the Outgoing section.
To learn more about cherry-picking commits, see the Git webpage for the cherry-pick command.
Revert changes
Use the revert command to undo the changes made in commits pushed to shared branches. The revert command creates a new commit that undoes the changes made on a previous commit. The revert command doesn't rewrite the repository history, which makes it safe to use when you're working with others.
To revert changes made in a commit by using the command line, use the following commands. Replace the example ID with the ID of a real commit in your branch.
In the previous example, the commands will undo the changes made in commit 53333305 and create a new commit on the branch. The original commit is still in the Git history. To do the same in Visual Studio, right-click the commit you want to revert and then select Revert. After you confirm your action and the operation is complete, Visual Studio displays a success message and a new commit appears in the Outgoing section.
Select the new commit to confirm that it undoes the changes of the reverted commit.
To learn more about reverting changes, see the Git webpage for the revert command.
Reset a branch to a previous state
Use the reset command to bring a branch in your local repository back to the contents of a previous commit. This action discards all changes that have happened since the commit that you're resetting your branch to.
Don't reset shared branches, because you might delete other people's work. Use the revert command instead.
To reset a branch to a previous state by using the command line, use the following command. Replace the example ID with the ID of a real commit in your branch.
The --hard part of the command tells Git to reset the files to the state of the previous commit and discard any staged changes. To do the same in Visual Studio, right-click the commit that you want to reset your branch to, and then select Reset > Delete Changes (--hard).
To learn more about resetting branches, see the Git webpage for the reset command.
I googled it but was unable to find the answer to the question.
Thanks in advance.
P.S I know I can see the changes between commits and the differences in the working tree but I want to know how to reset to the previous commit in visual studio code
5 Answers 5
With the source control icon selected, if you then click the ellipsis . at the top right.
With v1.48 you will see a list of options for submenus: under Commit is Undo Last Commit . Under Changes is Discard All Changes .
but what that does is it even puts the changes that are now done to the previous commit . I want to reset back to the previous commit
There is also a "Discard All Changes" - that would undo all changes since the last commit - is that what you want?
ctrl + shift + p , type with 'discard', you can discard changes in single file or multiple files at once.
Provided that you have GitLens extension installed you should be able to simply select "Restore" action from selected "File history" commit.
I use GitLens for that:
- In the source control tab, open File History .
- Choose your commit, then right-click Commit .
- Click on Revert Commit. .
gitLens is an excellent product, it also shows the command in the terminal, so you can learn how to use it
You can use this option in the Gitlens "commits" section to reset any number of previous (local) commits: just right click on the commit you would like to reset your current local branch
Then a list appears to allow you to choose a suitable reset option, as usual:
In recent vscode (1.51.1 currently installed) Gitlens extension has been integrated in the source control side view, by the way, instead of having its own button in the sidebar as before.
Конечно можно 2 раза нажать на коммит и в Team Explorer появятся файлы, которые были изменены, но это не очень удобно. Можно ли состояние проекта "заменить" на состояние какого либо коммита, просто чтобы посмотреть что и как было на тот момент, без удаления других коммитов и создания новых?
Я нашел пока один вариант: ПКМ по коммиту - View details(детали коммита), в окне, где появятся детали коммита открываем Actions(на русском скорее всего действия) -> Copy Commit ID, далее переходим в консоль GIT - и делаем git checkout
@A1essandro, если найдёте другой вариант (помимо checkout ) — обязательно напишите торвальдсу, порадуйте старика новыми неизведанными возможностями. (это шутка. я конечно, знаю и про show , и про cat-file , и про ещё более изощрённые пути, но «каноническим» является, естественно, только checkout ).
@alexanderbarakin, чет не понял шутку. Даже если гуглить (я с git-ом не очень часто работаю, в основном mercurial) "перейти на определенный коммит git" то выдает чекаут. Объясните, пожалуйста, если я не прав.
2 ответа 2
В самой Visual Studio такого сделать не получится. Я установил программу Git Extensions и в ней открыл репозиторий/папку с проектом Visual Studio. Там выбрал коммит, ПКМ по нему и выбрал "Откатить текущую ветку сюда" и в появившемся окне выбрать "Жёсткий. "
Без потери коммитов, но с переключением рабочей директории -- на скриншоте кнопка "Переключиться на ревизию". Как раз что вам советовали в комментариях. В студии аналогичной кнопки не нашел.
Если задача состоит в том, чтобы только посмотреть коммит не создавая новых и не откатываясь по дереву коммитов, то самое простое - создать отдельную ветку. Нажимаем ПКМ в Visual Studio на текущую ветку (справа внизу окна) и выбираем View History. Появится вкладка с деревом коммитов.
Нажимаем ПКМ на нужном коммите и выбираем New Branch. (при этом все изменения текущей ветки должны быть закоммичены, иначе после создания ветки нельзя будет на неё переключиться). После того, как поработали с новой веткой, её можно удалить в Team Explorer (предварительно переключившись на другую ветку).
Читайте также: