Add files to Git and track changes
If you have enabled Git integration for your project, WebStorm suggests adding each newly created file under version control. You can change this behavior in the Settings dialog Ctrl+Alt+S under Version Control | Confirmation . If you want certain files to always remain unversioned, you can configure Git to ignore them.
All the settings files in the .idea directory should be put under version control except workspace.xml , which stores your local preferences. The workspace.xml file should be marked as ignored by VCS.
You can also add files to your local repository from the Project tool window. Select the files you want to add, and press Ctrl+Alt+A or choose Git | Add from the context menu.
Check project files status
WebStorm allows you to check the status of your local working copy compared to the repository version of the project. It lets you see which files have been modified, which new files have been added to Git, and which files are not being tracked by Git.
Open the Commit tool window Alt+0 .
- The Changes changelist shows all files that have been modified since you last synchronized with the remote repository (highlighted in blue), and all new files that have been added to Git, but have not been committed yet (highlighted in green).
- The Unversioned Files changelist shows all files that have been added to your project, but that are not being tracked by Git.
If you want ignored files to be also displayed in the Changes view, click on the toolbar and select Show Ignored Files .
You can perform deployment tasks, such as uploading files and folders or comparing them with deployed versions, directly from the Local Changes tab of the Version Control tool window. To do this, right-click an item and select Deployment from the context menu. Then choose the desired action from the submenu.
The option is only available if the FTP/SFTP/WebDAV Connectivity plugin is enabled and at least one server access configuration is defined.
Track changes to a file in the editor
You can also track changes to a file as you modify it in the editor. All changes are highlighted with change markers that appear in the gutter next to the modified lines and show the type of changes introduced since you last synchronized with the repository. When you commit changes to the repository, change markers disappear.
The changes you introduce to the text are color-coded:
You can customize the default colors for line statuses on the Editor | Color Scheme | VCS page of the IDE settings Ctrl+Alt+S .
To disable VCS markers in the gutter, deselect the Highlight modified lines in gutter option on the Version Control | Confirmation page of the IDE settings Ctrl+Alt+S .
You can manage changes using a toolbar that appears when you hover over a change marker and then click it. The toolbar is displayed together with a frame showing the previous contents of the modified line:
You can roll back changes by clicking and explore the differences between the current and the repository version of the current line by clicking . To highlight the fragments that were changed, click .
Instead of reverting the whole file, you can copy any part of the contents of this popup and paste it into the editor.
Delete files from the repository
If you delete a file that is under version control, it still exists in the repository until you’ve committed the changes. The deleted file is placed in the active changelist and is highlighted in grey.
- Select a file in the Project tool window and press Delete or choose Delete from the context menu.
- In the dialog that opens, you can choose whether you want to delete this file without searching for usages or to perform safe delete (to make sure that you are deleting an unused file) by checking the Safe delete option. If any usages have been found, the Usages Detected dialog will pop up listing them. You can view these usages and remove references to this file before deleting it.
- Commit the changes to the repository.
Жизнь без .gitignore
В статье рассказывается, что файл .gitignore — мусорка, которая может еще и навредить. Например, вы положили туда паттерн, который избавляет вас от ваших специфичных файлов, которые не должны попасть в VCS, а ваш коллега получил эту информацию, и узнал, например, какую вы, используете IDE. В той статье так же описано, как жить без .gitignore файла с помощью .git/info/exclude . Но если вам не хочется что-то править в .git и вы используете IDE от JetBrains, то добро пожаловать.
Основная идея в том, что вы сохраняете в настройках проекта информацию об игнорируемых для VSC файлах. Вообще есть мануал про игнорирование файлов, но это не основной путь когда вы только создали/клонировали проект. IDE от JetBrains следит за файлами в проекте, которые не попали в систему контроля и не игнорируются. Такие файлы называются Unversioned Files :
Их можно найти на вкладке Version Control -> Local Changes . И прямо там же их можно добавить в игнорирование:
Далее нужно будет выбрать паттерн для игнорирования: игнорировать ли все файлы в папке, игнорировать ли файлы с расширением, или игнорировать конкретный файл. И все. Больше никакого .gitignore , IDE сама будет следить за тем, чтобы игнорированные ей файлы не попали в систему контроля версий. Да еще и подсвечивает желтым те файлы, которые игнорирует:
- Alexey Nikitin
- [email protected]
Blog about Java programming, clean code and Android development
Создание локального репозитория git
У вас есть проект и вы хотите сохранить его на GitHub. Рассмотрим как сделать это из среды разработки IntelliJ IDEA.
Шаг 1: создадим локальный репозиторий на своем компьютере. Открываем свой проект в IntelliJ IDEA. Для инициализации локального git-репозитория в верхнем меню нажимаем пункт VCS ->Import into Version Control->Create Git Repository.
В открывшемся окошке выбираем путь где хотим инициализировать репозиторий (можно оставить по умолчанию) и нажимаем кнопку Ok:
После того как будет создан локальный репозиторий, внизу появится меню Version Control. Если меню не появилось, выбираем View->Tool Windows->Version Control:
Шаг 2: добавим файлы под версионный контроль. В окошке Version Control нас интересует вкладка Local Changes. В списке Unversioned Files находятся файлы, которые не отслеживаются git. Intellij IDEA выделяет их коричневым:
Выберем файлы, изменения в которых мы хотим отслеживать, вызываем контекстное меню и нажимаем кнопку Add to VCS:
Обычно это только java файлы. Конфигурационные и class файлы не следует добавлять в репозиторий.
После добавления, Main.java переместился в список Default Changelist — здесь находятся файлы отслеживаемые git, которые попадут под версионный контроль после коммита. Intellij IDEA выделяет только что добавленные файлы зеленым цветом:
Если проект уже находится под версионным контролем, то при добавлении нового файла, Intellij IDEA предлагает добавить его сразу же под версионный контроль:
Соглашаемся — жмем Yes.
Шаг 3: Коммит файлов. Наконец вы хотите сохранить состояние своего проекта в репозиторий git. Для этого делаем так называемый коммит, который создает снимок состояния (snapshot) проекта в данный момент. Выбираем Default Changelist, вызываем контекстное меню и жмем Commit:
В открывшемся окне заполняем поле Commit message — указываем какие изменения сделаны в этом коммите:
Состояние всех файлов, находящихся в Default Changelist сохраняется в снимке.
При изменении файла, который уже был закомичен, он опять попадает в Default Changelist, но теперь будет синего цвета.
Для того чтобы просмотреть все коммиты, перейдите во вкладку Log. Здесь можно увидеть всю информацию о сделанных коммитах: кто и когда сделал коммит, какие файлы были изменены.
Шаг 4: публикация проекта на GitHub. Наконец вы решили залить свой проект на Github. Для этого в верхнем меню нажимаем пункт VCS -> Import into Version Control -> Share Project on GitHub:
Шаг 5: Операция push. После публикации репозитория на Github вы сделали изменения в своем локальном репозитории, и хотите эти изменения добавить на GitHub. Для этого используется операция push: VCS->Git->Push.
Шаг 6: Операция pull. Если изменения в вашем локальном репозитории устарели и вы хотите подтянуть изменения с GitHub, используйте операцию pull: VCS->Git->Pull.
- Система контроля версий
- GitHub и Git
- Клонирование репозитория с GitHub
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.
With IntelliJ IDEA, you can shelve both separate files and entire changelists .
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 Commit tool window Alt+0 , right-click the files or the changelist you want to shelve and select Shelve changes from the context menu.
- 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.
You can also shelve changes silently, without displaying the Shelve Changes dialog. To do this, select the file or changelist you want to shelve and click the Shelve Silently icon on the toolbar or press Ctrl+Shift+H . The name of the changelist containing the changes you want to shelve will be used as the shelf name.
To avoid ending up with numerous shelves with the same name (such as Default , for example), you can drag a file or a changelist from the Commit to tab to the Shelf tab of the Commit tool window, wait for a second until it’s activated, and edit the new shelf name after releasing the mouse 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. You can enter the description of the new changelist in the Comment field (optional). If you want to make the new changelist active, select Set active . Otherwise, the current active changelist remains active.
- If you want IntelliJ IDEA to save the context of a task associated with the new changelist when deactivated and restore the context when the changelist becomes active, select the Track context option (refer to tasks and contexts for details) .
- If you want to remove the changes you are about to unshelve, select the Remove successfully applied files from the shelf option. The unshelved files will be removed from this shelf, added to another changelist, and marked as applied. They will not be removed completely until deleted explicitly by clicking on the toolbar or selecting Clean Already Unshelved from the context menu. If you’ve deleted unshelved files by accident, you can view and restore them from the Recently Deleted node.
- Click OK . If conflicts occur between the patched version and the current version, resolve them as described in Resolve conflicts.
You can also unshelve changes silently, without displaying the Unshelve Changes dialog. To do this, select a file or a changelist you want to unshelve and click the Unshelve Silently icon on the toolbar or press Ctrl+Alt+U . The unshelved files will be moved to the active pending changelist.
You can also drag a file or a changelist from the Shelf tab to the Commit to tab to unshelve it silently. If you drag it holding the Ctrl key, it will be copied to the Commit to branch tab but also kept in the shelf.
Discard shelved changes
- In the Shelf view, select the changelist that contains the changes you do not want to keep anymore.
- Right-click the changelist and choose Delete from the context menu or press Delete .
Restore unshelved changes
IntelliJ IDEA lets you reapply unshelved changes if necessary. All unshelved changes can be reused until they are removed explicitly by clicking the icon on the toolbar or selecting Clean Already Unshelved from the context menu.
- Make sure that the Show Already Unshelved toolbar option is enabled.
- 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.
- Press Ctrl+Alt+S to open the IDE settings and then select Version Control | Shelf .
- 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 the 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.
- Press Ctrl+Alt+S to open the IDE settings and then select Version Control | Shelf .
- 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: