-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
32 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,39 @@ | ||
import difflib | ||
from termcolor import colored | ||
|
||
def get_edits_string(old, new): | ||
def get_edits_string(old:str, new:str, on_color :bool= True): | ||
""" | ||
Colorize the differences between two strings. | ||
""" | ||
result = "" | ||
codes = difflib.SequenceMatcher(a=old, b=new).get_opcodes() | ||
reds = [] | ||
if on_color: | ||
for code in codes: | ||
if code[0] == "replace": | ||
reds += list(range(code[1],code[2])) | ||
elif code[0] == "delete": | ||
reds += list(range(code[1],code[2])) | ||
|
||
li = 0 | ||
|
||
for code in codes: | ||
if code[0] == "equal": | ||
result += old[code[1]:code[2]] | ||
for i in range(code[3],code[4]): | ||
result += colored(new[i],color=None,on_color='on_red' if i in reds else None) | ||
li=code[4] | ||
elif code[0] == "insert": | ||
result += colored(new[code[3]:code[4]],'green') | ||
for i in range(code[3],code[4]): | ||
result += colored(new[i],color='green',on_color='on_red' if i in reds else None) | ||
li=code[4] | ||
elif code[0] == "replace": | ||
result += colored(new[code[3]:code[4]],'green') | ||
for i in range(code[3],code[4]): | ||
result += colored(new[i],color='green',on_color='on_red' if i in reds else None) | ||
li=code[4] | ||
|
||
mr = max(reds) if len(reds) > 0 else 0 | ||
#print(mr, li, reds) | ||
if li < mr: | ||
result += colored(" "*(mr-li),color=None,on_color='on_red') | ||
|
||
return result |