| 1 |
"""Diff parsing functions and classes.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import re |
| 6 |
import textwrap |
| 7 |
import traceback |
| 8 |
import typing as t |
| 9 |
|
| 10 |
from .util import ( |
| 11 |
ApplicationError, |
| 12 |
) |
| 13 |
|
| 14 |
|
| 15 |
def parse_diff(lines: list[str]) -> list[FileDiff]: |
| 16 |
"""Parse the given diff lines and return a list of FileDiff objects representing the changes of each file.""" |
| 17 |
return DiffParser(lines).files |
| 18 |
|
| 19 |
|
| 20 |
class FileDiff: |
| 21 |
"""Parsed diff for a single file.""" |
| 22 |
|
| 23 |
def __init__(self, old_path: str, new_path: str) -> None: |
| 24 |
self.old = DiffSide(old_path, new=False) |
| 25 |
self.new = DiffSide(new_path, new=True) |
| 26 |
self.headers: list[str] = [] |
| 27 |
self.binary = False |
| 28 |
|
| 29 |
def append_header(self, line: str) -> None: |
| 30 |
"""Append the given line to the list of headers for this file.""" |
| 31 |
self.headers.append(line) |
| 32 |
|
| 33 |
@property |
| 34 |
def is_complete(self) -> bool: |
| 35 |
"""True if the diff is complete, otherwise False.""" |
| 36 |
return self.old.is_complete and self.new.is_complete |
| 37 |
|
| 38 |
|
| 39 |
class DiffSide: |
| 40 |
"""Parsed diff for a single 'side' of a single file.""" |
| 41 |
|
| 42 |
def __init__(self, path: str, new: bool) -> None: |
| 43 |
self.path = path |
| 44 |
self.new = new |
| 45 |
self.prefix = '+' if self.new else '-' |
| 46 |
self.eof_newline = True |
| 47 |
self.exists = True |
| 48 |
|
| 49 |
self.lines: list[tuple[int, str]] = [] |
| 50 |
self.lines_and_context: list[tuple[int, str]] = [] |
| 51 |
self.ranges: list[tuple[int, int]] = [] |
| 52 |
|
| 53 |
self._next_line_number = 0 |
| 54 |
self._lines_remaining = 0 |
| 55 |
self._range_start = 0 |
| 56 |
|
| 57 |
def set_start(self, line_start: int, line_count: int) -> None: |
| 58 |
"""Set the starting line and line count.""" |
| 59 |
self._next_line_number = line_start |
| 60 |
self._lines_remaining = line_count |
| 61 |
self._range_start = 0 |
| 62 |
|
| 63 |
def append(self, line: str) -> None: |
| 64 |
"""Append the given line.""" |
| 65 |
if self._lines_remaining <= 0: |
| 66 |
raise Exception('Diff range overflow.') |
| 67 |
|
| 68 |
entry = self._next_line_number, line |
| 69 |
|
| 70 |
if line.startswith(' '): |
| 71 |
pass |
| 72 |
elif line.startswith(self.prefix): |
| 73 |
self.lines.append(entry) |
| 74 |
|
| 75 |
if not self._range_start: |
| 76 |
self._range_start = self._next_line_number |
| 77 |
else: |
| 78 |
raise Exception('Unexpected diff content prefix.') |
| 79 |
|
| 80 |
self.lines_and_context.append(entry) |
| 81 |
|
| 82 |
self._lines_remaining -= 1 |
| 83 |
|
| 84 |
if self._range_start: |
| 85 |
if self.is_complete: |
| 86 |
range_end = self._next_line_number |
| 87 |
elif line.startswith(' '): |
| 88 |
range_end = self._next_line_number - 1 |
| 89 |
else: |
| 90 |
range_end = 0 |
| 91 |
|
| 92 |
if range_end: |
| 93 |
self.ranges.append((self._range_start, range_end)) |
| 94 |
self._range_start = 0 |
| 95 |
|
| 96 |
self._next_line_number += 1 |
| 97 |
|
| 98 |
@property |
| 99 |
def is_complete(self) -> bool: |
| 100 |
"""True if the diff is complete, otherwise False.""" |
| 101 |
return self._lines_remaining == 0 |
| 102 |
|
| 103 |
def format_lines(self, context: bool = True) -> list[str]: |
| 104 |
"""Format the diff and return a list of lines, optionally including context.""" |
| 105 |
if context: |
| 106 |
lines = self.lines_and_context |
| 107 |
else: |
| 108 |
lines = self.lines |
| 109 |
|
| 110 |
return ['%s:%4d %s' % (self.path, line[0], line[1]) for line in lines] |
| 111 |
|
| 112 |
|
| 113 |
class DiffParser: |
| 114 |
"""Parse diff lines.""" |
| 115 |
|
| 116 |
def __init__(self, lines: list[str]) -> None: |
| 117 |
self.lines = lines |
| 118 |
self.files: list[FileDiff] = [] |
| 119 |
|
| 120 |
self.action = self.process_start |
| 121 |
self.line_number = 0 |
| 122 |
self.previous_line: t.Optional[str] = None |
| 123 |
self.line: t.Optional[str] = None |
| 124 |
self.file: t.Optional[FileDiff] = None |
| 125 |
|
| 126 |
for self.line in self.lines: |
| 127 |
self.line_number += 1 |
| 128 |
|
| 129 |
try: |
| 130 |
self.action() |
| 131 |
except Exception as ex: |
| 132 |
message = textwrap.dedent(""" |
| 133 |
%s |
| 134 |
|
| 135 |
Line: %d |
| 136 |
Previous: %s |
| 137 |
Current: %s |
| 138 |
%s |
| 139 |
""").strip() % ( |
| 140 |
ex, |
| 141 |
self.line_number, |
| 142 |
self.previous_line or '', |
| 143 |
self.line or '', |
| 144 |
traceback.format_exc(), |
| 145 |
) |
| 146 |
|
| 147 |
raise ApplicationError(message.strip()) from None |
| 148 |
|
| 149 |
self.previous_line = self.line |
| 150 |
|
| 151 |
self.complete_file() |
| 152 |
|
| 153 |
def process_start(self) -> None: |
| 154 |
"""Process a diff start line.""" |
| 155 |
self.complete_file() |
| 156 |
|
| 157 |
match = re.search(r'^diff --git "?(?:a/)?(?P<old_path>.*)"? "?(?:b/)?(?P<new_path>.*)"?$', self.line) |
| 158 |
|
| 159 |
if not match: |
| 160 |
raise Exception('Unexpected diff start line.') |
| 161 |
|
| 162 |
self.file = FileDiff(match.group('old_path'), match.group('new_path')) |
| 163 |
self.action = self.process_continue |
| 164 |
|
| 165 |
def process_range(self) -> None: |
| 166 |
"""Process a diff range line.""" |
| 167 |
match = re.search(r'^@@ -((?P<old_start>[0-9]+),)?(?P<old_count>[0-9]+) \+((?P<new_start>[0-9]+),)?(?P<new_count>[0-9]+) @@', self.line) |
| 168 |
|
| 169 |
if not match: |
| 170 |
raise Exception('Unexpected diff range line.') |
| 171 |
|
| 172 |
self.file.old.set_start(int(match.group('old_start') or 1), int(match.group('old_count'))) |
| 173 |
self.file.new.set_start(int(match.group('new_start') or 1), int(match.group('new_count'))) |
| 174 |
self.action = self.process_content |
| 175 |
|
| 176 |
def process_continue(self) -> None: |
| 177 |
"""Process a diff start, range or header line.""" |
| 178 |
if self.line.startswith('diff '): |
| 179 |
self.process_start() |
| 180 |
elif self.line.startswith('@@ '): |
| 181 |
self.process_range() |
| 182 |
else: |
| 183 |
self.process_header() |
| 184 |
|
| 185 |
def process_header(self) -> None: |
| 186 |
"""Process a diff header line.""" |
| 187 |
if self.line.startswith('Binary files '): |
| 188 |
self.file.binary = True |
| 189 |
elif self.line == '--- /dev/null': |
| 190 |
self.file.old.exists = False |
| 191 |
elif self.line == '+++ /dev/null': |
| 192 |
self.file.new.exists = False |
| 193 |
else: |
| 194 |
self.file.append_header(self.line) |
| 195 |
|
| 196 |
def process_content(self) -> None: |
| 197 |
"""Process a diff content line.""" |
| 198 |
if self.line == r'\ No newline at end of file': |
| 199 |
if self.previous_line.startswith(' '): |
| 200 |
self.file.old.eof_newline = False |
| 201 |
self.file.new.eof_newline = False |
| 202 |
elif self.previous_line.startswith('-'): |
| 203 |
self.file.old.eof_newline = False |
| 204 |
elif self.previous_line.startswith('+'): |
| 205 |
self.file.new.eof_newline = False |
| 206 |
else: |
| 207 |
raise Exception('Unexpected previous diff content line.') |
| 208 |
|
| 209 |
return |
| 210 |
|
| 211 |
if self.file.is_complete: |
| 212 |
self.process_continue() |
| 213 |
return |
| 214 |
|
| 215 |
if self.line.startswith(' '): |
| 216 |
self.file.old.append(self.line) |
| 217 |
self.file.new.append(self.line) |
| 218 |
elif self.line.startswith('-'): |
| 219 |
self.file.old.append(self.line) |
| 220 |
elif self.line.startswith('+'): |
| 221 |
self.file.new.append(self.line) |
| 222 |
else: |
| 223 |
raise Exception('Unexpected diff content line.') |
| 224 |
|
| 225 |
def complete_file(self) -> None: |
| 226 |
"""Complete processing of the current file, if any.""" |
| 227 |
if not self.file: |
| 228 |
return |
| 229 |
|
| 230 |
self.files.append(self.file) |