get_diff_lines_of_file.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python3
  2. import argparse
  3. import json
  4. import os
  5. import requests
  6. import subprocess
  7. import sys
  8. def get_diff_lines_of_file(base_sha, head_sha, file_path):
  9. print(f"base_sha: {base_sha}")
  10. print(f"head_sha: {head_sha}")
  11. print(f"file_path: {file_path}")
  12. # Use git to get two versions of file
  13. result_base = subprocess.run(['git', 'show', base_sha + ':' + file_path], capture_output=True, text=True)
  14. if result_base.returncode != 0:
  15. raise RuntimeError(f"Error running git show: {result_base.stderr}")
  16. result_head = subprocess.run(['git', 'show', head_sha + ':' + file_path], capture_output=True, text=True)
  17. if result_head.returncode != 0:
  18. raise RuntimeError(f"Error running git show: {result_base.stderr}")
  19. base_set_lines = set([line for line in result_base.stdout.splitlines() if line])
  20. head_set_lines = set([line for line in result_head.stdout.splitlines() if line])
  21. added_lines = list(head_set_lines - base_set_lines)
  22. removed_lines = list(base_set_lines - head_set_lines)
  23. print("\n### Added Lines:")
  24. print("\n".join(added_lines))
  25. print("\n### Removed Lines:")
  26. print("\n".join(removed_lines))
  27. return added_lines, removed_lines
  28. def main(base_sha, head_sha, file_path):
  29. added_lines, removed_lines = get_diff_lines_of_file(base_sha, head_sha, file_path)
  30. if added_lines or removed_lines:
  31. print(f"file {file_path} changed")
  32. else:
  33. print(f"file {file_path} not changed")
  34. if __name__ == "__main__":
  35. parser = argparse.ArgumentParser(
  36. description="Returns added and removed lines for file compared by git diff in two commit sha's"
  37. )
  38. parser.add_argument('--base_sha', type=str, required=True)
  39. parser.add_argument('--head_sha', type=str, required=True)
  40. parser.add_argument('--file_path', type=str, required=True)
  41. args = parser.parse_args()
  42. main(args.base_sha, args.head_sha, args.file_path)