git_hyper_blame.py 12 KB

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