Как удалить файлы из коммита idea

Обновлено: 07.07.2024

позже, я обнаружил, что файл был ошибочно добавлен в фиксации.

Как я могу удалить файл из последнего коммита?

  1. удалить файл git rm <file>
  2. фиксация с флагом изменения: git commit --amend

существующие ответы все говорят об удалении ненужных файлов из последние commit.

если вы хотите удалить ненужные файлы старый commit (даже нажал) и не хотите создавать новую фиксацию, которая не нужна, из-за действия:

1.

найти коммит, который вы хотите, чтобы файл, чтобы соответствовать.

вы можете сделать это несколько раз, если вы хотите удалить много файлов.

2.

3.

найти commit_id фиксации , на котором файлы были добавлены по ошибке, скажем "35c23c2" здесь

эта команда открывает редактор в соответствии с вашими настройками. По умолчанию ВИМ.

переместите последнюю фиксацию ,которая должна быть "удалить ненужные файлы", в следующую строку неправильной фиксации ("35c23c2" в нашем случае) и установите команду как fixup :

вы должны быть хороши после сохранения файла.

закончить :

если вы, к сожалению, получаете конфликты, вы должны решить их вручную.

как показывает принятый ответ, вы можете сделать это, сбросив всю фиксацию. Но это довольно тяжелый подход.
Более чистый способ сделать это-сохранить фиксацию и просто удалить из нее измененные файлы.

The git reset возьмет файл, как это было в предыдущей фиксации, и разместит его в индексе. Файл в рабочем каталоге остается нетронутым.
Элемент git commit затем зафиксирует и раздавит индекс в текущий совершать.

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

Если вы не нажали изменения на сервере, вы можете использовать

он сбросит все изменения и вернется к одному фиксации назад

Если вы нажали ваши изменения, то выполните действия, как ответил @CharlesB

удаление файла с помощью rm удалит его!

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

чтобы вернуть файл в некоторое предыдущее состояние:

или вернуть его в состояние на удаленном головой:

затем изменить коммит и вы должны найти файл исчез из списка (и не удаляется с вашего диска!)

ниже будет unstage только файл, который вы намеревались, что ОП спросил.

вы увидите что-то вроде следующего.

изменения для фиксации: (используйте " git reset HEAD . "чтобы отменить добавление)

изменено: / path / to / file

изменения, не поставленные для фиксации: (используйте "git add . " обновлять что будет совершено) (используйте " git checkout -- . " отбрасывать изменения в рабочем каталоге)

изменено: / path / to / file

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

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

когда вы будете готовы совершить:

или (если у вас есть некоторые другие изменения, которые вы еще не хотите совершать)

я объясню вам на примере.
Пусть A, B, C-3 последовательных коммита. Commit B содержит файл, который не должен был быть зафиксирован.

enter image description here

использование Git GUI может упростить удаление файла из предыдущей фиксации.

предполагая, что это не общая ветвь, и вы не возражаете переписывание истории, затем запустите:

вы можете отменить проверку файла, который был ошибочно зафиксирован, а затем нажмите кнопку "зафиксировать".

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

5 , если вы хотите увидеть последние пять коммитов. Затем в текстовом редакторе измените слово pick на drop рядом с каждым коммитом, который вы хотите удалить. Сохраните и закройте редактор. Вуаля!

Как удалить коммит гит?

Полное удаление последнего коммита

1 вы получите состояние A←B←HEAD (коммит C будет удален). HEAD теперь указывает на коммит B.

Как удалить последний коммит гит?

Как удалить определенный коммит?

Как удалить локальный коммит git?

Как удалить последний коммит?

Как удалить файлы из GitHub?

Как откатить запущенный коммит?

Удалить неопубликованные коммиты

Как удалить коммит с Битбакета?

Отмена нескольких изменений с помощью git reset

Как удалить первый коммит git?

Как удалить коммит Intellij IDEA?

Все текущие изменения до выбранного вами коммита пропадут!

Как удалить коммит из Пулл Реквеста?

Если вы хотите добавить этот коммит в текущую ветку, но не имеет смысла быть частью текущего PR, вы можете вместо этого сделать следующее:

    использовать git rebase -i HEAD

Как удалить локальный репозиторий Git?

