shelve changes git что это

Фишки IDEA. Часть 2

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

shelve changes git что это. Смотреть фото shelve changes git что это. Смотреть картинку shelve changes git что это. Картинка про shelve changes git что это. Фото shelve changes git что это

Scratch-файлы

Shelve

IDEA Shelve по аналогии с git stash позволяет не смешивать контексты при переключении с одной задачи на другую.

Кстати, IDEA многое отправляет в shelve автоматически.

Если собственный механизм IDEA почему-то не нравится, можно переключиться на git stash.

Закачка на удаленный хост

Следующая рекомендация для тех, кто любит все выполнять только в IDEA.

shelve changes git что это. Смотреть фото shelve changes git что это. Смотреть картинку shelve changes git что это. Картинка про shelve changes git что это. Фото shelve changes git что это

Инструмент позволяет даже создавать файлы на сервере.

Интеграция с Docker

shelve changes git что это. Смотреть фото shelve changes git что это. Смотреть картинку shelve changes git что это. Картинка про shelve changes git что это. Фото shelve changes git что это

У IDEA есть интерфейс для работы с docker’ом. Здесь можно запускать контейнеры, просматривать логи, подключаться к контейнеру через терминал, расшаривать порты и т.д.

Changelist

Изменения можно перетаскивать из одного changelist-а в другой. Также changelist-ы можно разбивать или объединять.

Подробное описание работы с Changelist есть в документации.

Дерево коммитов

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

В дереве коммитов есть поиск по commit message, имени задачи и хэшу коммита.

shelve changes git что это. Смотреть фото shelve changes git что это. Смотреть картинку shelve changes git что это. Картинка про shelve changes git что это. Фото shelve changes git что это

Дерево коммитов показывает несколько проектов, если ранее вы подключили их в одно окно. Чтобы не запутаться, можно показать дерево только для одного репозитория (для этого в Paths надо выбрать, какой репозиторий сейчас актуален).

Дерево открывает широкие возможности для манипулирования коммитами. В частности, оно позволяет:

откатывать коммит (Undo commit), после чего он попадает обратно в Change list;

перетаскивать ветку с одного коммита на другой;

сравнивать два разных коммита между собой.

Breakpoints

В процессе отладки IDEA позволяет устанавливать Breakpoint-ы. В этот момент можно, например, выводить информацию в лог.

shelve changes git что это. Смотреть фото shelve changes git что это. Смотреть картинку shelve changes git что это. Картинка про shelve changes git что это. Фото shelve changes git что это

В настройках можно также указать, что точка остановка должна сработать только один раз. Или она должна быть неактивна, пока мы не достигли определенной точки (Disable until hitting the following breakpoint).

shelve changes git что это. Смотреть фото shelve changes git что это. Смотреть картинку shelve changes git что это. Картинка про shelve changes git что это. Фото shelve changes git что это

А если поджимает время выполнения запроса, можно выбрать Evaluate and log. Выполнение не остановится, но данные будут выводиться в консоль.

Останавливаясь на breakpoint, можно воспользоваться кнопкой Evaluate Expression (горячая клавиша Alt + Shift + 8). Она открывает окно, в котором можно исполнять код прямо в рантайме в точке остановки, где будут доступны все зарезервированные объекты. Так можно модифицировать запросы из кода, проверяя быстрые гипотезы.

Тестирование в IDEA

У тестирования непосредственно через IDEA есть одно важное преимущество. Если запускать тесты сторонним инструментом, в консоли появится индекс запускаемого теста. Если же тесты запускать через IDEA, она выведет названия тестов.

Профайлер IDEA

В IDEA предусмотрена интеграция с инструментами для профилирования. Из коробки доступны Async Profiler и Java Flight Recorder. Выбрать, какой будет использоваться в данный момент, можно через Preferences в секции Profiler.

shelve changes git что это. Смотреть фото shelve changes git что это. Смотреть картинку shelve changes git что это. Картинка про shelve changes git что это. Фото shelve changes git что это

Преимущество использования профайлера непосредственно из под IDEA в том, что при изучении результатов можно перемещаться не только по этой картинке, но и по исходному коду.

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

Анализ stack trace

Лайфхак для код-ревью

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

