Инструменты для слияния

При слиянии файлов Mercurial использует специальные инструменты.

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

Инструменты используются командами 'hg resolve', 'hg merge', 'hg update', 'hg backout' и несколькими расширениями.

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

Доступные инструменты слияния

Внешние инструменты слияния и их свойства настраиваются в секции merge-tools конфигурационного файла (см 'hg help config'), но как правило можно просто указать имя их исполнимого файла.

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

Существуют также встроенные инструменты слияния:

":dump"
Creates three versions of the files to merge, containing the contents of local, other and base. These files can then be used to perform a merge manually. If the file to be merged is named "a.txt", these files will accordingly be named "a.txt.local", "a.txt.other" and "a.txt.base" and they will be placed in the same directory as "a.txt".

This implies premerge. Therefore, files aren't dumped, if premerge runs successfully. Use :forcedump to forcibly write files out.

(actual capabilities: binary, symlink)

":fail"
Rather than attempting to merge files that were modified on both branches, it marks them as unresolved. The resolve command must be used to resolve these conflicts.

(actual capabilities: binary, symlink)

":forcedump"
Creates three versions of the files as same as :dump, but omits premerge.

(actual capabilities: binary, symlink)

":local"
Uses the local 'p1()' version of files as the merged version.

(actual capabilities: binary, symlink)

":merge"
Uses the internal non-interactive simple merge algorithm for merging files. It will fail if there are any conflicts and leave markers in the partially merged file. Markers will have two sections, one for each side of merge.
":merge-local"
Like :merge, but resolve all conflicts non-interactively in favor of the local 'p1()' changes.
":merge-other"
Like :merge, but resolve all conflicts non-interactively in favor of the other 'p2()' changes.
":merge3"
Uses the internal non-interactive simple merge algorithm for merging files. It will fail if there are any conflicts and leave markers in the partially merged file. Marker will have three sections, one from each side of the merge and one for the base content.
":mergediff"
Uses the internal non-interactive simple merge algorithm for merging files. It will fail if there are any conflicts and leave markers in the partially merged file. The marker will have two sections, one with the content from one side of the merge, and one with a diff from the base content to the content on the other side. (experimental)
":other"
Uses the other 'p2()' version of files as the merged version.

(actual capabilities: binary, symlink)

":prompt"
Asks the user which of the local 'p1()' or the other 'p2()' version to keep as the merged version.

(actual capabilities: binary, symlink)

":tagmerge"
Uses the internal tag merge algorithm (experimental).
":union"
Uses the internal non-interactive simple merge algorithm for merging files. It will use both local and other sides for conflict regions by adding local on top of other. No markers are inserted.
":union-other-first"
Like :union, but add other on top of local.

Internal tools are always available and do not require a GUI but will by default not handle symlinks or binary files. See next section for detail about "actual capabilities" described above.

Выбор инструмента слияния

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

  1. Если инструмент был задан с помощью опции --tool, то используется он. Если это имя инструмента из секции merge-tools, используются настройки оттуда. В противном случае, заданный инструмент должен быть пригодным для запуска командной оболочкой.
  2. Если переменная окружения "HGMERGE" установлена, используется ее значение, оно должно быть исполняемо оболочкой.
  3. If the filename of the file to be merged matches any of the patterns in the merge-patterns configuration section, the first usable merge tool corresponding to a matching pattern is used.
  4. Если ui.merge установлен, он рассматривается следующим. Если значение не является именем сконфигурированного инструмента, используется указанное значение, которое должно быть исполнимо командной оболочкой. В противном случае по возможности используется заданный инструмент.
  5. Если в секции merge-tools присутствуют любые подходящие инструменты слияния, используется инструмент с максимальным приоритетом.
  6. Если программа "hgmerge" может быть найдена в системе, она будет использована, но по умолчанию она не будет использоваться для символьных ссылок и бинарных файлов по умолчанию.
  7. If the file to be merged is not binary and is not a symlink, then internal ":merge" is used.
  8. Otherwise, ":prompt" is used.

For historical reason, Mercurial treats merge tools as below while examining rules above.

step specified via binary symlink
1. --tool o/o o/o
2. HGMERGE o/o o/o
3. merge-patterns o/o(*) x/?(*)
4. ui.merge x/?(*) x/?(*)

Each capability column indicates Mercurial behavior for internal/external merge tools at examining each rule.

If "merge.strict-capability-check" configuration is true, Mercurial checks capabilities of merge tools strictly in (*) cases above (= each capability column becomes "?/?"). It is false by default for backward compatibility.

Примечание:

After selecting a merge program, Mercurial will by default attempt to merge the files using a simple merge algorithm first. Only if it doesn't succeed because of conflicting changes will Mercurial actually execute the merge program. Whether to use the simple merge algorithm first can be controlled by the premerge setting of the merge tool. Premerge is enabled by default unless the file is binary or a symlink.

Подробнее см. секции merge-tools и ui в 'hg help config' или man hgrc.