Как отменить коммит idea
Перейти к содержимому

Как отменить коммит idea

  • автор:

Undo changes in Git repository

You can always undo the changes you’ve made locally before you commit them:

In the Commit tool window Alt+0 , select one or more files that you want to revert, and select Rollback from the context menu, or press Ctrl+Alt+Z .

All changes made to the selected files since the last commit will be discarded, and they will disappear from the active changelist.

Unstage files

By default, IntelliJ IDEA uses the changelists concept where modified files are staged automatically.

If a file is already under version control, and you do not want to commit it, you can:

Remove it from the commit: do not select it in the Changes area of the Commit tool window.

If you are more used to the staging concept, select the Enable staging area option in the Version Control | Git page of the IDE settings Ctrl+Alt+S .

Also, by default IntelliJ IDEA suggests adding each newly created file under version control. You can change this behavior in Settings | Version Control | Confirmation using When files are created and When files are deleted settings respectively.

Undo the last commit

IntelliJ IDEA allows you to undo the last commit in the current branch.

You cannot undo a commit if it was pushed to a protected branch, that is a branch to which force —push is not allowed (configure protected branches in the Version Control | Git page of the IDE settings Ctrl+Alt+S ) Note that if a branch is marked as protected on GitHub, IntelliJ IDEA will automatically mark it as protected when you check it out.

Open the Git tool window Alt+9 and switch to the Log tab.

Select the last commit in the current branch and choose Undo Commit from the context menu.

In the dialog that opens, select a changelist where the changes you are going to discard will be moved. You can either select an existing changelist from the Name list, or specify the name of a new changelist (the commit message is used by default).

Select the Set active option if you want to make the changelist with the changes you are about to discard the active changelist.

Select the Track context option if you want IntelliJ IDEA to remember your context and reload currently opened files in the editor when this changelist becomes active.

Revert a pushed commit

If you notice an error in a specific commit that has already been pushed, you can revert that commit. This operation results in a new commit that reverses the effect of the commit you want to undo. Thus, project history is preserved, as the original commit remains intact.

Locate the commit you want to revert in the Log tab of the Git tool window Alt+9 , right-click it and select Revert Commit from the context menu. This option is also available from the context menu of a commit in the file History view. The Commit Changes dialog will open with an automatically generated commit message.

If you apply this action to multiple commits selected in the Log view, a separate commit will be created to revert each of them.

If the selected commit contains several files, and you only need to revert some of them, deselect the files you do not want to touch.

Click Commit to commit a changeset that reverts the changes to the selected files in this particular commit.

Revert selected changes

IntelliJ IDEA lets you undo selected changes from a pushed commit if this commit contains multiple files and you only need to revert some of them.

In the Log view select the commit containing the changes you want to discard.

In the Changed Files pane, right-click the file that you want to revert and select Revert Selected Changes from the context menu.

This results in a new commit that reverses the changes you want to undo.

Drop a commit

Unlike reverting a commit, which is reflected in the branch history, you can discard a pushed commit in the current branch without leaving any traces of the operation.

