blob: fb3c84c18bee6e3188e8d4377ed65221e68dd8b6 [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 Wu6948ecc2018-09-11 17:43:49 +080053def clone(git_repo, repo_url, reference=None):
54 if not os.path.exists(git_repo):
55 os.makedirs(git_repo)
56 cmd = ['git', 'clone', repo_url, '.']
57 if reference:
58 cmd += ['--reference', reference]
59 util.check_call(*cmd, cwd=git_repo)
60
61
Kuang-che Wue41e0062017-09-01 19:04:14 +080062def checkout_version(git_repo, rev):
63 """git checkout.
64
65 Args:
66 git_repo: path of git repo.
67 rev: git commit revision to checkout.
68 """
69 util.check_call('git', 'checkout', '-q', '-f', rev, cwd=git_repo)
70
71
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +080072def init(git_repo):
73 """git init.
74
75 git_repo and its parent directories will be created if they don't exist.
76
77 Args:
78 git_repo: path of git repo.
79 """
80 if not os.path.exists(git_repo):
81 os.makedirs(git_repo)
82
83 util.check_call('git', 'init', '-q', cwd=git_repo)
84
85
86def commit_file(git_repo,
87 path,
88 message,
89 content,
90 commit_time=None,
91 author_time=None):
92 """Commit a file.
93
94 Args:
95 git_repo: path of git repo
96 path: file path, relative to git_repo
97 message: commit message
98 content: file content
99 commit_time: commit timestamp
100 author_time: author timestamp
101 """
102 if author_time is None:
103 author_time = commit_time
104
105 env = {}
106 if author_time:
107 env['GIT_AUTHOR_DATE'] = str(author_time)
108 if commit_time:
109 env['GIT_COMMITTER_DATE'] = str(commit_time)
110
111 full_path = os.path.join(git_repo, path)
112 dirname = os.path.dirname(full_path)
113 if not os.path.exists(dirname):
114 os.makedirs(dirname)
115 with open(full_path, 'w') as f:
116 f.write(content)
117
118 util.check_call('git', 'add', path, cwd=git_repo)
119 util.check_call(
120 'git', 'commit', '-q', '-m', message, path, cwd=git_repo, env=env)
121
122
Kuang-che Wue41e0062017-09-01 19:04:14 +0800123def is_containing_commit(git_repo, rev):
124 """Determines given commit exists.
125
126 Args:
127 git_repo: path of git repo.
128 rev: git commit revision in query.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800129
130 Returns:
131 True if rev is inside given git repo. If git_repo is not a git folder,
132 returns False as well.
Kuang-che Wue41e0062017-09-01 19:04:14 +0800133 """
134 try:
135 return util.check_output(
136 'git', 'cat-file', '-t', rev, cwd=git_repo) == 'commit\n'
137 except subprocess.CalledProcessError:
138 return False
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800139 except OSError:
140 return False
Kuang-che Wue41e0062017-09-01 19:04:14 +0800141
142
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800143def is_ancestor_commit(git_repo, old, new):
144 """Determines `old` commit is ancestor of `new` commit.
145
146 Args:
147 git_repo: path of git repo.
148 old: the ancestor commit.
149 new: the descendant commit.
150
151 Returns:
152 True only if `old` is the ancestor of `new`. One commit is not considered
153 as ancestor of itself.
154 """
155 return util.check_output(
156 'git',
157 'rev-list',
158 '--ancestry-path',
159 '-1',
160 '%s..%s' % (old, new),
161 cwd=git_repo) != ''
162
163
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800164def get_commit_metadata(git_repo, rev):
165 """Get metadata of given commit.
166
167 Args:
168 git_repo: path of git repo.
169 rev: git commit revision in query.
170
171 Returns:
172 dict of metadata, including (if available):
173 tree: hash of git tree object
174 parent: list of parent commits; this field is unavailable for the very
175 first commit of git repo.
176 author: name and email of author
177 author_time: author timestamp (without timezone information)
178 committer: name and email of committer
179 committer_time: commit timestamp (without timezone information)
180 message: commit message text
181 """
182 meta = {}
183 data = util.check_output(
184 'git', 'cat-file', '-p', rev, cwd=git_repo, log_output=False)
185 header, meta['message'] = data.split('\n\n', 1)
186 for line in header.splitlines():
187 m = re.match(r'^tree (\w+)', line)
188 if m:
189 meta['tree'] = m.group(1)
190 continue
191
192 m = re.match(r'^parent (\w+)', line)
193 if m:
194 meta['parent'] = line.split()[1:]
195 continue
196
197 m = re.match(r'^(author|committer) (.*) (\d+) (\S+)$', line)
198 if m:
199 meta[m.group(1)] = m.group(2)
200 meta['%s_time' % m.group(1)] = int(m.group(3))
201 continue
202 return meta
203
204
Kuang-che Wue41e0062017-09-01 19:04:14 +0800205def get_revlist(git_repo, old, new):
206 """Enumerates git commit between two revisions (inclusive).
207
208 Args:
209 git_repo: path of git repo.
210 old: git commit revision.
211 new: git commit revision.
212
213 Returns:
214 list of git revisions. The list contains the input revisions, old and new.
215 """
216 assert old
217 assert new
218 cmd = ['git', 'rev-list', '--reverse', '%s^..%s' % (old, new)]
219 revlist = util.check_output(*cmd, cwd=git_repo).splitlines()
220 return revlist
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800221
222
223def get_commit_log(git_repo, rev):
224 """Get git commit log.
225
226 Args:
227 git_repo: path of git repo.
228 rev: git commit revision.
229
230 Returns:
231 commit log message
232 """
233 cmd = ['git', 'log', '-1', '--format=%B', rev]
234 msg = util.check_output(*cmd, cwd=git_repo)
235 return msg
236
237
Kuang-che Wu68db08a2018-03-30 11:50:34 +0800238def get_commit_hash(git_repo, rev):
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800239 """Get git commit hash.
240
241 Args:
242 git_repo: path of git repo.
243 rev: could be git tag, branch, or (shortened) commit hash
244
245 Returns:
246 full git commit hash
247 """
248 cmd = ['git', 'rev-parse', rev]
Kuang-che Wu68db08a2018-03-30 11:50:34 +0800249 git_rev = util.check_output(*cmd, cwd=git_repo).strip()
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800250 assert git_rev
251 return git_rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800252
253
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800254def get_commit_time(git_repo, rev, path):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800255 """Get git commit timestamp.
256
257 Args:
258 git_repo: path of git repo
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800259 rev: git commit id, branch name, tag name, or other git object
260 path: path, relative to git_repo
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800261
262 Returns:
263 timestamp (int)
264 """
265 line = util.check_output(
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800266 'git', 'log', '-1', '--format=%ct', rev, '--', path, cwd=git_repo)
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800267 return int(line)
268
269
270def get_file_from_revision(git_repo, rev, path):
271 """Get file content of given revision.
272
273 Args:
274 git_repo: path of git repo
275 rev: git commit id
276 path: file path
277
278 Returns:
279 file content (str)
280 """
281 return util.check_output(
282 'git', 'show', '%s:%s' % (rev, path), cwd=git_repo, log_output=False)
283
284
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800285def list_dir_from_revision(git_repo, rev, path):
286 """Lists entries of directory of given revision.
287
288 Args:
289 git_repo: path of git repo
290 rev: git commit id
291 path: directory path, relative to git root
292
293 Returns:
294 list of names
295
296 Raises:
297 subprocess.CalledProcessError: if `path` doesn't exists in `rev`
298 """
299 return util.check_output(
300 'git',
301 'ls-tree',
302 '--name-only',
303 '%s:%s' % (rev, path),
304 cwd=git_repo,
305 log_output=False).splitlines()
306
307
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800308def get_rev_by_time(git_repo, timestamp, branch, path=None):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800309 """Query commit of given time.
310
311 Args:
312 git_repo: path of git repo.
313 timestamp: timestamp
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800314 branch: only query parent of the `branch`. If branch=None, it means 'HEAD'
315 (current branch, usually).
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800316 path: only query history of path, relative to git_repo
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800317
318 Returns:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800319 git commit hash. None if path didn't exist at the given time.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800320 """
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800321 if not branch:
322 branch = 'HEAD'
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800323
324 cmd = [
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800325 'git',
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800326 'rev-list',
327 '--first-parent',
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800328 '-1',
329 '--before',
330 str(timestamp),
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800331 branch,
332 ]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800333 if path:
334 cmd += ['--', path]
335
336 result = util.check_output(*cmd, cwd=git_repo).strip()
337 return result or None
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800338
339
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800340def get_history(git_repo,
341 path,
342 branch=None,
343 after=None,
344 before=None,
345 padding=False):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800346 """Get commit history of given path.
347
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800348 `after` and `before` could be outside of lifetime of `path`. `padding` is
349 used to control what to return for such cases.
350
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800351 Args:
352 git_repo: path of git repo.
353 path: path to query, relative to git_repo
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800354 branch: branch name or ref name
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800355 after: limit history after given time (inclusive)
356 before: limit history before given time (inclusive)
357 padding: If True, pads returned result with dummy record at exact 'after'
358 and 'before' time, if 'path' existed at that time. Otherwise, only
359 returns real commits.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800360
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800361 Returns:
362 List of (timestamp, git hash); They are all events when `path` was added,
363 removed, modified, and start and end time if `padding` is true.
364
365 For each pair, at `timestamp`, the repo state is `git hash`. In other
366 words, `timestamp` is not necessary the commit time of `git hash` for the
367 padded entries.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800368 """
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800369 cmd = ['git', 'log', '--reverse', '--first-parent', '--format=%ct %H']
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800370 if after:
371 cmd += ['--after', str(after)]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800372 if before:
373 cmd += ['--before', str(before)]
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800374 if branch:
375 assert not is_git_rev(branch)
376 cmd += [branch]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800377 # '--' is necessary otherwise if `path` is removed in current revision, git
378 # will complain it's an ambiguous argument which may be path or something
379 # else (like git branch name, tag name, etc.)
380 cmd += ['--', path]
381
382 result = []
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800383 for line in util.check_output(*cmd, cwd=git_repo).splitlines():
384 commit_time, git_rev = line.split()
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800385 result.append((int(commit_time), git_rev))
386
387 if padding:
388 assert before or after, "padding=True make no sense if they are both None"
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800389 if before is not None and get_rev_by_time(
390 git_repo, before, branch, path=path):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800391 before = int(before)
392 if not result or result[-1][0] != before:
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800393 git_rev = get_rev_by_time(git_repo, before, branch)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800394 assert git_rev
395 result.append((before, git_rev))
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800396 if after is not None and get_rev_by_time(
397 git_repo, after, branch, path=path):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800398 after = int(after)
399 if not result or result[0][0] != after:
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800400 git_rev = get_rev_by_time(git_repo, after, branch)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800401 assert git_rev
402 result.insert(0, (after, git_rev))
403
404 return result
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800405
406
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800407def get_history_recursively(git_repo, path, after, before, parser_callback):
408 """Get commit history of given path and its dependencies.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800409
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800410 In comparison to get_history(), get_history_recursively also takes
411 dependencies into consideration. For example, if file A referenced file B,
412 get_history_recursively(A) will return commits of B in addition to A. This
413 applies recursively, so commits of C will be included if file B referenced
414 file C, and so on.
415
416 This function is file type neutral. `parser_callback(filename, content)` will
417 be invoked to parse file content and should return list of filename of
418 dependencies.
419
420 Args:
421 git_repo: path of git repo
422 path: path to query, relative to git_repo
423 after: limit history after given time (inclusive)
424 before: limit history before given time (inclusive)
425 parser_callback: callback to parse file content. See above comment.
426
427 Returns:
428 list of (commit timestamp, git hash)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800429 """
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800430 history = get_history(
431 git_repo, path, after=after, before=before, padding=True)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800432
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800433 # Collect include information of each commit.
434 includes = {}
435 for commit_time, git_rev in history:
436 content = get_file_from_revision(git_repo, git_rev, path)
437 for include_name in parser_callback(path, content):
438 if include_name not in includes:
439 includes[include_name] = set()
440 includes[include_name].add(git_rev)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800441
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800442 # Analyze the start time and end time of each include.
443 dependencies = []
444 for include in includes:
445 appeared = None
446 for commit_time, git_rev in history:
447 if git_rev in includes[include]:
448 if not appeared:
449 appeared = commit_time
450 else:
451 if appeared:
452 dependencies.append((include, appeared, commit_time))
453 appeared = None
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800454
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800455 if appeared is not None:
456 dependencies.append((include, appeared, before))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800457
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800458 # Recursion and merge.
459 result = list(history)
460 for include, appeared, disappeared in dependencies:
461 result += get_history_recursively(git_repo, include, appeared, disappeared,
462 parser_callback)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800463
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800464 # Sort and dedup.
465 result2 = []
466 for x in sorted(result):
467 if result2 and result2[-1] == x:
468 continue
469 result2.append(x)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800470
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800471 return result2
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800472
473
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800474def list_commits_between_commits(git_repo, old, new):
475 """Get all commits between (old, new].
476
477 Args:
478 git_repo: path of git repo.
479 old: old commit hash (exclusive)
480 new: new commit hash (inclusive)
481
482 Returns:
483 list of (timestamp, rev)
484 """
485 assert old and new
486 assert old == new or is_ancestor_commit(git_repo, old, new)
487 commits = []
488 # --first-parent is necessary for Android, see following link for more
489 # discussion.
490 # https://docs.google.com/document/d/1c8qiq14_ObRRjLT62sk9r5V5cyCGHX66dLYab4MVnks/edit#heading=h.n3i6mt2n6xuu
491 for line in util.check_output(
492 'git',
493 'rev-list',
494 '--timestamp',
495 '--reverse',
496 '--first-parent',
497 '%s..%s' % (old, new),
498 cwd=git_repo).splitlines():
499 timestamp, git_rev = line.split()
500 commits.append([int(timestamp), git_rev])
501
502 # bisect-kit has a fundamental assumption that commit timestamps are
503 # increasing because we sort and bisect the commits by timestamp across git
504 # repos. If not increasing, we have to adjust the timestamp as workaround.
505 # This might lead to bad bisect result, however the bad probability is low in
506 # practice since most machines' clocks are good enough.
507 if commits != sorted(commits, key=lambda x: x[0]):
508 logger.warning('Commit timestamps are not increasing')
509 last_timestamp = -1
510 adjusted = 0
511 for commit in commits:
512 if commit[0] < last_timestamp:
513 commit[0] = last_timestamp
514 adjusted += 1
515
516 last_timestamp = commit[0]
517 logger.warning('%d timestamps adjusted', adjusted)
518
519 return commits