How to resolve merge conflicts in git

How to resolve merge conflicts in git

Git merge conflicts

Version control systems are all about managing contributions between multiple distributed authors ( usually developers ). Sometimes multiple developers may try to edit the same content. If Developer A tries to edit code that Developer B is editing a conflict may occur. To alleviate the occurrence of conflicts developers will work in separate isolated branches. The git merge command’s primary responsibility is to combine separate branches and resolve any conflicting edits.

Understanding merge conflicts

Merging and conflicts are a common part of the Git experience. Conflicts in other version control tools like SVN can be costly and time-consuming. Git makes merging super easy. Most of the time, Git will figure out how to automatically integrate new changes.

Conflicts generally arise when two people have changed the same lines in a file, or if one developer deleted a file while another developer was modifying it. In these cases, Git cannot automatically determine what is correct. Conflicts only affect the developer conducting the merge, the rest of the team is unaware of the conflict. Git will mark the file as being conflicted and halt the merging process. It is then the developers’ responsibility to resolve the conflict.

Types of merge conflicts

A merge can enter a conflicted state at two separate points. When starting and during a merge process. The following is a discussion of how to address each of these conflict scenarios.

Git fails to start the merge

Git fails during the merge

A failure DURING a merge indicates a conflict between the current local branch and the branch being merged. This indicates a conflict with another developers code. Git will do its best to merge the files but will leave things for you to resolve manually in the conflicted files. A mid-merge failure will output the following error message:

Creating a merge conflict

In order to get real familiar with merge conflicts, the next section will simulate a conflict to later examine and resolve. The example will be using a Unix-like command-line Git interface to execute the example simulation.

This code example executes a sequence of commands that accomplish the following.

Now we have a new repo with one branch main and a file merge.txt with content in it. Next, we will create a new branch to use as the conflicting merge.

The proceeding command sequence achieves the following:

With this new branch: new_branch_to_merge_later we have created a commit that overrides the content of merge.txt

BOOM 💥. A conflict appears. Thanks, Git for letting us know about this!

How to identify merge conflicts

As we have experienced from the proceeding example, Git will produce some descriptive output letting us know that a CONFLICT has occcured. We can gain further insight by running the git status command

The output from git status indicates that there are unmerged paths due to a conflict. The merge.text file now appears in a modified state. Let’s examine the file and see whats modified.

Here we have used the cat command to put out the contents of the merge.txt file. We can see some strange new additions

Think of these new lines as «conflict dividers». The ======= line is the «center» of the conflict. All the content between the center and the line is content that exists in the current branch main which the HEAD ref is pointing to. Alternatively all content between the center and >>>>>>> new_branch_to_merge_later is content that is present in our merging branch.

How to resolve merge conflicts using the command line

The most direct way to resolve a merge conflict is to edit the conflicted file. Open the merge.txt file in your favorite editor. For our example lets simply remove all the conflict dividers. The modified merge.txt content should then look like:

Once the file has been edited use git add merge.txt to stage the new merged content. To finalize the merge create a new commit by executing:

Git will see that the conflict has been resolved and creates a new merge commit to finalize the merge.

Git commands that can help resolve merge conflicts

General tools

The status command is in frequent use when a working with Git and during a merge it will help identify conflicted files.

diff helps find differences between states of a repository/files. This is useful in predicting and preventing merge conflicts.

Tools for when git fails to start a merge

checkout can be used for undoing changes to files, or for changing branches

reset can be used to undo changes to the working directory and staging area.

Tools for when git conflicts arise during a merge

Git reset can be used during a merge conflict to reset conflicted files to a know good state

Summary

Merge conflicts can be an intimidating experience. Luckily, Git offers powerful tools to help navigate and resolve conflicts. Git can handle most merges on its own with automatic merging features. A conflict arises when two separate branches have made edits to the same line in a file, or when a file has been deleted in one branch but edited in the other. Conflicts will most likely happen when working in a team environment.

How To Resolve Merge Conflicts in Git

Home » DevOps and Development » How To Resolve Merge Conflicts in Git

The git merge command helps a contributor add to a project from a branch. The concept is one of the core ideas of collaborative programming, allowing multiple people to work on their part of the code without any conflicts.

When multiple contributors work on the same part of a code or work with numerous branches, merge conflicts are bound to happen. The primary goal of git merge is to resolve or warn about these conflicts automatically.

This guide explains what a merge conflict is and offers resolutions for when they do not sort out automatically. The article also provides helpful tips for preventing Git merge conflicts.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

What Is a Git Merge Conflict?

When working with version control systems such as Git, most merge conflicts resolve automatically. However, there are situations where git merge is unable to resolve an issue.

Some examples of merge conflicts include:

Since the problem happens locally and the rest of the project members are unaware of the issue, resolving the conflict is of high priority and requires an immediate fix.

Types Of Git Merge Conflicts

The general types of merge conflicts depend on when the issue appears. The conflicts happen either:

How To Resolve Merge Conflicts in Git

There are three ways to resolve a merge conflict in Git:

1. Accept the local version. To accept all changes on a file from the local version, run:

Alternatively, to accept the local version for all conflicting files, use:

2. Accept the remote version. To update the changes on a file from the remote branch, run:

Accept the remote version for all conflicting files with:

Ultimately, the choice of what parts of the code stay and which do not depends on the developer’s decision for the current project.

Getting a Merge Conflict in Git

The merge conflict in Git happens when the command git merge throws an error.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

The error message prints the information about where the conflict is present. Check the file from the error message and look at the contents where the merge conflict happened:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Git automatically adds three indicators alongside the conflicting lines of code:

The added syntax helps search through the code to find the location of the merge conflict. However, a much more straightforward approach is to use a difference/merging tool to discover the issues and track the changes.

Setting Up a Default Diff Tool in Git

To set up the default diff tool for git mergetool :

1. Run the following line in your terminal:

The output prints out all the supported diff tools for your current setup:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Different tools are available based on the editor of choice. For example:

The further steps show an example of how to set up the vimdiff tool for Vim.

2. Change the git config to set the default merge tool:

For example, if using Vim, run:

3. Set the diff tool to show the common ancestor for both files, which is the version before any edits:

4. Set the option to not prompt before running:

The diff tool setup for Git is complete.

Using Mergetool to See the Differences

To use the mergetool and see the differences, run:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

The output displays a window with four views:

1. LOCAL represents the file version from the current branch.

2. BASE is how the file looked before any changes.

3. REMOTE shows how the file looks in the remote branch where the conflicting information is.

4. MERGED has the final merge file. This result represents what gets saved to the repository.

The primary navigation commands between these windows are:

Updating and Resolving a Merge Conflict

Update the MERGED file to resolve a conflict. Some shortcuts for updating the MERGED version include:

Note: Ensure the cursor is on the line where the conflicts are before running these commands.

Commit and Cleanup

The final step is to commit and clean up the extra files. Commit the updated version by running:

Note: If you made a mistake while committing, you could undo the last commit.

The diff tool creates extra files on the project for comparing versions. Clean them up with:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Tips On How to Prevent Merge Conflicts

Merge conflicts only happen when the computer is not able to resolve the problem automatically.

Here are some tips on how to prevent merge conflicts:

Merge conflicts happen when working in Git or other version control programs from time to time. By following the instructions in this guide, you know how to handle merge conflicts and how to prevent them from happening.

For more Git resources, check out our article on What Is Git Upstream and How To Set Upstream Branch.

Безболезненное разрешение Merge конфликтов в Git

Предлагаю читателям «Хабрахабра» перевод публикации «Painless Merge Conflict Resolution in Git»
из блога blog.wuwon.id.au.

В моей повседневной работе, часто приходится иметь дело со множеством git ветвей (branch). Это могут быть ветви промежуточных релизов, ветви с устаревшим API находящиеся на поддержке для некоторых клиентов, или ветви с экспериментальными свойствами. Лёгкость создания ветвей в модели Git так и соблазняет разработчиков создавать все больше и больше ветвей, и как правило бремя от большого количества ветвей становится очень ощутимым, когда приходится все эти ветви поддерживать и периодически делать слияния (merge) с другими ветвями.

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

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

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

Голубые Розы (Roses are Blue)

Давайте предположим что вашей команде поручили писать поэмы в отведённом для этих целей репозитории. (Какой кошмар!) А вам доверили самое главное — делать слияния последних фиксов из ветки master в ветку beta. Итак, вы переключаетесь в ветку beta и выполняете следующую команду:

Ого, это конфликт. Вы решаете просмотреть файл на который ссылается git:

Замечательно! Весь файл, как показывает Listing 1, находится в конфликтном состоянии. Какой же вариант файла является более корректным? Оба варианта выглядят корректно. Верхний вариант написан в хакер-стиле с элементами цветовой кодировки в стиле HTML и с использованием только строчных букв. Нижний вариант выглядит более натурально, с использованием пунктуации и заглавных букв.

Если бы это был ваш проект, вы бы могли просто выбрать один вариант и покончить с этим слиянием. Но проблема в том, что это не ваша поэма, вы никогда не читали эту поэму раньше, не были ответственны за написание или редактирование, и вы отлично понимаете что в случае не верного решения чья-то тяжёлая работа может кануть в небытие. Однако вас всё же назначили ответственным по слиянию этих веток. Что же вам делать?

Назад к Базе (Back to Base)

Хитрость заключается в том, что Listing 1 не даёт вам полную информацию, необходимую для совершения корректного слияния. На самом деле, в процессе слияния участвуют четыре важных части информации (состояния), три из которых просто необходимы для успешного разрешения конфликта. В случае Listing 1, Git предоставил вам только два состояния.

Следующая диаграмма иллюстрирует эти четыре состояния:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Состояния (B) и © относятся к текущим положениям (head) веток master и beta соответственно, эти два состояния как раз таки и отражены в Listing 1. Состояние (D) это результат слияния, то что вы хотите получить/сгенерировать в конечном итоге (в большинстве случаев Git автоматически генерирует состояние (D)). Состояние (А) на самом верху, представляет собой базу (основу) слияния веток master и beta. База слияния (A) это последний общий предок веток master и beta, и пока предположим что это база слияния уникальна. Как мы увидим позже состояние (A) играет ключевую роль в разрешении конфликтов. На диаграмме я также отразил дельты 1 и 2, которые представляют изменения между состояниями (A)-(B), и (A)-© соответственно. Зная состояния (A), (B) и © дельты 1 и 2 могут быть легко получены (вычислены). Обратите внимание, что дельты 1 и 2 могут состоять из более чем одного коммита. Но для наших целей будем считать что все дельты монолитны.

Чтобы понять, как получить состояние (D), вы должны понимать что же операция слияния пытается сделать. Состояние (D) должно представлять собой сочетание изменений, внесённых в ветку master и beta соответственно. Т.е. другими словами сочетание дельт 1 и 2. Идея проста на поверхности и большую часть времени не требует вмешательства со стороны человека, за исключением особых случаев когда дельты затрагивают наслаиваемые (пересекающиеся) части файла. В такой ситуации вам требуется помочь машине сгенерировать результат (D), путём сравнения дельт 1 и 2.

Определение Отличий (Identifying the Differences)

Для того чтобы найти изменения внесённые в каждую ветку, необходимо знать как выглядит база слияния, состояние (A). Самый простой механизм получения информации о базе слияния, это установка опции merge.conflictstyle в значение diff3

Теперь мы видим третий фрагмент посередине, который и является базой слияния или состояние (A). Изменения видны как на ладони: в ветке beta (HEAD) человеческие названия цветов были заменены на HTML коды, а в ветку master добавили капитализацию и пунктуацию. Основываясь на этих знаниях, мы теперь знаем что результат должен включать в себя капитализацию, пунктуацию и HTML коды цветов.

В принципе на этом можно было бы и закончить, потому что результат достигнут. Но есть решение и получше.

Графическое Слияние (GUI Merging)

Хотя и простое текстовое представление конфликта слияния делает свою работу в простых случаях, на практике конфликты могут быть более радикальными и сложными. В таких случаях могут помочь графические инструменты. Мой выбор пал на простой инструмент написанный на Python под названием meld, но может подойти любой другой графический инструмент, способный представить слияние в трёх-колоночном виде.

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

Последует вопрос какой программой для слияния вы хотели бы воспользоваться, просто введите meld и нажмите Enter. Вот как окно программы может выглядеть (подразумевается опция merge.conflictstyle не была включена):

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Несмотря на то что информация представлена бок о бок, она не отображает нужные фрагменты которые были в Listing 2. Мы не видим здесь фрагмента базы слияния (состояния (A)), что мы видим это файл roses.txt.LOCAL.2760.txt в левой колонке и файл roses.txt.REMOTE.2760.txt в правой колонке и файл посередине это неудачное слияние. Т.е. по сути нам представили состояния (B), © и несостоявшееся состояние (D), но состояние (A) отсутствует.

Правда отсутствует? Давайте проверим, в старом добром терминале:

Видим интересующий нас файл: roses.txt.BASE.2760.txt. Это и есть файл базы слияния. Теперь нам осталось всего лишь найти изменения внесённые в ветки master и beta, по отношению к базе. Мы можем сделать это двумя отдельными вызовами meld:

(Кто-то может подметить что было бы более разумно, поменять порядок аргументов в первом вызове, для того чтобы файл базы находился в левой колонке в обоих случаях, но именно такой порядок сохраняет подобие трёх-колоночного вида, при котором база остаётся по середине.) Результат выполнения — два окна как показано ниже:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in gitHow to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

При чтении первого окна справа налево и второго окна слева направо, становится ясно как день, какие изменения произошли в каждой ветке. Так как meld любезно подсветил все изменения, теперь практически не возможно пропустить даже мелко заметные правки (Кто-нибудь заметил добавление предлога «of» при просмотре текстового представления разрешения конфликта Listing 1 или даже Listing 2?)

Вооружившись этими знаниями, мы теперь можем вернуться к трёх-колоночному представлению и сделать изменения. Моя стратегия ручного слияния это взять весь текст из ветки с более весомыми изменениями (в данном случае master/REMOTE т.е. beta), и поверх него производить пошаговые правки, т.е. вносить изменения сделанные в другой ветке (master). Вот что получилось:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

А теперь всё вместе (All Together Now)

И добавьте следующее в ваш

Теперь, когда вы в следующий раз будете запускать команду git mergetool для разрешения конфликта, откроются все три окна:

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

Бонус от переводчика

Для тех кто пользуется tmux и n?vim, предлагаю следующий скрипт gitmerge:

Примечание: если вы не используете эту опцию в своем

/.tmux.conf, то вам надо поменять в двух последних строках «$sn:1» на «$sn:0»

Соответственно добавьте следующее в ваш

Воркфлоу разрешения конфликта будет выглядеть так:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Пока игнорируем вопрос (Was the merge successful [y/n]?) и переключаемся в сессию под названием gitmerge (сочетание TMUXPREFIX + s):

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Видим наше трёх-оконное представление на одном экране. Цифрами обозначены сплиты (panes) tmux’a, буквами соответствующие состояния. Делаем правки для разрешения конфликта, т.е. редактируем состояние (D) и сохраняем. После этого возвращаемся обратно в исходную сессию tmux’a и подтверждаем что слияние произошло успешно.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

git rebase master

Лично я предпочитаю и считаю более правильным делать сначала rebase master в ветке beta, и только после этого переключаться в master и делать git merge beta. В принципе воркфлоу не сильно отличается, за исключением трёх-оконного вида.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Переключаемся в сессию gitmerge

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Обратите внимание, что состояния (B) и © поменялись местами:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Рекомендую всем поиграться с примером репозитария хотя бы один раз, сделать разрешение конфликта по вышеописанной схеме. Лично я больше не гадаю а что же выбрать «Accept theirs» или «Accept yours».

How to Resolve Merge Conflicts in Git?

Last updated on Aug 5, 2022 625198

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Git Tutorial

GIT Tutorial For Beginner

What is Git: Features, Command and Workflow in Git

Git Installation on Windows: A (Step-by-Step) Guide

All The Git Commands You Need to Know About

Git Push Command Explained With Demo

Git Pull Request Basics Explained with Demo

How to Resolve Merge Conflicts in Git?

What is GitHub And How To Use It?

Git vs GitHub: What are the Major Differences?

What is GitLab and How To use It?

Top 40 Git Interview Questions and Answers

Table of Contents

Git is one of the most popular source-control systems that enable software development professionals in all industries, enabling multiple team members to work concurrently on projects. Since many users are simultaneously working from different places on the same file, however, you may end up with a merge conflict. This article explains the basics of Git merge conflicts and one of the advanced operations of Git: resolving a Git merge conflict.В

First, we’ll go over the basics of Git.

What is Git?

Git is an open-source, distributed version control system (VCS), which has a remote repository on the server-side and a local repository on the client-side. This means that the file or code is not present in a central server, but there is a copy of the file stored on the client’s computer.В

DevOps Engineer Master’s Program

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

A distributed version control system enables multiple developers to work in parallel with each other without any code conflicts. Git enables developers to revert and go back to an older version of the code whenever necessary.В

Git helps both developers and non-tech professionals by keeping track of their project files. It makes it easier for multiple individuals to work together, and it plays an extremely significant role in big projects that involve large teams.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Basic Git Commands

What is a Git Merge Conflict?

A merge conflict is an event that takes place when Git is unable to automatically resolve differences in code between two commits. Git can merge the changes automatically only if the commits are on different lines or branches.

The following is an example of how a Git merge conflict works:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Let’s assume there are two developers: Developer A and Developer B. Both of them pull the same code file from the remote repository and try to make various amendments in that file. After making the changes, Developer A pushes the file back to the remote repository from his local repository. Now, when Developer B tries to push that file after making the changes from his end, he is unable to do so, as the file has already been changed in the remote repository.

To prevent such conflicts, developers work in separate isolated branches. The Git merge command combines separate branches and resolves any conflicting edits.

Now that we have gone through the basics of the Git merge conflict, let’s look at the various types of conflicts next.

FREE GIT Training

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Types of Git Merge ConflictsВ

There are two points when a merge can enter a conflicted state:

1. Starting the Merge ProcessВ

If there are changes in the working directory’s stage area for the current project, merging won’t start.В

In this case, conflicts happen due to pending changes that need to be stabilized using different Git commands.

2. During the Merge Process

The failure during the merge process indicates that there is a conflict between the local branch and the branch being merged.

In this case, Git resolves as much as possible, but there are things that have to be resolved manually in the conflicted files.

We will now go over resolving merge conflicts in Git.

How to Resolve Merge Conflicts in Git?

There are a few steps that could reduce the steps needed to resolve merge conflicts in Git.

Let us now look into the Git commands that may play a significant role in resolving conflicts.

Git Commands to Resolve Conflicts

2. git diffВ

The git diff command helps to identify the differences between the states repositories or files

3. git checkoutВ

The git checkout command is used to undo the changes made to the file, or for changing branches

6. git reset

The git reset command is used at the time of merge conflict to reset the conflicted files to their original state

FREE DevOps Certification Training

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Demo: Resolving Git Merge Conflicts

First, initialize two repositories:В

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Add the remote address in the A repository:

git remote add origin *address*

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

The next step is to pull all the changes in the central repository to the local repository.

git pull origin master

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Follow the same process to add the origin in the B repository.

git remote add origin *address*

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

The pull command is executed again to retrieve all the content from the remote repository and move it to the local repository.

git pull origin master

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Both of these repositories represent two different repositories of two different developers.

Post Graduate Program in DevOps

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Let’s get back to the A repository.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

In the A repository, a readme file is opened in order to make various changes.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Make the necessary changes in the file, and then save it.

The git status command is then executed in order to see the reflected changes.В

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

The next step is to add these changes to the staging area and commit them.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Free Course: Introduction to DevOps Tools

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

After the commit is finished, the changed file is pushed to the remote repository.

git push origin master

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Now, return to the B repository.В

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Open a readme fileВ

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Make changes to the file, save it, and close it. After that, add the changed file and commit it.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

The next step is to push the file to the remote repository.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

An error is shown, meaning that the updates are rejected.

Next, we need to execute:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Currently, there are visible conflicts that need to be resolved manually.

After managing this conflict manually, we will open the merge tool.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

After we input this command, all of the files will be processed.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

These are all the processes and the modifications done in the file.

You can see three different files there, and you can see everything that was added or removed.В

After scrolling, you can verify where exactly the conflict happened.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

You can then decide if you want to continue with this particular file or not. I will proceed with removing that line.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Manual modifications have allowed us to resolve file conflicts. Save the file and close the final file.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Next, we will run:

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Now, when the conflict is resolved, we must be able to push the file to the remote repository.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

You can now check the commits in your remote repository.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Explore the opportunities of working with the latest DevOps tools such as Docker, Git, Jenkins, and more by choosing our DevOps Engineer Certification Course. Grab your seat fast by contacting our admission counselor TODAY!

Conclusion

We hope that this comprehensive tutorial will help you with Git merge conflicts. We went over the basics of the merge conflicts, including the types of merge conflicts and possible explanations for their occurrence. We also provided a detailed example through a step-by-step demo. In the demo, we saw how we can manually resolve merge conflicts.В

Want to Learn More?

As we mentioned, Git is a powerful and powerful tool used by companies across the world. That means that qualified professionals are in high demand. If you want to kick start your career, check out Simplilearn’s DevOps Certification Course today. In it, you will gain in-depth knowledge of Git and other popular version control systems, and much more.

Find our DevOps Engineer Online Bootcamp in top cities:

NameDatePlace
DevOps EngineerClass starts on 27th Aug 2022,
Weekend batch
Your CityView Details
DevOps EngineerClass starts on 3rd Sep 2022,
Weekend batch
Your CityView Details
DevOps EngineerClass starts on 10th Sep 2022,
Weekend batch
Your CityView Details

About the Author

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

How to Resolve Merge Conflicts in Git

Advanced Git Tutorial

GitKraken’s in-app merge conflict tool will allow you to perform more advanced Git actions without the related risk – your solution is just a few clicks away.

Git Merge Conflicts

Watch this advanced Git tutorial video to learn more about merge conflicts in Git and when they occur.

When Git is unable to automatically resolve differences in code between two commits because there are conflicting changes to the same line of code, a merge conflict occurs. Merge conflicts in Git can happen when merging a Git branch, rebasing a branch, or cherry picking a commit.

See how to communicate with Git to resolve a merge conflict and proceed with your Git merge, Git rebase, or Git cherry pick.

What is a Git merge conflict?

When working in Git, users can combine commits from two different branches through an action known as merging. Files are automatically merged unless there are conflicting sets of changes (i.e. the commits update the same line of code differently).

A merge conflict is an event that occurs when Git is unable to automatically resolve differences in code between two commits.

When all the changes in the code occur on different lines or in different files, Git will successfully merge commits without your help.

However, when there are conflicting changes on the same lines, a “merge conflict” occurs because Git doesn’t know which code to keep and which to discard.

When can a Git merge conflict occur?

Merge conflicts can happen when merging a branch, rebasing a branch, or cherry picking a commit.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

If Git detects a conflict, it will highlight the conflicted area and ask which code you wish to keep.

Once you tell Git which code you want, you can save the file and proceed with the merge, rebase, or cherry pick.

No matter whether your merge conflict occurs during a merge, rebase, or cherry pick, GitKraken will lead the way to a quick and easy resolution.

How do you resolve merge conflicts in Git with GitKraken?

While merge conflicts can be intimidating in the command line, they’re a snap with the GitKraken Git GUI.

Let’s say we have two branches that have modified the same line in the same file. When you drag-and-drop to perform a merge, GitKraken will detect the merge conflict and notify you that it needs your help.

How to resolve merge conflicts in git. Смотреть фото How to resolve merge conflicts in git. Смотреть картинку How to resolve merge conflicts in git. Картинка про How to resolve merge conflicts in git. Фото How to resolve merge conflicts in git

Click View Conflicts to view a list of conflicted files. Then, when you click a file, it will open the merge tool, showing you the conflicting changes between the two branches along with an output view at the bottom. You may check the box for each hunk of code you wish to keep or select the code one line at a time.

You can even type in the output box to fine-tune your code further. Once you’re satisfied with the changes, hit Save to exit the merge tool and proceed to the next conflicted file. After resolving all conflicted files, you may proceed with the merge.

Ready for easier merge conflict resolution in Git? The cross-platform GitKraken Git GUI has the robust features you need to safely scale Git across your projects and organization.

Источники информации:

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

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