Если изменений в коде много, для ревью удобно вытянуть всю ветку к себе, откатить все коммиты этого реквеста (Reset soft) до того, как он был влит в мастер, и выполнить git reset master. Все изменения в этом реквесте останутся в рабочей копии и будут отображаться, как будто они внесены собственными силами. Изменения попадут индекс Git и будут там подсвечиваться (сами они при этом не изменяются). Можно будет перемещаться по зависимостям.

В отличие от Git-> Compare with branch, который просто показывает список изменения, здесь будет более удобная навигация. Правда, можно случайно что-то поправить в коде, и новые изменения не будут выделяться на фоне остальных.

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

Статья написана по материалам внутренних митапов Максилект.

Источник

Shelve and unshelve changes

Shelving is temporarily storing pending changes you have not committed yet. This is useful, for example, if you need to switch to another task, and you want to set your changes aside to work on them later.

You cannot shelve unversioned files, which are files that have not been added to version control.

Once shelved, a change can be applied as many times as you need.

Shelve changes

In the Shelve Changes dialog, review the list of modified files.

In the Commit Message field, enter the name of the shelf to be created and click the Shelve Changes button.

If you need to copy your changes to a shelf without resetting local changes, press Ctrl+Shift+A and look for the Save to Shelf action.

Unshelve changes

Unshelving is moving postponed changes from a shelf to a pending changelist. Unshelved changes can be filtered out from view or removed from the shelf.

In the Shelf tab, select the changelist or the files you want to unshelve.

Press Ctrl+Shift+U or choose Unshelve from the context menu of the selection.

In the Unshelve Changes dialog, specify the changelist you want to restore the unshelved changes to in the Name field. You can select an existing changelist from the list or enter the name for a new changelist to be created containing the unshelved changes. You can enter the description of the new changelist in the Comment field (optional).

If you want WebStorm to preserve the context of a task associated with the new changelist on its deactivation and restore the context when the changelist becomes active, select the Track context option (see tasks and contexts for details).

If you’ve deleted unshelved files by accident, you can view and restore them from the Recently Deleted node.

You can also drag a file or a changelist from the Shelf tab to the Local Changes view to unshelve it silently. If you drag it holding the Ctrl key, it will be copied to the Local Changes tab instead of being removed from the shelf.

Discard shelved changes

In the Shelf view, select the changelist that contains the changes you do not want to keep any more.

Restore unshelved changes

Select the files or the shelf you want to restore.

From the context menu of the selection, choose Restore.

Apply external patches

You can import patches created inside or outside WebStorm and apply them as shelved changes.

In the Shelf view, choose Import Patches from the context menu.

In the dialog that opens, select the patch file to apply. The selected patch appears in the Shelf tab as a shelf.

Select the newly added shelf with the patch and choose Unshelve Changes from the context menu of the selection.

Automatically shelve base revision

It may be useful to configure WebStorm to always shelve base revisions of files that are under Git version control.

Select the Shelve base revisions of files under distributed version control systems option.

If this option is enabled, the base revision of files will be saved to a shelf that will be used during a 3-way merge if applying a shelf leads to conflicts. If it is disabled, WebStorm will look for the base revision in the project history, which may take a while; moreover, the revision that the conflicting shelf was based on may be missing (for example, if the history was changed as a result of the rebase operation).

Change the default shelf location

By default, the shelf directory is located under your project directory. However, you may want to change the default shelf location. This can be useful, for example, if you want to avoid deleting shelves accidentally when cleaning up your working copy, or if you want to store them in a separate repository allowing shelves to be shared among your team members.

Click Change Shelves Location and specify the new location in the dialog that opens.

If necessary, select Move shelves to the new location to move existing shelves to the new directory.

Watch this video tutorial on how to benefit from shelves to be able to switch to a different task without losing unfinished work:

Источник

Shelve and unshelve changes

Shelving is temporarily storing pending changes you have not committed yet. This is useful, for example, if you need to switch to another task, and you want to set your changes aside to work on them later.

You cannot shelve unversioned files, which are files that have not been added to version control.

Once shelved, a change can be applied as many times as you need.

Shelve changes

In the Shelve Changes dialog, review the list of modified files.

