core/utils/diff.py

47 lines
1.0 KiB
Python
Raw Normal View History

2024-02-02 12:03:44 +00:00
import re
from difflib import ndiff
def get_diff(original: str, modified: str) -> list[str]:
2024-02-02 12:03:44 +00:00
"""
Get the difference between two strings using difflib.
Parameters:
- original: The original string.
- modified: The modified string.
Returns:
A list of differences.
"""
return list(ndiff(original.split(), modified.split()))
2024-02-02 12:03:44 +00:00
2024-02-02 12:59:22 +00:00
def apply_diff(original: str, diff: list[str]) -> str:
2024-02-02 12:03:44 +00:00
"""
Apply the difference to the original string.
Parameters:
- original: The original string.
- diff: The difference obtained from get_diff function.
Returns:
The modified string.
"""
result = []
2024-04-17 15:32:23 +00:00
pattern = re.compile(r"^(\+|-) ")
2024-02-02 12:03:44 +00:00
for line in diff:
match = pattern.match(line)
if match:
op = match.group(1)
content = line[2:]
2024-04-17 15:32:23 +00:00
if op == "+":
2024-02-02 12:03:44 +00:00
result.append(content)
2024-04-17 15:32:23 +00:00
elif op == "-":
2024-02-02 12:03:44 +00:00
# Ignore deleted lines
pass
else:
result.append(line)
2024-04-17 15:32:23 +00:00
return " ".join(result)