diff.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python3
  2. # sys: for reading command-line arguments.
  3. # rich: for coloring the text.
  4. import sys
  5. from rich import print
  6. # Print Usage message if enough arguments are not passed.
  7. if len(sys.argv) < 3:
  8. print("Usage:")
  9. print("\tMust provide two file names as command-line arguments.")
  10. print("\tdiff.py <orignal_file> <changed_file>")
  11. exit(1)
  12. orignal = sys.argv[1]
  13. changed = sys.argv[2]
  14. # Read the contents of the files in lists.
  15. orignal_contents = open(orignal, "r").readlines()
  16. changed_contents = open(changed, "r").readlines()
  17. color = "green"
  18. symbol = f"[bold {color}][+]"
  19. print()
  20. # Determine which file has changed much.
  21. if len(changed_contents) <= len(orignal_contents):
  22. color = "red"
  23. symbol = f"[bold {color}][-]"
  24. smallest_sloc, largest_sloc = changed_contents, orignal_contents
  25. else:
  26. smallest_sloc, largest_sloc = orignal_contents, changed_contents
  27. # Go over all the lines to check the changes.
  28. for line in range(0, len(smallest_sloc)):
  29. if orignal_contents[line] == changed_contents[line]:
  30. # Ignore if the lines are same.
  31. continue
  32. else:
  33. # Display the changes on the respective lines of the files.
  34. print(f"[bold red][-] Line {line + 1}:[/bold red] {orignal_contents[line]}", end = "")
  35. print(f"[bold green][+] Line {line + 1}:[/bold green] {changed_contents[line]}")
  36. # Show the additions [+] or deletions [-] for the file that is the largest.
  37. if line == len(smallest_sloc) - 1:
  38. for new_line in range(line + 1, len(largest_sloc)):
  39. print(f"{symbol} Line {new_line + 1}:[/bold {color}] {largest_sloc[new_line]}")