git_hyper_blame.py 12 KB

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