Skip to content

Commit

Permalink
IMPR: simplify diff.Hunk.create_diff
Browse files Browse the repository at this point in the history
- remove check_line and replace it with a single f-string
- create a prefix dict for tags and prefixes
- combine processing for equal and delete tags

Change-Id: Ia1e0e1aff06ee440f37ffed92605d62d7e0c60ba
  • Loading branch information
xqt committed Dec 10, 2024
1 parent 9b4fe6f commit 84c2ec7
Showing 1 changed file with 8 additions and 13 deletions.
21 changes: 8 additions & 13 deletions pywikibot/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,25 +93,20 @@ def create_diff(self) -> Iterable[str]:
Check each line ends with line feed to prevent behaviour like
:issue:`46395`
"""
def check_line(line: str) -> str:
r"""Make sure each line ends with '\n'."""
return line if line.endswith('\n') else line + '\n'

lf = '\n' # required for Python < 3.12
prefix = {'insert': '+ ', 'delete': '- ', 'replace': '', 'equal': ' '}
for tag, i1, i2, j1, j2 in self.group:
# equal/delete/insert add additional space after the sign as it's
# what difflib.ndiff does do too.
if tag == 'equal':
for line in self.a[i1:i2]:
yield ' ' + check_line(line)
elif tag == 'delete':
for line in self.a[i1:i2]:
yield '- ' + check_line(line)
elif tag == 'insert':
if tag == 'insert':
for line in self.b[j1:j2]:
yield '+ ' + check_line(line)
yield f'{prefix[tag]}{line.strip(lf)}{lf}'
elif tag == 'replace':
for line in difflib.ndiff(self.a[i1:i2], self.b[j1:j2]):
yield check_line(line)
yield f'{prefix[tag]}{line.strip(lf)}{lf}'
else: # equal, delete
for line in self.a[i1:i2]:
yield f'{prefix[tag]}{line.strip(lf)}{lf}'

def format_diff(self) -> Iterable[str]:
"""Color diff lines."""
Expand Down

0 comments on commit 84c2ec7

Please sign in to comment.