Compare the bytes of two files. Simulates the output of GNU diff.
(file1, file2, return_str=False)
| 249 | |
| 250 | |
| 251 | def diff_bytes(file1, file2, return_str=False): |
| 252 | """ |
| 253 | Compare the bytes of two files. |
| 254 | Simulates the output of GNU diff. |
| 255 | """ |
| 256 | texts = [] |
| 257 | for f in [file1, file2]: |
| 258 | with open(f, 'rb') as f: |
| 259 | text = f.read() |
| 260 | text = text.replace(b'\r\n', b'\n') # Ignore line breaks for Windows |
| 261 | texts += [text.split(b'\n')] |
| 262 | text1, text2 = texts |
| 263 | |
| 264 | output = [] |
| 265 | new_part = True |
| 266 | num = 0 |
| 267 | for line in difflib.diff_bytes(difflib.unified_diff, text1, text2, |
| 268 | fromfile=file1.encode(), tofile=file2.encode(), n=0, lineterm=b''): |
| 269 | num += 1 |
| 270 | if num < 3: |
| 271 | line = line.decode() |
| 272 | line = line.replace('--- ', '<<< ') |
| 273 | line = line.replace('+++ ', '>>> ') |
| 274 | output += [line.encode()] |
| 275 | continue |
| 276 | |
| 277 | flag = line[0:1] |
| 278 | if flag == b'-': # line unique to sequence 1 |
| 279 | new_flag = b'< ' |
| 280 | elif flag == b'+': # line unique to sequence 2 |
| 281 | new_flag = b'> ' |
| 282 | if new_part: |
| 283 | new_part = False |
| 284 | output += [b'---'] |
| 285 | elif flag == b' ': # line common to both sequences |
| 286 | # new_flag = b' ' |
| 287 | continue |
| 288 | elif flag == b'?': # line not present in either input sequence |
| 289 | new_flag = b'? ' |
| 290 | elif flag == b'@': |
| 291 | output += [re.sub(rb'@@ -([^ ]+) \+([^ ]+) @@', rb'\1c\2', line)] |
| 292 | new_part = True |
| 293 | continue |
| 294 | else: |
| 295 | new_flag = flag |
| 296 | output += [new_flag + line[1:]] |
| 297 | |
| 298 | if return_str: |
| 299 | return '\n'.join([repr(line)[2:-1] for line in output]) |
| 300 | else: |
| 301 | return b'\n'.join(output) |
| 302 | |
| 303 | |
| 304 | def md5sum(filename): |