patch.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. # Applies a unified diff to a directory tree.
  2. from io import open
  3. from os.path import abspath, isdir, join as joinpath, sep
  4. import re
  5. import sys
  6. class LineScanner(object):
  7. def __init__(self, stream, lineFilter = None):
  8. '''Scans the given stream.
  9. Any object providing readline() can be passed as stream, such as file
  10. objects. The line scanner does not close the stream.
  11. The optional line filter is a function that will be called for every
  12. line read from the stream; iff the filter returns False, the line is
  13. skipped. This can be useful for example for skipping comment lines.
  14. '''
  15. if not hasattr(stream, 'readline'):
  16. raise TypeError(
  17. 'Invalid type for stream: %s' % type(stream).__name__
  18. )
  19. self.__stream = stream
  20. self.__filter = lineFilter
  21. self.__currLine = None
  22. self.__lineNo = 0
  23. self.nextLine()
  24. def end(self):
  25. '''Returns True iff the end of the stream has been reached.
  26. '''
  27. return self.__currLine is None
  28. def peek(self):
  29. '''Returns the current line.
  30. Like readline(), the returned string includes the newline characteter
  31. if it is present in the stream.
  32. '''
  33. return self.__currLine
  34. def nextLine(self):
  35. '''Moves on to the next line.
  36. Raises OSError if there is a problem reading from the stream.
  37. '''
  38. stream = self.__stream
  39. lineFilter = self.__filter
  40. while True:
  41. line = stream.readline()
  42. self.__lineNo += 1
  43. if line:
  44. if lineFilter is None or lineFilter(line):
  45. break
  46. else:
  47. line = None
  48. break
  49. self.__currLine = line
  50. def getLineNumber(self):
  51. '''Returns the line number of the current line.
  52. The first line read from the stream is considered line 1.
  53. '''
  54. return self.__lineNo
  55. def parseError(self, msg, lineNo = None):
  56. '''Returns a ParseError object with a descriptive message.
  57. Raising the exception is left to the caller, to make sure the backtrace
  58. is meaningful.
  59. If a line number is given, that line number is used in the message,
  60. otherwise the current line number is used.
  61. '''
  62. stream = self.__stream
  63. if lineNo is None:
  64. lineNo = self.getLineNumber()
  65. return ParseError(
  66. lineNo,
  67. 'Error parsing %s at line %d: %s' % (
  68. '"%s"' % stream.name if hasattr(stream, 'name') else 'stream',
  69. lineNo,
  70. msg
  71. )
  72. )
  73. class ParseError(Exception):
  74. def __init__(self, lineNo, msg):
  75. Exception.__init__(self, msg)
  76. self.lineNo = lineNo
  77. class _Change(object):
  78. oldInc = None
  79. newInc = None
  80. action = None
  81. def __init__(self, content):
  82. self.content = content
  83. def __str__(self):
  84. return self.action + self.content.rstrip()
  85. class _Context(_Change):
  86. oldInc = 1
  87. newInc = 1
  88. action = ' '
  89. class _Add(_Change):
  90. oldInc = 0
  91. newInc = 1
  92. action = '+'
  93. class _Remove(_Change):
  94. oldInc = 1
  95. newInc = 0
  96. action = '-'
  97. class Hunk(object):
  98. '''Contains the differences between two versions of a single section within
  99. a file.
  100. '''
  101. reDeltaLine = re.compile(r'@@ -(\d+),(\d+) \+(\d+),(\d+) @@')
  102. changeClasses = dict( (cc.action, cc) for cc in (_Context, _Add, _Remove) )
  103. @classmethod
  104. def parse(cls, scanner):
  105. delta = cls.reDeltaLine.match(scanner.peek())
  106. if delta is None:
  107. raise scanner.parseError('invalid delta line')
  108. oldLine, oldLen, newLine, newLen = ( int(n) for n in delta.groups() )
  109. deltaLineNo = scanner.getLineNumber()
  110. scanner.nextLine()
  111. def lineCountMismatch(oldOrNew, declared, actual):
  112. return scanner.parseError(
  113. 'hunk %s size mismatch: %d declared, %d actual' % (
  114. oldOrNew, declared, actual
  115. ),
  116. deltaLineNo
  117. )
  118. def iterChanges():
  119. oldCount = 0
  120. newCount = 0
  121. while not scanner.end():
  122. line = scanner.peek()
  123. if (line.startswith('---') or line.startswith('+++')) \
  124. and oldCount == oldLen and newCount == newLen:
  125. # Hunks for a new file start here.
  126. # Since a change line could start with "---" or "+++"
  127. # as well we also have to check whether we are at the
  128. # declared end of this hunk.
  129. break
  130. if len(line) == 1:
  131. # Assume this is an empty context line that had its single
  132. # space character removed.
  133. line = ' '
  134. changeClass = cls.changeClasses.get(line[0])
  135. if changeClass is None:
  136. break
  137. content = line[1 : ]
  138. scanner.nextLine()
  139. if not scanner.end() and scanner.peek().startswith('\\'):
  140. # No newline at end of file.
  141. assert content[-1] == '\n'
  142. content = content[ : -1]
  143. scanner.nextLine()
  144. change = changeClass(content)
  145. yield change
  146. oldCount += change.oldInc
  147. newCount += change.newInc
  148. if oldCount != oldLen:
  149. raise lineCountMismatch('old', oldLen, oldCount)
  150. if newCount != newLen:
  151. raise lineCountMismatch('new', newLen, newCount)
  152. return cls(oldLine, newLine, iterChanges())
  153. def __init__(self, oldLine, newLine, changes):
  154. self.__oldLine = oldLine
  155. self.__newLine = newLine
  156. self.__changes = tuple(changes)
  157. def __str__(self):
  158. return 'hunk(old=%d,new=%d)' % (self.__oldLine, self.__newLine)
  159. def getOldLine(self):
  160. return self.__oldLine
  161. def getNewLine(self):
  162. return self.__newLine
  163. def iterChanges(self):
  164. return iter(self.__changes)
  165. class Diff(object):
  166. '''Contains the differences between two versions of a single file.
  167. '''
  168. @classmethod
  169. def load(cls, path):
  170. '''Iterates through the differences contained in the given diff file.
  171. Only the unified diff format is supported.
  172. Each element returned is a Diff object containing the differences to
  173. a single file.
  174. '''
  175. with open(path, 'r', encoding='utf-8') as inp:
  176. scanner = LineScanner(inp, lambda line: not line.startswith('#'))
  177. error = scanner.parseError
  178. def parseHunks():
  179. while not scanner.end():
  180. if scanner.peek().startswith('@@'):
  181. yield Hunk.parse(scanner)
  182. else:
  183. break
  184. while not scanner.end():
  185. if scanner.peek().startswith('diff '):
  186. scanner.nextLine()
  187. diffLineNo = scanner.getLineNumber()
  188. if not scanner.peek().startswith('--- '):
  189. raise error('"---" expected (not a unified diff?)')
  190. scanner.nextLine()
  191. newFileLine = scanner.peek()
  192. if not newFileLine.startswith('+++ '):
  193. raise error('"+++" expected (not a unified diff?)')
  194. index = 4
  195. length = len(newFileLine)
  196. while index < length and not newFileLine[index].isspace():
  197. index += 1
  198. filePath = newFileLine[4 : index]
  199. scanner.nextLine()
  200. try:
  201. yield cls(filePath, parseHunks())
  202. except ValueError as ex:
  203. raise error('inconsistent hunks: %s' % ex, diffLineNo)
  204. def __init__(self, path, hunks):
  205. self.__path = path
  206. self.__hunks = sorted(hunks, key = lambda hunk: hunk.getOldLine())
  207. # Sanity check on line numbers.
  208. offset = 0
  209. for hunk in self.__hunks:
  210. declaredOffset = hunk.getNewLine() - hunk.getOldLine()
  211. if offset != declaredOffset:
  212. raise ValueError(
  213. 'hunk offset mismatch: %d declared, %d actual' % (
  214. declaredOffset, offset
  215. )
  216. )
  217. offset += sum(
  218. change.newInc - change.oldInc for change in hunk.iterChanges()
  219. )
  220. def __str__(self):
  221. return 'diff of %d hunks to "%s"' % (len(self.__hunks), self.__path)
  222. def getPath(self):
  223. return self.__path
  224. def iterHunks(self):
  225. '''Iterates through the hunks in this diff in order of increasing
  226. old line numbers.
  227. '''
  228. return iter(self.__hunks)
  229. def patch(diff, targetDir):
  230. '''Applies the given Diff to the given target directory.
  231. No fuzzy matching is done: if the diff does not apply exactly, ValueError
  232. is raised.
  233. '''
  234. absTargetDir = abspath(targetDir) + sep
  235. absFilePath = abspath(joinpath(absTargetDir, diff.getPath()))
  236. if not absFilePath.startswith(absTargetDir):
  237. raise ValueError(
  238. 'Refusing to patch file "%s" outside destination directory'
  239. % diff.getPath()
  240. )
  241. # Read entire file into memory.
  242. # The largest file we expect to patch is the "configure" script, which is
  243. # typically about 1MB.
  244. with open(absFilePath, 'r', encoding='utf-8') as inp:
  245. lines = inp.readlines()
  246. for hunk in diff.iterHunks():
  247. # We will be modifying "lines" at index "newLine", while "oldLine" is
  248. # only used to produce error messages if there is a context or remove
  249. # mismatch. As a result, "newLine" is 0-based and "oldLine" is 1-based.
  250. oldLine = hunk.getOldLine()
  251. newLine = hunk.getNewLine() - 1
  252. for change in hunk.iterChanges():
  253. if change.oldInc == 0:
  254. lines.insert(newLine, change.content)
  255. else:
  256. assert change.oldInc == 1
  257. if change.content.rstrip() != lines[newLine].rstrip():
  258. raise ValueError('mismatch at line %d' % oldLine)
  259. if change.newInc == 0:
  260. del lines[newLine]
  261. oldLine += change.oldInc
  262. newLine += change.newInc
  263. with open(absFilePath, 'w', encoding='utf-8') as out:
  264. out.writelines(lines)
  265. def main(diffPath, targetDir):
  266. try:
  267. differences = list(Diff.load(diffPath))
  268. except OSError as ex:
  269. print('Error reading diff:', ex, file=sys.stderr)
  270. sys.exit(1)
  271. except ParseError as ex:
  272. print(ex, file=sys.stderr)
  273. sys.exit(1)
  274. if not isdir(targetDir):
  275. print('Destination directory "%s" does not exist' % targetDir, file=sys.stderr)
  276. sys.exit(1)
  277. for diff in differences:
  278. targetPath = joinpath(targetDir, diff.getPath())
  279. try:
  280. patch(diff, targetDir)
  281. except OSError as ex:
  282. print('I/O error patching "%s": %s' % (
  283. targetPath, ex
  284. ), file=sys.stderr)
  285. sys.exit(1)
  286. except ValueError as ex:
  287. print('Patch could not be applied to "%s": %s' % (
  288. targetPath, ex
  289. ), file=sys.stderr)
  290. sys.exit(1)
  291. else:
  292. print('Patched:', targetPath)
  293. if __name__ == '__main__':
  294. if len(sys.argv) == 3:
  295. main(*sys.argv[1 : ])
  296. else:
  297. print('Usage: python3 patch.py diff target', file=sys.stderr)
  298. sys.exit(2)