You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

517 lines
18KB

  1. # diff.py
  2. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  3. #
  4. # This module is part of GitPython and is released under
  5. # the BSD License: http://www.opensource.org/licenses/bsd-license.php
  6. import re
  7. from git.cmd import handle_process_output
  8. from git.compat import (
  9. defenc,
  10. PY3
  11. )
  12. from git.util import finalize_process, hex_to_bin
  13. from .compat import binary_type
  14. from .objects.blob import Blob
  15. from .objects.util import mode_str_to_int
  16. __all__ = ('Diffable', 'DiffIndex', 'Diff', 'NULL_TREE')
  17. # Special object to compare against the empty tree in diffs
  18. NULL_TREE = object()
  19. _octal_byte_re = re.compile(b'\\\\([0-9]{3})')
  20. def _octal_repl(matchobj):
  21. value = matchobj.group(1)
  22. value = int(value, 8)
  23. if PY3:
  24. value = bytes(bytearray((value,)))
  25. else:
  26. value = chr(value)
  27. return value
  28. def decode_path(path, has_ab_prefix=True):
  29. if path == b'/dev/null':
  30. return None
  31. if path.startswith(b'"') and path.endswith(b'"'):
  32. path = (path[1:-1].replace(b'\\n', b'\n')
  33. .replace(b'\\t', b'\t')
  34. .replace(b'\\"', b'"')
  35. .replace(b'\\\\', b'\\'))
  36. path = _octal_byte_re.sub(_octal_repl, path)
  37. if has_ab_prefix:
  38. assert path.startswith(b'a/') or path.startswith(b'b/')
  39. path = path[2:]
  40. return path
  41. class Diffable(object):
  42. """Common interface for all object that can be diffed against another object of compatible type.
  43. :note:
  44. Subclasses require a repo member as it is the case for Object instances, for practical
  45. reasons we do not derive from Object."""
  46. __slots__ = ()
  47. # standin indicating you want to diff against the index
  48. class Index(object):
  49. pass
  50. def _process_diff_args(self, args):
  51. """
  52. :return:
  53. possibly altered version of the given args list.
  54. Method is called right before git command execution.
  55. Subclasses can use it to alter the behaviour of the superclass"""
  56. return args
  57. def diff(self, other=Index, paths=None, create_patch=False, **kwargs):
  58. """Creates diffs between two items being trees, trees and index or an
  59. index and the working tree. It will detect renames automatically.
  60. :param other:
  61. Is the item to compare us with.
  62. If None, we will be compared to the working tree.
  63. If Treeish, it will be compared against the respective tree
  64. If Index ( type ), it will be compared against the index.
  65. If git.NULL_TREE, it will compare against the empty tree.
  66. It defaults to Index to assure the method will not by-default fail
  67. on bare repositories.
  68. :param paths:
  69. is a list of paths or a single path to limit the diff to.
  70. It will only include at least one of the given path or paths.
  71. :param create_patch:
  72. If True, the returned Diff contains a detailed patch that if applied
  73. makes the self to other. Patches are somewhat costly as blobs have to be read
  74. and diffed.
  75. :param kwargs:
  76. Additional arguments passed to git-diff, such as
  77. R=True to swap both sides of the diff.
  78. :return: git.DiffIndex
  79. :note:
  80. On a bare repository, 'other' needs to be provided as Index or as
  81. as Tree/Commit, or a git command error will occur"""
  82. args = []
  83. args.append("--abbrev=40") # we need full shas
  84. args.append("--full-index") # get full index paths, not only filenames
  85. args.append("-M") # check for renames, in both formats
  86. if create_patch:
  87. args.append("-p")
  88. else:
  89. args.append("--raw")
  90. # in any way, assure we don't see colored output,
  91. # fixes https://github.com/gitpython-developers/GitPython/issues/172
  92. args.append('--no-color')
  93. if paths is not None and not isinstance(paths, (tuple, list)):
  94. paths = [paths]
  95. diff_cmd = self.repo.git.diff
  96. if other is self.Index:
  97. args.insert(0, '--cached')
  98. elif other is NULL_TREE:
  99. args.insert(0, '-r') # recursive diff-tree
  100. args.insert(0, '--root')
  101. diff_cmd = self.repo.git.diff_tree
  102. elif other is not None:
  103. args.insert(0, '-r') # recursive diff-tree
  104. args.insert(0, other)
  105. diff_cmd = self.repo.git.diff_tree
  106. args.insert(0, self)
  107. # paths is list here or None
  108. if paths:
  109. args.append("--")
  110. args.extend(paths)
  111. # END paths handling
  112. kwargs['as_process'] = True
  113. proc = diff_cmd(*self._process_diff_args(args), **kwargs)
  114. diff_method = (Diff._index_from_patch_format
  115. if create_patch
  116. else Diff._index_from_raw_format)
  117. index = diff_method(self.repo, proc)
  118. proc.wait()
  119. return index
  120. class DiffIndex(list):
  121. """Implements an Index for diffs, allowing a list of Diffs to be queried by
  122. the diff properties.
  123. The class improves the diff handling convenience"""
  124. # change type invariant identifying possible ways a blob can have changed
  125. # A = Added
  126. # D = Deleted
  127. # R = Renamed
  128. # M = Modified
  129. # T = Changed in the type
  130. change_type = ("A", "D", "R", "M", "T")
  131. def iter_change_type(self, change_type):
  132. """
  133. :return:
  134. iterator yielding Diff instances that match the given change_type
  135. :param change_type:
  136. Member of DiffIndex.change_type, namely:
  137. * 'A' for added paths
  138. * 'D' for deleted paths
  139. * 'R' for renamed paths
  140. * 'M' for paths with modified data
  141. * 'T' for changed in the type paths
  142. """
  143. if change_type not in self.change_type:
  144. raise ValueError("Invalid change type: %s" % change_type)
  145. for diff in self:
  146. if diff.change_type == change_type:
  147. yield diff
  148. elif change_type == "A" and diff.new_file:
  149. yield diff
  150. elif change_type == "D" and diff.deleted_file:
  151. yield diff
  152. elif change_type == "R" and diff.renamed:
  153. yield diff
  154. elif change_type == "M" and diff.a_blob and diff.b_blob and diff.a_blob != diff.b_blob:
  155. yield diff
  156. # END for each diff
  157. class Diff(object):
  158. """A Diff contains diff information between two Trees.
  159. It contains two sides a and b of the diff, members are prefixed with
  160. "a" and "b" respectively to inidcate that.
  161. Diffs keep information about the changed blob objects, the file mode, renames,
  162. deletions and new files.
  163. There are a few cases where None has to be expected as member variable value:
  164. ``New File``::
  165. a_mode is None
  166. a_blob is None
  167. a_path is None
  168. ``Deleted File``::
  169. b_mode is None
  170. b_blob is None
  171. b_path is None
  172. ``Working Tree Blobs``
  173. When comparing to working trees, the working tree blob will have a null hexsha
  174. as a corresponding object does not yet exist. The mode will be null as well.
  175. But the path will be available though.
  176. If it is listed in a diff the working tree version of the file must
  177. be different to the version in the index or tree, and hence has been modified."""
  178. # precompiled regex
  179. re_header = re.compile(br"""
  180. ^diff[ ]--git
  181. [ ](?P<a_path_fallback>"?a/.+?"?)[ ](?P<b_path_fallback>"?b/.+?"?)\n
  182. (?:^old[ ]mode[ ](?P<old_mode>\d+)\n
  183. ^new[ ]mode[ ](?P<new_mode>\d+)(?:\n|$))?
  184. (?:^similarity[ ]index[ ]\d+%\n
  185. ^rename[ ]from[ ](?P<rename_from>.*)\n
  186. ^rename[ ]to[ ](?P<rename_to>.*)(?:\n|$))?
  187. (?:^new[ ]file[ ]mode[ ](?P<new_file_mode>.+)(?:\n|$))?
  188. (?:^deleted[ ]file[ ]mode[ ](?P<deleted_file_mode>.+)(?:\n|$))?
  189. (?:^index[ ](?P<a_blob_id>[0-9A-Fa-f]+)
  190. \.\.(?P<b_blob_id>[0-9A-Fa-f]+)[ ]?(?P<b_mode>.+)?(?:\n|$))?
  191. (?:^---[ ](?P<a_path>[^\t\n\r\f\v]*)[\t\r\f\v]*(?:\n|$))?
  192. (?:^\+\+\+[ ](?P<b_path>[^\t\n\r\f\v]*)[\t\r\f\v]*(?:\n|$))?
  193. """, re.VERBOSE | re.MULTILINE)
  194. # can be used for comparisons
  195. NULL_HEX_SHA = "0" * 40
  196. NULL_BIN_SHA = b"\0" * 20
  197. __slots__ = ("a_blob", "b_blob", "a_mode", "b_mode", "a_rawpath", "b_rawpath",
  198. "new_file", "deleted_file", "raw_rename_from", "raw_rename_to",
  199. "diff", "change_type", "score")
  200. def __init__(self, repo, a_rawpath, b_rawpath, a_blob_id, b_blob_id, a_mode,
  201. b_mode, new_file, deleted_file, raw_rename_from,
  202. raw_rename_to, diff, change_type, score):
  203. self.a_mode = a_mode
  204. self.b_mode = b_mode
  205. assert a_rawpath is None or isinstance(a_rawpath, binary_type)
  206. assert b_rawpath is None or isinstance(b_rawpath, binary_type)
  207. self.a_rawpath = a_rawpath
  208. self.b_rawpath = b_rawpath
  209. if self.a_mode:
  210. self.a_mode = mode_str_to_int(self.a_mode)
  211. if self.b_mode:
  212. self.b_mode = mode_str_to_int(self.b_mode)
  213. if a_blob_id is None or a_blob_id == self.NULL_HEX_SHA:
  214. self.a_blob = None
  215. else:
  216. self.a_blob = Blob(repo, hex_to_bin(a_blob_id), mode=self.a_mode, path=self.a_path)
  217. if b_blob_id is None or b_blob_id == self.NULL_HEX_SHA:
  218. self.b_blob = None
  219. else:
  220. self.b_blob = Blob(repo, hex_to_bin(b_blob_id), mode=self.b_mode, path=self.b_path)
  221. self.new_file = new_file
  222. self.deleted_file = deleted_file
  223. # be clear and use None instead of empty strings
  224. assert raw_rename_from is None or isinstance(raw_rename_from, binary_type)
  225. assert raw_rename_to is None or isinstance(raw_rename_to, binary_type)
  226. self.raw_rename_from = raw_rename_from or None
  227. self.raw_rename_to = raw_rename_to or None
  228. self.diff = diff
  229. self.change_type = change_type
  230. self.score = score
  231. def __eq__(self, other):
  232. for name in self.__slots__:
  233. if getattr(self, name) != getattr(other, name):
  234. return False
  235. # END for each name
  236. return True
  237. def __ne__(self, other):
  238. return not (self == other)
  239. def __hash__(self):
  240. return hash(tuple(getattr(self, n) for n in self.__slots__))
  241. def __str__(self):
  242. h = "%s"
  243. if self.a_blob:
  244. h %= self.a_blob.path
  245. elif self.b_blob:
  246. h %= self.b_blob.path
  247. msg = ''
  248. line = None # temp line
  249. line_length = 0 # line length
  250. for b, n in zip((self.a_blob, self.b_blob), ('lhs', 'rhs')):
  251. if b:
  252. line = "\n%s: %o | %s" % (n, b.mode, b.hexsha)
  253. else:
  254. line = "\n%s: None" % n
  255. # END if blob is not None
  256. line_length = max(len(line), line_length)
  257. msg += line
  258. # END for each blob
  259. # add headline
  260. h += '\n' + '=' * line_length
  261. if self.deleted_file:
  262. msg += '\nfile deleted in rhs'
  263. if self.new_file:
  264. msg += '\nfile added in rhs'
  265. if self.rename_from:
  266. msg += '\nfile renamed from %r' % self.rename_from
  267. if self.rename_to:
  268. msg += '\nfile renamed to %r' % self.rename_to
  269. if self.diff:
  270. msg += '\n---'
  271. try:
  272. msg += self.diff.decode(defenc)
  273. except UnicodeDecodeError:
  274. msg += 'OMITTED BINARY DATA'
  275. # end handle encoding
  276. msg += '\n---'
  277. # END diff info
  278. # Python2 silliness: have to assure we convert our likely to be unicode object to a string with the
  279. # right encoding. Otherwise it tries to convert it using ascii, which may fail ungracefully
  280. res = h + msg
  281. if not PY3:
  282. res = res.encode(defenc)
  283. # end
  284. return res
  285. @property
  286. def a_path(self):
  287. return self.a_rawpath.decode(defenc, 'replace') if self.a_rawpath else None
  288. @property
  289. def b_path(self):
  290. return self.b_rawpath.decode(defenc, 'replace') if self.b_rawpath else None
  291. @property
  292. def rename_from(self):
  293. return self.raw_rename_from.decode(defenc, 'replace') if self.raw_rename_from else None
  294. @property
  295. def rename_to(self):
  296. return self.raw_rename_to.decode(defenc, 'replace') if self.raw_rename_to else None
  297. @property
  298. def renamed(self):
  299. """:returns: True if the blob of our diff has been renamed
  300. :note: This property is deprecated, please use ``renamed_file`` instead.
  301. """
  302. return self.renamed_file
  303. @property
  304. def renamed_file(self):
  305. """:returns: True if the blob of our diff has been renamed
  306. """
  307. return self.rename_from != self.rename_to
  308. @classmethod
  309. def _pick_best_path(cls, path_match, rename_match, path_fallback_match):
  310. if path_match:
  311. return decode_path(path_match)
  312. if rename_match:
  313. return decode_path(rename_match, has_ab_prefix=False)
  314. if path_fallback_match:
  315. return decode_path(path_fallback_match)
  316. return None
  317. @classmethod
  318. def _index_from_patch_format(cls, repo, proc):
  319. """Create a new DiffIndex from the given text which must be in patch format
  320. :param repo: is the repository we are operating on - it is required
  321. :param stream: result of 'git diff' as a stream (supporting file protocol)
  322. :return: git.DiffIndex """
  323. ## FIXME: Here SLURPING raw, need to re-phrase header-regexes linewise.
  324. text = []
  325. handle_process_output(proc, text.append, None, finalize_process, decode_streams=False)
  326. # for now, we have to bake the stream
  327. text = b''.join(text)
  328. index = DiffIndex()
  329. previous_header = None
  330. for header in cls.re_header.finditer(text):
  331. a_path_fallback, b_path_fallback, \
  332. old_mode, new_mode, \
  333. rename_from, rename_to, \
  334. new_file_mode, deleted_file_mode, \
  335. a_blob_id, b_blob_id, b_mode, \
  336. a_path, b_path = header.groups()
  337. new_file, deleted_file = bool(new_file_mode), bool(deleted_file_mode)
  338. a_path = cls._pick_best_path(a_path, rename_from, a_path_fallback)
  339. b_path = cls._pick_best_path(b_path, rename_to, b_path_fallback)
  340. # Our only means to find the actual text is to see what has not been matched by our regex,
  341. # and then retro-actively assign it to our index
  342. if previous_header is not None:
  343. index[-1].diff = text[previous_header.end():header.start()]
  344. # end assign actual diff
  345. # Make sure the mode is set if the path is set. Otherwise the resulting blob is invalid
  346. # We just use the one mode we should have parsed
  347. a_mode = old_mode or deleted_file_mode or (a_path and (b_mode or new_mode or new_file_mode))
  348. b_mode = b_mode or new_mode or new_file_mode or (b_path and a_mode)
  349. index.append(Diff(repo,
  350. a_path,
  351. b_path,
  352. a_blob_id and a_blob_id.decode(defenc),
  353. b_blob_id and b_blob_id.decode(defenc),
  354. a_mode and a_mode.decode(defenc),
  355. b_mode and b_mode.decode(defenc),
  356. new_file, deleted_file,
  357. rename_from,
  358. rename_to,
  359. None, None, None))
  360. previous_header = header
  361. # end for each header we parse
  362. if index:
  363. index[-1].diff = text[header.end():]
  364. # end assign last diff
  365. return index
  366. @classmethod
  367. def _index_from_raw_format(cls, repo, proc):
  368. """Create a new DiffIndex from the given stream which must be in raw format.
  369. :return: git.DiffIndex"""
  370. # handles
  371. # :100644 100644 687099101... 37c5e30c8... M .gitignore
  372. index = DiffIndex()
  373. def handle_diff_line(line):
  374. line = line.decode(defenc)
  375. if not line.startswith(":"):
  376. return
  377. meta, _, path = line[1:].partition('\t')
  378. old_mode, new_mode, a_blob_id, b_blob_id, _change_type = meta.split(None, 4)
  379. # Change type can be R100
  380. # R: status letter
  381. # 100: score (in case of copy and rename)
  382. change_type = _change_type[0]
  383. score_str = ''.join(_change_type[1:])
  384. score = int(score_str) if score_str.isdigit() else None
  385. path = path.strip()
  386. a_path = path.encode(defenc)
  387. b_path = path.encode(defenc)
  388. deleted_file = False
  389. new_file = False
  390. rename_from = None
  391. rename_to = None
  392. # NOTE: We cannot conclude from the existence of a blob to change type
  393. # as diffs with the working do not have blobs yet
  394. if change_type == 'D':
  395. b_blob_id = None
  396. deleted_file = True
  397. elif change_type == 'A':
  398. a_blob_id = None
  399. new_file = True
  400. elif change_type == 'R':
  401. a_path, b_path = path.split('\t', 1)
  402. a_path = a_path.encode(defenc)
  403. b_path = b_path.encode(defenc)
  404. rename_from, rename_to = a_path, b_path
  405. elif change_type == 'T':
  406. # Nothing to do
  407. pass
  408. # END add/remove handling
  409. diff = Diff(repo, a_path, b_path, a_blob_id, b_blob_id, old_mode, new_mode,
  410. new_file, deleted_file, rename_from, rename_to, '',
  411. change_type, score)
  412. index.append(diff)
  413. handle_process_output(proc, handle_diff_line, None, finalize_process, decode_streams=False)
  414. return index