blob: bd5789a6febd677abaf416acfe1d57c0fb70ce59 [file] [log] [blame]
Edward Lesmes98eda3f2019-08-12 21:09:53 +00001#!/usr/bin/env python
mgiuca@chromium.org81937562016-02-03 08:00:53 +00002# 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
6"""Wrapper around git blame that ignores certain commits.
7"""
8
9from __future__ import print_function
Edward Lemur12a537f2019-10-03 21:57:15 +000010from __future__ import unicode_literals
mgiuca@chromium.org81937562016-02-03 08:00:53 +000011
12import argparse
13import collections
14import logging
15import os
16import subprocess2
17import sys
18
19import git_common
20import git_dates
mgiuca@chromium.org63906ba2016-04-29 01:43:32 +000021import setup_color
mgiuca@chromium.org81937562016-02-03 08:00:53 +000022
23
24logging.getLogger().setLevel(logging.INFO)
25
26
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +000027DEFAULT_IGNORE_FILE_NAME = '.git-blame-ignore-revs'
28
29
mgiuca@chromium.org81937562016-02-03 08:00:53 +000030class Commit(object):
31 """Info about a commit."""
32 def __init__(self, commithash):
33 self.commithash = commithash
34 self.author = None
35 self.author_mail = None
36 self.author_time = None
37 self.author_tz = None
38 self.committer = None
39 self.committer_mail = None
40 self.committer_time = None
41 self.committer_tz = None
42 self.summary = None
43 self.boundary = None
44 self.previous = None
45 self.filename = None
46
47 def __repr__(self): # pragma: no cover
48 return '<Commit %s>' % self.commithash
49
50
51BlameLine = collections.namedtuple(
52 'BlameLine',
53 'commit context lineno_then lineno_now modified')
54
55
56def parse_blame(blameoutput):
57 """Parses the output of git blame -p into a data structure."""
58 lines = blameoutput.split('\n')
59 i = 0
60 commits = {}
61
62 while i < len(lines):
63 # Read a commit line and parse it.
64 line = lines[i]
65 i += 1
66 if not line.strip():
67 continue
68 commitline = line.split()
69 commithash = commitline[0]
70 lineno_then = int(commitline[1])
71 lineno_now = int(commitline[2])
72
73 try:
74 commit = commits[commithash]
75 except KeyError:
76 commit = Commit(commithash)
77 commits[commithash] = commit
78
79 # Read commit details until we find a context line.
80 while i < len(lines):
81 line = lines[i]
82 i += 1
83 if line.startswith('\t'):
84 break
85
86 try:
87 key, value = line.split(' ', 1)
88 except ValueError:
89 key = line
90 value = True
91 setattr(commit, key.replace('-', '_'), value)
92
93 context = line[1:]
94
95 yield BlameLine(commit, context, lineno_then, lineno_now, False)
96
97
Edward Lemur0d462e92020-01-08 20:11:31 +000098def print_table(outbuf, table, align):
mgiuca@chromium.org81937562016-02-03 08:00:53 +000099 """Print a 2D rectangular array, aligning columns with spaces.
100
101 Args:
Edward Lemur0d462e92020-01-08 20:11:31 +0000102 align: string of 'l' and 'r', designating whether each column is left- or
103 right-aligned.
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000104 """
105 if len(table) == 0:
106 return
107
108 colwidths = None
109 for row in table:
110 if colwidths is None:
Edward Lemur12a537f2019-10-03 21:57:15 +0000111 colwidths = [len(x) for x in row]
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000112 else:
Edward Lemur12a537f2019-10-03 21:57:15 +0000113 colwidths = [max(colwidths[i], len(x)) for i, x in enumerate(row)]
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000114
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000115 for row in table:
116 cells = []
117 for i, cell in enumerate(row):
Edward Lemur12a537f2019-10-03 21:57:15 +0000118 padding = ' ' * (colwidths[i] - len(cell))
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000119 if align[i] == 'r':
120 cell = padding + cell
121 elif i < len(row) - 1:
122 # Do not pad the final column if left-aligned.
123 cell += padding
Edward Lemur0d462e92020-01-08 20:11:31 +0000124 cells.append(cell.encode('utf-8', 'replace'))
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000125 try:
Edward Lemur0d462e92020-01-08 20:11:31 +0000126 outbuf.write(b' '.join(cells) + b'\n')
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000127 except IOError: # pragma: no cover
128 # Can happen on Windows if the pipe is closed early.
129 pass
130
131
Edward Lemur0d462e92020-01-08 20:11:31 +0000132def pretty_print(outbuf, parsedblame, show_filenames=False):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000133 """Pretty-prints the output of parse_blame."""
134 table = []
135 for line in parsedblame:
136 author_time = git_dates.timestamp_offset_to_datetime(
137 line.commit.author_time, line.commit.author_tz)
138 row = [line.commit.commithash[:8],
139 '(' + line.commit.author,
140 git_dates.datetime_string(author_time),
141 str(line.lineno_now) + ('*' if line.modified else '') + ')',
142 line.context]
143 if show_filenames:
144 row.insert(1, line.commit.filename)
145 table.append(row)
Edward Lemur0d462e92020-01-08 20:11:31 +0000146 print_table(outbuf, table, align='llllrl' if show_filenames else 'lllrl')
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000147
148
149def get_parsed_blame(filename, revision='HEAD'):
150 blame = git_common.blame(filename, revision=revision, porcelain=True)
151 return list(parse_blame(blame))
152
153
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000154# Map from (oldrev, newrev) to hunk list (caching the results of git diff, but
155# only the hunk line numbers, not the actual diff contents).
156# hunk list contains (old, new) pairs, where old and new are (start, length)
157# pairs. A hunk list can also be None (if the diff failed).
158diff_hunks_cache = {}
159
160
161def cache_diff_hunks(oldrev, newrev):
162 def parse_start_length(s):
163 # Chop the '-' or '+'.
164 s = s[1:]
165 # Length is optional (defaults to 1).
166 try:
167 start, length = s.split(',')
168 except ValueError:
169 start = s
170 length = 1
171 return int(start), int(length)
172
173 try:
174 return diff_hunks_cache[(oldrev, newrev)]
175 except KeyError:
176 pass
177
178 # Use -U0 to get the smallest possible hunks.
179 diff = git_common.diff(oldrev, newrev, '-U0')
180
181 # Get all the hunks.
182 hunks = []
183 for line in diff.split('\n'):
184 if not line.startswith('@@'):
185 continue
186 ranges = line.split(' ', 3)[1:3]
187 ranges = tuple(parse_start_length(r) for r in ranges)
188 hunks.append(ranges)
189
190 diff_hunks_cache[(oldrev, newrev)] = hunks
191 return hunks
192
193
194def approx_lineno_across_revs(filename, newfilename, revision, newrevision,
195 lineno):
196 """Computes the approximate movement of a line number between two revisions.
197
198 Consider line |lineno| in |filename| at |revision|. This function computes the
199 line number of that line in |newfilename| at |newrevision|. This is
200 necessarily approximate.
201
202 Args:
203 filename: The file (within the repo) at |revision|.
204 newfilename: The name of the same file at |newrevision|.
205 revision: A git revision.
206 newrevision: Another git revision. Note: Can be ahead or behind |revision|.
207 lineno: Line number within |filename| at |revision|.
208
209 Returns:
210 Line number within |newfilename| at |newrevision|.
211 """
212 # This doesn't work that well if there are a lot of line changes within the
213 # hunk (demonstrated by GitHyperBlameLineMotionTest.testIntraHunkLineMotion).
214 # A fuzzy heuristic that takes the text of the new line and tries to find a
215 # deleted line within the hunk that mostly matches the new line could help.
216
217 # Use the <revision>:<filename> syntax to diff between two blobs. This is the
218 # only way to diff a file that has been renamed.
219 old = '%s:%s' % (revision, filename)
220 new = '%s:%s' % (newrevision, newfilename)
221 hunks = cache_diff_hunks(old, new)
222
223 cumulative_offset = 0
224
225 # Find the hunk containing lineno (if any).
226 for (oldstart, oldlength), (newstart, newlength) in hunks:
227 cumulative_offset += newlength - oldlength
228
229 if lineno >= oldstart + oldlength:
230 # Not there yet.
231 continue
232
233 if lineno < oldstart:
234 # Gone too far.
235 break
236
237 # lineno is in [oldstart, oldlength] at revision; [newstart, newlength] at
238 # newrevision.
239
240 # If newlength == 0, newstart will be the line before the deleted hunk.
241 # Since the line must have been deleted, just return that as the nearest
242 # line in the new file. Caution: newstart can be 0 in this case.
243 if newlength == 0:
244 return max(1, newstart)
245
246 newend = newstart + newlength - 1
247
248 # Move lineno based on the amount the entire hunk shifted.
249 lineno = lineno + newstart - oldstart
250 # Constrain the output within the range [newstart, newend].
251 return min(newend, max(newstart, lineno))
252
253 # Wasn't in a hunk. Figure out the line motion based on the difference in
254 # length between the hunks seen so far.
255 return lineno + cumulative_offset
256
257
Edward Lemur0d462e92020-01-08 20:11:31 +0000258def hyper_blame(outbuf, ignored, filename, revision):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000259 # Map from commit to parsed blame from that commit.
260 blame_from = {}
261
262 def cache_blame_from(filename, commithash):
263 try:
264 return blame_from[commithash]
265 except KeyError:
266 parsed = get_parsed_blame(filename, commithash)
267 blame_from[commithash] = parsed
268 return parsed
269
270 try:
271 parsed = cache_blame_from(filename, git_common.hash_one(revision))
272 except subprocess2.CalledProcessError as e:
Edward Lemur0d462e92020-01-08 20:11:31 +0000273 sys.stderr.write(e.stderr.decode())
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000274 return e.returncode
275
276 new_parsed = []
277
278 # We don't show filenames in blame output unless we have to.
279 show_filenames = False
280
281 for line in parsed:
282 # If a line references an ignored commit, blame that commit's parent
283 # repeatedly until we find a non-ignored commit.
284 while line.commit.commithash in ignored:
285 if line.commit.previous is None:
286 # You can't ignore the commit that added this file.
287 break
288
289 previouscommit, previousfilename = line.commit.previous.split(' ', 1)
290 parent_blame = cache_blame_from(previousfilename, previouscommit)
291
292 if len(parent_blame) == 0:
293 # The previous version of this file was empty, therefore, you can't
294 # ignore this commit.
295 break
296
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000297 # line.lineno_then is the line number in question at line.commit. We need
298 # to translate that line number so that it refers to the position of the
299 # same line on previouscommit.
300 lineno_previous = approx_lineno_across_revs(
301 line.commit.filename, previousfilename, line.commit.commithash,
302 previouscommit, line.lineno_then)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000303 logging.debug('ignore commit %s on line p%d/t%d/n%d',
304 line.commit.commithash, lineno_previous, line.lineno_then,
305 line.lineno_now)
306
307 # Get the line at lineno_previous in the parent commit.
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000308 assert 1 <= lineno_previous <= len(parent_blame)
309 newline = parent_blame[lineno_previous - 1]
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000310
311 # Replace the commit and lineno_then, but not the lineno_now or context.
Matt Giuca2cd3c142017-04-10 17:31:44 +1000312 line = BlameLine(newline.commit, line.context, newline.lineno_then,
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000313 line.lineno_now, True)
Matt Giuca2cd3c142017-04-10 17:31:44 +1000314 logging.debug(' replacing with %r', line)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000315
316 # If any line has a different filename to the file's current name, turn on
317 # filename display for the entire blame output.
318 if line.commit.filename != filename:
319 show_filenames = True
320
321 new_parsed.append(line)
322
Edward Lemur0d462e92020-01-08 20:11:31 +0000323 pretty_print(outbuf, new_parsed, show_filenames=show_filenames)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000324
325 return 0
326
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000327
328def parse_ignore_file(ignore_file):
329 for line in ignore_file:
330 line = line.split('#', 1)[0].strip()
331 if line:
332 yield line
333
334
Edward Lemur0d462e92020-01-08 20:11:31 +0000335def main(args, outbuf):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000336 parser = argparse.ArgumentParser(
337 prog='git hyper-blame',
338 description='git blame with support for ignoring certain commits.')
339 parser.add_argument('-i', metavar='REVISION', action='append', dest='ignored',
340 default=[], help='a revision to ignore')
Edward Lemur0d462e92020-01-08 20:11:31 +0000341 parser.add_argument('--ignore-file', metavar='FILE', dest='ignore_file',
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000342 help='a file containing a list of revisions to ignore')
343 parser.add_argument('--no-default-ignores', dest='no_default_ignores',
Matt Giuca17a53072017-04-10 15:27:55 +1000344 action='store_true',
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000345 help='Do not ignore commits from .git-blame-ignore-revs.')
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000346 parser.add_argument('revision', nargs='?', default='HEAD', metavar='REVISION',
347 help='revision to look at')
348 parser.add_argument('filename', metavar='FILE', help='filename to blame')
349
350 args = parser.parse_args(args)
351 try:
352 repo_root = git_common.repo_root()
353 except subprocess2.CalledProcessError as e:
Edward Lemur0d462e92020-01-08 20:11:31 +0000354 sys.stderr.write(e.stderr.decode())
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000355 return e.returncode
356
357 # Make filename relative to the repository root, and cd to the root dir (so
358 # all filenames throughout this script are relative to the root).
359 filename = os.path.relpath(args.filename, repo_root)
360 os.chdir(repo_root)
361
362 # Normalize filename so we can compare it to other filenames git gives us.
363 filename = os.path.normpath(filename)
364 filename = os.path.normcase(filename)
365
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000366 ignored_list = list(args.ignored)
367 if not args.no_default_ignores and os.path.exists(DEFAULT_IGNORE_FILE_NAME):
368 with open(DEFAULT_IGNORE_FILE_NAME) as ignore_file:
369 ignored_list.extend(parse_ignore_file(ignore_file))
370
371 if args.ignore_file:
Edward Lemur0d462e92020-01-08 20:11:31 +0000372 with open(args.ignore_file) as ignore_file:
373 ignored_list.extend(parse_ignore_file(ignore_file))
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000374
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000375 ignored = set()
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000376 for c in ignored_list:
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000377 try:
378 ignored.add(git_common.hash_one(c))
379 except subprocess2.CalledProcessError as e:
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000380 # Custom warning string (the message from git-rev-parse is inappropriate).
Edward Lemur0d462e92020-01-08 20:11:31 +0000381 sys.stderr.write('warning: unknown revision \'%s\'.\n' % c)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000382
Edward Lemur0d462e92020-01-08 20:11:31 +0000383 return hyper_blame(outbuf, ignored, filename, args.revision)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000384
385
386if __name__ == '__main__': # pragma: no cover
mgiuca@chromium.org63906ba2016-04-29 01:43:32 +0000387 setup_color.init()
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000388 with git_common.less() as less_input:
Edward Lemur0d462e92020-01-08 20:11:31 +0000389 sys.exit(main(sys.argv[1:], less_input))