Удалите каталог . git в корневом каталоге вашего репозитория, если вы хотите удалить только информацию, связанную с git (ветви, версии). Если вы хотите удалить все (git-данные, код и т. д.), просто удалите весь каталог.

Что такое Revert commit?

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

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.

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.

Use this dialog to commit (check in) local changes to the repository and, optionally, to create a patch file.

Starting from IntelliJ IDEA version 2020.1, you can switch to a non-modal commit interface: select the Use non-modal commit interface option (enabled by default for new installations) on the Version Control | Commit page of the IDE settings Ctrl+Alt+S .

The options available in this dialog depend on the version control system you are using.

Modified files pane

This section lists all files that have been modified since the last commit. Deselect the check-boxes next to the files that you want to exclude from the current commit.

The summary under the modified files pane shows statistics on the currently selected changelist, such as the number of modified, new, deleted and unversioned files. This area also shows how many files of each type are shown, and how many of them will be committed.

Commit Message pane

In this area, enter a comment to the current commit. You cannot commit your changes until you enter some description in the Commit Message field.

This comment will also be used as the name of the patch file, if you decide to create a patch.

You can click Commit Message history Ctrl+M to choose from the list of recent commit messages.

VCS-specific controls

The controls in this section are located in the top-right part of the dialog, and contain the options that are specific for the version control system you are using.

Use this list to select the author of the changes that you are going to commit. This may be useful when you are committing changes made by another person.

Select this checkbox to replace the previous commit with the current changes (see Git Basics: Undoing Things for details).

select if you want to sign off your commit to certify that the changes you are about to check in have been made by you, or that you take the responsibility for the code you're committing.

When this option is enabled, the following line is automatically added at the end of the commit message: Signed off by: <username>

Select this checkbox to replace the previous commit with the current changes (see Git Basics: Undoing Things for details).

Keep files locked

Select this checkbox to keep the changed files locked after they are checked in.

These controls are available only if you select the Enable Perforce Jobs Support checkbox on the Perforce settings page.

Use the controls in this area to search for Perforce jobs, link jobs to the selected changelist, and detach the currently linked jobs.

Unlink selected jobs : click this button to detach the selected job from the changelist.

Edit associated jobs : click this button to open the Edit Jobs Linked to Changelist dialog where you can search for available jobs, view their details, and link jobs to the selected changelist.

Find and link job matching the pattern : click this button to start quick search for the job that matches the pattern specified in the field and attach the job to the changelist.

In the field, specify the exact name of the job or a search pattern according to the Perforce jobs syntax rules.

If only one job matching the pattern is found, it is attached to the changelist automatically. Otherwise, to select a job among several available jobs, click the button and find the desired job using the Edit Jobs Linked to Changelist dialog.

The list in the bottom of the area displays the jobs that are currently attached to the selected changelist.

Before Submit / Before Commit section

Use the controls in this area to define which additional actions you want IntelliJ IDEA to perform before committing the selected files.

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


289 1 1 золотой знак 5 5 серебряных знаков 17 17 бронзовых знаков revert не подходит? или хочется именно снести коммиты (что плохо). И хочется это сделать по нормальному или неправильно (через idea)? Те коммиты, которые следуют за 3м(т.е к примеру 3й коммит был удачной версией) не нужны. Смысл в том, чтобы не тратить время на изменение неудачного кода, а с помощью гита быстро вернуть всё в необходимое состояние, т.е в определённый коммит. Вам нужен git revert. В принципе, он есть прямо с gui Почти, но не то. git revert в идее откатывает изменения пошагово и использует локальные данные. Мне же необходимо использовать именно коммиты из удалённого репозитория. Что-то вроде pull, только с возможностью выбора определенного коммита.

Пожалуйста, имейте в виду, что нижепредставленный способ – это крайний случай.
Все текущие изменения до выбранного вами коммита пропадут!

  1. Узнаёшь хэш нужного коммита, например, в своём репозитории на гитхабе в разделе коммиты. Пусть будет такой 1382e90bcb6f50b372as49857190f2b5480a85e88
  2. Заходишь в папку репозитория через консоль.
    Например, cd /AnonPC/Projects/Project
  3. Откатываешься к этому коммиту:
    git reset --hard 1382e90bcb6f50b372as49857190f2b5480a85e88
  4. Отправляешь на гитхаб текущее состояние проекта:
    git push --force

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

Читайте также: