Files
core/utils/diff.py

46 lines
1.1 KiB
Python
Raw Normal View History

2024-02-02 15:03:44 +03:00
import re
from difflib import ndiff
def get_diff(original: str, modified: str) -> list[str]:
2024-02-02 15:03:44 +03:00
"""
Get the difference between two strings using difflib.
Parameters:
- original: The original string.
- modified: The modified string.
Returns:
A list of differences.
"""
2025-07-31 18:55:59 +03:00
diff = list(ndiff(original.split(), modified.split()))
return [d for d in diff if d.startswith(("+", "-"))]
2024-02-02 15:03:44 +03:00
2024-02-02 15:59:22 +03:00
def apply_diff(original: str, diff: list[str]) -> str:
2024-02-02 15:03:44 +03: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.
"""
2024-04-17 18:32:23 +03:00
pattern = re.compile(r"^(\+|-) ")
2024-02-02 15:03:44 +03:00
2025-07-02 22:30:21 +03:00
# Используем list comprehension вместо цикла с append
result = []
2024-02-02 15:03:44 +03:00
for line in diff:
match = pattern.match(line)
if match:
op = match.group(1)
2024-04-17 18:32:23 +03:00
if op == "+":
2025-07-02 22:30:21 +03:00
result.append(line[2:]) # content
# Игнорируем удаленные строки (op == "-")
2024-02-02 15:03:44 +03:00
else:
result.append(line)
2024-04-17 18:32:23 +03:00
return " ".join(result)