update-patches.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python
  2. import os
  3. import os.path
  4. import subprocess
  5. IGNORE = subprocess.DEVNULL
  6. EXERCISES_PATH = "exercises"
  7. ANSWERS_PATH = "answers"
  8. PATCHES_PATH = "patches/patches"
  9. # Heals all the exercises.
  10. def heal():
  11. maketree(ANSWERS_PATH)
  12. with os.scandir(EXERCISES_PATH) as it:
  13. for entry in it:
  14. name = entry.name
  15. original_path = entry.path
  16. patch_path = os.path.join(PATCHES_PATH, patch_name(name))
  17. output_path = os.path.join(ANSWERS_PATH, name)
  18. patch(original_path, patch_path, output_path)
  19. def main():
  20. heal()
  21. with os.scandir(EXERCISES_PATH) as it:
  22. for entry in it:
  23. name = entry.name
  24. broken_path = entry.path
  25. healed_path = os.path.join(ANSWERS_PATH, name)
  26. patch_path = os.path.join(PATCHES_PATH, patch_name(name))
  27. with open(patch_path, "w") as file:
  28. term = subprocess.run(
  29. ["diff", broken_path, healed_path],
  30. stdout=file,
  31. text=True,
  32. )
  33. assert term.returncode == 1
  34. def maketree(path):
  35. return os.makedirs(path, exist_ok=True)
  36. # Returns path with the patch extension.
  37. def patch_name(path):
  38. name, _ = os.path.splitext(path)
  39. return name + ".patch"
  40. # Applies patch to original, and write the file to output.
  41. def patch(original, patch, output):
  42. subprocess.run(
  43. ["patch", "-i", patch, "-o", output, original], stdout=IGNORE, check=True
  44. )
  45. main()