Last active
June 22, 2023 13:14
-
-
Save KaoruNishikawa/55781991af9d50494dd85ac6db0cad89 to your computer and use it in GitHub Desktop.
Print Git-like diff of arbitrary 2 strings in Python
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
import difflib | |
def diff(a: str, b: str) -> None: | |
line_color = {"+": 32, "-": 31} | |
diffs = difflib.ndiff(a.splitlines(keepends=True), b.splitlines(keepends=True)) | |
diff_list = list(diffs) | |
styled: list[str] = [] | |
for prev, next in zip(diff_list, diff_list[1:] + [""]): | |
color = line_color.get(prev[0], 0) | |
match prev[0]: | |
case " ": | |
styled.append(prev) | |
case "+" | "-": | |
index = [i for i, c in enumerate(next) if c == "^"] | |
_prev = list(prev) | |
for idx in index: | |
_prev[idx] = f"\x1b[97;{color+10};1m{_prev[idx]}\x1b[0;{color}m" | |
styled.append(f'\x1b[{color}m{"".join(_prev)}\x1b[0m') | |
case "?": | |
continue | |
print("".join(styled)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment