blob: 6a8dae88aadcaf41ef7838ad5e1deda05067039a [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 = {}
Josip Sokcevicd682fa42020-03-24 21:04:57 +0000261 filename = os.path.normpath(filename)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000262
263 def cache_blame_from(filename, commithash):
264 try:
265 return blame_from[commithash]
266 except KeyError:
267 parsed = get_parsed_blame(filename, commithash)
268 blame_from[commithash] = parsed
269 return parsed
270
271 try:
272 parsed = cache_blame_from(filename, git_common.hash_one(revision))
273 except subprocess2.CalledProcessError as e:
Edward Lemur0d462e92020-01-08 20:11:31 +0000274 sys.stderr.write(e.stderr.decode())
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000275 return e.returncode
276
277 new_parsed = []
278
279 # We don't show filenames in blame output unless we have to.
280 show_filenames = False
281
282 for line in parsed:
283 # If a line references an ignored commit, blame that commit's parent
284 # repeatedly until we find a non-ignored commit.
285 while line.commit.commithash in ignored:
286 if line.commit.previous is None:
287 # You can't ignore the commit that added this file.
288 break
289
290 previouscommit, previousfilename = line.commit.previous.split(' ', 1)
291 parent_blame = cache_blame_from(previousfilename, previouscommit)
292
293 if len(parent_blame) == 0:
294 # The previous version of this file was empty, therefore, you can't
295 # ignore this commit.
296 break
297
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000298 # line.lineno_then is the line number in question at line.commit. We need
299 # to translate that line number so that it refers to the position of the
300 # same line on previouscommit.
301 lineno_previous = approx_lineno_across_revs(
302 line.commit.filename, previousfilename, line.commit.commithash,
303 previouscommit, line.lineno_then)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000304 logging.debug('ignore commit %s on line p%d/t%d/n%d',
305 line.commit.commithash, lineno_previous, line.lineno_then,
306 line.lineno_now)
307
308 # Get the line at lineno_previous in the parent commit.
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000309 assert 1 <= lineno_previous <= len(parent_blame)
310 newline = parent_blame[lineno_previous - 1]
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000311
312 # Replace the commit and lineno_then, but not the lineno_now or context.
Matt Giuca2cd3c142017-04-10 17:31:44 +1000313 line = BlameLine(newline.commit, line.context, newline.lineno_then,
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000314 line.lineno_now, True)
Matt Giuca2cd3c142017-04-10 17:31:44 +1000315 logging.debug(' replacing with %r', line)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000316
317 # If any line has a different filename to the file's current name, turn on
318 # filename display for the entire blame output.
Josip Sokcevicd682fa42020-03-24 21:04:57 +0000319 # Use normpath to make variable consistent across platforms.
320 if os.path.normpath(line.commit.filename) != filename:
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000321 show_filenames = True
322
323 new_parsed.append(line)
324
Edward Lemur0d462e92020-01-08 20:11:31 +0000325 pretty_print(outbuf, new_parsed, show_filenames=show_filenames)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000326
327 return 0
328
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000329
330def parse_ignore_file(ignore_file):
331 for line in ignore_file:
332 line = line.split('#', 1)[0].strip()
333 if line:
334 yield line
335
336
Edward Lemur0d462e92020-01-08 20:11:31 +0000337def main(args, outbuf):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000338 parser = argparse.ArgumentParser(
339 prog='git hyper-blame',
340 description='git blame with support for ignoring certain commits.')
341 parser.add_argument('-i', metavar='REVISION', action='append', dest='ignored',
342 default=[], help='a revision to ignore')
Edward Lemur0d462e92020-01-08 20:11:31 +0000343 parser.add_argument('--ignore-file', metavar='FILE', dest='ignore_file',
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000344 help='a file containing a list of revisions to ignore')
345 parser.add_argument('--no-default-ignores', dest='no_default_ignores',
Matt Giuca17a53072017-04-10 15:27:55 +1000346 action='store_true',
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000347 help='Do not ignore commits from .git-blame-ignore-revs.')
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000348 parser.add_argument('revision', nargs='?', default='HEAD', metavar='REVISION',
349 help='revision to look at')
350 parser.add_argument('filename', metavar='FILE', help='filename to blame')
351
352 args = parser.parse_args(args)
353 try:
354 repo_root = git_common.repo_root()
355 except subprocess2.CalledProcessError as e:
Edward Lemur0d462e92020-01-08 20:11:31 +0000356 sys.stderr.write(e.stderr.decode())
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000357 return e.returncode
358
359 # Make filename relative to the repository root, and cd to the root dir (so
360 # all filenames throughout this script are relative to the root).
361 filename = os.path.relpath(args.filename, repo_root)
362 os.chdir(repo_root)
363
364 # Normalize filename so we can compare it to other filenames git gives us.
365 filename = os.path.normpath(filename)
366 filename = os.path.normcase(filename)
367
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000368 ignored_list = list(args.ignored)
369 if not args.no_default_ignores and os.path.exists(DEFAULT_IGNORE_FILE_NAME):
370 with open(DEFAULT_IGNORE_FILE_NAME) as ignore_file:
371 ignored_list.extend(parse_ignore_file(ignore_file))
372
373 if args.ignore_file:
Edward Lemur0d462e92020-01-08 20:11:31 +0000374 with open(args.ignore_file) as ignore_file:
375 ignored_list.extend(parse_ignore_file(ignore_file))
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000376
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000377 ignored = set()
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000378 for c in ignored_list:
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000379 try:
380 ignored.add(git_common.hash_one(c))
381 except subprocess2.CalledProcessError as e:
mgiuca@chromium.orgcd0a1cf2016-02-22 00:40:33 +0000382 # Custom warning string (the message from git-rev-parse is inappropriate).
Edward Lemur0d462e92020-01-08 20:11:31 +0000383 sys.stderr.write('warning: unknown revision \'%s\'.\n' % c)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000384
Edward Lemur0d462e92020-01-08 20:11:31 +0000385 return hyper_blame(outbuf, ignored, filename, args.revision)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000386
387
388if __name__ == '__main__': # pragma: no cover
mgiuca@chromium.org63906ba2016-04-29 01:43:32 +0000389 setup_color.init()
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000390 with git_common.less() as less_input:
Edward Lemur0d462e92020-01-08 20:11:31 +0000391 sys.exit(main(sys.argv[1:], less_input))