Эта глава содержит следующие разделы:

3.1 Об управлении версиями приложений с помощью системы управления версиями

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

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

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

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

 3.2 Управление версиями приложений с помощью Git

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

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

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

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

3.2.1 Возможности визуализации Git

Среда IDE предоставляет несколько средств получения информации о состоянии файлов, которые упрощают процесс работы с файлами с контролем версий, включая:

  • Цветовое кодирование. Позволяет просматривать текущее состояние файлов с контролем версий.
  • Аннотации. Позволяет просматривать информацию о редакции и авторе для каждой строки файлов с контролем версий.

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

Для получения дополнительной документации по поддержке Git и самому Git смотрите следующие ресурсы:

Руководство пользователя NetBeans Git: https://rigin.net/raznoe/netbeans/ispolzovanie-git-v-apache-netbeans.html  (перевод)  https://netbeans.apache.org/tutorial/main/kb/docs/ide/git/ (английский)

 

Git Home:
http://git-scm.com/

Документация по Git:

http://git-scm.com/documentation

3.2.2 Как инициализировать репозиторий Git

Среда IDE позволяет вам инициализировать репозиторий Git из существующих файлов, которые еще не находятся в системе управления версиями.

Чтобы инициализировать репозиторий Git:

  1. В окне Проекты выберите неверсированный проект и выберите либо:

    • Управление версиями > Инициализировать репозиторий Git (Versioning > Initialize Git Repository) из контекстного меню узла.

    • Группа > Git > Инициализировать репозиторий (Team > Git > Initialize Repository) из главного меню IDE.

  2. В диалоговом окне Инициализация репозитория Git укажите путь к репозиторию, в котором вы собираетесь хранить свои версионные файлы, или нажмите "Обзор" и найдите требуемый каталог.

  3. Нажмите "ОК".
     В папке, указанной вами на шаге 2 (папка вашего проекта NetBeans по умолчанию), которая является вашим репозиторием Git, где хранятся все данные моментальных снимков вашего проекта, создается подпапка .git. Git запускает проверку версий всех файлов в указанной вами папке. Вы можете просмотреть файлы, добавляемые в репозиторий, из окна вывода (Окно > Вывод) (Window > Output).

    • Все файлы проекта помечены как добавленные (Added) в ваше рабочее дерево.

    • После инициализации репозитория Git вы либо добавляете файлы, либо напрямую фиксируете их в репозитории Git.

3.2.3 Как клонировать репозиторий Git

Среда IDE позволяет вам клонировать внешний репозиторий Git и сделать его доступным в среде IDE. Вы фактически создаете копию или клон всего репозитория для работы в среде IDE.

Чтобы клонировать репозиторий Git:

  1. Выберите Команду Группа > Git > Клонировать (Team > Git > Clone)  в главном меню IDE. Откроется мастер клонирования репозитория.

  2. На панели удаленного репозитория мастера укажите URL-адрес, содержащий протокол подключения и местоположение репозитория Git, имя пользователя и пароль (при необходимости вы можете сохранить последний на будущее).

  3. (Необязательно) Нажмите "Конфигурация прокси" (Proxy Configuration), чтобы отобразить диалоговое окно "Параметры" и задать параметры прокси-сервера. По завершении нажмите "ОК".

  4. Нажмите кнопку Далее, чтобы перейти к следующему шагу мастера.

  5. На панели Удаленные ветви (Remote Branches) выберите ветви репозитория, которые будут загружены в ваш локальный репозиторий. Нажмите Далее.

  6. На панели Каталог назначения (Destination Directory) укажите следующее:

    • В поле Родительский каталог (Parent Directory) укажите путь к каталогу, предназначенному для клонированного хранилища на вашем жестком диске (в качестве альтернативы нажмите кнопку Обзор и перейдите к каталогу). Поле Родительский каталог предварительно заполняется путем к каталогу NetBeansProjects по умолчанию, в котором хранятся все проекты NetBeans.

    • В поле Имя клона (Clone Name) укажите имя локальной папки, в которую будет клонирован исходный проект. По умолчанию имя клона заполняется фактическим именем репозитория Git.

    • В поле Контрольная Ветвь (Checkout Branch) выберите ветвь, которая будет извлечена в рабочее дерево.

    • В поле Удаленное имя (Remote Name) укажите имя, представляющее исходный клонируемый репозиторий. origin - это псевдоним клонируемого репозитория по умолчанию. Это рекомендуемое значение.

    • Оставьте флажок "Сканировать проекты NetBeans после клонирования" (Scan for NetBeans Projects after Clone) установленным, чтобы активировать последующее сканирование сразу после завершения клонирования. (Плагин выполняет поиск проектов NetBeans в клонированных ресурсах и предлагает открыть найденные проекты.)

  7. Нажмите Готово.
     После клонирования репозитория Git внутри папки, выбранной вами в мастере, создается папка метаданных  .git.

Примечание:

Выберите параметр "Сканировать проекты NetBeans после клонирования" (Scan for NetBeans projects after clone), если вы собираетесь немедленно работать с клонированными источниками.

Если исходники содержат проекты, появится диалоговое окно с предложением открыть их в IDE.

Если исходники не содержат проекта, появится диалоговое окно с предложением создать новый проект из исходников и затем открыть их в IDE. При создании нового проекта для таких источников выберите соответствующую категорию проекта в мастере создания проекта, а затем используйте шаблон «Создать проект с существующими источниками» (Create Project with Existing Sources) в этой категории.

IDE поддерживает следующие URL-адреса Git:

ПротоколМетод доступаПример
file

Прямой доступ к репозиторию (на локальном диске)

file:///path_to_repository>

или

path_to_repository

http

Доступ по протоколу HTTP

http://hostname/path_to_repository>
https

Доступ по протоколу HTTP с шифрованием SSL

https://hostname/path_to_repository>
ssh

Доступ по протоколу SSH

ssh://hostname/path_to_repository
sftp

Доступ по протоколу SFTP

sftp://hostname/path_to_repository>
git

Доступ по протоколу GIT

git://hostname/path_to_repository

3.2.3.1 Клонирование репозитория из GitHub с использованием протокола SSH

Чтобы клонировать репозиторий из GitHub с использованием протокола SSH, выполните следующие действия:

Примечание:

Вам нужно иметь учетную запись GitHub и быть участником проекта, чтобы клонировать с помощью SSH.
  1. Выберите Команду Группа > Git > Клонировать ( Team  > Git > Clone)в главном меню. Откроется мастер клонирования репозитория.

  2. На странице Удаленного репозитория мастера клонирования репозитория укажите путь к требуемому репозиторию в поле URL репозитория, например, git@github.com:tstupka/koliba.git.

  3. Убедитесь, что git указан в текстовом поле Имя пользователя (Username).

  4. Выберите опцию Закрытый/открытый ключ (Private/public key).

  5. (Пропустите, если используете SSH-agent или Pageant для автоматического доступа по SSH к Git-серверу.) Выполните следующие действия, чтобы получить доступ к Git-серверу, используя свой личный SSH-ключ и парольную фразу:

    1. Укажите путь к ключевому файлу, например C:\Users\key.

      Примечание:

      Требуется формат закрытого ключа OpenSSH. Ключи, сгенерированные PuTTYgen для Microsoft Windows, должны быть преобразованы в формат OpenSSH перед использованием их в среде IDE.
    2. Введите кодовую фразу для ключевого файла, например, abcd.

    3. (Необязательно) При необходимости выберите опцию Сохранить парольную фразу.

  6. (Применяется при использовании SSH-agent или Pageant для автоматического доступа по SSH к серверу Git.) Оставьте поля файла закрытого ключа и парольной фразы пустыми, чтобы получить аутентифицированный доступ из IDE к серверу Git через правильно настроенный SSH-агент или Pageant.

  7. (опционально) Нажмите Настройка прокси-сервера, чтобы отобразить диалоговое окно параметров и задать параметры прокси-сервера. По завершении нажмите кнопку ОК.

  8. Нажмите кнопку Далее.

  9. На странице Удаленные ветви (Remote Branches) выберите ветви репозитория, которые будут извлечены (загружены) в ваш локальный репозиторий, например master.

  10. Нажмите кнопку Далее.

  11. На странице каталога назначения укажите следующее:

    • В поле Родительский каталог (Parent Directory)  укажите путь к каталогу, предназначенному для клонированного хранилища на вашем жестком диске (в качестве альтернативы нажмите кнопку Обзор и перейдите к каталогу).

      Поле Родительский каталог предварительно заполняется путем к каталогу NetBeansProjects по умолчанию, в котором хранятся все проекты NetBeans.

    • В поле Имя клона (Clone Name) укажите имя локальной папки, в которую будет клонирован исходный проект.

      По умолчанию Имя клона заполняется фактическим именем репозитория Git.

    • В поле Оформить ветку (Checkout Branch) выберите ветку, которая будет извлечена в рабочее дерево.

    • В поле Удаленное имя (Remote Name) укажите имя, представляющее клонируемый исходный репозиторий.

      origin - это псевдоним по умолчанию для клонируемого репозитория. Это рекомендуемое значение.

    • Оставьте флажок Проверять проекты NetBeans после клонирования (Scan for NetBeans Projects after Clone) установленным, чтобы активировать последующее сканирование сразу после завершения клонирования. (Плагин выполняет поиск проектов NetBeans в клонированных ресурсах и предлагает открыть найденные проекты.)

  12. Нажмите кнопку Готово.

    После клонирования репозитория отображается сообщение о завершении клонирования.

  13. Выберите нужные параметры сканирования для проектов NetBeans после клонирования.

3.2.4 Как добавить файлы в репозиторий

Среда IDE позволяет отслеживать новый файл, а также вносить изменения в уже отслеживаемый файл в репозитории Git. Вы фактически добавляете свои исходные тексты в локальный репозиторий Git. Файлы репозитория размещаются в каталоге .git в каталоге проекта.

Чтобы добавить файлы в репозиторий Git:

При добавлении файлов в репозиторий Git среда IDE сначала создает и сохраняет снимки вашего проекта в индексе. После выполнения фиксации среда IDE сохраняет эти снимки в HEAD. Среда IDE позволяет вам выбирать между двумя рабочими процессами:

  • Явно добавляйте новые или измененные файлы в индекс, а затем фиксируйте в HEAD только те, которые размещены в индексе поэтапно.

  • Пропустите добавление новых или измененных файлов в индекс и зафиксируйте необходимые файлы непосредственно в HEAD.

Чтобы добавить файлы в индекс, а затем зафиксировать подготовленные файлы:

  1. В окне Проекты (Projects) щелкните правой кнопкой мыши файл, который вы хотите добавить.

  2. В контекстном меню выберите Git > Добавить (Git > Add). Это добавит содержимое файла в индекс перед его фиксацией.

  3. В окне Проекты (Projects) щелкните правой кнопкой мыши файл, который вы хотите зафиксировать.

  4. В диалоговом окне фиксации выберите переключатель "Изменения между заголовком и индексом" (Changes between HEAD and Index). Здесь отображается список файлов, которые уже размещены.

  5. Зафиксируйте файл, как описано в разделе 3.2.5 "Как зафиксировать исходные тексты в репозитории Git".

Чтобы пропустить добавление файлов в индекс и зафиксировать файлы напрямую:

  1. В окне Проекты (Projects) щелкните правой кнопкой мыши файл, который вы хотите зафиксировать.

  2. В контекстном меню выберите Git > Commit.

  3. В диалоговом окне фиксации выберите переключатель Выбрать изменения между индексом и рабочим деревом (Select the Changes between Index and Working Tree). При этом отображается список файлов, которые не были обработаны поэтапно.

  4. Зафиксируйте файл, как описано в разделе 3.2.5 "Как зафиксировать исходные тексты в репозитории Git".

3.2.5 Как зафиксировать исходные тексты в репозитории Git

Среда IDE позволяет вам фиксировать файлы в репозитории Git. Среда IDE выполняет фиксацию и сохраняет ваши изменения в репозитории после успешной фиксации.

Чтобы зафиксировать версионные файлы в репозитории:

  1. Выберите  команду Группа > Фиксация (Team > Commit) в главном меню IDE. Откроется диалоговое окно фиксации.

  2. Введите сообщение о фиксации в текстовой области сообщения о фиксации (Commit Message). В качестве альтернативы вы можете выполнить любое из следующих действий:

    • Нажмите Последние сообщения (Recent Messages), чтобы просмотреть и выбрать из списка сообщения, которые вы использовали ранее.

    • Нажмите кнопку Загрузить шаблон (Load Template), чтобы выбрать шаблон сообщения.

  3. Укажите имена автора (Author) и отправителя (Committer) в соответствующих полях.

  4. Выберите файлы, которые будут зафиксированы, в разделе Файлы для фиксации (Files to Commit).

  5. В разделе Обновить Задачу (Update Task) укажите и измените задачи, связанные с фиксируемым изменением, если требуется.

  6. После указания действий для отдельных файлов нажмите кнопку Зафиксировать (Commit).

Примечание:

Строка состояния IDE, расположенная в правом нижнем углу интерфейса, отображается по мере выполнения действия фиксации.

После успешной фиксации значки управления версиями исчезают в окнах "Проекты", "Файлы" и "Избранное", а цветовая кодировка зафиксированных файлов возвращается к черному.

3.2.6 Как отменить изменения

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

Чтобы отменить изменения:

  1. Выберите версионный проект, файл или папку, для которых вы хотите отменить изменения.

  2. Выберите команду Группа > Отменить изменения (Team  > Revert Modifications) в главном меню IDE или Git > Отменить изменения (Git > Revert Modifications) в контекстном меню выбранного элемента.

  3. В диалоговом окне "Отменить изменения" выберите любой из следующих параметров:

    • Отменить все незафиксированные изменения в рабочем дереве и индексе (Revert All Uncommitted Changes in Working Tree and Index). - Удаляет все незафиксированные изменения и возвращает состояние файлов в HEAD.

      • Удалить также новые файлы и папки (Remove also New Files and Folders). - Удаляет новые файлы и папки, которые не были сохранены в HEAD.

    • Вернуть незафиксированные изменения в рабочем дереве в состояние в индексе (Revert Uncommitted Changes in Working Tree to the State in Index).  - Удаляет незафиксированные изменения в рабочем дереве и возвращает текущее состояние файлов в Индексе.

      • Удалить также новые файлы и папки (Remove also New Files and Folders). - Удаляет новые файлы и папки, созданные в рабочем дереве, но не добавленные в индекс.

    • Вернуть в HEAD только незафиксированные изменения в индексе (Revert only Uncommitted Changes in Index to HEAD). -  Удаляет незафиксированные изменения в индексе и возвращает к состоянию файлов в HEAD.

  4. Нажмите кнопку Восстановить (Revert). Интегрированная среда разработки заменит выбранные файлы на те, которые вы указали в выбранном параметре.

3.2.7 Как сбросить настройки

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

Для сброса:

  1. Выберите версионный проект, файл или папку.

  2. Выберите Команду Группа > Отменить/восстановить > Сброс (Team > Revert/Recover > Reset) в главном меню IDE или Git > Отменить/Восстановить > Сброс (Git > Revert/Recover > Reset) в контекстном меню выбранного элемента.

  3. В диалоговом окне Git Reset укажите любой из следующих параметров:

    • Пересмотр (Revision). Укажите требуемую редакцию, введя идентификатор фиксации, существующую ветвь или название тега в поле Редакция (Revision), или нажмите Выбрать, чтобы просмотреть список редакций, хранящихся в репозитории. В следующих полях отображается информация, относящаяся к выбранной редакции:

      • ID фиксации (Commit ID). - Уникальный идентификатор указанной ревизии.

      • Автор (Author). - Уникальный идентификатор указанной ревизии.

      • Сообщение (Message). - Сообщение, указанное во время фиксации изменения.

    • Опции (Options). Выберите любой из приведенных ниже режимов сброса:

      • Не изменять индекс или рабочее дерево (--soft) (Do Not Modify Index or Working Tree (--soft)). - Выберите, чтобы переместить заголовок в указанную фиксацию и оставить все изменения в Индексе и рабочем дереве.

      • Изменить рабочее дерево (--mixed) (Modify Working Tree (--mixed)). - Выберите, чтобы перезаписать все изменения в индексе и оставить изменения в рабочем дереве.

      • Обновить индекс и рабочее дерево (--hard) (Update Index and Working Tree (--hard)). - Выберите, чтобы перезаписать все изменения, внесенные в ваш индекс и рабочее дерево.

  4. Нажмите Сброс. Интегрированная среда разработки отменит изменения в соответствии с выбранным параметром.

3.2.8 Как создать тег

Вы можете создавать теги для ссылок на конкретный коммит. Это может упростить поиск элементов в конкретном коммите.

Чтобы создать тег:

  1. В диалоговом окне Создать тег (Create Tag) укажите следующее:

    • Имя тега (Tag Name). - Укажите имя создаваемого тега.

    • Cообщение тега (Tag Message). - Введите комментарий, который будет включен в тег.

    • Принудительное обновление (Force Update). - Выберите, чтобы заменить существующий тег с идентичным именем.

    • Редакция (Revision). - Введите конкретную редакцию выбранного элемента, указав ID фиксации, существующую ветвь или название тега. В качестве альтернативы, нажмите "Выбрать", чтобы открыть диалоговое окно "Выбрать редакцию", в котором вы можете просмотреть список редакций, хранящихся в хранилище, и выбрать нужную.

  2. Просмотрите информацию, относящуюся к указанной редакции, в следующих полях:

    • ID фиксации (Commit ID). - Уникальный идентификатор указанной ревизии.

    • Автор (Author). - Имя человека, который внес изменения.

    • Сообщение (Message). - Сообщение, указанное во время фиксации изменения.

  3. Нажмите кнопку Создать (Create).

    Тег будет добавлен в указанную редакцию.

3.2.9 Как сравнить версии файлов

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

Чтобы получить доступ к средству просмотра различий, выберите файл или папку с управлением версиями (например, в окне "Проекты", "Файлы" или "Избранное") и выберите либо  Git > Различия > Отличия от HEAD (Git > Diff > Diff To HEAD) в контекстном меню, либо Группа > Различия > Отличия от HEAD (Team > Diff > Diff To HEAD) в главном меню.

В следующей таблице перечислены команды Git, доступные на панели инструментов средства просмотра различий:

ИконкаИмяФункция
HEAD vs Working icon

Изменения между заголовком и рабочим деревом

Отображает список файлов, которые либо уже загружены, либо только изменены/созданы и еще не загружены.

HEAD vs Index icon

Изменения между HEAD и Index

Отображает список подготовленных файлов.
Index vs Working

Изменения между индексом и рабочим деревом

Отображает файлы, которые имеют различия между состоянием промежуточного и рабочего дерева.
Go to Next Difference

Переходим к следующему отличию

Отображает следующее различие в файле.
Go to Previous Difference

Перейти к предыдущему отличию

Отображает предыдущее отличие в файле.
Refresh Statuses icon

Обновлять статусы

Обновляет статус выбранных файлов и папок. Файлы, отображаемые в окне управления версиями, могут быть обновлены с учетом любых изменений, которые могли быть внесены извне.
Revert Modifications icon Отменить изменения Отображает диалоговое окно "Отменить изменения".
Commit Changes icon Фиксация изменений Отображает диалоговое окно фиксации.

Средство просмотра различий предоставляет следующие компоненты пользовательского интерфейса:

Синий

Указывает строки, которые были изменены со времени предыдущей редакции.

Зеленый

Указывает строки, которые были добавлены со времени предыдущей редакции.

Красный

Указывает строки, которые были удалены со времени предыдущей редакции.

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

Replace icon Вставляет выделенный текст в копию рабочего дерева.
Move All icon Возвращает всю локальную копию рабочего дерева.
Remove icon Удаляет выделенный текст из локальной копии рабочего дерева.

3.2.10 Как работать с ветками

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

  • создание ветви

  • проверка ветви

  • объединение ветвей

  • удаление ветвей

3.2.10.1 Создание ветви

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

Чтобы создать локальную ветку:
  1. В окне Проекты (Projects) или Файлы (Files) выберите проект или папку из репозитория, в котором вы хотите создать ветку.

  2. Выберите Группа > Ветвь/тег > Создать ветьв (Team > Branch/Tag > Create Branch) в главном меню (альтернативно щелкните правой кнопкой мыши проект или папку с версией и выберите Git > Ветвь/тег > Создать ветвь (Git > Branch/Tag > Create Branch) в контекстном меню). Откроется диалоговое окно Создать ветвь.

  3. В поле Название Ветки (Branch Name) введите название создаваемого филиала.

  4. Введите конкретную редакцию выбранного элемента, введя идентификатор фиксации (commit ID), существующую ветвь или название тега в поле Редакция (Revision), или нажмите кнопку Выбрать (Select), чтобы просмотреть список редакций, хранящихся в репозитории, и выбрать нужную.

  5. Просмотрите информацию в полях Идентификатор фиксации (Commit ID), Автор (Author) и Сообщение (Message), относящуюся к редакции, из которой выполняется ветвление, и нажмите Создать (Create). Ветвь будет добавлена в папку Branches/Local репозитория Git.

3.2.10.2 Проверка ветви

Чтобы отредактировать файлы в уже существующей ветке, вы можете проверить эту ветку и скопировать файлы в ваше рабочее дерево.

Чтобы ознакомиться с версией:
  1. В главном меню выберите Группа > Получить > Получение редакции.. (Team > Checkout > Checkout Revision). Откроется диалоговое окно Получить выбранную редакцию.

  2. Укажите требуемую ревизию, введя ID фиксации, существующую ветвь или название тега в поле Ревизия (Revision), или нажмите кнопку Выбрать (Select), чтобы просмотреть список ревизий, хранящихся в репозитории, и указать требуемую.

    Примечание:

    Укажите требуемую ревизию, введя ID фиксации, существующую ветвь или название тега в поле Ревизия, или нажмите кнопку Выбрать, чтобы просмотреть список ревизий, хранящихся в репозитории, и указать требуемую.
  3. Просмотрите информацию в полях ID фиксации (Commit ID), Автор (Author) и Сообщение (Message), относящуюся к извлекаемой версии.

  4. Чтобы создать новую ветвь из проверенной редакции, выберите опцию Оформить как новую ветвь (Checkout as New Branch) и введите название в поле Название ветви (Branch Name).

  5. Нажмите кнопку Оформить (Checkout), чтобы проверить версию. Файлы в рабочем дереве и в индексе обновляются в соответствии с версией в указанной редакции.

Чтобы извлечь файлы:
  1. В главном меню выберите Группа > Оформить заказ > Оформить файлы (Team > Checkout > Checkout Files). Откроется диалоговое окно "Оформить выбранные пути".

  2. (Необязательно) Выберите опцию Обновить индекс (Update Index) с записями из выбранной редакции, чтобы обновить индекс с учетом состояния в выбранной редакции перед самой проверкой.

  3. (Включается, если выбрана опция Обновлять индекс записями из выбранной редакции.) Укажите требуемую редакцию, нажав кнопку Выбрать.

  4. Просмотрите информацию в полях ID фиксации, Автор, Cообщение (Commit ID, Author, Message), относящуюся к извлекаемой ревизии.

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

3.2.10.3 Объединение

Объединение позволяет переносить изменения из версии репозитория в Рабочее дерево.

Для слияния:
  1. В главном меню выберите Группа > Ветвь/тег > Объединить редакцию (Team > Branch/Tag > Merge Revision). Откроется диалоговое окно "Объединить редакцию".

  2. Укажите требуемую ревизию, введя идентификатор фиксации, существующую ветвь или название тега в поле Ревизия, или нажмите кнопку Выбрать, чтобы просмотреть список ревизий, хранящихся в репозитории, и указать требуемую.

  3. Просмотрите информацию в полях ID фиксации, Автор, Сообщение, (Commit ID, Author, Message) относящуюся к объединяемой ревизии.

  4. Нажмите Объединить (Merge). Выполняется трехстороннее объединение текущей ветви, содержимого вашего рабочего дерева и указанной ветви.

Примечание:

После слияния вы все равно должны зафиксировать изменения, чтобы они были добавлены в заголовок.

3.2.10.4 Удаление

Вы можете удалить ненужную локальную ветку.

Чтобы удалить ветку:
  1. В главном меню выберите Группа > Браузер репозитория (Team > Repository Browser).

  2. В Браузере Репозитория (Repository Browser) Git  выберите ветку, которую нужно удалить.

    Примечание:

    Ветвь должна быть неактивной, то есть в данный момент не извлечена из рабочего дерева.
  3. Щелкните правой кнопкой мыши на выбранной ветви и выберите во всплывающем меню пункт Удалить ветвь.

  4. В диалоговом окне "Удалить ветку" нажмите "ОК", чтобы подтвердить удаление ветки. Ветка будет удалена из локального репозитория, а также из браузера репозитория Git.

 

3.2.11 Как работать с удаленными репозиториями

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

  • Выборка (fetching)

  • Вытягивание (pushing)

  • Выталкивание (pulling)

3.2.11.1 Выборка

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

Для получения обновлений из удаленного хранилища:
  1. Выберите Группа > Удаленный > Выбрать (Team > Remote > Fetch).

  2. На первой панели мастера выберите либо настроенный репозиторий (чтобы использовать путь к ранее настроенному репозиторию), либо укажите параметр расположения репозитория Git (чтобы определить путь к удаленному репозиторию, к которому еще не был осуществлен доступ, его имя, логин, пароль, файл закрытого ключа, ключевую фразу и настройка прокси-сервера, если требуется). Нажмите кнопку Далее.

  3. На второй панели мастера выберите ветви, в которые нужно внести изменения. Нажмите "Готово". Будет создана локальная копия удаленной ветви. Выбранные ветви будут обновлены в каталоге Ветви > Удаленный (Branches > Remote directory) в браузере репозитория Git. Затем полученные обновления могут быть объединены в локальную ветку.

3.2.11.2 Вытягивание

При вытягивании некоторых обновлений из удаленного репозитория Git изменения извлекаются из него и объединяются в текущий заголовок вашего локального репозитория.

Чтобы вытянуть данные из удаленного хранилища:
  1. Выберите Группа > Удаленный > Вытянуть (Team > Remote > Pull).

  2. На странице мастера удаленного репозитория выберите либо настроенный репозиторий (чтобы использовать путь к ранее настроенному репозиторию), либо укажите параметр Расположения репозитория Git (чтобы указать путь к удаленному репозиторию, к которому еще не был осуществлен доступ, его имя, логин, пароль, файл закрытого ключа и ключевую фразу, если требуется) и нажмите кнопку Далее.

  3. На странице мастера «Удаленные ветки» выберите ветки, из которых вы хотите получить изменения, и нажмите «Готово». Ваш локальный репозиторий синхронизируется с исходным репозиторием.

3.2.11.3 Выталкивание

Выталкивание позволяет вам вносить изменения из локального репозитория Git в общедоступный репозиторий Git.

Чтобы отправить в удаленный репозиторий:
  1. Выберите Группа > Удаленный > Вытолкнуть (Team > Remote > Push).

  2. На первой панели мастера выберите либо настроенный репозиторий (чтобы использовать путь к ранее настроенному репозиторию), либо укажите параметр расположения репозитория Git (чтобы указать путь к удаленному репозиторию, к которому еще не был осуществлен доступ, его имя, логин, пароль, файл закрытого ключа и ключевую фразу, если требуется) и нажмите кнопку Далее.

  3. На второй панели мастера выберите разделы, в которые необходимо внести изменения. Нажмите "Далее".

  4. На третьей панели мастера выберите ветку(ки), которые необходимо обновить, в каталоге Remotes вашего локального репозитория и нажмите кнопку Готово. Указанная ветвь удаленного репозитория обновляется в соответствии с последним состоянием вашей локальной ветви.

3.2.12 Как установить глобальные параметры Git

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

Чтобы установить глобальные параметры Git:
  1. Выберите Сервис > Параметры (Tools > Options). Откроется окно Параметров интегрированной среды разработки.

  2. Выберите вкладки Группа > Управление версиями (Team > Versioning), затем выберите Git в разделе Системы управления версиями.

Можно задать следующие свойства глобальных параметров Git:

Автоматическое открытие вкладок окна вывода

Если этот параметр выбран, окно вывода отображается при выполнении операций управления версиями, связанных с взаимодействием с репозиторием Git (например, clone, fetch, pull, push).

Исключать новые файлы из автоматической фиксации

