-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
conflictutils.py
48 lines (40 loc) · 1.2 KB
/
conflictutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Functions to deal with conflicts
@author: Aurélien Gâteau <mail@agateau.com>
@license: GPL v3 or later
"""
from difflib import Differ
CONFLICT_BEGIN = "<<< LOCAL"
CONFLICT_MIDDLE = "==="
CONFLICT_END = ">>> REMOTE"
_TRANSITIONS = {
(" ", "-"): [CONFLICT_BEGIN],
(" ", "+"): [CONFLICT_BEGIN, CONFLICT_MIDDLE],
("-", " "): [CONFLICT_MIDDLE, CONFLICT_END],
("-", "+"): [CONFLICT_MIDDLE],
("+", " "): [CONFLICT_END],
("+", "-"): [CONFLICT_END, CONFLICT_BEGIN],
}
def _switchToState(state, newState):
if state == newState:
return []
return [x + "\n" for x in _TRANSITIONS[(state, newState)]]
def prepareConflictText(local, remote):
differ = Differ()
diff = differ.compare(local.splitlines(keepends=True),
remote.splitlines(keepends=True))
state = " "
lines = []
for line in diff:
newState = line[0]
rest = line[2:]
if rest[-1] != "\n":
rest += "\n"
if newState == "?":
continue
else:
lines.extend(_switchToState(state, newState))
state = newState
lines.append(rest)
lines.extend(_switchToState(state, " "))
return "".join(lines)