diff.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import difflib
  2. import whatthepatch
  3. def get_diff(old_contents: str, new_contents: str, filepath: str = 'file') -> str:
  4. diff = list(
  5. difflib.unified_diff(
  6. old_contents.split('\n'),
  7. new_contents.split('\n'),
  8. fromfile=filepath,
  9. tofile=filepath,
  10. # do not output unchange lines
  11. # because they can cause `parse_diff` to fail
  12. n=0,
  13. )
  14. )
  15. return '\n'.join(map(lambda x: x.rstrip(), diff))
  16. def parse_diff(diff_patch: str) -> list[whatthepatch.patch.Change]:
  17. # handle empty patch
  18. if diff_patch.strip() == '':
  19. return []
  20. patch = whatthepatch.parse_patch(diff_patch)
  21. patch_list = list(patch)
  22. assert len(patch_list) == 1, (
  23. 'parse_diff only supports single file diff. But got:\nPATCH:\n'
  24. + diff_patch
  25. + '\nPATCH LIST:\n'
  26. + str(patch_list)
  27. )
  28. changes = patch_list[0].changes
  29. # ignore changes that are the same (i.e., old_lineno == new_lineno)
  30. output_changes = []
  31. for change in changes:
  32. if change.old != change.new:
  33. output_changes.append(change)
  34. return output_changes