splitdiff.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env python
  2. import sys
  3. import getopt
  4. prefix = 1
  5. inPreamble = True
  6. inPatch = False
  7. lineNr = 0
  8. fileNr = 0
  9. fd = None
  10. def die(msg=None):
  11. if msg:
  12. sys.stderr.write(msg + "\n")
  13. sys.exit(1)
  14. def out(data):
  15. fd.write(data)
  16. try:
  17. (opts, args) = getopt.getopt(sys.argv[1:], "p:")
  18. except getopt.GetoptError:
  19. usage()
  20. die()
  21. for (o, v) in opts:
  22. if o in ("-p",):
  23. try:
  24. prefix = int(v)
  25. if prefix < 0:
  26. raise ValueError
  27. except ValueError:
  28. die("Invalid -p")
  29. while 1:
  30. line = sys.stdin.readline()
  31. if not line:
  32. break
  33. lineNr += 1
  34. if line.startswith("diff ") or \
  35. line.startswith("--- ") or \
  36. line.startswith("+++ "):
  37. if inPreamble or inPatch:
  38. path = line.strip().split(" ")[-1]
  39. path = path.split("/")
  40. if len(path) <= prefix:
  41. die("Could not strip all prefix")
  42. path = path[prefix:]
  43. filename = "-".join(path)
  44. filename = "%03d-%s.diff" % (fileNr, filename)
  45. fileNr += 1
  46. if fd:
  47. fd.close()
  48. fd = file(filename, "w")
  49. out(line)
  50. inPreamble = False
  51. inPatch = False
  52. continue
  53. else:
  54. out(line)
  55. continue
  56. if line.startswith("index "):
  57. if not inPreamble:
  58. out(line)
  59. continue
  60. if line.startswith("\\ No newline at end of file") or \
  61. line.startswith("old mode") or \
  62. line.startswith("new mode") or \
  63. line.startswith("new file mode ") or \
  64. line.startswith("deleted file mode ") or \
  65. line.startswith("+") or \
  66. line.startswith("-") or \
  67. line.startswith(" ") or \
  68. line.startswith("@@ "):
  69. if not inPreamble:
  70. inPatch = True
  71. out(line)
  72. continue
  73. if not inPreamble:
  74. die("Parse error in line %d" % lineNr)
  75. sys.exit(0)