Выберите, чтобы не добавлять новые файлы во время фиксации.
Добавить строку Signed-off-by в сообщение о фиксации фиксации Выберите, чтобы добавить имя отправителя в качестве подписывающего лица в сообщение журнала во время фиксации.
Постоянно игнорировать папки, не используемые совместно При выборе этого параметра среда IDE игнорирует файлы и папки, не предназначенные для фиксации (например, build и dist fдля проектов J2SE), и добавляет пути к ним в файл .gitignore.

3.2.13 Как отложить изменения (Git)

Отложенный доступ позволяет вносить изменения в проект без фиксации и передачи их в систему управления версиями Git.

Чтобы временно отложить некоторые еще не внесенные изменения в рабочий каталог в виде файла исправления:
  1. Выберите версионный проект, файл или папку.

  2. В главном меню выберите Группа > Отложить изменения > Отложить изменения (Team > Shelve Changes > Shelve Changes).

  3. Укажите имя патча, который нужно отложить, в поле Имя патча (Patch Name).

  4. Укажите параметры патча на панели Параметры (Options) диалогового окна.

  5. Нажмите кнопку Отложить (Shelve).

    Среда IDE сохраняет еще не внесенные изменения, содержащиеся в выбранном проекте, файле или папке, в файл исправления и возвращает измененные файлы в рабочую копию (локальные изменения удаляются из рабочей копии). Ранее измененные файлы становятся актуальными.

3.2.14 Как выполнить перебазирование (Git)

Перебазирование применяет изменения из одного направления работы в другое в том порядке, в котором они были внесены.

Чтобы перенаправить локальные коммиты в другой целевой коммит:
  1. Выберите версионный проект, файл или папку.

  2. В главном меню выберите Группа > Ветвь/тег > Перебазировать (Team > Branch/Tag > Rebase).

    Либо щелкните выбранный элемент правой кнопкой мыши и выберите Git > Ветка/тег > Перебазировать (Git > Branch/Tag > Rebase) в контекстном меню.

  3. Задайте необходимые свойства в диалоговом окне «Выбор коммитов для перебазирования».

  4. Нажмите Перебазировать (Rebase), чтобы завершить перебазирование в соответствии с заданными настройками.

3.3 Versioning Applications with Subversion

Subversion is a type of version control system that aids developer groups working with shared source files in common repositories by managing file revision history information.

The IDE's Subversion support enables you to manage changes to version-controlled files as you work. In the IDE, you can call Subversion commands on both files and directories in the Projects, Files, Versioning, and Favorites windows. The IDE also provides a graphical Diff Viewer, enabling you to compare file revisions, as well as a History Viewer, allowing you to search a file or folder's history for versions based on specific criteria.

The IDE's Subversion support allows you to:

  • Rename documents in your repository and keep the whole history of the document's revisions.

  • Treat commits as whole entities. If you attempt to commit changes to several files and the commit fails, no files are changed in the repository

3.3.1 Subversion Visualization Features

The IDE provides several file status information tools that simplify the process of working with version-controlled files, including:

  • Color Coding. Enables you to view the current status of version-controlled files.

  • Annotations. Enables you to view revision and author information for each line of version-controlled files.

3.3.2 Working with Subversion

The following table outlines the basic workflow when working with Subversion in the IDE.

TaskDetails

Set Up Subversion

See Section 3.3.5, "How to Set Up Subversion."

Synchronize local files with repository

Check out files from a repository. See Section 3.3.6, "How to Check Out Files From a Remote Repository (Subversion)."

Import your project into a Subversion repository. See Section 3.3.7, "How to Place Projects Under Version Control (Subversion)."

Edit Sources Make changes to local copies of versioned files.

Diff file revisions between repository versions and your local working copies. See Section 3.3.9, "How to Compare File Revisions in Subversion."

Merge changes in repository revisions with the local copies. See Section 3.3.14, "How to Merge File Revisions in Subversion."

Update Local Versions

Update local versions of files with changes committed to the Subversion repository. See Section 3.3.8, "How To Update Files in a Local Working Directory (Subversion)."
Resolve Conflicts Resolve conflicts between local versions of files with changes committed to Subversion repository revisions. See Section 3.3.15, "Resolving Merge Conflicts in Subversion."
Commit Sources Commit local changes to files into the repository. See Section 3.3.10, "How to Commit Local Changes to a Remote Repository (Subversion)."

3.3.3 How to View File Status Information

The IDE's Subversion support enables you to view and manage the evolution of changes in version-controlled files.

You can view version status information in many of the IDE's windows, including the Versioning, Projects, Files, and Favorites windows. The Versioning window, however, represents the primary place within which to manage version-controlled files by displaying a list of all of the new, modified, and removed files in the currently selected project or directory.

To open the Versioning window, select either:

  • Subversion > Show Changes from the context menu of a version-controlled file or folder from the Projects, Files, or Favorites window.

  • Team > (Subversion >) Show Changes from the main menu.

  • Window > Versioning > Subversion from the main menu.

The IDE's Subversion support provides file status information in the following ways:

TaskDetails

Status Labels

Textual indication of file status in the Versioning, Projects, Files, and Favorites windows. To display status labels, select View > Show Versioning Labels from the main menu.

Status Color

Textual indication of file status in the Versioning, Projects, Files, and Favorites windows. To display status labels, select View > Show Versioning Labels from the main menu.
Status Badges Graphical indication of the status of files contained within your project, folder, and package nodes. Displayed in the Projects, Files, and Favorites windows.

Revision Annotations

Displays commit message, author, date, and revision number information in the left margin of files open in the Source Editor. To display annotations, select a versioned file and select Show Annotations (or Subversion > Show Annotations) from its context menu. Alternatively, select Versioning, > Show Annotations from the main menu.

The IDE displays version-controlled files using the following color coding and font styles:

Color CodingDescription
Green color coding Indicates that the file is a new local file that does not yet exist in the repository.
Blue color coding Indicates that the file has been modified locally.
Red color coding Indicates that the file contains conflicts. You must employ the Resolve Conflicts command (Subversion > Resolve Conflicts) for such files.
Grey color coding Indicates that the file is ignored by Subversion and will not be included when calling versioning commands. In the Versioning window, grey text signifies deleted files.
Strike-through color coding Indicates that the file is excluded when calling the Commit command. All other Subversion commands, however, work as usual. Note that files displayed in the strike-through style only appear in the Versioning window and Commit dialog. They will not appear in Diff panes, nor will their parent folders (or packages) display badges if they are modified.

Current Subversion file status is indicated by adding the following badges to project, package and directory icons:

BadgeDescription
Locally modified badge A blue badge on a folder or package node marks folders or packages that contain locally modified or new files. In the case of packages, this badge applies only to the package itself and not its subpackages. For folders, the badge indicates local modifications in that folder or any of its subfolders.
Conflict badge A red badge on a folder or package node marks folders or packages that contain files for which the repository copy of the file contains changes which conflict with the local version. In case of packages, this badge applies only to the package itself and not its subpackages. For folders, the badge indicates local modifications in that folder or any of its subfolders.

Note: Parent folders (or packages) of files excluded from commits and displayed in the strike-through style will not display badges if they are modified.

3.3.4 How to Work with Version Histories

Searching the histories of files can be helpful when you need to find specific commits, for example when backporting bugs. The IDE's Search Histories window enables you to view a summary of a file's evolution over time by revision number.

You can view file histories in the IDE's Search History window. To do so, select a versioned file (for example, from the Projects, Files, or Favorites window) and select either Subversion > Search History from the context menu or Team > (Subversion >) Search History from the main menu. Alternatively, in the Versioning window you can select Search History from a file's context menu.

3.3.4.1 Searching for Specific Revisions

Using the Search History window, you can search a file or folder's history for versions based on several criteria. These are:

CriteriaDescription

Message

The description submitted with the commit.

Username

The author of the commit
From The tag, revision number, or date from which the commit was made.

To

The tag, revision number, or date before which the commit was made.

To search for a specific revision:

  1. Select the file or folder for which you want to find a specific revision.

  2. Select Team > (Subversion >) Search History from the main menu. Alternatively, you can select Subversion > Search History from the selected file's context menu. The IDE displays the file's revision history in the Search History window.

  3. Enter search criteria information in the Message, Username, From, and To fields. You can also use the Browse buttons to designate any tag, branch, revision, or date you want to limit your search to.

  4. Click Search. The IDE displays the file's revision history in the Search History window.

Note:

If you want to perform a diff, or revert (that is, 'rollback') changes from a specific commit, you can do so from the displayed revision history using the Diff and Revert links to the right of each revision.

3.3.4.2 Comparing Revisions in the Search History Window

You can compare a file with previous versions from within the Search Histories window using the Diff button.

To view revision differences in the Search History window:

  1. Click the Diff button in the toolbar.

  2. Select the revision against which you want to compare your local working copy. The IDE displays a diff of the file's revisions within the Search History window. Note that you can navigate between the differences using the Previous Difference ( Previous difference button) and Next Difference ( Next difference button) buttons.

3.3.5 How to Set Up Subversion

Before you can take advantage of the IDE's Subversion support, you need to have Subversion client software installed on your system. The IDE supports Subversion client versions 1.3.x and higher. The IDE's Subversion support works by interacting with the Subversion client to carry out the commands.

You can download Subversion as a binary package from the following link:

http://www.collab.net/downloads/subversion

Though the Subversion site does not guarantee the quality of the binary downloads, you might find them easier to work with. For example, the executable binary for Microsoft Windows systems sets up the environment variable that enables your system and the IDE to recognize the Subversion installation. If you do not use an installer, follow the Subversion installation instructions closely to make sure that you set up everything correctly on your system.

If you are using Mac OS X, you may need to manually register the Subversion executable home folder in the IDE. See Specifying the Path to the Subversion Executable in the Guided Tour of Subversion for more details:

http://netbeans.org/kb/docs/ide/subversion.html

After the Subversion client is set up, you can run Subversion commands from the IDE's Team > Subversion menu. To check out files from a Subversion repository, select Team > (Subversion >) Checkout. In the process of checking out, the IDE automatically registers the working directory where your local copies of version-controlled files and their status information will be stored.

If you have already checked out files from a Subversion repository (using Subversion client 1.3.x or higher), the IDE automatically recognizes the files as versioned files if those files are part of an open IDE project or if they are added to the Favorites window. You can call Subversion commands on such files from the Subversion menu or by right-clicking a file or folder and choosing from the Subversion submenu.

3.3.6 How to Check Out Files From a Remote Repository (Subversion)

In order to work on shared files located in a remote repository, you need to copy the necessary files and directories to your local working directory. This is done by checking out the files from the repository.

To check out files from a remote repository:

  1. Select Team > (Subversion >) Checkout from the main menu. The Subversion Checkout wizard opens.

  2. In the first panel of the wizard, enter a URL that contains the connection protocol and the location of the repository.

    • If you enter a protocol such as http://, https://, or svn://, User and Password fields appear in the wizard. Fill in these fields as necessary.

    • If you enter svn+ssh://, you must supply the command to establish the external tunnel.

    • If you are using a proxy, click the Proxy Configuration button and enter the required information.

    Click Next.

  3. In the Folders to Checkout panel of the wizard, specify the folder that you want to check out in the Repository Folder field or click Browse to choose from a list of all folders in the repository.

    • To check out only the contents of the folder you are specifying (rather than the folder itself), select the Skip "<selected_folder>" and check out only its content option.

  4. If you need to specify a revision number, enter the information in the Repository Revision field or click the Browse button to view and select from a list of all revisions in the repository.

  5. Specify the local folder into which you want to check out the selected folders. Alternatively, click the Browse button to navigate to the desired directory on your system.

  6. Click Finish to check out the files. The IDE initiates the checkout action and the IDE's status bar indicates the progress of the files downloading from the repository to your local working directory. You can also view files being checked out from the Output window (Ctrl+4).

Note:

Select the Scan for NetBeans projects after Checkout option if you intend to immediately work with the checked-out sources. If the sources contain projects, a dialog will appear prompting you to open them in the IDE. If the sources do not contain a project, the dialog will appear prompting you to create a new project from the sources and then open them in the IDE. When you create a new project for such sources, select the appropriate project category and then use the ”With Existing Sources” template in that category.

3.3.7 How to Place Projects Under Version Control (Subversion)

The IDE enables you to place any project you are working on under version control. You effectively import your sources into the remote repository. To do so, you need to be able to access a Subversion repository for which you have write privileges.

To place an IDE project under version control:

  1. In the Projects window, select an unversioned project and then select either:

    • Versioning > Import into Subversion Repository from the node's context menu.

    • Team > Subversion > Import into Repository from the IDE's main menu.

    The Subversion Import wizard opens.

  2. In the Subversion Repository page of the Import wizard, specify the protocol and location of the Subversion repository as defined by the Subversion URL. Depending on your selection, you may require to specify further settings, such as repository username and password, or, in the case of svn+ssh://, you must specify the tunnel command to establish the external tunnel. Click Next.

  3. In the Repository Folder panel, specify the repository folder in which you want to place the project in the repository. A folder containing the name of your project is suggested for you in the Repository Folder text field by default.

  4. In the text area beneath Specify the Message, enter a description of the project you are importing into the repository.

  5. Click Finish to initiate the import, or optionally, click Next to continue to a third panel that enables you to preview all files that are prepared for import. From this panel, you can choose to exclude individual files from import, or identify the MIME types of files before importing. Upon clicking Finish, the IDE uploads the project files to the repository and the Output window opens to display the progress.

The IDE supports the following Subversion protocol types:

ProtocolAccess MethodExample

file

Direct repository access (on local disk) file:///repository_path[@REV]

http

Access using WebDAV protocol to a Subversion-aware server http://hostname/repository_path[@REV]

https

Access using HTTP protocol with SSL encryption https://hostname/repository_path[@REV]

svn

Access using custom protocol to an svnserve server svn://hostname/repository_path[@REV]

svn+ssh

Access using SVN protocol through an external SSH tunnel svn+ssh://hostname/repository_path[@REV]

3.3.8 How To Update Files in a Local Working Directory (Subversion)

Updating files or folders enables you to incorporate any changes that other developers have committed to the repository since your previous checkout or update.

To update a local version of a file or folder:

  • Select a versioned file (for example, in the Projects, Files, or Favorites window) and select Subversion > Update. Alternatively, select a file in the Versioning window and select Update from the context menu. The IDE incorporates any changes existing in the repository version of the file.

Note:

It is recommended that you perform an update on all files prior to committing them to the repository. Doing so allows you to become aware of any conflicts prior to performing the commit.

3.3.8.1 Updating Projects with Dependencies

If you are working on a project for which there are other required projects, you can update both the main project and all dependent projects using the IDE's Update with Dependencies command.

To update an entire project and all dependent projects:

  1. Right-click the project node in the Projects window.

  2. Select Subversion > Update With Dependencies. The IDE incorporates any changes existing in the repository version of all of the projects with your local working copy.

3.3.9 How to Compare File Revisions in Subversion

The Diff command compares different revisions of a file and displays the differences found graphically.

3.3.9.1 Comparing File Revisions Graphically

The IDE's graphical Diff Viewer enables you to compare different versions of a file side by side using color coding to emphasize the differences between the files being compared.

The previous ( Previous difference button) and next ( Next difference button) difference buttons in the toolbar enable you to navigate among the differences in the file. You can also refresh the status and update files from within the Diff Viewer using the Refresh Diff ( Refresh button) and Update ( Update button) buttons. When you are finished comparing the files, you can commit your changes using the Diff Viewer's Commit button ( Commit button).

To generate a graphical diff comparing a repository revision to your working copy:

  • Right-click a versioned file node in the Projects, Files, or Versioning window and select Diff (or Subversion > Diff). The IDE displays the results in the Diff Viewer in a new tab of the main window.

Note:

If you want to perform a diff on all files contained in a folder, select a folder and select Subversion > Diff from the context menu. All files that contain differences between your local version and the repository version will be listed in the upper pane of the Diff Viewer. You can then view individual diffs on files by clicking a file from the list.

To make changes to a file while comparing it in the Diff Viewer:

  1. Navigate through differences between the two versions using the previous difference and next difference arrow icons.

  2. Click any of the displayed icons to perform immediate changes to your local copy.

Note:

Your local copy appears in the right pane of the Diff Viewer. You can also make changes to your local copy by typing directly into it in the Diff Viewer.

Any changes made in the Diff Viewer are automatically saved as they occur.

The following icons enable you to make changes directly within the Diff Viewer:

  • Replace. Inserts the highlighted text from the previous revision into the current revision

  • Move All. Reverts the file's current version to the state of the selected previous version.

  • Remove. Removes the highlighted text from the current version so that it mirrors the previous version.

3.3.10 How to Commit Local Changes to a Remote Repository (Subversion)

Once your working copies of version-controlled files have been edited, you can then place changes into the repository using the Subversion Commit action.

Note:

Subversion versioned files and folders must be recognized by the IDE as such in order to call Subversion actions on them. To do so, you must first check out sources from a Subversion repository.

To commit changes in local files to a remote repository:

  1. Select a version-controlled file or folder (for example, from the Projects, Files, or Favorites window) and select Subversion > Commit from the context menu. The Commit Dialog opens, listing all files that contain local changes. If the files you want to commit do not already exist in the repository, the commit action will add them.

  2. Enter a commit message in the Commit Message text area, indicating the purpose of the commit.

    • Click the Recent Messages icon in the upper right corner of the dialog to view recent commit messages.

  3. Click Commit. The IDE executes the commit and sends your local changes to the repository.

Note:

It is recommended that you perform an update (Subversion > Update) on any files prior to committing them to the repository. By doing so, you will be able to identify and handle any conflicts arising from repository changes prior to performing your commit.

When working in the Commit dialog, you can exclude individual files from a commit. To do so, click on the Commit Action column for the specific file and select Exclude from Commit. The file name responds by displaying in strike-through text.

3.3.10.1 Ignoring Files

If your local working directory includes files or directories that you do not want to place under version control, you can set the IDE to ignore them permanently using the Ignore command.

Note:

You cannot employ the Ignore command on files that already exist in the repository.

To ignore local files in your working directory:

  1. Select the file or directory you wish to ignore from the Projects, Files, Favorites, or Versioning window.

  2. Select Ignore (or Subversion > Ignore) from the context menu of selected file or directory. The IDE ignores the file or directory whenever Subversion commands are called on it or on the directory within which it is stored.

Note:

To change the status of ignored files so that they can be acted upon in Subversion, select the specific file and select Subversion > Unignore.

3.3.11 How to Work with Branches in Subversion

The IDE's Subversion support enables you to:

  • checkout branches from a remote repository.

  • create branches in the repository you are working from.

  • switch to a branch in the repository you are working from.

For more information on working with branches, see the Subversion documentation at:

http://svnbook.red-bean.com/

3.3.11.1 Checking Out Branches

If you need to edit files on a branch folder that already exists, you can check out the branch to copy the files to a local working directory. You must however create a new local working directory within which to checkout the branch.

To checkout a branch to your local working directory:

  1. Select Team > (Subversion >) Checkout from the main menu. The Subversion Checkout wizard opens.

  2. In the first panel of the wizard, enter a URL that contains the connection protocol and location to the repository. Depending on your protocol selection and connection requirements, enter any required parameters, such as username, password, proxy configuration, etc. Click Next.

  3. In the Folders to Checkout panel of the wizard, specify the folder that represents the branch you want to check out in the Repository Folder field. You can click Browse to choose from a list of all folders in the repository. Specify the revision number if you want to work from a specific revision.

    • To check out only the contents of the folder you are specifying (that is, not the folder itself), select the Skip "<selected_folder>" and check out only its content option.

  4. Specify the local working directory into which you want to checkout the selected branch folder. Alternatively, click the Browse button to navigate to the desired directory on your system.

  5. Click Finish to check out the branch folder. The IDE initiates the checkout action and the IDE's status bar indicates the progress of the files downloading from the repository to your local working directory. You can also view files being checked out from the Output window (Ctrl+4).

3.3.11.2 Creating Branches

If you want to work on a separate version of your file system for stabilization or experimentation purposes, you can do so by creating a branch. To create a branch in Subversion, you are effectively copying a version-controlled project or folder and adding it to a new location within the repository. The IDE's Subversion support enables you to select a source from either your local working copy, or browse to a location in the repository you are working from. You can create branches in the IDE by choosing Subversion > Copy To from a versioned file or folder's context menu.

To create a branch:

  1. Select the versioned project or folder (for example, in the Projects, Files, or Favorites window) that you want to be the root of your branch and select Subversion > Copy To. The Subversion Copy dialog box opens.

  2. Under Source, select Local Folder if you want to create a branch from your local working copy, otherwise select Remote Folder to specify the version maintained in the repository.

    • You can specify a specific revision of the selected item by entering a revision number in the Revision text box. Clicking the Search button adjacent to the Revision text box allows you to view revisions maintained in the repository.

    • Click the Skip selected Folder and copy only its Contents option if you want to avoid including the selected folder when creating a copy.

  3. Under Destination, select the target location for the new branch copy. In Repository Location, type in a path relative to the repository, otherwise click the Browse button to open a new dialog that aids in browsing the repository folders.

  4. Enter a description for the new branch folder in the Copy Description text area. If you want to switch to the branch after creating it, select the Switch to Copy checkbox.

  5. Click Copy. The IDE creates the branch by copying the folder contents to the specified location in the repository.

3.3.11.3 Switching to a Branch

If you want to switch your local working copy to point to a branch or other location in the repository, you can do so using the Subversion Switch to command.

To switch to a branch or other location in the repository:

  1. Select a versioned file or folder (for example, from the Projects, Files, or Favorites window) and select either Subversion > Switch to Copy from the context menu or Team > (Subversion >) Switch to from the IDE's main menu. The Subversion Switch dialog box opens.

  2. For Repository Folder, enter the branch folder you want to switch to, or click Browse to view a list of all locations in the repository.

    • If you need to specify a previous revision, enter the revision number for the selected location. Leave blank if you require the most recent revision. To display a log of all revisions for the selected location, you can click the Search button.

  3. Click Switch. The IDE updates your working copy to reflect the content maintained by the newly selected branch location in the repository. Note that any differences arising between your local working copy and the location that you are switching to will be overwritten by the new location.

3.3.12 How to Revert Modifications (Subversion)

Occasionally it may be desirable or necessary to revert changes made to files in your local working copy. You may need to either revert changes made locally, or retrieve revisions from the repository, and undo any changes to files caused by these revisions. The IDE enables you to do this using the Revert Modifications command.

To revert modifications:

  1. Select the versioned file for which you want to revert changes (for example, from the Projects, Files, Favorites or Versioning window) and select Revert Modifications (or Subversion > Revert Modifications). The Revert Modifications dialog box opens, enabling you to specify criteria.

    If you have created files or folders since the point to which you are reverting, you can delete them by selecting the Remove Newly Added Files and Folders option.

  2. In the Revert Modifications dialog box, select one of three options:

    • Revert Local Changes. Reverts any changes made in your local working copy to the previously committed or updated version.

    • Revert Modifications from Single Commit. Reverts the local working copy to the repository revision made prior to the previous commit. (Specify a revision number in the Revision text field.)

    • Revert Modifications from Previous Commits. Reverts the local working copy to a specified revision from the repository. (Specify starting and ending revision numbers in the corresponding text fields.)

  3. Click Revert. The IDE reverts any changes in the local file to a state that corresponds with the repository version, according to the specified parameters.

3.3.13 How to Recover Deleted Files (Subversion)

When working with version-controlled sources, you may sometimes find it useful to be able to recover locally deleted files from the repository. The IDE's version control support enables you to recover versioned files by performing a revert delete action on files maintained in your local working copy.

To revert deletes made to files in your local working copy:

  1. Right-click the project or folder that previously contained the deleted files (for example, from the Projects, Files, or Favorites window) and select Subversion > Show Changes from the context menu. The Versioning window opens in the bottom panel of the IDE displaying file changes. The file names of recently deleted files display in grey text with status listed as Locally Deleted.

  2. Right-click the file you want to recover and select Revert Delete.

  3. In the Confirm Overwrite dialog that displays, click Yes to enable the IDE to recover the file from its local history repository. The file disappears from the Versioning window and is relisted in the project directory within your local working copy.

3.3.14 How to Merge File Revisions in Subversion

The Merge command is useful for porting changes from a specific repository revision to your local working copy of a file or folder. You can also port the changes made within a given range of revisions to your local working copy.

To port changes from a revision or range of revisions to your local working copy:

  1. In the Projects, Files, or Favorites window, right-click the files or folders on which you want to perform the merge operation and select Subversion > Merge Changes.

  2. In the dialog that appears, fill in the following fields:

    • Merge From. Select one of the following types of merge:

      • One Repository Folder. Port changes from one repository folder.

      • Two Repository Folders. Port changes from two repository folders.

      • One Repository Folder Since Its Origin. Port changes that have occurred between the time of the folder's creation and the revision number that you specify in the Ending Revision Field.

    • Repository Folder. The folder from which you want to port changes. (If you select Two Repository Folders in the Merge From field, this field is replaced by First Repository Folder and Second Repository Folder fields.)

    • Starting Revision. If merging from a single revision, enter the revision number. If merging changes that occurred within a range of revisions, enter the starting point of that range.

    • Ending Revision. If merging changes that occurred within a range of revisions, enter the ending point of that range.

  3. Click Merge. The IDE incorporates any differences found in the selected revision to the local copy of the file. If merge conflicts occur, the file's status is updated to Merge Conflict to indicate this.

Note:

After merging file changes to your local working directory, you must still commit changes using the Commit command in order for them to be added to the repository.

3.3.15 Resolving Merge Conflicts in Subversion

When merge conflicts occur, a Merge Conflict badge ( Error badge) appears on the parent folder (or package) of file. Within the file itself, each conflict is marked with arrows followed by the lines from the two revisions that caused the conflict.

Note:

Merge conflicts must be resolved prior to checking your local file into the repository.

To resolve merge conflicts graphically with the Merge Conflicts Resolver:

  1. In the Projects, Files, Favorites, or Versioning window, select the file whose status indicates that there is a conflict and select Resolve Conflicts from the menu. The Merge Conflicts Resolver displays with merge conflicts highlighted in red.

  2. Use the Next ( Next difference button) and Previous ( Previous difference button) difference buttons in the upper-left corner to navigate to each conflict in the file.

  3. For each conflict, click Accept above the pane containing the text that you wish to accept. Once you have chosen the correct text, it is highlighted in green and displayed in the Merge Result pane. The text you did not choose is highlighted in blue.

  4. If neither pane contains the text you want, exit the Merge Conflict Resolver and edit your source file manually. When you are done making changes, right-click the file and select Resolve Conflicts (or Subversion > Resolve Conflicts) from the context menu. Then repeat the procedure, beginning with Step 1.

  5. After resolving each conflict, click OK to exit the Merge Conflict Resolver. The IDE updates your local working copy with the desired changes.

Note:

Once you have resolved each merge conflict, you still need to commit the file to add your changes to the repository copy.

3.3.16 How to Create and Apply a Patch (Subversion)

Patch files enable software developers who are not sharing a common repository to distribute and integrate changes that have been made to the code. The IDE enables you to create and apply patches that update copies of source files so that you do not have to incorporate the changes manually.

To create a patch file:

  1. Select a versioned file (for example, in the Projects, Files, or Favorites window) for which you want to create a patch.

  2. Select Team > (Subversion >) Export Diff Patch from the main menu. The Export Diff Patch dialog opens.

  3. Select one of the following:

    • Save to File. When selected, enter a name for the patch file and specify the location where you want to save the patch.

    • Attach to Task. When selected, select the task repository and specify a task ID and description. The patch file is added as an attachment to the specified task.

  4. Click OK. A patch file is created containing the differences between the source file versions.

Note:

the Export Diff Patch command is only available on files and folders which contain local or remote changes that have not already been merged.

To apply a patch to a local file or folder:

  1. Select a versioned file or folder (for example, in the Projects, Files, or Favorites window) on which you want to apply the patch.

  2. Select Team > (Subversion >) Apply Diff Patch from the main menu. The Apply Diff Patch dialog displays.

  3. In the dialog, type the path or navigate to the patch file you want to apply.

  4. Click Patch. The patch is applied to the selected file and a dialog opens, confirming that the patch was applied successfully. Click Yes to view changes in the IDE's Diff Viewer.

Note:

Because patches on folders use relative paths to the files within them, folder patches must be applied on the same folder node that the patch was created on to ensure that the patch is applied properly.

If you are uncertain to which file or directory the patch should be applied, you can find the context information in the patch file itself. Patch files generated by the IDE contain the context in which the patch was originally created in the first few lines of the file.

3.3.17 How to Shelve Changes (Subversion)

Shelving allows to make changes to a project without committing them to Subversion.

To temporarily set aside some not yet committed changes in a working directory as a patch file:

  1. Select a versioned project, file, or folder.

  2. Select Team > Shelve > Shelve Changes from the main menu.

  3. Specify the name for a patch to be shelved in the Patch Name field.

  4. Click Shelve.

    The IDE stashes away the not yet committed changes contained in the selected project, file, or folder into a patch file and reverts the modified files in the working copy (the working copy gets clear of the local changes). The previously modified files become up to date.

3.4 Управление версиями приложений с помощью Mercurial

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

Поддержка плагинов Mercurial в IDE позволяет вам управлять изменениями в файлах с контролем версий во время работы. В IDE вы можете вызывать команды Mercurial как для файлов, так и для каталогов в окнах Проекты (Projects), Файлы (Files) и Избранное (Favorites). Среда IDE также предоставляет графический просмотрщик различий, позволяющий сравнивать версии файлов, а также поддерживает встроенные различия непосредственно в редакторе.

Преимущества распределенной системы контроля версий, подобной Mercurial, заключаются в следующем:

  • Улучшена поддержка распределенных команд за счет устранения централизованного узкого места

  • Лучшая масштабируемость при большом количестве одновременных пользователей

  • После первоначального клонирования, более быстрая в работе, независимая от сетевой инфраструктуры пользователя

3.4.1 О функциях визуализации Mercurial

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

  • Цветовая маркировка. Позволяет просматривать текущее состояние файлов с контролем версий.

  • Аннотации. Позволяет просматривать информацию о редакции и авторе для каждой строки файлов, контролируемых версиями.

Поддержка Mercurial в IDE схожа по стилю с поддержкой Subversion в IDE. Основное отличие заключается в том, что, поскольку Mercurial - это распределенная система контроля версий, вы обычно начинаете с клонирования внешнего репозитория для работы. Этот клон является полной копией репозитория, включая историю изменений. Вы можете клонировать эту локальную копию так часто, как вам нравится, и, когда захотите, вы можете перенести свои изменения обратно в исходный репозиторий, если у вас есть разрешения, или экспортировать свои изменения и отправить их владельцу, если у вас их нет.

Дополнительную документацию по поддержке плагина Mercurial и самому Mercurial смотрите на следующих ресурсах:

NetBeans Mercurial Home: http://wiki.netbeans.org/MercurialVersionControl

Mercurial Home: http://mercurial.selenic.com/wiki/

Understanding Mercurial: http://mercurial.selenic.com/wiki/UnderstandingMercurial

Mercurial Man Pages: http://www.selenic.com/mercurial/wiki/index.cgi/ManPages

3.4.2 Как просмотреть информацию о состоянии файла в Mercurial

Поддержка Mercurial в среде IDE позволяет просматривать и управлять развитием изменений в файлах с контролем версий.

3.4.2.1 Просмотр информации о ревизии

Поддержка Mercurial в среде IDE позволяет просматривать информацию о состоянии версии во многих окнах среды IDE, включая окна Состояние (Status), Проекты (Projects), Файлы (Files) и Избранное (Favorites). Окно состояния, однако, представляет собой основное место, в котором вы управляете файлами с контролем версий, отображая список всех новых, измененных и удаленных файлов в текущем выбранном проекте или каталоге.

Чтобы открыть окно состояния, выберите один из следующих вариантов:

  • Mercurial > Status from the context menu of a version-controlled file or folder from the Projects, Files, or Favorites window.

  • Team > Mercurial > Status from the main menu.

  • Window > Versioning > Mercurial from the main menu.

The IDE's Mercurial support provides file status information in the following ways:

  • Status Labels. Textual indication of file status in the Status, Projects, Files, and Favorites windows. To display status labels, select View > Show Versioning Labels from the main menu.

  • Status Color. Graphical indication of file status in the Status, Projects, Files, and Favorites windows.

  • Status Badges. Graphical indication of the status of files contained within your project, folder, and package nodes. Displayed in the Projects, Files, and Favorites windows.

  • Revision Annotations. Displays commit message, author, date, and revision number information in the left margin of files open in the Source Editor. To display annotations, select a versioned file and select Show Annotations (or Mercurial > Show Annotations) from its context menu. Alternatively, select Versioning, > Show Annotations from the main menu.

The IDE displays version-controlled files using the following color coding and font styles:

  • Green. Indicates that the file is a new local file that does not yet exist in the repository.

  • Blue. Indicates that the file has been modified locally.

  • Red. Indicates that the file contains conflicts. You must employ the Resolve Conflicts command (Mercurial > Resolve Conflicts) for such files.

  • Grey. Indicates that the file is ignored by Mercurial and will not be included when calling versioning commands. In the Status window, grey text signifies deleted files.

  • Strike-through. Indicates that the file is excluded when calling the Commit command. All other Mercurial commands, however, work as usual. Note that files displayed in the strike-through style only appear in the Status window and Commit dialog. They will not appear in Diff panes, nor will their parent folders (or packages) display badges if they are modified.

Current Mercurial file status is indicated by adding the following badges to project, package and directory icons:

  • Locally Modified Badge. A blue badge on a folder or package node marks folders or packages that contain locally modified or new files. In the case of packages, this badge applies only to the package itself and not its subpackages. For folders, the badge indicates local modifications in that folder or any of its subfolders.

  • Conflict Badge. A red badge on a folder or package node marks folders or packages that contain files for which the repository copy of the file contains changes that conflict with the local version. In case of packages, this badge applies only to the package itself and not its subpackages. For folders, the badge indicates local modifications in that folder or any of its subfolders.

The IDE enables you to clone an external Mercurial Repository and to make it available within the IDE. You effectively create a copy or clone of the entire repository to work with in the IDE. To do so, you need to be able to access a Mercurial repository that you have read privileges for.

Note that the parent folders (or packages) of files excluded from commits and displayed in the strike-through style will not display badges if they are modified.

3.4.3 How to Set Up Mercurial

Before you can take advantage of the IDE's Mercurial support, you need to have Mercurial client software installed on your system. The IDE supports Mercurial client versions 1.04 and higher. The IDE's Mercurial support works by using the same commands as the Mercurial command line interface.

You can download Mercurial as either sources or as a binary package from the following link:

http://mercurial.selenic.com/wiki/Download?action=show&redirect=BinaryPackages

To set the path to the Mercurial executable file in the IDE:

  1. Select Tools > Options (NetBeans > Preferences on OS X) from the main menu. The Options dialog opens.

  2. Select the Team icon along the top of the dialog, then click the Versioning tab. In the left pane under Versioning Systems, select Mercurial. User-defined options for Mercurial display in the main window of the dialog.

  3. In the Mercurial Executable Path text field, either type in the path to the executable file or click Browse to navigate to it on your system. Note that you need not include the Mercurial executable file in the path.

  4. Click OK.

After the Mercurial client is set up, you can run Mercurial commands from the IDE's Team > Mercurial menu. To clone an external Mercurial repository, select Team > Mercurial > Clone Other. In the process of cloning, the IDE automatically imports all of the history and status information for the cloned files.

If you have already cloned a Mercurial repository, the IDE automatically recognizes the files as versioned files if those files are part of an open IDE project or if they are added to the Favorites window. You can call Mercurial commands on such files from the Mercurial menu or by right-clicking a file or folder and choosing from the Mercurial submenu.

3.4.4 How to Clone an External Mercurial Repository

The IDE enables you to clone an external Mercurial Repository and to make it available within the IDE. You effectively create a copy or clone of the entire repository to work with in the IDE. To do so, you need to be able to access a Mercurial repository that you have read privileges for.

To clone a Mercurial Repository:

  1. Select Team > Mercurial > Clone Other from the IDE's main menu. The Mercurial Clone Other wizard opens.

  2. In the Mercurial Repository panel of the wizard, enter a URL that contains the connection protocol and the location of the repository.

  3. Click Next.

  4. In step 2 of the wizard, Clone External Repository, specify the default pull and push paths to the repository.

  5. In step 3 of the wizard, Destination Directory, specify the Parent directory into which you want to place the Clone of the repository. Alternatively, you can click the Browse button to navigate to the desired directory on your system.

  6. Specify the Clone Name.

  7. Click Finish. The IDE initiates the clone action and the IDE's status bar indicates the progress of the files downloading from the repository to your local working directory. You can also view files being cloned from the Output window (Ctrl+4).

Note:

Select the Scan for NetBeans projects after clone option if you intend to immediately work with the cloned sources.

If the sources contain projects, a dialog will appear prompting you to open them in the IDE.

If the sources do not contain a project, the dialog will appear prompting you to create a new project from the sources and then open them in the IDE. When you create a new project for such sources, select the appropriate project category in the Create Project wizard and then use the Create Project with Existing Sources template in that category.

The IDE supports the following Mercurial URLs:

ProtocolAccess MethodExample

file

Direct repository access (on local disk) file:///repository_path>

http

Access using WebDAV protocol to a Mercurial-aware server http://hostname/repository_path>

https

Access using HTTP protocol with SSL encryption https://hostname/repository_path>

static-http

Access using HTTP also, albeit slower, allows access to a Mercurial repository where you simply use a web server to publish the .hg directory as static content static-http://hostname/repository_path>

ssh

Access using SSH ssh://hostname/repository_path

SSH requires an accessible shell account on the destination machine and a copy of Mercurial (hg) in the remote path or specified with as remotecmd.

path is relative to the remote user's home directory by default. Use an extra slash at the start of a path to specify an absolute path: ssh://example.com//tmp/repository

Mercurial does not use its own compression through SSH; the right thing to do is to configure it in your ~/.ssh/config, for example:

  • Host *.mylocalnetwork.example.com
    Compression no

  • Host *
    Compression yes

3.4.5 How to Place Projects Under Version Control

The IDE enables you to place any project you are working on under version control. You effectively import your sources into a local Mercurial repository. The repository files are placed under a .hg directory under the project directory.

To place an IDE project under version control:

  1. In the Projects window, select an unversioned project and select either:

    Versioning > Initialize Mercurial Repository from the node's context menu.

    Team > Mercurial > Initialize Repository from the IDE's main menu.

  2. Putting the project under Mercurial revision control. The IDE initiates the Mercurial initialize action and the IDE's status bar indicates the progress of the repository creation under your local working directory. You can also view files being added to the repository from the Output window (Ctrl+4).

    All the project files are now registered in the repository as Locally New.

    The new files and their status can be viewed by clicking on Mercurial > Show Changes from the context menu.

  3. Select Mercurial > Commit from the project's context menu to commit these project files to the Mercurial repository. The Commit - [ProjectName] dialog box opens.

  4. Type your message in the Commit Message text area, and then click Commit.

    Note:

    The committed files are placed together with the .hg directory in the Mercurial repository directory. The commit details are available in the IDE Output window (Ctrl+4 on Windows/Command-4 on OS X).

3.4.6 How to Use the Mercurial Diff Viewer

The IDE's graphical Diff Viewer enables you to compare revisions of a file side by side using color coding to emphasize the differences between the files being compared.

You access the Diff Viewer in one of the following manners:

  • Select a version-controlled file or folder (for example, from the Projects, Files or Favorites window) and select either Mercurial > Diff from the context menu or Team > Mercurial > Diff from the main menu

  • Select the Diff view from the Status Window

The Diff Viewer tool bar provides you with the following functionality:

  • Navigate among differences found in the compared files. Choose to view differences as they appear from top to bottom by clicking the appropriate icon:

    • Go to previous difference.

    • Go to next difference.

  • Refresh the status of the diff (for example, in the event that changes to your local working directory have been made externally), and update the status of the repository versions of files listed in the diff:

    • Update the working directory from the repository

  • Commit any changes contained in your local working directory:

    • Commit the selected item to the repository.

The Diff Viewer provides the following UI components:

Blue

Indicates lines that have been changed since the earlier revision.

Green

Indicates lines that have been added since the earlier revision.

Red

Indicates lines that have been removed since the earlier revision.

The following icons allow you to make changes directly to your local working copy:

Replace

Inserts the highlighted text into your Working Tree copy.

Move All

Reverts the whole local Working Tree copy.

Remove

Removes the highlighted text from the local Working Tree copy.

3.4.7 How to Use the Mercurial Status Window

The Mercurial Status window presents a real-time view of the changes made in your local working copy for selected version-controlled directories. It opens by default in the bottom panel of the IDE, listing added, deleted or modified files.

To open the Status window, select Window > Versioning > Mercurial from the main menu. Alternatively, you can select a versioned file or folder (for example, from the Projects, Files, or Favorites window) and either select Mercurial > Status from the node's context menu, or select Team > Status from the main menu.

By default, the Status window displays a list of all modified files within the selected package or folder. The toolbar label includes the current revision of the working directory and the Mercurial ChangeSet ID. You can click the column headings above the listed files to sort the files by name, status or location.

The Status window toolbar includes buttons that enable you to invoke the most common Mercurial tasks on all files displayed in the list. The following table lists the Mercurial commands available in the toolbar of the Status window:

IconNameFunction
file

Changes between HEAD and Working Tree

Displays a list of files that are either already staged or only modified/created and not staged yet.

http

Refresh status

Refreshes the status of the selected files. Files displayed in the Status window can be refreshed to reflect any changes that may have been made externally.
https

Diff All

Opens the Diff Viewer providing you with a side-by-side comparison of your local copies and the versions maintained in the repository.
ssh

Update All

Updates the working directory from the repository.
sftp

Update Target

Allows you to specify the revision to update the working directory to.
git

Commit All

Enables you to commit local changes to the repository.

You can access other Mercurial commands in the Status window by selecting a table row that corresponds to a modified file, and choosing a command from the context menu. You can, for example, perform the following actions on a file:

  • Open. Open the file in the Source Editor.

  • Diff. Launch the Diff Viewer for this file, to compare the local file with that stored in the Repository.

  • Commit. Launches the Commit Dialog to allow this file to be Committed.

  • Mark as Resolved. Allows you to mark a file that is in a Conflict state after a Merge as resolved.

  • Show Annotations. Displays commit message, author, date, and revision number information in the left margin of files open in the Source Editor.

  • Revert Modifications. Enables you to revert any changes to the copy in your local working directory back to the current version maintained in the repository.

  • Revert Delete. Enables you to revert any delete actions that you have committed to files in your local working copy. When you invoke the Revert Delete command, the specified file will be retrieved from the repository and reinstated into your local working copy.

  • Exclude from Commit. Allows you to mark the file to be excluded when performing a commit.

Note:

You can also exclude files from a commit in the Commit dialog box.

You can select multiple files in the Status window by holding down the Ctrl key when you select files.

3.4.8 How to Merge File Revisions

NetBeans IDE enables you to merge changes between repository revisions and your local working copy. Specifically, this combines two separate changesets in a repository into a new changeset that describes how they combine.

To merge file revisions:

  1. In the Projects, Files, or Favorites window, right-click the files or folders on which you want to perform the merge operation and select Mercurial > Branch/Tag > Merge Changes. The Merge with Revision dialog displays.

  2. In the Choose From Revisions drop-down list, select the revision.

    You are porting all changes made on a local working copy file from the time it was created.

  3. Ensure the Description, Author, and Date data are correct.

  4. Click Merge.

    The IDE incorporates any differences found between the repository revisions and your local copy of the file. If merge conflicts occur, the file's status is updated to Merge Conflict to indicate this.

Note:

After merging revisions to your local working copy, you must still commit changes using the Commit command in order for them to be added to the repository.

3.4.9 How to Switch Branches in the Repository

The Switch Branch In Repository dialog box enables you to switch the branch that your working directory is on to a branch that already exists in your repository.

To switch a branch:

  1. In the Choose from Branches list, specify the branch you want to switch to.

  2. (Optional) Specify your filtering criteria in the Filter text field to filter the displayed branches.

  3. Review information specific to the branch in the following fields:

    • Author: Name of a person who committed the revision.

    • Date: Date when a commit was made.

    • Description: A message specified during the commit of the revision.

  4. (Optional) Select the Do a Forced Update option to switch to a selected branch even if your local changes are lost.

  5. Click Switch.

Note:

The name of the branch you have switched to is displayed in a label that follows the project name. Select View > Show Versioning Labels from the main menu to display a label.

3.4.10 How to Commit Changes to the Repository

Mercurial versioned files and folders must be recognized by the IDE as such in order to call Mercurial actions on them. To do so, you must first clone sources from an external repository or place the project under Mercurial control.

It is a good idea to update any copies you have against the repository prior to performing a commit in order to ensure that conflicts do not arise.

To perform an update on sources that you have modified:

  • Select Team > Update from the main menu.

Once your working copies of version-controlled files have been edited, you can then place changes into the repository using the Mercurial Commit action. If you have an task repository set up with your source code repository, the commit dialog box lets you associate your commit action with an existing task.

To commit changes in local files to the repository:

  1. Select a version-controlled file or folder (for example, from the Projects, Files, or Favorites window) and select Mercurial > Commit from the context menu. The Commit Dialog opens, listing all files that contain local changes. If the files you want to commit do not already exist in the repository, the commit action will add them.

  2. Enter a commit message in the Commit Message text area, indicating the purpose of the commit.

    • Click the Recent Messages icon ( Recent messages button) in the upper right corner of the dialog to view recent commit messages.

  3. Click Commit. The IDE executes the commit and sends your local changes to the repository. You can also view files being committed to the repository from the Output window (Ctrl+4).

Note:

When working in the Commit dialog, you can exclude individual files from a commit. To do so, click on the Commit Action column for the specific file and select Exclude from Commit. The file name responds by displaying in strike-through text.

3.4.10.1 Updating Tasks

You can update a task associating your commit action with an existing task in your repository's task repository. To do so, click on the Update Task heading in the Commit dialog box to expand it, then specify the following:

ElementDescription

Task Repository

Specify the task repository that your source code repository uses, by selecting a task repository from the drop-down list. The drop-down provides you with a list of all task repositories registered with the IDE. If your source code repository's task repository is not registered, click the New button to register it.

Task

Specify the task ID. You can do this by typing in the ID, or part of the description.

You can also specify the following options:

ElementDescription

Resolve as FIXED:

When selected, the status of the task is marked as Resolved.

Add Commit Message from Above

When selected, the commit message is added to the task.
Add Revision Information to the Task When selected, the task is updated to include the revision information such as the author, date, etc. You can click Change Format to modify the format of the revision information that is added to the task.
Add Task Information to Commit Message When selected, the task ID and summary are added to the commit message. You can click Change Format to modify the format of the task information that is added to the message.
After Commit When selected, the task is updated after you commit the changes.
After Push When selected, the task is updated only after the changes are pushed to the source code repository.

3.4.10.2 Ignoring Files

If your local working directory includes files or directories that you do not want to place under version control, you can set the IDE to ignore them permanently using the Ignore command.

You cannot employ the Ignore command on files that already exist in the repository.

To ignore local files in your working directory:

  1. Select the file or directory you wish to ignore from the Projects, Files, Favorites, or Status window.

  2. Select Ignore (or Mercurial > Ignore) from the context menu of selected file or directory. The IDE ignores the file or directory whenever Mercurial commands are called on it or on the directory within which it is stored.

To change the status of ignored files so that they can be acted upon in Mercurial, select the specific file and select Mercurial > Unignore.

3.4.10.3 Pushing Local Changes to the Shared Repository

Before pushing changes that you have committed locally to the shared repository, you need to synchronize your local repository with the shared repository.

To synchronize your local repository with the shared repository:

  • Select Team > Remote > Fetch from the main menu.

    After you perform a successful Fetch, your local repository becomes synchronized with the shared repository.

To push changes:

  • Select Team > Remote > Push Current Branch, Team > Remote > Push All Branches, or Team > Remote > Push from the main menu.

    The output from a successful Push will list any changesets created.

    Note:

    Since you maintain a copy of the entire repository on your system, the general practice is to make multiple commits to your local repository and only after the particular task is complete, perform the push to the shared repository.

3.4.11 How to Set Mercurial Project Properties

Open the Mercurial Properties Dialog in one of the following ways:

  • Select Team > Mercurial > Properties from the IDE's main menu

  • Select Mercurial > Properties from the context menu of a Mercurial-versioned project

The following table describes the Mercurial properties that can be set:

ElementDescription

default-pull

Specify the local repository path to Pull changes from when choosing Mercurial > "Pull from - default" from the Mercurial controlled project's context menu.

default-push

Specify the local repository path to Push changes to when choosing Mercurial > "Push to - default" from the Mercurial controlled project's context menu.
username Set the username to record when committing changes to the repository. This property overrides the global Mercurial User Name Option for this project.

Note:

To Push to other external locations select Team > Mercurial > Share > Push Other.

To Pull from other external locations select Team > Mercurial > Share > Pull Other.

3.4.12 How to Set Mercurial Global Options

Open the Mercurial Options window:

  • Select Tools > Options. The IDE's Options window opens.

  • Select the Team > Versioning tabs, then select Mercurial under Versioning Systems.

The following list describes the Mercurial Global Options property that can be set.

ElementDescription

Mercurial User Name

Set the username to record when committing changes to the repository. May be overridden for a given project using the Mercurial Project Properties username setting.

Mercurial Executable Path

Set the executable path to the installed Mercurial Hg executable. You only need to use this if Mercurial has been placed somewhere other than your standard PATH.
Default Export Filename Set the export filename used when using Team > Export Diff Patch from the IDE's main menu when a Mercurial-versioned project is selected. The following identifiers can used in the filename:
  • %b: Project Directory name

  • %r: Current revision number being exported.

  • %h: Changeset ID being exported.

Mercurial Status Labels Set the Status labels to be displayed in the Project view for a Mercurial controlled project. To enable, select View > Show Versioning Labels from the IDE's main menu. The following labels can used:
  • {status}: Status of the file.

  • {revision}: Revision of the file.

  • {folder}: Branch or Tag Name.

Mercurial Extensions Opens a dialog to allow you to add Mercurial extensions. Currently, the NetBeans IDE adds the hgk extension to support the Mercurial > View from the a Mercurial project's context menu. You can change its location from this dialog if necessary.

Note:

Select the Automatically open Output window option to set the Output window to display when versioning operations that involve interaction with the repository take place (for example, clone, fetch, pull, push). This option is selected by default.

3.4.13 How to Enable Support for Mercurial Queues

Since Mercurial Queues is an extension, you must explicitly enable it before you can use it.

To start running Mercurial Queues on your Mercurial repository:

  1. On your system, browse to the .hgrc file. The default location of the .hgrc file on OS X and Linux is $HOME/.hgrc, on Windows - %USERPROFILE%\Mercurial.ini.

  2. Add the following lines to your .hgrc file:

    [extensions]
    hgext.mq =
    
  3. Save the file.

3.4.14 How to Create a Patch

To create a patch:

  1. In the Projects window, select a versioned project and select Team > Queues > Create Patch (alternatively, right-click the project name and select Mercurial > Queues > Create Patch from the context menu).

    The Create Patch dialog box displays.

  2. Specify the name for a patch in the Patch Name text field.

  3. Provide the description of a patch in the Patch Message field.

    Alternatively, select either of the following options and click OK afterwards:

    • click Recent Messages to select a message from a list of most recent commit messages

    • click Load Template to select a message template for a commit message

      Note:

      The provided description of a patch will be used as a commit message when turning the patch into a permanent changeset.
  4. Select files to be included into the patch in the Files To Include In Patch table.

  5. (Optional) Specify information pertinent to a task related to the created patch using the fields of the Update Task area.

  6. Click Create Patch.

    A new patch is created and added to the .hg/patches directory.

3.4.15 How to Refresh a Patch With Local Modifications

To save your progress into the patch you are creating, you need to complete the following steps:

  1. Select Team > Queues > Refresh Patch from the main menu (alternatively, right-click the project name and select Mercurial > Queues > Refresh Patch from the context menu).

    The Refresh Patch dialog box displays.

  2. Provide the description of a patch in the Patch Message field.

    Alternatively, select either of the following options and click OK afterwards:

    • click the Recent Messages button to select a message from a list of most recent commit messages

    • click the Load Template button to select a message template for a commit message.

    Note:

    The provided description of a patch will be used as a commit message when turning the patch into a permanent changeset.
  3. Select files to be included into the patch in the Files To Include In Patch table.

  4. (Optional) In the Update Task area, specify information pertinent to a task related to the changes being committed.

  5. Click Refresh Patch.

    The patch you are working on is updated.

3.4.16 How to Compare Patch Revisions

To generate a patch for review and compare revisions of a patch side by side

  1. Select Team > Queues > Diff from the main menu (alternatively, right-click the project name and select Mercurial > Queues > Diff from the pop-up menu).

    The Diff Viewer displays differences found in the current patch and all your uncommitted/unrefreshed local changes in side-by-side panels

  2. Review and revise differences found in the compared files using either Graphical or Textual Diff Viewer.

    Note:

    The Graphical Diff Viewer highlights changes in the files using the following color encoding.
ElementDescription

Blue

Indicates lines that have been changed since the earlier patch.
Green Indicates lines that have been added since the earlier patch.
Red Indicates lines that have been removed since the earlier patch.

The following icons enable you to make changes directly within the Graphical Diff Viewer.

ElementDescription

Replace

Inserts the highlighted text from the previous patch into the current patch.

Replace All

Reverts current version of a patch to the state of its selected previous version.

Remove

Removes the highlighted text from the current version of a patch so that it mirrors the previous version of a patch.

3.4.17 How to Switch Between Patches

To switch to a particular patch in a patch queue series:

Note:

To switch between patches there must be no local modifications in the working copy, otherwise the switch fails.
  1. Select Team > Queues > Go To Patch from the main menu (alternatively, right-click the project name and select Mercurial > Queues > Go To Patch from the context menu).

    The Go To Patch dialog box displays a list of all patches available in a stack.

    Note:

    Names of applied patches display in bold.

    Note:

    Select Team > Queues > Pop All Patches to remove the applied patches from the top of the stack and update the working directory to undo the effects of the applied patches.
  2. Select the required patch and click Go.

    The IDE applies the changes contained in the selected patch to the chosen project, file, or folder.

3.4.18 How to Finish Applied Patches

Once your work on a patch is done, it can be turned into a permanent changeset.

To turn all applied patches in a patch queue series into regular changesets:

  1. Select Team > Queues > Finish Patches from the main menu (alternatively, right-click the project name and select Mercurial > Queues > Finish Patches from the context menu).

    The Finish Patches dialog box displays.

  2. Select the name of a patch to be finished in the patches field.

    Note:

    All patches in the series before the selected patch will also be finished.
  3. Click Finish Patches.

    The IDE turns all applied patches up to the selected patch into regular changesets.

3.4.19 How to Shelve Changes (Mercurial)

Shelving allows to make changes to a project without committing and pushing them to Mercurial.

To temporarily set aside some not yet committed changes in a working directory as a patch file:

  1. Select a versioned project, file, or folder.

  2. Select Team > Shelve > Shelve Changes from the main menu.

  3. Specify the name for a patch to be shelved in the Patch Name field.

  4. Leave the Back up any Locally Modified files to <file>.orig option selected to get all local changes stored in a <file>.orig file directly in the working copy (if required).

  5. Leave the Remove Newly Added Files and Folders option selected to get all newly added files and folders deleted (if required).

  6. Click Shelve.

    Note:

    After a patch with all the modifications is created and shelved, the local, not yet committed, modifications are reverted in the working copy (that is the working copy gets clear of the local changes). The previously modified files become up to date.

3.4.20 How to Rebase (Mercurial)

Sometimes it is required to move revisions from a point to another.

To append the private changes on top of any destination commit:

  1. Select a versioned project, file or folder in the Projects window.

  2. Select Team > Branch/Tag > Rebase from the main menu.

    Alternatively, right-click the selected item and choose Mercurial > Branch/Tag > Rebase from the context menu.

  3. Set the required properties in the Select Changesets to Rebase dialog box.

  4. Click Rebase to complete rebasing according to the defined settings.

3.5 Versioning Applications with CVS

CVS (Concurrent Version System) is a type of version control system that aids developer groups working with shared source files in common repositories by managing file revision history information.

The IDE's CVS built-in support enables you to manage changes to version-controlled files as you work. In the IDE, you can call CVS commands on both files and directories in the Projects, Files, Versioning, and Favorites windows. For an overview of the typical workflow when using CVS in the IDE, see Section 3.5.1, "How to Work with CVS.".

3.5.1 How to Work with CVS

The following table outlines the basic workflow when working with CVS in the IDE.

ElementDescription

Set up CVS

Set up CVS. See Section 3.5.5, "How to Set Up CVS."
Synchronize local files with repository Check out files from a repository. See Section 3.5.7, "How to Check Out Files from a Remote Repository (CVS)."

Import your project into a CVS repository.

Edit sources Make changes to local copies of versioned files.

Diff file revisions between repository versions and your local working copies. See Section 3.5.16, "How to Resolve Merge Conflicts."

Merge changes in repository revisions with the local copies. See Section 3.5.15, "How to Merge File Revisions from a Branch (CVS)."

Update local versions Update local versions of files with changes committed to the CVS repository. See Section 3.5.8, "How to Update Files in a Local Working Directory (CVS)."
Resolve conflicts Resolve conflicts between local versions of files with changes committed to CVS repository revisions. See Section 3.5.9, "How to Compare File Revisions in CVS."
Commit sources Commit local changes to files into the repository. See Section 3.5.10, "How to Commit Local Changes to a Remote Repository (CVS)."

3.5.2 How to Use CVS with the IDE

The IDE's CVS support enables you to manage the evolution of changes in version-controlled files by displaying status information directly in the IDE's various windows (for example, Projects, Files, Favorites, Versioning) so that you can call CVS commands as you work.

The Versioning window presents a real-time view of the changes in selected directories. It opens at the bottom of the IDE whenever you view changes made in version-controlled files. By default, the Versioning window displays a list of all modified files within the selected package or folder.

You can open the Versioning window by selecting Team > (CVS >) Show Changes from the main menu. Alternatively, you can right-click any versioned project, directory, or file and select CVS > Show Changes.

Using the filter buttons in the toolbar, you can limit the list of displayed files to either locally or remotely modified files. The Versioning window toolbar also includes buttons that enable you to invoke the most common CVS tasks on all files displayed in the list, such as committing, updating, refreshing status, and performing diffs.

The following CVS commands are available in the Versioning window's toolbar:

ElementDescription

Refresh status

Refreshes the status of the selected files and folders. Files displayed in the Versioning window can be refreshed to reflect any changes that may have been made externally.
Diff all Opens the Diff Viewer providing you with a side-by-side comparison of your local copies and the versions maintained in the repository.
Update all Updates all selected files from the repository.
Update local versions Update local versions of files with changes committed to the CVS repository.
Commit All Enables you to commit local changes to the repository.

You can call CVS commands on versioned-controlled files (those existing within a registered working directory) using the CVS menu in the IDE's main window. In addition, many CVS commands are available in the context-sensitive menu for a selected file or directory.

You can access the CVS commands context-sensitive menu by right-clicking a file or directory in any of the following:

  • Projects window

  • Files window

  • Favorites window

  • Versioning window

  • History Viewer

  • Source Editor (that is, from the tab of an open file)

Note:

The IDE's status bar, located in the bottom right of the interface, displays the current command's status.

3.5.3 How to View File Status Information (CVS)

The IDE's CVS support enables you to view and manage the evolution of changes in version-controlled files.

3.5.3.1 Viewing Revision Information

The IDE's CVS support enables you to view version status information in many of the IDE's windows, including the Versioning, Projects, Files, and Favorites windows. The Versioning window, however, represents the primary place within which to manage version-controlled files by displaying a list of all of the new, modified, and removed files in the currently selected project or directory.

To open the Versioning window, choose either:

  • CVS > Show Changes from the context menu of a version-controlled file or folder from the Projects, Files, or Favorites window.

  • Team > (CVS >) Show Changes from the main menu.

  • Window > Versioning > CVS from the main menu.

The IDE's CVS support provides file status information in the following ways:

ElementDescription

Status Labels

Textual indication of file status in the Versioning, Projects, Files, and Favorites windows. To display status labels, select View > Show Versioning Labels from the main menu.
Status Color. Graphical indication of file status in the Versioning, Projects, Files, and Favorites windows.
Status Badges Graphical indication of the status of files contained within your project, folder, and package nodes. Displayed in the Projects, Files, and Favorites windows.
Revision Annotations Displays commit message, author, date, and revision number information in the left margin of files open in the Source Editor. To display annotations, select a versioned file and select Show Annotations (or CVS > Show Annotations) from its context menu. Alternatively, select Versioning, > Show Annotations from the main menu.

The IDE displays version-controlled files using the following color coding and font styles:

ElementDescription

Green

Indicates that the file is a new local file that does not yet exist in the repository.
Blue Indicates that the file has been modified locally.
Red Indicates that the file contains conflicts. You must employ the Resolve Conflicts command (CVS > Resolve Conflicts) for such files.
Grey Indicates that the file is ignored by CVS and will not be included when calling versioning commands. In the Versioning window, grey text signifies deleted files.
Strike-through Indicates that the file is excluded when calling the Commit command. All other CVS commands, however, work as usual. Note that files displayed in the strike-through style only appear in the Versioning window and Commit dialog. They will not appear in Diff panes, nor will their parent folders (or packages) display badges if they are modified.

Current CVS file status is indicated by adding the following badges to project, package and directory icons:

ElementDescription

Locally Modified Badge

A blue badge on a folder or package node marks folders or packages that contain locally modified or new files. In the case of packages, this badge applies only to the package itself and not its subpackages. For folders, the badge indicates local modifications in that folder or any of its subfolders.
Conflict Badge A red badge on a folder or package node marks folders or packages that contain files for which the repository copy of the file contains changes which conflict with the local version. In case of packages, this badge applies only to the package itself and not its subpackages. For folders, the badge indicates local modifications in that folder or any of its subfolders

3.5.4 How to Work with Version Histories

Searching the histories of files can be helpful when you need to find specific commits, when backporting bugs for example. The IDE's Search Histories window enables you to view a summary of a file's evolution over time by revision number.

You can view file histories in the IDE's Search History window. To do so, select a versioned file (for example, from the Projects, Files, or Favorites window) and select either CVS > Search History from the context menu or Team > (CVS >) Search History from the main menu. Alternatively, in the Versioning window you can select Search History from a file's context menu.

Using the Search History window, you can search a file or folder's history for versions based on several criteria. The Search Histories window enables you to search for changes in version controlled files by:

ElementDescription

Message

The description submitted with the commit.
Username The author of the commit.
From Tag The tag, revision number, or date from which the commit was made.
To Tag The tag, revision number, or date before which the commit was made.

To search for a specific revision:

  1. Select the file or folder for which you want to find a specific revision.

  2. Select CVS > Search Histories from the context menu. The IDE opens the Search History window to display the selected item's revision history.

  3. Enter search criteria information in the Message, Name, From, and To fields. You can also use the Browse buttons to designate any tag, branch, revision, or date you want to limit your search to.

  4. Click Search. The IDE displays the file's revision history in the Search History window.

Note:

If you want to view other files that were included in a specific commit, you can broaden your search using the "your_project" and Open Projects links to the right of each revision.

3.5.4.1 Comparing Revisions in the Search History Window

You can compare a file with previous versions from within the Search Histories window using the Diff button.

To view revision differences in the Search History window:

  1. Click the Diff button in the toolbar.

  2. Select the revision against which you want to compare your local working copy. The IDE displays a diff of the file's revisions within the Search History window. Note that you can navigate between the differences using the Previous Difference and Next Difference buttons.

3.5.5 How to Set Up CVS

In the IDE, no special setup is necessary in order to use CVS. You need only to check out the files located in a remote repository to a local working directory on your system. In the process of checking out, the IDE automatically registers the working directory where your local copies of version-controlled files and their status information will be stored.

If you have previously checked out files to a local working directory on your system using another CVS executable or the command line, you can still work with the files using the IDE's CVS support. The IDE automatically recognizes the files as versioned files, enabling you to call CVS commands on them. See Checking Out Files from a Remote Repository for more information.

Note:

If you want to set up a local repository, you must do so manually using a CVS command line client. For information, see the CVS documentation at http://ximbiot.com/cvs/manual/.

3.5.6 How to Adjust CVS Settings in the IDE

The IDE enables you to make changes to CVS settings, such as:

  • applying arbitrary metadata to files or directories by adding, removing, or modifying the status label format of versioning labels for versioned files

  • adjusting CVS settings in the IDE, such as excluding new files from commit actions automatically

  • limiting the number of characters per line in commit messages

To change the status label format for versioned files:

  • In the Status Label Format text box, enter the format in which you want the status labels to be displayed. You can enter your own label, otherwise specify a CVS-reserved label by clicking Add Variable and selecting from the available options.

Note:

In order to make versioning labels visible, select View from the main menu, then select the Show Versioning Labels option. Versioning labels display in light grey text to the immediate right of versioned files in the Projects, Files, Favorites windows.

To automatically exclude new files from commit actions:

  • Select the Apply "Exclude from Commit" On New Files Automatically option. When selected, newly created files will have to be manually included in commit actions.

To limit the number of characters per line in commit messages:

  1. Select the Wrap Commit Messages To (characters) option.

  2. In the adjacent text box, enter the number of characters to indicate the length of each line. Commit messages longer than the specified number of characters will be wrapped to multiple lines.

3.5.7 How to Check Out Files from a Remote Repository (CVS)

In order to work on shared files located in a remote repository, you need to copy the necessary files and directories to your local working directory. This is done by checking out the files from the repository.

To check out files from a remote repository:

  1. Select Team > (CVS >) Checkout from the main menu.

  2. On the first page of the CVS Checkout wizard, specify the location of the CVS repository by choosing it from the CVS Root drop-down menu. If you are unfamiliar with the syntax, you can click the Edit button and enter the required information using the dialog. For information on supported CVS protocols, view supported CVS root types below.

  3. Enter your password in the Password field.

  4. If you are using a proxy, click the Proxy Configuration button and enter the required information. Click Next.

  5. On the Module to Checkout page, specify the modules you want to check out in the Module field or click the Browse button to choose from a list of all modules in the repository. Note that if you do not specify a module, the entire repository will be checked out.

  6. If you need to specify a specific branch, revision number, or tag for the checkout, enter the information in the Branch field or click the Browse button to choose from a list of all branches in the repository.

  7. Specify the local working directory into which you want to check out the selected modules or branches. Alternatively, you can click the Browse button to navigate to the desired directory on your system.

  8. Click Finish to check out the files. The IDE initiates the check out command and the IDE's Status bar, displayed in the lower right corner of the IDE, indicates the progress of the files downloading from the repository to your local working directory.

If the checked-out sources contain a project, a dialog will appear prompting you to open them in the IDE. If the sources do not contain a project, the dialog will appear prompting you to create a new project from the sources and then open them in the IDE.

The IDE directly supports the following CVS root types:

ElementDescription

pserver

For connecting to pserver repositories.

:pserver:username@hostname:/repository_path

ext For connecting to CVS repositories using SSH, etc.

:ext:username@hostname:/repository_path.

The following root types require an external CVS executable:

ElementDescription
fork For protocol access to local CVS repository :fork:/repository_path
local For direct access to local CVS repository :local:/repository_path

3.5.8 How to Update Files in a Local Working Directory (CVS)

Updating files or folders enables you to incorporate any changes that other developers have committed to the repository since your previous checkout or update.

To update a local version of a file or folder:

  • Select a versioned file (for example, in the Projects, Files, or Favorites window) and select CVS > Update. Alternatively, select a file in the Versioning window and select Update from the context menu. The IDE incorporates any changes existing in the repository version of the file.

Note:

It is recommended that you perform an update on all files prior to committing them to the repository. Doing so allows you to become aware of any conflicts prior to performing the commit.

3.5.8.1 Updating Projects with Dependencies

If you are working on a project for which there are other required projects, you can update both the main project and all dependent projects using the IDE's Update with Dependencies command.

To update an entire project and all dependent projects:

  1. Right-click the project node in the Projects window.

  2. Select CVS > Update With Dependencies. The IDE incorporates any changes existing in the repository version of all of the projects with your local working copy.

3.5.9 How to Compare File Revisions in CVS

The Diff command compares different revisions of a file and displays the differences found graphically.

The IDE's graphical Diff Viewer enables you to compare different versions of a file side by side using color coding to emphasize the differences between the files being compared.

The previous and next difference buttons in the toolbar enable you to navigate among the differences in the file. You can also refresh the status and update files from within the Diff Viewer using the Refresh Diff and Update buttons. When you are finished comparing the files, you can commit your changes using the Diff Viewer's Commit button.

To generate a graphical diff comparing a repository revision to your working copy:

  • Right-click a versioned file node in the Projects, Files, or Versioning window and select Diff (or CVS > Diff). The IDE displays the results in the Diff Viewer in a new tab of the main window.

If you want to perform a diff on all files contained in a folder, select a folder and then select CVS > Diff from the context menu. All files that contain differences between your local version and the repository version will be listed in the upper pane of the Diff Viewer. You can then view individual diffs on files by clicking a file from the list.

To make changes to a file while comparing it in the Diff Viewer:

  1. Navigate through differences between the two versions using the previous difference and next difference arrow icons.

  2. Click any of the displayed icons to perform immediate changes to your local copy.

Note:

Your local copy appears in the right pane of the Diff Viewer. You can also make changes to your local copy by typing directly into it in the Diff Viewer.

Any changes made in the Diff Viewer are automatically saved as they occur.

The following icons enable you to make changes directly within the Diff Viewer:

ElementDescription
Replace Inserts the highlighted text from the previous revision into the current revision.
Move All Reverts the file's current version to the state of the selected previous version.
Remove Removes the highlighted text from the current version so that it mirrors the previous version.

3.5.10 How to Commit Local Changes to a Remote Repository (CVS)

Once your working copies of version-controlled files have been edited, you can then place your changes into the repository using the Commit command.

Note: Project directories must be located within a local working directory that is registered with the IDE in order to call CVS commands on them.

To commit changes in local files to a remote repository:

  1. In the Versioning window, confirm that you want to commit the listed files.

  2. Ensure that your local copies of the files are up-to-date by clicking the Update All button prior to committing your changes.

  3. Once the Update command has finished, commit the files by clicking the Commit All button. If the files you want to commit do not already exist in the repository, the Commit command will add them.

  4. Enter a message describing your changes in the CVS Commit dialog that appears and click Commit. The IDE executes the Commit command and the selected files are committed to the repository.

Click the Recent Messages icon in the upper right corner of the dialog to view recent commit messages.

Note:

You can also commit files or directories from the Projects window, Files window, or Favorites window by right-clicking the files or directories you wish to commit and choosing CVS > Commit.

3.5.10.1 Excluding Files from a Commit

The IDE enables you to specify which files in your local working directory are recognized when using CVS commands. Using the Exclude from Commit command, you can set the IDE to temporarily disregard files when making commits.

To exclude local files in your working directory:

  1. Select the files or directories you wish to ignore in the Versioning window, Projects window, Files window, or Favorites window.

  2. Right-click and select the CVS > Exclude from Commit option. If you have the Versioning window opened, note that the IDE displays the file or directory name in strike-through text and disregards the item whenever the commit command is called. Note that the files remain excluded until you include them.

To remove the exclude status from a file or directory, right-click the selected file or directory, select CVS and deselect the Exclude from Commit option.

3.5.10.2 Ignoring Files

If your local working directory includes files or directories that you do not want to place under version control, you can set the IDE to ignore them permanently using the Ignore command.

To ignore local files in your working directory:

  1. Select the files or directories you wish to ignore in the Versioning window, Projects window, Files window, or Favorites window.

  2. Right-click and select CVS > Ignore. Note that the Ignore command is unavailable for files that already exist in the repository. The IDE ignores the file or directory whenever CVS commands are called on them or the directories within which they are stored.

3.5.11 How to Revert Modifications (CVS)

Occasionally it may be desirable or necessary to revert local file changes to their current status maintained in the repository. The IDE enables you to do this using the Revert Modifications command.

To revert modifications:

  1. Select the versioned file for which you want to revert changes (for example, from the Projects, Files, Favorites or Versioning window) and select Revert Modifications (or CVS > Revert Modifications) from the context menu. A Confirm Overwrite dialog displays notifying you that your local copy is about to be overwritten with the current repository version.

  2. Click Yes to initiate the process. Your selected file will be overwritten with the repository version and changes are automatically reflected if the file is already opened in the IDE's editor.

3.5.12 How to Recover Deleted Files (CVS)

When working with version-controlled sources, you may sometimes find it useful to be able to recover locally deleted files from the repository. The IDE's version control support enables you to recover versioned files by performing a revert delete action on files maintained in your local working copy.

To revert deletes made to files in your local working copy:

  1. Select the project or folder that previously contained the deleted files (for example, from the Projects, Files or Favorites window) and select CVS > Show Changes from the context menu. The Versioning window opens in the bottom panel of the IDE displaying file changes. The file names of recently deleted files display in grey text with status listed as Locally Deleted.

  2. Right-click the file you want to recover and select Revert Delete.

  3. In the Confirm Overwrite dialog that displays, click Yes to enable the IDE to recover the file from its local history repository. The file disappears from the Versioning window and is relisted in the project directory within your local working copy.

3.5.13 How to Work with Tags

It is often helpful to tag version controlled files for reference purposes, when you want to mark the point a particular branch was made, for example. Using the CVS Tag command you can attach an existing tag to a file or folder or create a new tag.

To apply a tag to a file or directory:

  1. Right-click the file or folder and select CVS > Tag.

  2. Enter the tag name in the text field. Alternatively, click Browse to select from a list of existing tags.

    If the tag you entered does not already exist, a new tag will be created.

  3. If you want to ensure that the tag is not attached to local revisions that are not up to date, select the Avoid Tagging Locally Modified Files checkbox.

  4. If you want to move an existing tag to the current revision in your local working directory, select the Move Existing Tags checkbox. The IDE attaches the tag on the specified file or directory.

3.5.14 How to Work with Branches in CVS

The IDE's CVS support enables you to maintain different versions of an entire code base using branches. Branches are created by attaching a branch tag to a file or folder in the repository. When you modify files in a branch it does not affect the files in the main code line or ”trunk”. You can, however, merge any modifications you make in the branch back to the trunk at a later stage.

3.5.14.1 Checking out Branches

If you need to edit files on a branch that already exists, you can check out the branch to copy the files to a local working directory. You must, however, create a new local working directory within which to checkout the branch.

To check out a branch to a local working directory:

  1. Select Team > (CVS >) Checkout from the main menu.

  2. On the first page of the CVS Checkout wizard, specify the location of the CVS repository by choosing a preconfigured URL from the CVS Root drop-down menu. If you are unfamiliar with the syntax, click Edit and enter the required information in the Edit CVS Root dialog.

  3. Enter your repository password in the Password field.

  4. If you are using a proxy, click the Proxy Configuration button and enter the required information. Click Next.

  5. On the Module to Checkout page, specify the files and directories you want to check out in the Module field or click the Browse button to choose from a list of all modules in the repository.

  6. Specify the branch, revision number, or tag to checkout in the Branch field or click the Browse button to choose from a list of all branches in the repository.

  7. Specify the local working directory into which you want to check out the selected branches. Alternatively, you can click the Browse button to navigate to the desired directory on your system.

  8. Click Finish to check out the files. The IDE initiates the checkout command for the branch. The IDE's Status bar, displaying in the lower right corner of the IDE, indicates the progress of the files downloading from the repository branch to your local working directory.

3.5.14.2 Switching to a Branch

If you want to switch a project, directory, or file to a branch that already exists for stabilization or experimentation purposes, you can do so using the Switch to Branch command.

To switch to a branch:

  1. In the Projects, Files, or Versioning window, right-click the file or folder you want to be the root of your branch and select CVS > Switch to Branch.

  2. In the Switch to Branch dialog, enter a branch name or click Browse to see a list of available branches.

  3. Click Switch. The IDE moves the selected file to the specified branch by adding a branch tag.

3.5.14.3 Creating a Branch

If you want to work on a separate version of your file system for stabilization or experimentation purposes, you can do so by creating a branch. Branches are created by adding a branch tag to a project, directory, or file revision.

To create a branch:

  1. In the Projects, Files, or Versioning window, right-click the file or folder you want to be the root of your branch and select CVS > Branch.

  2. In the Branch dialog, enter a Branch name or click Browse to see a list of available branches.

  3. If you want to tag the file or directory, select the Tag Before Branching checkbox and enter a Tag name.

  4. If you want to switch to the new branch after creating it, select the Switch to This Branch Afterwards checkbox.

  5. Click Branch. The IDE creates the branch by adding a branch tag to the selected file or directory.

Note:

When you add a branch tag, the branch is created in the repository immediately and does not require using the Commit command.

3.5.15 How to Merge File Revisions from a Branch (CVS)

The Merge command is useful for incorporating changes made on different branches of the repository with your local working copy of a file or directory. Any changes you make on one branch can be merged to another branch, including back to the trunk. You can also merge the difference between two earlier revisions with your local working copy.

To merge a file from a branch with your local working copy:

  1. In the Projects, Files, Favorites, or Versioning window, select the files or folders that you want to merge into your local working copy and select CVS > Merge Changes from Branch.

  2. In the dialog that appears, select the branch you want to merge the changes from. If you want to merge changes from a branch other than the trunk, enter the branch name or click Browse to see a list of available branches.

  3. If you want to merge changes after a specific tag, select the Merge Only Changes Made after Tag checkbox and designate the tag in the Tag Name field. Alternatively, you can click Browse to choose from a list of available tags.

  4. If you want to tag the merge, select the Tag Trunk after Merge (or Tag branch_name after Merge) checkbox and enter the desired tag name. Alternatively, click Browse to choose from a list of available tags.

  5. Click Merge. The IDE incorporates any differences found in the branch version into your local copy of the file. If merge conflicts occur, the file's status is updated to Merge Conflict to indicate this.

After merging file changes from a branch to your local working directory, you must still commit the changes using the Commit command in order for them to added to the repository.

3.5.16 How to Resolve Merge Conflicts

When merge conflicts occur, a Merge Conflict badge appears on the parent folder (or package) of file. Within the file itself, each conflict is marked with arrows followed by the lines from the two revisions that caused the conflict.

Note:

Merge conflicts must be resolved prior to checking your local file into the repository.

To resolve merge conflicts graphically with the Merge Conflicts Resolver:

  1. Right-click the node of the file whose status indicates that there is a conflict and select Resolve Conflicts from the pop-up menu. The Merge Conflicts Resolver is displayed with merge conflicts highlighted in red.

  2. Use the Next and Previous difference buttons in the upper-left corner to navigate to each conflict in the file.

  3. For each conflict, click Accept above the pane containing the text that you wish to accept. Once you have chosen the correct text, it is highlighted in green and displayed in the Merge Result pane. The text you did not choose is highlighted in blue.

  4. If neither pane contains the text you want, exit the Merge Conflict Resolver and edit your source file manually. When you are done making changes, right-click the node of the file and choose CVS > Update from the context menu. Then repeat the procedure, beginning from Step 1.

  5. After resolving each conflict, click OK to exit the Merge Conflict Resolver. The IDE updates your local working copy with the desired changes.

Note:

You can also resolve conflicts manually in the Source Editor. To do so, open the file in the editor. For each conflict in the file, delete the arrows and text that you do not want, then save the file. The IDE updates your local working copy with the desired changes.

Once you have resolved each merge conflict, you still need to commit the file to add your changes to the repository copy.

3.5.17 How to Create and Apply a Patch

Patch files enable software developers who are not sharing a common repository to distribute and integrate changes that have been made to the code. The IDE enables you to create and apply patches that update copies of source files so that you do not have to incorporate the changes manually.

To create a patch file:

  1. Select a versioned file (for example, in the Projects, Files, or Favorites window) for which you want to create a patch.

  2. Select Team > (CVS >) Export Diff Patch from the main menu. The Export Diff Patch dialog opens.

  3. In the dialog, enter a name for the patch file and specify the location where you want to save the patch.

  4. Click Export. A patch file is created in the specified location containing the differences between the source file versions.

Note:

The Export Diff Patch command is only available on files and folders which contain local or remote changes that have not already been merged.

To apply a patch to a local file or folder:

  1. Select a versioned file or folder (for example, in the Projects, Files, or Favorites window) on which you want to apply the patch.

  2. Select Team > (CVS >) Apply Diff Patch from the main menu. The Apply Diff Patch dialog displays.

  3. In the dialog, type the path or navigate to the patch file you want to apply.

  4. Click Patch. The patch is applied to the selected file and a dialog opens, confirming that the patch was applied successfully. Click Yes to view changes in the IDE's Diff Viewer.

Note:

Because patches on folders use relative paths to the files within them, folder patches must be applied on the same folder node that the patch was created on to ensure that the patch is applied properly.

If you are uncertain to which file or directory the patch should be applied, you can find the context information in the patch file itself. Patch files generated by the IDE contain the context in which the patch was originally created in the first few lines of the file.

3.6 About Local History

The IDE provides built-in versioning support for local projects and files. Similar to conventional versioning systems, the IDE maintains an internal history of recent changes made to sources in your local working directory. Whenever you save a file, this is registered as a 'commit' of a new version of the file in the local history. You can inspect all revisions in the local history and diff them against the current files.

3.6.1 About the IDE's Local History Tools

The IDE provides a Graphical Diff Viewer. Enables you to select previously saved versions of a file and compare differences between versions graphically.

3.6.2 How to Browse Local File History

The IDE's local history functionality automatically maintains previous versions of your project sources. You can use local history tools to do the following:

  • create versions of a file

  • compare two versions side-by-side

  • revert your current file to a previous version

  • recover previously deleted files

Each time you make changes to, then save (Ctrl+S) a file, the IDE automatically creates a new version of that file.

To examine previous versions for a specific file:

  1. Select the file from the Projects or Files window and select History > Show History. A graphical Diff Viewer opens in the main window.

  2. Select a version from the table displayed in the upper area of the graphical diff viewer. Note that versions are chronologically ordered. Upon selecting a version, the file automatically displays on the left side in the Diff Viewer below.

Note:

Select a version from the table displayed in the upper area of the graphical diff viewer. Versions are chronologically ordered. Upon selecting a version, the file automatically displays on the left side in the Diff Viewer below.

3.6.3 How to Recover Deleted Files

The IDE's local history repository maintains previous versions of your project sources, including files or folders which you have recently deleted.You can take advantage of the IDE's local history tools to recover previously deleted files and reinstate them into your project.

If you have previously deleted files and they are still maintained in the IDE's local history repository, you can invoke the Revert Deleted command to retrieve them.

To recover previously deleted files:

  • From the Projects or Files window, right-click the project or directory that previously contained the files which you deleted and select History > Revert Deleted. The previously deleted files reappear beneath the project or folder you selected.

Note:

In order to recover deleted files using the Revert Deleted command, files must not be created or deleted externally.

3.6.4 How to Revert a File to a Previous Version

The IDE's local history functionality enables you to revert your current file to a previous version. You do this by using the graphical Diff Viewer.

If you want to examine a previous version and revert only specific changes in your current file to areas within that version, you can perform a side-by-side comparison between the two versions in the Diff Viewer, and revert changes in your current file based on the comparison.

To revert changes in a file using the Diff Viewer:

  1. From the Projects or Files window, right-click the file you want to revert changes to and select History > Show History. The graphical Diff Viewer opens.

  2. Select a version from the table displayed in the upper area of the viewer. The selected version displays on the left side in the Diff Viewer below and is compared against your current version.

  3. After examining differences between the two versions, use the icons displayed in the Diff Viewer to make changes:

    • Replace. Inserts the highlighted text from the previous revision into the current revision

    • Move All. Reverts the file's current version to the state of the selected previous version.

    • Remove. Removes the highlighted text from the current version so that it mirrors the previous version.

    Any changes made using the Diff Viewer's icons are immediately applied to the file's current version.

You can make changes to your current version directly in the graphical Diff Viewer. To do so, place the cursor directly in the Current Version pane and edit where appropriate. The current version is instantaneously updated to reflect changes.

3.6.5 How to Adjust Local History Settings

The IDE's local file history support currently enables you to adjust the duration of time for which files are locally stored on your system.

To adjust the local history storage duration:

  1. Select Tools > Options from the main menu.

  2. Select the Team category along the top of the Options window.

  3. Under Versioning Systems in the left column select History.

  4. In the corresponding text field, enter an integer for the number of days you want the IDE to retain local history versions.