core/utils/diff.py
Untone 82111ed0f6
All checks were successful
Deploy on push / deploy (push) Successful in 7s
Squashed new RBAC
2025-07-02 22:30:21 +03:00

45 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
from difflib import ndiff
def get_diff(original: str, modified: str) -> list[str]:
"""
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()))
def apply_diff(original: str, diff: list[str]) -> str:
"""
Apply the difference to the original string.
Parameters:
- original: The original string.
- diff: The difference obtained from get_diff function.
Returns:
The modified string.
"""
pattern = re.compile(r"^(\+|-) ")
# Используем list comprehension вместо цикла с append
result = []
for line in diff:
match = pattern.match(line)
if match:
op = match.group(1)
if op == "+":
result.append(line[2:]) # content
# Игнорируем удаленные строки (op == "-")
else:
result.append(line)
return " ".join(result)