Skip to content

Instantly share code, notes, and snippets.

@KaoruNishikawa
Last active June 22, 2023 13:14
Show Gist options
  • Save KaoruNishikawa/55781991af9d50494dd85ac6db0cad89 to your computer and use it in GitHub Desktop.
Save KaoruNishikawa/55781991af9d50494dd85ac6db0cad89 to your computer and use it in GitHub Desktop.
Print Git-like diff of arbitrary 2 strings in Python
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))
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment