differ.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import difflib
  2. import re
  3. class Differ:
  4. @classmethod
  5. def diff(cls, left, right):
  6. left = cls.__remove_pg_error_msgs(left).splitlines(keepends=True)
  7. right = cls.__remove_pg_error_msgs(right).splitlines(keepends=True)
  8. cls.__unify_tables(left, right)
  9. return list(difflib.diff_bytes(difflib.unified_diff, left, right, n=0, fromfile=b'sql', tofile=b'out'))
  10. __reErr = re.compile(b'(^ERROR: [^\n]+)(?:\nLINE \\d+: [^\n]+(?:\n\\s*\\^\\s*)?)?(?:\n(?:HINT|DETAIL|CONTEXT): [^\n]+)*(?:\n|$)',
  11. re.MULTILINE)
  12. @classmethod
  13. def __remove_pg_error_msgs(cls, s):
  14. return cls.__reErr.sub(rb"\1", s)
  15. __reUniversalTableMarker = re.compile(rb'^-{3,100}(?:\+-{3,100})*$')
  16. __reTableEndMarker = re.compile(rb'^\(\d+ rows?\)$')
  17. @classmethod
  18. def __is_table_start(cls, pgrun_output: str, row_idx):
  19. is_0_col_tbl_start = pgrun_output[row_idx] == b'--\n' and row_idx + 1 < len(pgrun_output) \
  20. and cls.__reTableEndMarker.match(pgrun_output[row_idx + 1])
  21. return is_0_col_tbl_start or cls.__reUniversalTableMarker.match(pgrun_output[row_idx])
  22. @classmethod
  23. def __reformat_table_row(cls, row, col_widths):
  24. cells = [c.strip() for c in row[:-1].split(b'|')]
  25. return b'|'.join(c.ljust(w) for (c, w) in zip(cells, col_widths))
  26. @classmethod
  27. def __remove_table_headers(cls, lines, header_line_numbers):
  28. for i in reversed(header_line_numbers):
  29. del lines[i]
  30. del lines[i-1]
  31. @classmethod
  32. def __unify_tables(cls, left, right):
  33. left_headers = []
  34. right_headers = []
  35. ucols = []
  36. in_table = False
  37. R = enumerate(right)
  38. for i, l in enumerate(left):
  39. if in_table:
  40. if cls.__reTableEndMarker.match(l):
  41. in_table = False
  42. for (j, r) in R:
  43. if cls.__reTableEndMarker.match(r):
  44. break
  45. right[j] = cls.__reformat_table_row(r, ucols)
  46. else:
  47. break
  48. continue
  49. left[i] = cls.__reformat_table_row(l, ucols)
  50. continue
  51. if cls.__is_table_start(left, i):
  52. for (j, r) in R:
  53. if cls.__is_table_start(right, j):
  54. break
  55. else:
  56. continue
  57. lcols = [len(c) for c in l[:-1].split(b'+')]
  58. rcols = [len(c) for c in r[:-1].split(b'+')]
  59. if left[i-1] == right[j-1]:
  60. continue
  61. if len(lcols) != len(rcols):
  62. continue
  63. ucols = [max(lw, rw) for lw, rw in zip(lcols, rcols)]
  64. left_headers.append(i)
  65. right_headers.append(j)
  66. in_table = True
  67. cls.__remove_table_headers(left, left_headers)
  68. cls.__remove_table_headers(right, right_headers)