Main Content

Merge Git Branches and Resolve Conflicts Programmatically

This example shows how to use the MATLAB® source control API to create and merge branches, and resolve conflicts.

Create New Git Repository

Create a new Git™ repository in the current folder.


Add File to Repository

Create a file and add it to the repository.


Commit the file change.

commit(repo,Message="Add README file");

Create Branches

Create two branches for your tasks.

Task1Branch = createBranch(repo,"Task1");
Task2Branch = createBranch(repo,"Task2");

Modify Files on Branches

On the Task1 branch, update the README file with the additional line "Contact". Then, commit the change.

commit(repo,Message="Modify README in Task1 branch");

On the Task2 branch, update the README file with the additional line "Create an issue". Then, commit the change.

writelines("Create an issue","",WriteMode="append");
commit(repo,Message="Modify README in Task2 branch");

Merge Branches

Merge the Task1 branch into the Task2 branch. The merge function reports that it cannot complete the merge due to a conflict in the README file.

     % The merge function throws an expected error because this branch merge
     % results in a conflict.
     fprintf("Unable to merge Task1 into Task2.\n\nCaused by:\n" + ...
         "Conflicted files:\n\nResolve and " + ...
         "commit conflicted files to complete the merge.")
Unable to merge Task1 into Task2.

Caused by:
Conflicted files:

Resolve and commit conflicted files to complete the merge.

Open and inspect the content of the README file.



<<<<<<< HEAD

Create an issue



>>>>>>> ebc20d468cc6b8255130ccb2350b7d5db8d863f3

Resolve Conflict

Resolve the conflicts using the Comparison and Merge Tool or by editing the README file. For instructions on how to resolve the conflict interactively, see Merge Text Files.

In this example, suppose you want to keep both changes. To keep both changes, simply delete the conflict markers.

writelines("Create an issue","",WriteMode="append");

Mark the conflict in the README file resolved using the add function. Then, commit the merge resolution.

commit(repo,Message="Resolve Conflict");

See Also

gitclone | gitrepo | commit | createBranch | switchBranch | merge

Related Topics

Set Up Git Source Control

Branch and Merge with Git

Related Examples

Resolve Conflicts in Project Using Simulink Three-Way Merge (Simulink)