Git: Resolve conflicts by choice

Apply resolution decisions to a conflicted file.

What to build

A program that resolves every conflict in a file according to a list of choices.

Requirements

  • Choices: ours, theirs, both (ours followed by theirs) or none (drop both sides). Marker lines are removed.
  • Print the resolved file, then remaining markers: 0 (count of marker lines left, always 0 if done correctly).

Input

Line 1: n. Then the n lines of the file. Then a line with the choices, one per conflict, separated by spaces.

Output

The resolved lines, then the count line.

Constraints

n ≤ 1,000.

Example

Input:

6
title = Notes
<<<<<<< HEAD
color = green
=======
color = red
>>>>>>> feature
theirs

Output:

title = Notes
color = red
remaining markers: 0

Why it works

Each block offers two candidate versions, so a resolution is a choice per block; the rest of the file already merged cleanly and stays as it is.

Examples

Example 1 · Input
6
title = Notes
<<<<<<< HEAD
color = green
=======
color = red
>>>>>>> feature
theirs
Expected output
title = Notes
color = red
remaining markers: 0
Example 2 · Input
7
import os
<<<<<<< HEAD
import sys
=======
import json
>>>>>>> feature
print("ok")
both
Expected output
import os
import sys
import json
print("ok")
remaining markers: 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Copy lines outside conflict blocks unchanged; for each block, collect ours and theirs, then output according to that block's choice.

Hint 2

The choices are used in order: the first choice for the first block, and so on.

Solution

Show one correct solution (try it yourself first)
lines = [input() for _ in range(int(input()))]
choices = input().split()
out, side, block, k = [], None, ([], []), 0
for line in lines:
    if line.startswith("<<<<<<<"):
        side, block = 0, ([], [])
    elif line.startswith("=======") and side == 0:
        side = 1
    elif line.startswith(">>>>>>>") and side is not None:
        choice = choices[k]
        k += 1
        if choice in ("ours", "both"):
            out += block[0]
        if choice in ("theirs", "both"):
            out += block[1]
        side = None
    elif side is not None:
        block[side].append(line)
    else:
        out.append(line)
for line in out:
    print(line)
markers = sum(1 for line in out if line.startswith(("<<<<<<<", "=======", ">>>>>>>")))
print("remaining markers:", markers)

Lesson: Resolving merge conflicts →