In the Commit Message field, enter the name of the shelf to be created and click the Shelve Changes button.

If you need to copy your changes to a shelf without resetting local changes, press Ctrl+Shift+A and look for the Save to Shelf action.

Unshelve changes

Unshelving is moving postponed changes from a shelf to a pending changelist. Unshelved changes can be filtered out from view or removed from the shelf.

In the Shelf tab, select the changelist or the files you want to unshelve.

Press Ctrl+Shift+U or choose Unshelve from the context menu of the selection.

In the Unshelve Changes dialog, specify the changelist you want to restore the unshelved changes to in the Name field. You can select an existing changelist from the list or enter the name for a new changelist to be created containing the unshelved changes. You can enter the description of the new changelist in the Comment field (optional).

If you’ve deleted unshelved files by accident, you can view and restore them from the Recently Deleted node.

You can also drag a file or a changelist from the Shelf tab to the Local Changes view to unshelve it silently. If you drag it holding the Ctrl key, it will be copied to the Local Changes tab instead of being removed from the shelf.

Discard shelved changes

In the Shelf view, select the changelist that contains the changes you do not want to keep any more.

Restore unshelved changes

Select the files or the shelf you want to restore.

From the context menu of the selection, choose Restore.

Apply external patches

You can import patches created inside or outside IntelliJ IDEA and apply them as shelved changes.

In the Shelf view, choose Import Patches from the context menu.

In the dialog that opens, select the patch file to apply. The selected patch appears in the Shelf tab as a shelf.

Select the newly added shelf with the patch and choose Unshelve Changes from the context menu of the selection.

Automatically shelve base revision

It may be useful to configure IntelliJ IDEA to always shelve base revisions of files that are under Git version control.

Select the Shelve base revisions of files under distributed version control systems option.

If this option is enabled, the base revision of files will be saved to a shelf that will be used during a 3-way merge if applying a shelf leads to conflicts. If it is disabled, IntelliJ IDEA will look for the base revision in the project history, which may take a while; moreover, the revision that the conflicting shelf was based on may be missing (for example, if the history was changed as a result of the rebase operation).

Change the default shelf location

By default, the shelf directory is located under your project directory. However, you may want to change the default shelf location. This can be useful, for example, if you want to avoid deleting shelves accidentally when cleaning up your working copy, or if you want to store them in a separate repository allowing shelves to be shared among your team members.

Click Change Shelves Location and specify the new location in the dialog that opens.

If necessary, select Move shelves to the new location to move existing shelves to the new directory.

Watch this video tutorial on how to benefit from shelves to be able to switch to a different task without losing unfinished work:

Источник

Use Git to work on several features simultaneously

Sometimes you need to switch between different tasks with things left unfinished and then return back to them. IntelliJ IDEA provides you with a few ways to conveniently work on several different features without losing your work:

You can stash or shelve pending changes.

Stashing changes is very similar to shelving. The only difference is in the way patches are generated and applied. Stashes are generated by Git, and can be applied from within IntelliJ IDEA, or outside it. Patches with shelved changes are generated by IntelliJ IDEA and are also applied through the IDE. Also, stashing involves all uncommitted changes, while when you put changes to a shelf, you can select some of the local changes instead of shelving them all.

Shelve changes

Shelving is temporarily storing pending changes you have not committed yet. This is useful, for example, if you need to switch to another task, and you want to set your changes aside to work on them later.

You cannot shelve unversioned files, which are files that have not been added to version control.

Once shelved, a change can be applied as many times as you need.

Shelve changes

In the Shelve Changes dialog, review the list of modified files.

In the Commit Message field, enter the name of the shelf to be created and click the Shelve Changes button.

If you need to copy your changes to a shelf without resetting local changes, press Ctrl+Shift+A and look for the Save to Shelf action.

Unshelve changes

Unshelving is moving postponed changes from a shelf to a pending changelist. Unshelved changes can be filtered out from view or removed from the shelf.

In the Shelf tab, select the changelist or the files you want to unshelve.

Press Ctrl+Shift+U or choose Unshelve from the context menu of the selection.

In the Unshelve Changes dialog, specify the changelist you want to restore the unshelved changes to in the Name field. You can select an existing changelist from the list or enter the name for a new changelist to be created containing the unshelved changes. You can enter the description of the new changelist in the Comment field (optional).

If you’ve deleted unshelved files by accident, you can view and restore them from the Recently Deleted node.

You can also drag a file or a changelist from the Shelf tab to the Local Changes view to unshelve it silently. If you drag it holding the Ctrl key, it will be copied to the Local Changes tab instead of being removed from the shelf.

Discard shelved changes

In the Shelf view, select the changelist that contains the changes you do not want to keep any more.

Restore unshelved changes

Select the files or the shelf you want to restore.

From the context menu of the selection, choose Restore.

Apply external patches

You can import patches created inside or outside IntelliJ IDEA and apply them as shelved changes.

In the Shelf view, choose Import Patches from the context menu.

In the dialog that opens, select the patch file to apply. The selected patch appears in the Shelf tab as a shelf.

Select the newly added shelf with the patch and choose Unshelve Changes from the context menu of the selection.

Automatically shelve base revision

It may be useful to configure IntelliJ IDEA to always shelve base revisions of files that are under Git version control.

Select the Shelve base revisions of files under distributed version control systems option.

If this option is enabled, the base revision of files will be saved to a shelf that will be used during a 3-way merge if applying a shelf leads to conflicts. If it is disabled, IntelliJ IDEA will look for the base revision in the project history, which may take a while; moreover, the revision that the conflicting shelf was based on may be missing (for example, if the history was changed as a result of the rebase operation).

Change the default shelf location

By default, the shelf directory is located under your project directory. However, you may want to change the default shelf location. This can be useful, for example, if you want to avoid deleting shelves accidentally when cleaning up your working copy, or if you want to store them in a separate repository allowing shelves to be shared among your team members.

Click Change Shelves Location and specify the new location in the dialog that opens.

If necessary, select Move shelves to the new location to move existing shelves to the new directory.

Watch this video tutorial on how to benefit from shelves to be able to switch to a different task without losing unfinished work:

Stash changes

Sometimes it may be necessary to revert your working copy to match the HEAD commit but you do not want to lose the work you have already done. This may happen if you learn that there are upstream changes that are possibly relevant to what you are doing, or if you need to make some urgent fixes.

Stashing involves recording the difference between the HEAD commit and the current state of the working directory (stash). Changes to the index can be stashed as well.

Unstashing involves applying a stored stash to a branch.

You can apply a stash to an existing branch or create a new branch on its basis.

A stash can be applied as many times as you need to any branch you need, just switch to the required branch. Keep in mind that:

Applying a stash after a series of commits results in conflicts that need to be resolved.

You cannot apply a stash to a «dirty» working copy, that is a working copy with uncommitted changes.

Save changes to a stash

In the Stash dialog that opens, select the appropriate Git root and make sure that the correct branch is checked out.

In the Message field describe the changes you are about to stash.

To stash local changes and bring the changes staged in the index to your working tree for examination and testing, select the Keep index option.

Apply a stash

Select the Git root where you want to apply a stash, and make sure that the correct branch is checked out.

Select the stash you want to apply from the list.

To remove the selected stash after it is applied, select the Pop stash option.

To apply stashed index modifications as well, select the Reinstate Index option.

If you want to create a new branch on the basis of the selected stash instead of applying it to the branch that is currently checked out, type the name of that branch in the As new branch field.

This operation may fail if you have conflicts. This happens because conflicts are stored in the index where you can no longer apply the changes in their original state.

Group changes into different changelists

When you are working on several related features, you may find it convenient to group changes into different changelists. This approach has its pros and cons as opposed to using feature branches to work on multiple tasks.

You can easily switch between different logical sets of changes and commit them separately from each other.

Unlike using branches for the same purpose, you have all your changes at hand without having to switch between branches which can take a while if your project is really large.

It’s convenient to test how different features work together.

You can remote-run a changelist on a build server.

While using changelists may seem a more lightweight option compared to branches, it’s not safe as there’s no backup for your changes until you have committed and pushed them. If something happens to your local working copy, all your changes will be lost as they are not part of Git project history.

No atomic testing of features is possible.

No collaboration on the same feature is possible. Also, you cannot make contributions from different machines unless you send patches with changes through email, which may not be very convenient.

All changelists are displayed in the Local Changes view All modified files are automatically placed in the active changelist, which is the Changes changelist unless you have created a different one and made it active.

You can create as many changelists as needed and make any of them active at any moment. You can move any uncommitted changes to any changelist.

Create a new changelist

In the New Changelist dialog, specify the name of the new changelist, and add a description (optional).

Set the active changelist

In the Local Changes view, select a non-active changelist and press Ctrl+Space or right-click it and choose Set Active Changelist from the context menu. All new changes will be automatically placed in this changelist.

Move changes between changelists

In the Local Changes view, Select the changes that you want to move to another changelist.

In the dialog that opens, select an existing changelist or enter the name for a new changelist.

You can choose to make the target changelist active and to track context for it (IntelliJ IDEA will save the context associated with this changelist, and will restore it when this changelist becomes active).

You can also drag files between changelists.

For instructions on how to place changes within one file into different changelists in Git, see Put changes into different changelists.

Delete a changelist

Right-click a changelist and choose Delete Changelist from the context menu.

Use feature branches

As opposed to using changelists to group changes, using feature branches is safe. After you’ve committed changes to Git, they become part of Git project history, so you can always restore your commit through Git reflog even if you corrupt your working tree. After you’ve pushed your changes, they are backed up.

You can develop parallel non-related features and test them atomically.

When you’ve finished development in your branch, you can reorder or squash commits, so that your history is linear and clean.

It is easy to collaborate on your feature, or develop it from different machines.

It can take time to switch branches on really large projects.

It’s not very convenient to test related features together.

You have to learn a workflow for using feature branches and integrating your changes into the main code base.

There are two major approaches for using feature branches and integrating your changes into the main code base:

Use merge to integrate changes from a feature branch

The major benefit of the merge option is full traceability, as commits merged into the main code base preserve their original hash and author, and all commits that are part of one feature can be grouped together.

This workflow is good for projects where committing changes to the main code base involves pull requests or an hierarchical approval procedure, as existing branches are not changed in any way.

The main drawback of this approach is that extraneous merge commits are created each time you need to incorporate changes, which intensely pollutes project history and makes it difficult to read.

Create a branch for your separate line of development.

Commit your changes while you develop.

Push your branch to a remote repository. This should be done for backup, and so that you can collaborate or work from different machines.

Switch to a different branch when you need to perform work that is not related to your feature.

Have your feature reviewed and tested, and make the necessary fixes.

When you are ready to integrate the results of your work into the main branch (for example master ), do the following:

Merge your feature branch into the main code base.

Use rebase to integrate changes from a feature branch

The major benefit of this option is that you get a clean project history that is easy for others to read and understand. Your log does not contain unnecessary merge commits produced by the merge operation, and you get linear history that is easy to navigate and search through.

When deciding to adopt this workflow, you should keep in mind, however, that rebase rewrites project history as it creates new commits for each commit in the original feature branch, so they will have different hashes, which obstructs traceability.

Create a branch for your separate line of development.

Commit your changes often while you develop.

Push your branch to a remote repository. This should be done for backup, and so that you can collaborate or work from different machines.

Rebase your feature branch onto master from time to time. It only makes sense to do this if your feature branch is a long one. This is useful to:

make sure your feature branch and master do not fall too far apart.

avoid resolving numerous conflicts when you finally integrate your changes into the main code base. When you rebase regularly, you can resolve conflicts iteratively and do not end up struggling with a long diff.

speed up checking out branches, as switching between branches gets slower as soon as they diverge sufficiently.

Rebasing involves the following steps:

Fetch changes from the remote, or pull changes into the master branch.

Force push the results of the rebase operation to your feature branch.

Have your feature reviewed and tested, and make the necessary fixes.

Perform Interactive Rebase when your feature has been completed. This allows you to reorder and squash commits to make your feature branch history look nice and clean.

When you are ready to integrate the results of your work into the main branch (for example master ), do the following:

It makes sense to use your initials or your nickname (if it’s short) as a prefix for your feature branches names. This way you can always easily find all your branches using speed search in the Branches menu.

Источник

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

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