git_hyper_blame.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. #!/usr/bin/env python
  2. # Copyright 2016 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Wrapper around git blame that ignores certain commits.
  6. """
  7. from __future__ import print_function
  8. import argparse
  9. import collections
  10. import logging
  11. import os
  12. import subprocess2
  13. import sys
  14. import git_common
  15. import git_dates
  16. logging.getLogger().setLevel(logging.INFO)
  17. class Commit(object):
  18. """Info about a commit."""
  19. def __init__(self, commithash):
  20. self.commithash = commithash
  21. self.author = None
  22. self.author_mail = None
  23. self.author_time = None
  24. self.author_tz = None
  25. self.committer = None
  26. self.committer_mail = None
  27. self.committer_time = None
  28. self.committer_tz = None
  29. self.summary = None
  30. self.boundary = None
  31. self.previous = None
  32. self.filename = None
  33. def __repr__(self): # pragma: no cover
  34. return '<Commit %s>' % self.commithash
  35. BlameLine = collections.namedtuple(
  36. 'BlameLine',
  37. 'commit context lineno_then lineno_now modified')
  38. def parse_blame(blameoutput):
  39. """Parses the output of git blame -p into a data structure."""
  40. lines = blameoutput.split('\n')
  41. i = 0
  42. commits = {}
  43. while i < len(lines):
  44. # Read a commit line and parse it.
  45. line = lines[i]
  46. i += 1
  47. if not line.strip():
  48. continue
  49. commitline = line.split()
  50. commithash = commitline[0]
  51. lineno_then = int(commitline[1])
  52. lineno_now = int(commitline[2])
  53. try:
  54. commit = commits[commithash]
  55. except KeyError:
  56. commit = Commit(commithash)
  57. commits[commithash] = commit
  58. # Read commit details until we find a context line.
  59. while i < len(lines):
  60. line = lines[i]
  61. i += 1
  62. if line.startswith('\t'):
  63. break
  64. try:
  65. key, value = line.split(' ', 1)
  66. except ValueError:
  67. key = line
  68. value = True
  69. setattr(commit, key.replace('-', '_'), value)
  70. context = line[1:]
  71. yield BlameLine(commit, context, lineno_then, lineno_now, False)
  72. def print_table(table, colsep=' ', rowsep='\n', align=None, out=sys.stdout):
  73. """Print a 2D rectangular array, aligning columns with spaces.
  74. Args:
  75. align: Optional string of 'l' and 'r', designating whether each column is
  76. left- or right-aligned. Defaults to left aligned.
  77. """
  78. if len(table) == 0:
  79. return
  80. colwidths = None
  81. for row in table:
  82. if colwidths is None:
  83. colwidths = [len(x) for x in row]
  84. else:
  85. colwidths = [max(colwidths[i], len(x)) for i, x in enumerate(row)]
  86. if align is None: # pragma: no cover
  87. align = 'l' * len(colwidths)
  88. for row in table:
  89. cells = []
  90. for i, cell in enumerate(row):
  91. padding = ' ' * (colwidths[i] - len(cell))
  92. if align[i] == 'r':
  93. cell = padding + cell
  94. elif i < len(row) - 1:
  95. # Do not pad the final column if left-aligned.
  96. cell += padding
  97. cells.append(cell)
  98. try:
  99. print(*cells, sep=colsep, end=rowsep, file=out)
  100. except IOError: # pragma: no cover
  101. # Can happen on Windows if the pipe is closed early.
  102. pass
  103. def pretty_print(parsedblame, show_filenames=False, out=sys.stdout):
  104. """Pretty-prints the output of parse_blame."""
  105. table = []
  106. for line in parsedblame:
  107. author_time = git_dates.timestamp_offset_to_datetime(
  108. line.commit.author_time, line.commit.author_tz)
  109. row = [line.commit.commithash[:8],
  110. '(' + line.commit.author,
  111. git_dates.datetime_string(author_time),
  112. str(line.lineno_now) + ('*' if line.modified else '') + ')',
  113. line.context]
  114. if show_filenames:
  115. row.insert(1, line.commit.filename)
  116. table.append(row)
  117. print_table(table, align='llllrl' if show_filenames else 'lllrl', out=out)
  118. def get_parsed_blame(filename, revision='HEAD'):
  119. blame = git_common.blame(filename, revision=revision, porcelain=True)
  120. return list(parse_blame(blame))
  121. # Map from (oldrev, newrev) to hunk list (caching the results of git diff, but
  122. # only the hunk line numbers, not the actual diff contents).
  123. # hunk list contains (old, new) pairs, where old and new are (start, length)
  124. # pairs. A hunk list can also be None (if the diff failed).
  125. diff_hunks_cache = {}
  126. def cache_diff_hunks(oldrev, newrev):
  127. def parse_start_length(s):
  128. # Chop the '-' or '+'.
  129. s = s[1:]
  130. # Length is optional (defaults to 1).
  131. try:
  132. start, length = s.split(',')
  133. except ValueError:
  134. start = s
  135. length = 1
  136. return int(start), int(length)
  137. try:
  138. return diff_hunks_cache[(oldrev, newrev)]
  139. except KeyError:
  140. pass
  141. # Use -U0 to get the smallest possible hunks.
  142. diff = git_common.diff(oldrev, newrev, '-U0')
  143. # Get all the hunks.
  144. hunks = []
  145. for line in diff.split('\n'):
  146. if not line.startswith('@@'):
  147. continue
  148. ranges = line.split(' ', 3)[1:3]
  149. ranges = tuple(parse_start_length(r) for r in ranges)
  150. hunks.append(ranges)
  151. diff_hunks_cache[(oldrev, newrev)] = hunks
  152. return hunks
  153. def approx_lineno_across_revs(filename, newfilename, revision, newrevision,
  154. lineno):
  155. """Computes the approximate movement of a line number between two revisions.
  156. Consider line |lineno| in |filename| at |revision|. This function computes the
  157. line number of that line in |newfilename| at |newrevision|. This is
  158. necessarily approximate.
  159. Args:
  160. filename: The file (within the repo) at |revision|.
  161. newfilename: The name of the same file at |newrevision|.
  162. revision: A git revision.
  163. newrevision: Another git revision. Note: Can be ahead or behind |revision|.
  164. lineno: Line number within |filename| at |revision|.
  165. Returns:
  166. Line number within |newfilename| at |newrevision|.
  167. """
  168. # This doesn't work that well if there are a lot of line changes within the
  169. # hunk (demonstrated by GitHyperBlameLineMotionTest.testIntraHunkLineMotion).
  170. # A fuzzy heuristic that takes the text of the new line and tries to find a
  171. # deleted line within the hunk that mostly matches the new line could help.
  172. # Use the <revision>:<filename> syntax to diff between two blobs. This is the
  173. # only way to diff a file that has been renamed.
  174. old = '%s:%s' % (revision, filename)
  175. new = '%s:%s' % (newrevision, newfilename)
  176. hunks = cache_diff_hunks(old, new)
  177. cumulative_offset = 0
  178. # Find the hunk containing lineno (if any).
  179. for (oldstart, oldlength), (newstart, newlength) in hunks:
  180. cumulative_offset += newlength - oldlength
  181. if lineno >= oldstart + oldlength:
  182. # Not there yet.
  183. continue
  184. if lineno < oldstart:
  185. # Gone too far.
  186. break
  187. # lineno is in [oldstart, oldlength] at revision; [newstart, newlength] at
  188. # newrevision.
  189. # If newlength == 0, newstart will be the line before the deleted hunk.
  190. # Since the line must have been deleted, just return that as the nearest
  191. # line in the new file. Caution: newstart can be 0 in this case.
  192. if newlength == 0:
  193. return max(1, newstart)
  194. newend = newstart + newlength - 1
  195. # Move lineno based on the amount the entire hunk shifted.
  196. lineno = lineno + newstart - oldstart
  197. # Constrain the output within the range [newstart, newend].
  198. return min(newend, max(newstart, lineno))
  199. # Wasn't in a hunk. Figure out the line motion based on the difference in
  200. # length between the hunks seen so far.
  201. return lineno + cumulative_offset
  202. def hyper_blame(ignored, filename, revision='HEAD', out=sys.stdout,
  203. err=sys.stderr):
  204. # Map from commit to parsed blame from that commit.
  205. blame_from = {}
  206. def cache_blame_from(filename, commithash):
  207. try:
  208. return blame_from[commithash]
  209. except KeyError:
  210. parsed = get_parsed_blame(filename, commithash)
  211. blame_from[commithash] = parsed
  212. return parsed
  213. try:
  214. parsed = cache_blame_from(filename, git_common.hash_one(revision))
  215. except subprocess2.CalledProcessError as e:
  216. err.write(e.stderr)
  217. return e.returncode
  218. new_parsed = []
  219. # We don't show filenames in blame output unless we have to.
  220. show_filenames = False
  221. for line in parsed:
  222. # If a line references an ignored commit, blame that commit's parent
  223. # repeatedly until we find a non-ignored commit.
  224. while line.commit.commithash in ignored:
  225. if line.commit.previous is None:
  226. # You can't ignore the commit that added this file.
  227. break
  228. previouscommit, previousfilename = line.commit.previous.split(' ', 1)
  229. parent_blame = cache_blame_from(previousfilename, previouscommit)
  230. if len(parent_blame) == 0:
  231. # The previous version of this file was empty, therefore, you can't
  232. # ignore this commit.
  233. break
  234. # line.lineno_then is the line number in question at line.commit. We need
  235. # to translate that line number so that it refers to the position of the
  236. # same line on previouscommit.
  237. lineno_previous = approx_lineno_across_revs(
  238. line.commit.filename, previousfilename, line.commit.commithash,
  239. previouscommit, line.lineno_then)
  240. logging.debug('ignore commit %s on line p%d/t%d/n%d',
  241. line.commit.commithash, lineno_previous, line.lineno_then,
  242. line.lineno_now)
  243. # Get the line at lineno_previous in the parent commit.
  244. assert 1 <= lineno_previous <= len(parent_blame)
  245. newline = parent_blame[lineno_previous - 1]
  246. # Replace the commit and lineno_then, but not the lineno_now or context.
  247. logging.debug(' replacing with %r', newline)
  248. line = BlameLine(newline.commit, line.context, lineno_previous,
  249. line.lineno_now, True)
  250. # If any line has a different filename to the file's current name, turn on
  251. # filename display for the entire blame output.
  252. if line.commit.filename != filename:
  253. show_filenames = True
  254. new_parsed.append(line)
  255. pretty_print(new_parsed, show_filenames=show_filenames, out=out)
  256. return 0
  257. def main(args, stdout=sys.stdout, stderr=sys.stderr):
  258. parser = argparse.ArgumentParser(
  259. prog='git hyper-blame',
  260. description='git blame with support for ignoring certain commits.')
  261. parser.add_argument('-i', metavar='REVISION', action='append', dest='ignored',
  262. default=[], help='a revision to ignore')
  263. parser.add_argument('revision', nargs='?', default='HEAD', metavar='REVISION',
  264. help='revision to look at')
  265. parser.add_argument('filename', metavar='FILE', help='filename to blame')
  266. args = parser.parse_args(args)
  267. try:
  268. repo_root = git_common.repo_root()
  269. except subprocess2.CalledProcessError as e:
  270. stderr.write(e.stderr)
  271. return e.returncode
  272. # Make filename relative to the repository root, and cd to the root dir (so
  273. # all filenames throughout this script are relative to the root).
  274. filename = os.path.relpath(args.filename, repo_root)
  275. os.chdir(repo_root)
  276. # Normalize filename so we can compare it to other filenames git gives us.
  277. filename = os.path.normpath(filename)
  278. filename = os.path.normcase(filename)
  279. ignored = set()
  280. for c in args.ignored:
  281. try:
  282. ignored.add(git_common.hash_one(c))
  283. except subprocess2.CalledProcessError as e:
  284. # Custom error message (the message from git-rev-parse is inappropriate).
  285. stderr.write('fatal: unknown revision \'%s\'.\n' % c)
  286. return e.returncode
  287. return hyper_blame(ignored, filename, args.revision, out=stdout, err=stderr)
  288. if __name__ == '__main__': # pragma: no cover
  289. with git_common.less() as less_input:
  290. sys.exit(main(sys.argv[1:], stdout=less_input))