patch.py 9.3 KB

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