blob: 8b0ee301ee3d4d6f430899a75a17336dbb7d3fcb [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
98def print_table(table, colsep=' ', rowsep='\n', align=None, out=sys.stdout):
99 """Print a 2D rectangular array, aligning columns with spaces.
100
101 Args:
102 align: Optional string of 'l' and 'r', designating whether each column is
103 left- or right-aligned. Defaults to left aligned.
104 """
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
115 if align is None: # pragma: no cover
116 align = 'l' * len(colwidths)
117
118 for row in table:
119 cells = []
120 for i, cell in enumerate(row):
Edward Lemur12a537f2019-10-03 21:57:15 +0000121 padding = ' ' * (colwidths[i] - len(cell))
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000122 if align[i] == 'r':
123 cell = padding + cell
124 elif i < len(row) - 1:
125 # Do not pad the final column if left-aligned.
126 cell += padding
127 cells.append(cell)
128 try:
129 print(*cells, sep=colsep, end=rowsep, file=out)
130 except IOError: # pragma: no cover
131 # Can happen on Windows if the pipe is closed early.
132 pass
133
134
135def pretty_print(parsedblame, show_filenames=False, out=sys.stdout):
136 """Pretty-prints the output of parse_blame."""
137 table = []
138 for line in parsedblame:
139 author_time = git_dates.timestamp_offset_to_datetime(
140 line.commit.author_time, line.commit.author_tz)
141 row = [line.commit.commithash[:8],
142 '(' + line.commit.author,
143 git_dates.datetime_string(author_time),
144 str(line.lineno_now) + ('*' if line.modified else '') + ')',
145 line.context]
146 if show_filenames:
147 row.insert(1, line.commit.filename)
148 table.append(row)
149 print_table(table, align='llllrl' if show_filenames else 'lllrl', out=out)
150
151
152def get_parsed_blame(filename, revision='HEAD'):
153 blame = git_common.blame(filename, revision=revision, porcelain=True)
154 return list(parse_blame(blame))
155
156
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000157# Map from (oldrev, newrev) to hunk list (caching the results of git diff, but
158# only the hunk line numbers, not the actual diff contents).
159# hunk list contains (old, new) pairs, where old and new are (start, length)
160# pairs. A hunk list can also be None (if the diff failed).
161diff_hunks_cache = {}
162
163
164def cache_diff_hunks(oldrev, newrev):
165 def parse_start_length(s):
166 # Chop the '-' or '+'.
167 s = s[1:]
168 # Length is optional (defaults to 1).
169 try:
170 start, length = s.split(',')
171 except ValueError:
172 start = s
173 length = 1
174 return int(start), int(length)
175
176 try:
177 return diff_hunks_cache[(oldrev, newrev)]
178 except KeyError:
179 pass
180
181 # Use -U0 to get the smallest possible hunks.
182 diff = git_common.diff(oldrev, newrev, '-U0')
183
184 # Get all the hunks.
185 hunks = []
186 for line in diff.split('\n'):
187 if not line.startswith('@@'):
188 continue
189 ranges = line.split(' ', 3)[1:3]
190 ranges = tuple(parse_start_length(r) for r in ranges)
191 hunks.append(ranges)
192
193 diff_hunks_cache[(oldrev, newrev)] = hunks
194 return hunks
195
196
197def approx_lineno_across_revs(filename, newfilename, revision, newrevision,
198 lineno):
199 """Computes the approximate movement of a line number between two revisions.
200
201 Consider line |lineno| in |filename| at |revision|. This function computes the
202 line number of that line in |newfilename| at |newrevision|. This is
203 necessarily approximate.
204
205 Args:
206 filename: The file (within the repo) at |revision|.
207 newfilename: The name of the same file at |newrevision|.
208 revision: A git revision.
209 newrevision: Another git revision. Note: Can be ahead or behind |revision|.
210 lineno: Line number within |filename| at |revision|.
211
212 Returns:
213 Line number within |newfilename| at |newrevision|.
214 """
215 # This doesn't work that well if there are a lot of line changes within the
216 # hunk (demonstrated by GitHyperBlameLineMotionTest.testIntraHunkLineMotion).
217 # A fuzzy heuristic that takes the text of the new line and tries to find a
218 # deleted line within the hunk that mostly matches the new line could help.
219
220 # Use the <revision>:<filename> syntax to diff between two blobs. This is the
221 # only way to diff a file that has been renamed.
222 old = '%s:%s' % (revision, filename)
223 new = '%s:%s' % (newrevision, newfilename)
224 hunks = cache_diff_hunks(old, new)
225
226 cumulative_offset = 0
227
228 # Find the hunk containing lineno (if any).
229 for (oldstart, oldlength), (newstart, newlength) in hunks:
230 cumulative_offset += newlength - oldlength
231
232 if lineno >= oldstart + oldlength:
233 # Not there yet.
234 continue
235
236 if lineno < oldstart:
237 # Gone too far.
238 break
239
240 # lineno is in [oldstart, oldlength] at revision; [newstart, newlength] at
241 # newrevision.
242
243 # If newlength == 0, newstart will be the line before the deleted hunk.
244 # Since the line must have been deleted, just return that as the nearest
245 # line in the new file. Caution: newstart can be 0 in this case.
246 if newlength == 0:
247 return max(1, newstart)
248
249 newend = newstart + newlength - 1
250
251 # Move lineno based on the amount the entire hunk shifted.
252 lineno = lineno + newstart - oldstart
253 # Constrain the output within the range [newstart, newend].
254 return min(newend, max(newstart, lineno))
255
256 # Wasn't in a hunk. Figure out the line motion based on the difference in
257 # length between the hunks seen so far.
258 return lineno + cumulative_offset
259
260
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000261def hyper_blame(ignored, filename, revision='HEAD', out=sys.stdout,
262 err=sys.stderr):
263 # Map from commit to parsed blame from that commit.
264 blame_from = {}
265
266 def cache_blame_from(filename, commithash):
267 try:
268 return blame_from[commithash]
269 except KeyError:
270 parsed = get_parsed_blame(filename, commithash)
271 blame_from[commithash] = parsed
272 return parsed
273
274 try:
275 parsed = cache_blame_from(filename, git_common.hash_one(revision))
276 except subprocess2.CalledProcessError as e:
Edward Lemur12a537f2019-10-03 21:57:15 +0000277 err.write(e.stderr.decode())
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000278 return e.returncode
279
280 new_parsed = []
281
282 # We don't show filenames in blame output unless we have to.
283 show_filenames = False
284
285 for line in parsed:
286 # If a line references an ignored commit, blame that commit's parent
287 # repeatedly until we find a non-ignored commit.
288 while line.commit.commithash in ignored:
289 if line.commit.previous is None:
290 # You can't ignore the commit that added this file.
291 break
292
293 previouscommit, previousfilename = line.commit.previous.split(' ', 1)
294 parent_blame = cache_blame_from(previousfilename, previouscommit)
295
296 if len(parent_blame) == 0:
297 # The previous version of this file was empty, therefore, you can't
298 # ignore this commit.
299 break
300
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000301 # line.lineno_then is the line number in question at line.commit. We need
302 # to translate that line number so that it refers to the position of the
303 # same line on previouscommit.
304 lineno_previous = approx_lineno_across_revs(
305 line.commit.filename, previousfilename, line.commit.commithash,
306 previouscommit, line.lineno_then)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000307 logging.debug('ignore commit %s on line p%d/t%d/n%d',
308 line.commit.commithash, lineno_previous, line.lineno_then,
309 line.lineno_now)
310
311 # Get the line at lineno_previous in the parent commit.
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000312 assert 1 <= lineno_previous <= len(parent_blame)
313 newline = parent_blame[lineno_previous - 1]
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000314
315 # Replace the commit and lineno_then, but not the lineno_now or context.
Matt Giuca2cd3c142017-04-10 17:31:44 +1000316 line = BlameLine(newline.commit, line.context, newline.lineno_then,
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000317 line.lineno_now, True)
Matt Giuca2cd3c142017-04-10 17:31:44 +1000318 logging.debug(' replacing with %r', line)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000319
320 # If any line has a different filename to the file's current name, turn on
321 # filename display for the entire blame output.
322 if line.commit.filename != filename:
323 show_filenames = True
324
325 new_parsed.append(line)
326
327 pretty_print(new_parsed, show_filenames=show_filenames, out=out)
328
329 return 0
330
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000331
332def parse_ignore_file(ignore_file):
333 for line in ignore_file:
334 line = line.split('#', 1)[0].strip()
335 if line:
336 yield line
337
338
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000339def main(args, stdout=sys.stdout, stderr=sys.stderr):
340 parser = argparse.ArgumentParser(
341 prog='git hyper-blame',
342 description='git blame with support for ignoring certain commits.')
343 parser.add_argument('-i', metavar='REVISION', action='append', dest='ignored',
344 default=[], help='a revision to ignore')
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000345 parser.add_argument('--ignore-file', metavar='FILE',
346 type=argparse.FileType('r'), dest='ignore_file',
347 help='a file containing a list of revisions to ignore')
348 parser.add_argument('--no-default-ignores', dest='no_default_ignores',
Matt Giuca17a53072017-04-10 15:27:55 +1000349 action='store_true',
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000350 help='Do not ignore commits from .git-blame-ignore-revs.')
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000351 parser.add_argument('revision', nargs='?', default='HEAD', metavar='REVISION',
352 help='revision to look at')
353 parser.add_argument('filename', metavar='FILE', help='filename to blame')
354
355 args = parser.parse_args(args)
356 try:
357 repo_root = git_common.repo_root()
358 except subprocess2.CalledProcessError as e:
Edward Lemur12a537f2019-10-03 21:57:15 +0000359 stderr.write(e.stderr.decode())
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000360 return e.returncode
361
362 # Make filename relative to the repository root, and cd to the root dir (so
363 # all filenames throughout this script are relative to the root).
364 filename = os.path.relpath(args.filename, repo_root)
365 os.chdir(repo_root)
366
367 # Normalize filename so we can compare it to other filenames git gives us.
368 filename = os.path.normpath(filename)
369 filename = os.path.normcase(filename)
370
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000371 ignored_list = list(args.ignored)
372 if not args.no_default_ignores and os.path.exists(DEFAULT_IGNORE_FILE_NAME):
373 with open(DEFAULT_IGNORE_FILE_NAME) as ignore_file:
374 ignored_list.extend(parse_ignore_file(ignore_file))
375
376 if args.ignore_file:
377 ignored_list.extend(parse_ignore_file(args.ignore_file))
378
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000379 ignored = set()
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000380 for c in ignored_list:
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000381 try:
382 ignored.add(git_common.hash_one(c))
383 except subprocess2.CalledProcessError as e:
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000384 # Custom warning string (the message from git-rev-parse is inappropriate).
385 stderr.write('warning: unknown revision \'%s\'.\n' % c)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000386
387 return hyper_blame(ignored, filename, args.revision, out=stdout, err=stderr)
388
389
390if __name__ == '__main__': # pragma: no cover
mgiuca@chromium.org63906ba2016-04-29 01:43:32 +0000391 setup_color.init()
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000392 with git_common.less() as less_input:
393 sys.exit(main(sys.argv[1:], stdout=less_input))