Like any operation that rewrites a branch history, dropping a commit requires a —force push and cannot be performed in protected branches (these can be configured in the Version Control | Git page of the IDE settings Ctrl+Alt+S .

Select a commit you want to discard in the Log view and choose Drop Commit from the context menu.

Reset a branch to a specific commit

If you notice an error in a set of recent commits and want to redo that part, you can roll back your repository to a specific state. This is done by resetting the current branch HEAD to a specified commit (and optionally resetting the index and working tree if you prefer not to reflect the undo in the history).

Open the Version Control tool window Alt+9 and switch to the Log tab.

Select the commit that you want to move HEAD onto and select Reset Current Branch to Here from the context menu.

In the Git Reset dialog that opens, select how you want your working tree and the index to be updated and click Reset :

Soft : all changes from commits that were made after the selected commit will be staged (that means they will be moved to the Local Changes view so that you can review them and commit later if necessary).

Mixed : changes made after the selected commit will be preserved but will not be staged for commit.

Hard : all changes made after the selected commit will be discarded (both staged and committed).

Keep : committed changes made after the selected commit will be discarded, but local changes will be kept intact.

Get a previous revision of a file

If you need to revert a single file instead of discarding a whole commit that includes changes to several files, you can return to a particular version of that file:

Select the required file in any view (in the Project tool window, in the editor, in the Local Changes view, and so on).

Select Git | Show History from the main VCS menu or from the context menu of the selection. The History tab is added to the Git tool window showing the history for the selected file and allowing you to review and compare its revisions.

When you’ve identified the revision you want to roll back to, select it in the list and choose Get from the context menu.

1. Местный коммит, как снять

Следующим образом я написал код ошибки и отправил локально. Теперь я хочу снять его

Мы можем version control Выберите записи, представленные перед меткой, чтобы вывести из

После вывода в дефальном Chanlist больше не будет записей.

Пока вы добавляете к управлению версией, все изменения, которые мы модифицируем, будут размещены в списке Defalut Changelist, предоставленных Idea. Когда мы совершаем, по умолчанию будет отправить записи в этом списке. Обратите внимание, что есть только один из Несколько изменений. Это активно. Именник этого активности по умолчанию по умолчанию по умолчанию. Значение активного: клавиша ярлыка (Ctrl + K) отправляется в измененный подрок, который настроен на Active.
Ссылка: https://www.pianshen.com/article/13091530169/

2. Удаленный коммит, как отменить или откатить

Как показано на рисунке, код отправляется удаленно, но я хочу уйти



Как указано выше, если мы не нажимаем на отправку, то в локальных изменениях будет дополнительный список. Мы также можем совершить здесь. Когда мы общеприняты, Локальная среда вернется к определенной версии, а локальный код вернется к предыдущему коду версии

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

3. Удаленный код отправлено, как локальный может вернуться к определенной версии

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

Выберите проект, справа -Найдите команду Reset


Или введите номер версии

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

4. Удалить записи

Ссылка: https://www.cnblogs.com/wuxun1997/p/13821086.html и никогда не пробовал

5. Плата падения

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

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

или же

Или вы можете решить это в соответствии с подсказками

6. Слияние, чтобы освоить

Когда DEV сильно изменяется, мы можем объединить его с основной ветвью

Можно видеть, что есть только предыдущая информация о версии на мастере

Когда мы хотим переключить все разработчики на мастер, есть два способа, один merge changes Этот метод быстрый. После того, как слияние напрямую объединено, его достаточное количество, но это недостаток заключается в том, что запись представления не является одной, но все измененные записи в разработке представлены, что заставляет мастер быть реальностью. Есть много информации о предыдущей записи. Как правило, мастер не должен быть представлен один раз.

Другим способом является то, что другие ветви тяги к основной ветви, но при подаче будет представлено много записей, как показано на рисунке

Также есть один, который после того, как DEV будет представлен сначала, а затем локальный сброс в определенную версию. В настоящее время код предыдущей версии станет кодом, где пользователь изменяет состояние. Stash Ceserves, как показано на рисунке

Затем мы переходим обратно на главную версию, а затем выпускаем код предыдущего тайника в этой версии, как показано на рисунке ::


Таким образом, мы объединяемся с главной записью, и мы можем перейти с нескольких записей на запись и регистрацию

7.stash

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



После отправки патча вы можете выпустить предыдущий код

8. Локальная модификация, удаленная модификация, ошибки отчета о конфликте

Откат коммита Git в Intellij Idea

Есть проект над которым работаю только я. Через идею расшарил проект на гитхабе. После некоторых изменений пушу весь проект на гитхаб. К примеру у меня есть 5 коммитов на гитхабе, но я что-то напортачил и точно знаю, что это произошло с 4го коммита. Как мне откатить в идее весь проект до 3го коммита?

user_Kyrt's user avatar

Если я правильно понял вопрос, то сначала клонируете проект с гитхаба, в Idea — VCS — Git — Сlone, затем идете на вкладку Version control, в ней вкладка log, в логе становитесь на нужный коммит, ПКМ — Reset Current Branch to Here — ну а там уже выбираете нужные варианты, самый жесткий/опасный, не оставляющий следов — hard.

Undo Last Commit

You want to fix it, but you haven’t memorized the Git voodoo chant. Good news. If you haven’t pushed yet, the IDE can make this really easy.

First go to the Git tool window and make sure you’re on the log tab.

It shows the list of commits on the current branch. The most recent one is at the top.

Right-click that commit and in the pop-up window, choose Undo Commit.

That commit has some changes. Let’s keep them in the default changelist. Now the commit tool window says I have changes.

And now that commit…never happened. Let’s look a little deeper.

The Problem

You are editing, say a Markdown file. Let’s leave the Commit tool window and Git tool window open, to see the updates as we go.

You change the title, and make a commit. And for the thousandth consecutive time, you spot a typo, just as the onkeyup event fires when clicking commit. Alas, the commit tool window shows that there are no changes. And, in your Git log, there it is, the mistaken commit.

That means it’s too late, right! Nope, if you haven’t pushed to a “protected” branch, you can clean things up locally. And the IDE puts a convenient UI atop the underlying Git command.

The Solution

In the Git tool window, find the most recent commit. It’s the one at the top. When we select it, we get more detail about the commit. We can double-click the file to see a diff of the change.

When you right-click on a commit, you get some actions you can take on it. Some might be grayed-out. For example, if we right-click on an older, pushed commit, we’ll see “Undo Commit” is grayed-out.

Back to the first commit. Right-click on it, and select “Undo Commit”.

Now, the commit had some changes in them, and these changes need to go somewhere. The IDE’s changelists provide such a place. We’ll stick with the Default Changelist .

This results in our Commit tool window showing the changes when we click ok.

A look in the Git log also shows a change.

That commit is…gone! We’re back to where we were before the commit.

What would this have been like from the command line? Let’s take a look at the Git tool’s Console tab, to see behind the scenes. There it is, the command that we would have had to type, from the command line.

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

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