Edward Lesmes | 98eda3f | 2019-08-12 21:09:53 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 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 | |
| 6 | """Wrapper around git blame that ignores certain commits. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import print_function |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 10 | from __future__ import unicode_literals |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 11 | |
| 12 | import argparse |
| 13 | import collections |
| 14 | import logging |
| 15 | import os |
| 16 | import subprocess2 |
| 17 | import sys |
| 18 | |
| 19 | import git_common |
| 20 | import git_dates |
mgiuca@chromium.org | 63906ba | 2016-04-29 01:43:32 +0000 | [diff] [blame] | 21 | import setup_color |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 22 | |
| 23 | |
| 24 | logging.getLogger().setLevel(logging.INFO) |
| 25 | |
| 26 | |
mgiuca@chromium.org | cd0a1cf | 2016-02-22 00:40:33 +0000 | [diff] [blame] | 27 | DEFAULT_IGNORE_FILE_NAME = '.git-blame-ignore-revs' |
| 28 | |
| 29 | |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 30 | class 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 | |
| 51 | BlameLine = collections.namedtuple( |
| 52 | 'BlameLine', |
| 53 | 'commit context lineno_then lineno_now modified') |
| 54 | |
| 55 | |
| 56 | def 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 Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 98 | def print_table(outbuf, table, align): |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 99 | """Print a 2D rectangular array, aligning columns with spaces. |
| 100 | |
| 101 | Args: |
Edward Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 102 | align: string of 'l' and 'r', designating whether each column is left- or |
| 103 | right-aligned. |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 104 | """ |
| 105 | if len(table) == 0: |
| 106 | return |
| 107 | |
| 108 | colwidths = None |
| 109 | for row in table: |
| 110 | if colwidths is None: |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 111 | colwidths = [len(x) for x in row] |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 112 | else: |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 113 | colwidths = [max(colwidths[i], len(x)) for i, x in enumerate(row)] |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 114 | |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 115 | for row in table: |
| 116 | cells = [] |
| 117 | for i, cell in enumerate(row): |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 118 | padding = ' ' * (colwidths[i] - len(cell)) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 119 | 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 Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 124 | cells.append(cell.encode('utf-8', 'replace')) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 125 | try: |
Edward Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 126 | outbuf.write(b' '.join(cells) + b'\n') |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 127 | except IOError: # pragma: no cover |
| 128 | # Can happen on Windows if the pipe is closed early. |
| 129 | pass |
| 130 | |
| 131 | |
Edward Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 132 | def pretty_print(outbuf, parsedblame, show_filenames=False): |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 133 | """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 Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 146 | print_table(outbuf, table, align='llllrl' if show_filenames else 'lllrl') |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 147 | |
| 148 | |
| 149 | def 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.org | 01d2cde | 2016-02-05 03:25:41 +0000 | [diff] [blame] | 154 | # 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). |
| 158 | diff_hunks_cache = {} |
| 159 | |
| 160 | |
| 161 | def 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 | |
| 194 | def 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 Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 258 | def hyper_blame(outbuf, ignored, filename, revision): |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 259 | # Map from commit to parsed blame from that commit. |
| 260 | blame_from = {} |
Josip Sokcevic | d682fa4 | 2020-03-24 21:04:57 +0000 | [diff] [blame^] | 261 | filename = os.path.normpath(filename) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 262 | |
| 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 Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 274 | sys.stderr.write(e.stderr.decode()) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 275 | 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.org | 01d2cde | 2016-02-05 03:25:41 +0000 | [diff] [blame] | 298 | # 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.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 304 | 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.org | 01d2cde | 2016-02-05 03:25:41 +0000 | [diff] [blame] | 309 | assert 1 <= lineno_previous <= len(parent_blame) |
| 310 | newline = parent_blame[lineno_previous - 1] |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 311 | |
| 312 | # Replace the commit and lineno_then, but not the lineno_now or context. |
Matt Giuca | 2cd3c14 | 2017-04-10 17:31:44 +1000 | [diff] [blame] | 313 | line = BlameLine(newline.commit, line.context, newline.lineno_then, |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 314 | line.lineno_now, True) |
Matt Giuca | 2cd3c14 | 2017-04-10 17:31:44 +1000 | [diff] [blame] | 315 | logging.debug(' replacing with %r', line) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 316 | |
| 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 Sokcevic | d682fa4 | 2020-03-24 21:04:57 +0000 | [diff] [blame^] | 319 | # Use normpath to make variable consistent across platforms. |
| 320 | if os.path.normpath(line.commit.filename) != filename: |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 321 | show_filenames = True |
| 322 | |
| 323 | new_parsed.append(line) |
| 324 | |
Edward Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 325 | pretty_print(outbuf, new_parsed, show_filenames=show_filenames) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 326 | |
| 327 | return 0 |
| 328 | |
mgiuca@chromium.org | cd0a1cf | 2016-02-22 00:40:33 +0000 | [diff] [blame] | 329 | |
| 330 | def 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 Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 337 | def main(args, outbuf): |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 338 | 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 Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 343 | parser.add_argument('--ignore-file', metavar='FILE', dest='ignore_file', |
mgiuca@chromium.org | cd0a1cf | 2016-02-22 00:40:33 +0000 | [diff] [blame] | 344 | help='a file containing a list of revisions to ignore') |
| 345 | parser.add_argument('--no-default-ignores', dest='no_default_ignores', |
Matt Giuca | 17a5307 | 2017-04-10 15:27:55 +1000 | [diff] [blame] | 346 | action='store_true', |
mgiuca@chromium.org | cd0a1cf | 2016-02-22 00:40:33 +0000 | [diff] [blame] | 347 | help='Do not ignore commits from .git-blame-ignore-revs.') |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 348 | 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 Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 356 | sys.stderr.write(e.stderr.decode()) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 357 | 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.org | cd0a1cf | 2016-02-22 00:40:33 +0000 | [diff] [blame] | 368 | 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 Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 374 | with open(args.ignore_file) as ignore_file: |
| 375 | ignored_list.extend(parse_ignore_file(ignore_file)) |
mgiuca@chromium.org | cd0a1cf | 2016-02-22 00:40:33 +0000 | [diff] [blame] | 376 | |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 377 | ignored = set() |
mgiuca@chromium.org | cd0a1cf | 2016-02-22 00:40:33 +0000 | [diff] [blame] | 378 | for c in ignored_list: |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 379 | try: |
| 380 | ignored.add(git_common.hash_one(c)) |
| 381 | except subprocess2.CalledProcessError as e: |
mgiuca@chromium.org | cd0a1cf | 2016-02-22 00:40:33 +0000 | [diff] [blame] | 382 | # Custom warning string (the message from git-rev-parse is inappropriate). |
Edward Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 383 | sys.stderr.write('warning: unknown revision \'%s\'.\n' % c) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 384 | |
Edward Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 385 | return hyper_blame(outbuf, ignored, filename, args.revision) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 386 | |
| 387 | |
| 388 | if __name__ == '__main__': # pragma: no cover |
mgiuca@chromium.org | 63906ba | 2016-04-29 01:43:32 +0000 | [diff] [blame] | 389 | setup_color.init() |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 390 | with git_common.less() as less_input: |
Edward Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 391 | sys.exit(main(sys.argv[1:], less_input)) |