blob: bb2813175c9632fdc2c67fdbb811f48dd45ddf21 [file] [log] [blame]
Kuang-che Wu6e4beca2018-06-27 17:45:02 +08001# -*- coding: utf-8 -*-
Kuang-che Wue41e0062017-09-01 19:04:14 +08002# Copyright 2017 The Chromium OS 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"""Git utility."""
6
7from __future__ import print_function
8import logging
Kuang-che Wubfc4a642018-04-19 11:54:08 +08009import os
Kuang-che Wue41e0062017-09-01 19:04:14 +080010import re
11import subprocess
12
13from bisect_kit import cli
14from bisect_kit import util
15
16logger = logging.getLogger(__name__)
17
18GIT_FULL_COMMIT_ID_LENGTH = 40
19
20# Minimal acceptable length of git commit id.
21#
22# For chromium, hash collision rate over number of digits:
23# - 6 digits: 4.85%
24# - 7 digits: 0.32%
25# - 8 digits: 0.01%
26# As foolproof check, 7 digits should be enough.
27GIT_MIN_COMMIT_ID_LENGTH = 7
28
29
30def is_git_rev(s):
31 """Is a git hash-like version string.
32
33 It accepts shortened hash with at least 7 digits.
34 """
35 if not GIT_MIN_COMMIT_ID_LENGTH <= len(s) <= GIT_FULL_COMMIT_ID_LENGTH:
36 return False
37 return bool(re.match(r'^[0-9a-f]+$', s))
38
39
40def argtype_git_rev(s):
41 """Validates git hash."""
42 if not is_git_rev(s):
43 msg = 'should be git hash, at least %d digits' % GIT_MIN_COMMIT_ID_LENGTH
44 raise cli.ArgTypeError(msg, '1a2b3c4d5e')
45 return s
46
47
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080048def is_git_root(path):
49 """Is given path root of git repo."""
50 return os.path.exists(os.path.join(path, '.git'))
51
52
Kuang-che Wue41e0062017-09-01 19:04:14 +080053def checkout_version(git_repo, rev):
54 """git checkout.
55
56 Args:
57 git_repo: path of git repo.
58 rev: git commit revision to checkout.
59 """
60 util.check_call('git', 'checkout', '-q', '-f', rev, cwd=git_repo)
61
62
63def is_containing_commit(git_repo, rev):
64 """Determines given commit exists.
65
66 Args:
67 git_repo: path of git repo.
68 rev: git commit revision in query.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080069
70 Returns:
71 True if rev is inside given git repo. If git_repo is not a git folder,
72 returns False as well.
Kuang-che Wue41e0062017-09-01 19:04:14 +080073 """
74 try:
75 return util.check_output(
76 'git', 'cat-file', '-t', rev, cwd=git_repo) == 'commit\n'
77 except subprocess.CalledProcessError:
78 return False
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080079 except OSError:
80 return False
Kuang-che Wue41e0062017-09-01 19:04:14 +080081
82
Kuang-che Wubfc4a642018-04-19 11:54:08 +080083def is_ancestor_commit(git_repo, old, new):
84 """Determines `old` commit is ancestor of `new` commit.
85
86 Args:
87 git_repo: path of git repo.
88 old: the ancestor commit.
89 new: the descendant commit.
90
91 Returns:
92 True only if `old` is the ancestor of `new`. One commit is not considered
93 as ancestor of itself.
94 """
95 return util.check_output(
96 'git',
97 'rev-list',
98 '--ancestry-path',
99 '-1',
100 '%s..%s' % (old, new),
101 cwd=git_repo) != ''
102
103
Kuang-che Wue41e0062017-09-01 19:04:14 +0800104def get_revlist(git_repo, old, new):
105 """Enumerates git commit between two revisions (inclusive).
106
107 Args:
108 git_repo: path of git repo.
109 old: git commit revision.
110 new: git commit revision.
111
112 Returns:
113 list of git revisions. The list contains the input revisions, old and new.
114 """
115 assert old
116 assert new
117 cmd = ['git', 'rev-list', '--reverse', '%s^..%s' % (old, new)]
118 revlist = util.check_output(*cmd, cwd=git_repo).splitlines()
119 return revlist
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800120
121
122def get_commit_log(git_repo, rev):
123 """Get git commit log.
124
125 Args:
126 git_repo: path of git repo.
127 rev: git commit revision.
128
129 Returns:
130 commit log message
131 """
132 cmd = ['git', 'log', '-1', '--format=%B', rev]
133 msg = util.check_output(*cmd, cwd=git_repo)
134 return msg
135
136
Kuang-che Wu68db08a2018-03-30 11:50:34 +0800137def get_commit_hash(git_repo, rev):
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800138 """Get git commit hash.
139
140 Args:
141 git_repo: path of git repo.
142 rev: could be git tag, branch, or (shortened) commit hash
143
144 Returns:
145 full git commit hash
146 """
147 cmd = ['git', 'rev-parse', rev]
Kuang-che Wu68db08a2018-03-30 11:50:34 +0800148 git_rev = util.check_output(*cmd, cwd=git_repo).strip()
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800149 assert git_rev
150 return git_rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800151
152
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800153def get_commit_time(git_repo, rev, path):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800154 """Get git commit timestamp.
155
156 Args:
157 git_repo: path of git repo
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800158 rev: git commit id, branch name, tag name, or other git object
159 path: path, relative to git_repo
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800160
161 Returns:
162 timestamp (int)
163 """
164 line = util.check_output(
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800165 'git', 'log', '-1', '--format=%ct', rev, '--', path, cwd=git_repo)
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800166 return int(line)
167
168
169def get_file_from_revision(git_repo, rev, path):
170 """Get file content of given revision.
171
172 Args:
173 git_repo: path of git repo
174 rev: git commit id
175 path: file path
176
177 Returns:
178 file content (str)
179 """
180 return util.check_output(
181 'git', 'show', '%s:%s' % (rev, path), cwd=git_repo, log_output=False)
182
183
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800184def list_dir_from_revision(git_repo, rev, path):
185 """Lists entries of directory of given revision.
186
187 Args:
188 git_repo: path of git repo
189 rev: git commit id
190 path: directory path, relative to git root
191
192 Returns:
193 list of names
194
195 Raises:
196 subprocess.CalledProcessError: if `path` doesn't exists in `rev`
197 """
198 return util.check_output(
199 'git',
200 'ls-tree',
201 '--name-only',
202 '%s:%s' % (rev, path),
203 cwd=git_repo,
204 log_output=False).splitlines()
205
206
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800207def get_rev_by_time(git_repo, timestamp, path=None, branch='HEAD'):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800208 """Query commit of given time.
209
210 Args:
211 git_repo: path of git repo.
212 timestamp: timestamp
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800213 path: only query history of path, relative to git_repo
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800214 branch: only the selected subset of history to query. If branch name is
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800215 specified, only parent of the said branch is queried. If omitted, only
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800216 queries the parent of HEAD.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800217
218 Returns:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800219 git commit hash. None if path didn't exist at the given time.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800220 """
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800221
222 cmd = [
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800223 'git',
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800224 'rev-list',
225 '--first-parent',
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800226 '-1',
227 '--before',
228 str(timestamp),
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800229 branch,
230 ]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800231 if path:
232 cmd += ['--', path]
233
234 result = util.check_output(*cmd, cwd=git_repo).strip()
235 return result or None
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800236
237
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800238def get_history(git_repo, path, after=None, before=None, padding=False):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800239 """Get commit history of given path.
240
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800241 `after` and `before` could be outside of lifetime of `path`. `padding` is
242 used to control what to return for such cases.
243
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800244 Args:
245 git_repo: path of git repo.
246 path: path to query, relative to git_repo
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800247 after: limit history after given time (inclusive)
248 before: limit history before given time (inclusive)
249 padding: If True, pads returned result with dummy record at exact 'after'
250 and 'before' time, if 'path' existed at that time. Otherwise, only
251 returns real commits.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800252
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800253 Returns:
254 List of (timestamp, git hash); They are all events when `path` was added,
255 removed, modified, and start and end time if `padding` is true.
256
257 For each pair, at `timestamp`, the repo state is `git hash`. In other
258 words, `timestamp` is not necessary the commit time of `git hash` for the
259 padded entries.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800260 """
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800261 cmd = ['git', 'log', '--reverse', '--first-parent', '--format=%ct %H']
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800262 if after:
263 cmd += ['--after', str(after)]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800264 if before:
265 cmd += ['--before', str(before)]
266 # '--' is necessary otherwise if `path` is removed in current revision, git
267 # will complain it's an ambiguous argument which may be path or something
268 # else (like git branch name, tag name, etc.)
269 cmd += ['--', path]
270
271 result = []
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800272 for line in util.check_output(*cmd, cwd=git_repo).splitlines():
273 commit_time, git_rev = line.split()
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800274 result.append((int(commit_time), git_rev))
275
276 if padding:
277 assert before or after, "padding=True make no sense if they are both None"
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800278 if before is not None and get_rev_by_time(git_repo, before, path=path):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800279 before = int(before)
280 if not result or result[-1][0] != before:
281 git_rev = get_rev_by_time(git_repo, before)
282 assert git_rev
283 result.append((before, git_rev))
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800284 if after is not None and get_rev_by_time(git_repo, after, path=path):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800285 after = int(after)
286 if not result or result[0][0] != after:
287 git_rev = get_rev_by_time(git_repo, after)
288 assert git_rev
289 result.insert(0, (after, git_rev))
290
291 return result
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800292
293
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800294def get_history_recursively(git_repo, path, after, before, parser_callback):
295 """Get commit history of given path and its dependencies.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800296
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800297 In comparison to get_history(), get_history_recursively also takes
298 dependencies into consideration. For example, if file A referenced file B,
299 get_history_recursively(A) will return commits of B in addition to A. This
300 applies recursively, so commits of C will be included if file B referenced
301 file C, and so on.
302
303 This function is file type neutral. `parser_callback(filename, content)` will
304 be invoked to parse file content and should return list of filename of
305 dependencies.
306
307 Args:
308 git_repo: path of git repo
309 path: path to query, relative to git_repo
310 after: limit history after given time (inclusive)
311 before: limit history before given time (inclusive)
312 parser_callback: callback to parse file content. See above comment.
313
314 Returns:
315 list of (commit timestamp, git hash)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800316 """
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800317 history = get_history(
318 git_repo, path, after=after, before=before, padding=True)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800319
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800320 # Collect include information of each commit.
321 includes = {}
322 for commit_time, git_rev in history:
323 content = get_file_from_revision(git_repo, git_rev, path)
324 for include_name in parser_callback(path, content):
325 if include_name not in includes:
326 includes[include_name] = set()
327 includes[include_name].add(git_rev)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800328
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800329 # Analyze the start time and end time of each include.
330 dependencies = []
331 for include in includes:
332 appeared = None
333 for commit_time, git_rev in history:
334 if git_rev in includes[include]:
335 if not appeared:
336 appeared = commit_time
337 else:
338 if appeared:
339 dependencies.append((include, appeared, commit_time))
340 appeared = None
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800341
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800342 if appeared is not None:
343 dependencies.append((include, appeared, before))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800344
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800345 # Recursion and merge.
346 result = list(history)
347 for include, appeared, disappeared in dependencies:
348 result += get_history_recursively(git_repo, include, appeared, disappeared,
349 parser_callback)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800350
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800351 # Sort and dedup.
352 result2 = []
353 for x in sorted(result):
354 if result2 and result2[-1] == x:
355 continue
356 result2.append(x)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800357
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800358 return result2
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800359
360
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800361def list_commits_between_commits(git_repo, old, new):
362 """Get all commits between (old, new].
363
364 Args:
365 git_repo: path of git repo.
366 old: old commit hash (exclusive)
367 new: new commit hash (inclusive)
368
369 Returns:
370 list of (timestamp, rev)
371 """
372 assert old and new
373 assert old == new or is_ancestor_commit(git_repo, old, new)
374 commits = []
375 # --first-parent is necessary for Android, see following link for more
376 # discussion.
377 # https://docs.google.com/document/d/1c8qiq14_ObRRjLT62sk9r5V5cyCGHX66dLYab4MVnks/edit#heading=h.n3i6mt2n6xuu
378 for line in util.check_output(
379 'git',
380 'rev-list',
381 '--timestamp',
382 '--reverse',
383 '--first-parent',
384 '%s..%s' % (old, new),
385 cwd=git_repo).splitlines():
386 timestamp, git_rev = line.split()
387 commits.append([int(timestamp), git_rev])
388
389 # bisect-kit has a fundamental assumption that commit timestamps are
390 # increasing because we sort and bisect the commits by timestamp across git
391 # repos. If not increasing, we have to adjust the timestamp as workaround.
392 # This might lead to bad bisect result, however the bad probability is low in
393 # practice since most machines' clocks are good enough.
394 if commits != sorted(commits, key=lambda x: x[0]):
395 logger.warning('Commit timestamps are not increasing')
396 last_timestamp = -1
397 adjusted = 0
398 for commit in commits:
399 if commit[0] < last_timestamp:
400 commit[0] = last_timestamp
401 adjusted += 1
402
403 last_timestamp = commit[0]
404 logger.warning('%d timestamps adjusted', adjusted)
405
406 return commits