PHP Git

Resolving Merge Conflicts in Complex Feature Branches

When multiple developers are working on the same project, especially on long-lived feature branches, merge conflicts are inevitable. Let's examine how to approach resolving these conflicts in the landing project.

Understanding the Conflict

Merge conflicts arise when Git is unable to automatically reconcile changes from different branches. This commonly occurs when multiple developers have modified the same lines in a file, or when one developer deletes a file that another has modified. The commit message indicates conflicts in src/module/component.file, suggesting modifications in different feature branches are clashing.

Resolving the Conflict

The standard workflow for resolving merge conflicts involves the following steps:

  1. Identify Conflicted Files: Git clearly marks the files containing conflicts. Use git status to see the list.

  2. Examine the Conflict Markers: Open the conflicted file in a text editor. Look for conflict markers:

    <<<<<<< HEAD
    // Your changes in the current branch
    =======
    // Changes from the branch being merged
    >>>>>>> branch-name
    
  3. Edit the File: Carefully review both sets of changes and decide how to integrate them. You might need to combine the changes, discard one set, or rewrite the code entirely.

  4. Remove Conflict Markers: After resolving the conflict, remove the <<<<<<<, =======, and >>>>>>> markers.

  5. Stage the Resolved File: Use git add <filename> to stage the resolved file.

  6. Commit the Changes: Create a new commit with a descriptive message explaining how the conflicts were resolved.

Example

Suppose two developers, Alice and Bob, are working on the same landing project. Both modify a PHP file:

<?php

namespace App\Services;

class UserService
{
    public function getUserName(int $userId): string
    {
        // Original implementation
        return "User " . $userId;
    }
}

Alice changes the return string to include a prefix:

return "ID: " . $userId;

Bob modifies the same line to format the ID with leading zeros:

return "User ID: " . sprintf('%04d', $userId);

When merging Bob's changes into Alice's branch, a conflict occurs. The resolved code might look like this:

return "ID: " . sprintf('%04d', $userId);

Best Practices

  • Communicate: Talk to the other developers involved to understand the changes and agree on a resolution.
  • Test Thoroughly: Ensure the resolved code works as expected and doesn't introduce new issues.
  • Resolve Conflicts Early: Don't let conflicts accumulate. The longer you wait, the harder they become to resolve.

By following these steps and adopting good communication practices, developers can effectively resolve merge conflicts and maintain a healthy codebase.

Resolving Merge Conflicts in Complex Feature Branches
GERARDO RUIZ

GERARDO RUIZ

Author

Share: