blob: 51b2bdd67adfca82f2afd5fea1ff4dfa744b1a6f [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
Kuang-che Wu3d04eda2019-09-05 23:56:40 +080011import shutil
Zheng-Jie Chang29144442020-02-18 11:53:25 +080012import stat
Kuang-che Wue41e0062017-09-01 19:04:14 +080013import subprocess
Kuang-che Wu2b1286b2019-05-20 20:37:26 +080014import time
Kuang-che Wue41e0062017-09-01 19:04:14 +080015
16from bisect_kit import cli
17from bisect_kit import util
18
19logger = logging.getLogger(__name__)
20
21GIT_FULL_COMMIT_ID_LENGTH = 40
22
23# Minimal acceptable length of git commit id.
24#
25# For chromium, hash collision rate over number of digits:
26# - 6 digits: 4.85%
27# - 7 digits: 0.32%
28# - 8 digits: 0.01%
29# As foolproof check, 7 digits should be enough.
30GIT_MIN_COMMIT_ID_LENGTH = 7
31
32
33def is_git_rev(s):
34 """Is a git hash-like version string.
35
36 It accepts shortened hash with at least 7 digits.
37 """
38 if not GIT_MIN_COMMIT_ID_LENGTH <= len(s) <= GIT_FULL_COMMIT_ID_LENGTH:
39 return False
40 return bool(re.match(r'^[0-9a-f]+$', s))
41
42
43def argtype_git_rev(s):
44 """Validates git hash."""
45 if not is_git_rev(s):
46 msg = 'should be git hash, at least %d digits' % GIT_MIN_COMMIT_ID_LENGTH
47 raise cli.ArgTypeError(msg, '1a2b3c4d5e')
48 return s
49
50
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080051def is_git_root(path):
52 """Is given path root of git repo."""
53 return os.path.exists(os.path.join(path, '.git'))
54
55
Kuang-che Wu08366542019-01-12 12:37:49 +080056def is_git_bare_dir(path):
57 """Is inside .git folder or bare git checkout."""
58 if not os.path.isdir(path):
59 return False
60 try:
61 return util.check_output(
62 'git', 'rev-parse', '--is-bare-repository', cwd=path) == 'true\n'
63 except subprocess.CalledProcessError:
64 return False
65
66
Kuang-che Wu6948ecc2018-09-11 17:43:49 +080067def clone(git_repo, repo_url, reference=None):
68 if not os.path.exists(git_repo):
69 os.makedirs(git_repo)
70 cmd = ['git', 'clone', repo_url, '.']
71 if reference:
72 cmd += ['--reference', reference]
73 util.check_call(*cmd, cwd=git_repo)
74
75
Kuang-che Wue41e0062017-09-01 19:04:14 +080076def checkout_version(git_repo, rev):
77 """git checkout.
78
79 Args:
80 git_repo: path of git repo.
81 rev: git commit revision to checkout.
82 """
83 util.check_call('git', 'checkout', '-q', '-f', rev, cwd=git_repo)
84
85
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +080086def init(git_repo):
87 """git init.
88
89 git_repo and its parent directories will be created if they don't exist.
90
91 Args:
92 git_repo: path of git repo.
93 """
94 if not os.path.exists(git_repo):
95 os.makedirs(git_repo)
96
97 util.check_call('git', 'init', '-q', cwd=git_repo)
98
99
100def commit_file(git_repo,
101 path,
102 message,
103 content,
104 commit_time=None,
105 author_time=None):
106 """Commit a file.
107
108 Args:
109 git_repo: path of git repo
110 path: file path, relative to git_repo
111 message: commit message
112 content: file content
113 commit_time: commit timestamp
114 author_time: author timestamp
115 """
116 if author_time is None:
117 author_time = commit_time
118
119 env = {}
120 if author_time:
121 env['GIT_AUTHOR_DATE'] = str(author_time)
122 if commit_time:
123 env['GIT_COMMITTER_DATE'] = str(commit_time)
124
125 full_path = os.path.join(git_repo, path)
126 dirname = os.path.dirname(full_path)
127 if not os.path.exists(dirname):
128 os.makedirs(dirname)
129 with open(full_path, 'w') as f:
130 f.write(content)
131
132 util.check_call('git', 'add', path, cwd=git_repo)
133 util.check_call(
134 'git', 'commit', '-q', '-m', message, path, cwd=git_repo, env=env)
135
136
Kuang-che Wu1e49f512018-12-06 15:27:42 +0800137def config(git_repo, *args):
138 """Wrapper of 'git config'.
139
140 Args:
141 git_repo: path of git repo.
142 args: parameters pass to 'git config'
143 """
144 util.check_call('git', 'config', *args, cwd=git_repo)
145
146
147def fetch(git_repo, *args):
Kuang-che Wu2b1286b2019-05-20 20:37:26 +0800148 """Wrapper of 'git fetch' with retry support.
Kuang-che Wu1e49f512018-12-06 15:27:42 +0800149
150 Args:
151 git_repo: path of git repo.
152 args: parameters pass to 'git fetch'
153 """
Kuang-che Wu2b1286b2019-05-20 20:37:26 +0800154 for tries in range(5):
155 if tries > 0:
156 delay = min(60, 10 * 2**tries)
157 logger.warning('git fetch failed, will retry %s seconds later', delay)
158 time.sleep(delay)
159
160 stderr_lines = []
161 try:
162 util.check_call(
163 'git',
164 'fetch',
165 *args,
166 cwd=git_repo,
167 stderr_callback=stderr_lines.append)
168 break
169 except subprocess.CalledProcessError:
170 stderr = ''.join(stderr_lines)
171 # only retry 5xx internal server error
172 if 'The requested URL returned error: 5' not in stderr:
173 raise
174 else:
175 # Reached retry limit but haven't succeeded.
176 # In other words, there must be exceptions raised inside above loop.
177 logger.error('git fetch failed too much times')
178 # It's okay to raise because we are in the same scope as above loop.
179 # pylint: disable=misplaced-bare-raise
180 raise
Kuang-che Wu1e49f512018-12-06 15:27:42 +0800181
182
Kuang-che Wue41e0062017-09-01 19:04:14 +0800183def is_containing_commit(git_repo, rev):
184 """Determines given commit exists.
185
186 Args:
187 git_repo: path of git repo.
188 rev: git commit revision in query.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800189
190 Returns:
191 True if rev is inside given git repo. If git_repo is not a git folder,
192 returns False as well.
Kuang-che Wue41e0062017-09-01 19:04:14 +0800193 """
194 try:
195 return util.check_output(
196 'git', 'cat-file', '-t', rev, cwd=git_repo) == 'commit\n'
197 except subprocess.CalledProcessError:
198 return False
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800199 except OSError:
200 return False
Kuang-che Wue41e0062017-09-01 19:04:14 +0800201
202
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800203def is_ancestor_commit(git_repo, old, new):
204 """Determines `old` commit is ancestor of `new` commit.
205
206 Args:
207 git_repo: path of git repo.
208 old: the ancestor commit.
209 new: the descendant commit.
210
211 Returns:
212 True only if `old` is the ancestor of `new`. One commit is not considered
213 as ancestor of itself.
214 """
215 return util.check_output(
216 'git',
217 'rev-list',
218 '--ancestry-path',
219 '-1',
220 '%s..%s' % (old, new),
221 cwd=git_repo) != ''
222
223
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800224def get_commit_metadata(git_repo, rev):
225 """Get metadata of given commit.
226
227 Args:
228 git_repo: path of git repo.
229 rev: git commit revision in query.
230
231 Returns:
232 dict of metadata, including (if available):
233 tree: hash of git tree object
234 parent: list of parent commits; this field is unavailable for the very
235 first commit of git repo.
236 author: name and email of author
237 author_time: author timestamp (without timezone information)
238 committer: name and email of committer
239 committer_time: commit timestamp (without timezone information)
240 message: commit message text
241 """
242 meta = {}
243 data = util.check_output(
Kuang-che Wubcafc552019-08-15 15:27:02 +0800244 'git', 'cat-file', '-p', rev, cwd=git_repo, log_stdout=False)
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800245 header, meta['message'] = data.split('\n\n', 1)
246 for line in header.splitlines():
247 m = re.match(r'^tree (\w+)', line)
248 if m:
249 meta['tree'] = m.group(1)
250 continue
251
252 m = re.match(r'^parent (\w+)', line)
253 if m:
254 meta['parent'] = line.split()[1:]
255 continue
256
257 m = re.match(r'^(author|committer) (.*) (\d+) (\S+)$', line)
258 if m:
259 meta[m.group(1)] = m.group(2)
260 meta['%s_time' % m.group(1)] = int(m.group(3))
261 continue
262 return meta
263
264
Kuang-che Wue41e0062017-09-01 19:04:14 +0800265def get_revlist(git_repo, old, new):
266 """Enumerates git commit between two revisions (inclusive).
267
268 Args:
269 git_repo: path of git repo.
270 old: git commit revision.
271 new: git commit revision.
272
273 Returns:
274 list of git revisions. The list contains the input revisions, old and new.
275 """
276 assert old
277 assert new
278 cmd = ['git', 'rev-list', '--reverse', '%s^..%s' % (old, new)]
279 revlist = util.check_output(*cmd, cwd=git_repo).splitlines()
280 return revlist
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800281
282
283def get_commit_log(git_repo, rev):
284 """Get git commit log.
285
286 Args:
287 git_repo: path of git repo.
288 rev: git commit revision.
289
290 Returns:
291 commit log message
292 """
293 cmd = ['git', 'log', '-1', '--format=%B', rev]
294 msg = util.check_output(*cmd, cwd=git_repo)
295 return msg
296
297
Kuang-che Wu68db08a2018-03-30 11:50:34 +0800298def get_commit_hash(git_repo, rev):
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800299 """Get git commit hash.
300
301 Args:
302 git_repo: path of git repo.
303 rev: could be git tag, branch, or (shortened) commit hash
304
305 Returns:
306 full git commit hash
Kuang-che Wu5e7c9b02019-01-03 21:16:01 +0800307
308 Raises:
309 ValueError: `rev` is not unique or doesn't exist
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800310 """
Kuang-che Wu5e7c9b02019-01-03 21:16:01 +0800311 try:
312 # Use '^{commit}' to restrict search only commits.
313 # Use '--' to avoid ambiguity, like matching rev against path name.
314 output = util.check_output(
315 'git', 'rev-parse', '%s^{commit}' % rev, '--', cwd=git_repo)
316 git_rev = output.rstrip('-\n')
317 except subprocess.CalledProcessError:
318 # Do not use 'git rev-parse --disambiguate' to determine uniqueness
319 # because it searches objects other than commits as well.
320 raise ValueError('%s is not unique or does not exist' % rev)
321 assert is_git_rev(git_rev)
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800322 return git_rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800323
324
Zheng-Jie Chang868c1752020-01-21 14:42:41 +0800325def get_commit_time(git_repo, rev, path=None):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800326 """Get git commit timestamp.
327
328 Args:
329 git_repo: path of git repo
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800330 rev: git commit id, branch name, tag name, or other git object
331 path: path, relative to git_repo
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800332
333 Returns:
334 timestamp (int)
335 """
Zheng-Jie Chang868c1752020-01-21 14:42:41 +0800336 cmd = ['git', 'log', '-1', '--format=%ct', rev]
337 if path:
338 cmd += ['--', path]
339 line = util.check_output(*cmd, cwd=git_repo)
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800340 return int(line)
341
342
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800343def is_symbolic_link(git_repo, rev, path):
344 """Check if a file is symbolic link.
345
346 Args:
347 git_repo: path of git repo
348 rev: git commit id
349 path: file path
350
351 Returns:
352 True if the specified file is a symbolic link in repo.
Zheng-Jie Chang29144442020-02-18 11:53:25 +0800353
354 Raises:
355 ValueError if not found
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800356 """
Zheng-Jie Chang29144442020-02-18 11:53:25 +0800357 # format: 120000 blob 8735a8c1dd96ede39a21d983d5c96792fd15c1a5 default.xml
358 splitted = util.check_output(
359 'git', 'ls-tree', rev, '--full-name', path, cwd=git_repo).split()
360 if len(splitted) >= 4 and splitted[3] == path:
361 return stat.S_ISLNK(int(splitted[0], 8))
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800362
363 raise ValueError(
364 'file %s is not found in repo:%s rev:%s' % (path, git_repo, rev))
365
366
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800367def get_file_from_revision(git_repo, rev, path):
368 """Get file content of given revision.
369
370 Args:
371 git_repo: path of git repo
372 rev: git commit id
373 path: file path
374
375 Returns:
376 file content (str)
377 """
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800378 result = util.check_output(
Kuang-che Wubcafc552019-08-15 15:27:02 +0800379 'git', 'show', '%s:%s' % (rev, path), cwd=git_repo, log_stdout=False)
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800380 if is_symbolic_link(git_repo, rev, path):
381 return get_file_from_revision(git_repo, rev, result)
382 return result
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800383
384
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800385def list_dir_from_revision(git_repo, rev, path):
386 """Lists entries of directory of given revision.
387
388 Args:
389 git_repo: path of git repo
390 rev: git commit id
391 path: directory path, relative to git root
392
393 Returns:
394 list of names
395
396 Raises:
397 subprocess.CalledProcessError: if `path` doesn't exists in `rev`
398 """
399 return util.check_output(
400 'git',
401 'ls-tree',
402 '--name-only',
403 '%s:%s' % (rev, path),
404 cwd=git_repo,
Kuang-che Wubcafc552019-08-15 15:27:02 +0800405 log_stdout=False).splitlines()
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800406
407
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800408def get_rev_by_time(git_repo, timestamp, branch, path=None):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800409 """Query commit of given time.
410
411 Args:
412 git_repo: path of git repo.
413 timestamp: timestamp
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800414 branch: only query parent of the `branch`. If branch=None, it means 'HEAD'
415 (current branch, usually).
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800416 path: only query history of path, relative to git_repo
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800417
418 Returns:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800419 git commit hash. None if path didn't exist at the given time.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800420 """
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800421 if not branch:
422 branch = 'HEAD'
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800423
424 cmd = [
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800425 'git',
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800426 'rev-list',
427 '--first-parent',
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800428 '-1',
429 '--before',
430 str(timestamp),
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800431 branch,
432 ]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800433 if path:
434 cmd += ['--', path]
435
436 result = util.check_output(*cmd, cwd=git_repo).strip()
437 return result or None
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800438
439
Kuang-che Wu3d04eda2019-09-05 23:56:40 +0800440def reset_hard(git_repo):
441 """Restore modified and deleted files.
442
443 This is simply wrapper of "git reset --hard".
444
445 Args:
446 git_repo: path of git repo.
447 """
448 util.check_call('git', 'reset', '--hard', cwd=git_repo)
449
450
451def list_untracked(git_repo, excludes=None):
452 """List untracked files and directories.
453
454 Args:
455 git_repo: path of git repo.
456 excludes: files and/or directories to ignore, relative to git_repo
457
458 Returns:
459 list of paths, relative to git_repo
460 """
461 exclude_flags = []
462 if excludes:
463 for exclude in excludes:
464 assert not os.path.isabs(exclude), 'should be relative'
465 exclude_flags += ['--exclude', '/' + re.escape(exclude)]
466
467 result = []
468 for path in util.check_output(
469 'git',
470 'ls-files',
471 '--others',
472 '--exclude-standard',
473 *exclude_flags,
474 cwd=git_repo).splitlines():
475 # Remove the trailing slash, which means directory.
476 path = path.rstrip('/')
477 result.append(path)
478 return result
479
480
481def distclean(git_repo, excludes=None):
482 """Clean up git repo directory.
483
484 Restore modified and deleted files. Delete untracked files.
485
486 Args:
487 git_repo: path of git repo.
488 excludes: files and/or directories to ignore, relative to git_repo
489 """
490 reset_hard(git_repo)
491
492 # Delete untracked files.
493 for untracked in list_untracked(git_repo, excludes=excludes):
494 path = os.path.join(git_repo, untracked)
495 logger.debug('delete untracked: %s', path)
496 if os.path.isdir(path):
497 shutil.rmtree(path)
498 else:
499 os.unlink(path)
500
501
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800502def get_history(git_repo,
Zheng-Jie Chang0fc704b2019-12-09 18:43:38 +0800503 path=None,
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800504 branch=None,
505 after=None,
506 before=None,
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800507 padding=False,
508 with_subject=False):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800509 """Get commit history of given path.
510
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800511 `after` and `before` could be outside of lifetime of `path`. `padding` is
512 used to control what to return for such cases.
513
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800514 Args:
515 git_repo: path of git repo.
516 path: path to query, relative to git_repo
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800517 branch: branch name or ref name
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800518 after: limit history after given time (inclusive)
519 before: limit history before given time (inclusive)
520 padding: If True, pads returned result with dummy record at exact 'after'
521 and 'before' time, if 'path' existed at that time. Otherwise, only
522 returns real commits.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800523 with_subject: If True, return commit subject together
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800524
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800525 Returns:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800526 List of (timestamp, git hash, subject); or (timestamp, git hash) depends
527 on with_subject flag. They are all events when `path` was added, removed,
528 modified, and start and end time if `padding` is true. If `padding` and
529 `with_subject` are both true, 'dummy subject' will be returned as padding
530 history's subject.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800531
532 For each pair, at `timestamp`, the repo state is `git hash`. In other
533 words, `timestamp` is not necessary the commit time of `git hash` for the
534 padded entries.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800535 """
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800536 log_format = '%ct %H' if not with_subject else '%ct %H %s'
537 cmd = ['git', 'log', '--reverse', '--first-parent', '--format=' + log_format]
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800538 if after:
539 cmd += ['--after', str(after)]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800540 if before:
541 cmd += ['--before', str(before)]
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800542 if branch:
543 assert not is_git_rev(branch)
544 cmd += [branch]
Zheng-Jie Chang0fc704b2019-12-09 18:43:38 +0800545 if path:
546 # '--' is necessary otherwise if `path` is removed in current revision, git
547 # will complain it's an ambiguous argument which may be path or something
548 # else (like git branch name, tag name, etc.)
549 cmd += ['--', path]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800550
551 result = []
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800552 for line in util.check_output(*cmd, cwd=git_repo).splitlines():
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800553 # array = [timestamp, git_rev, subject] or [timestamp, git_rev]
554 array = line.split(' ', 2)
555 array[0] = int(array[0])
556 result.append(tuple(array))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800557
558 if padding:
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800559 assert before or after, 'padding=True make no sense if they are both None'
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800560 history = [0, '']
561 if with_subject:
562 history.append('dummy subject')
563
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800564 if before is not None and get_rev_by_time(
565 git_repo, before, branch, path=path):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800566 before = int(before)
567 if not result or result[-1][0] != before:
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800568 git_rev = get_rev_by_time(git_repo, before, branch)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800569 assert git_rev
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800570 history[0:2] = [before, git_rev]
571 result.append(tuple(history))
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800572 if after is not None and get_rev_by_time(
573 git_repo, after, branch, path=path):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800574 after = int(after)
575 if not result or result[0][0] != after:
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800576 git_rev = get_rev_by_time(git_repo, after, branch)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800577 assert git_rev
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800578 history[0:2] = [after, git_rev]
579 result.insert(0, tuple(history))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800580
581 return result
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800582
583
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800584def get_history_recursively(git_repo,
585 path,
586 after,
587 before,
588 parser_callback,
589 branch=None):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800590 """Get commit history of given path and its dependencies.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800591
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800592 In comparison to get_history(), get_history_recursively also takes
593 dependencies into consideration. For example, if file A referenced file B,
594 get_history_recursively(A) will return commits of B in addition to A. This
595 applies recursively, so commits of C will be included if file B referenced
596 file C, and so on.
597
598 This function is file type neutral. `parser_callback(filename, content)` will
599 be invoked to parse file content and should return list of filename of
Kuang-che Wu7d0c7592019-09-16 09:59:28 +0800600 dependencies. If `parser_callback` returns None (usually syntax error), the
601 commit is omitted.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800602
603 Args:
604 git_repo: path of git repo
605 path: path to query, relative to git_repo
606 after: limit history after given time (inclusive)
607 before: limit history before given time (inclusive)
608 parser_callback: callback to parse file content. See above comment.
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800609 branch: branch name or ref name
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800610
611 Returns:
612 list of (commit timestamp, git hash)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800613 """
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800614 history = get_history(
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800615 git_repo, path, after=after, before=before, padding=True, branch=branch)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800616
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800617 # Collect include information of each commit.
618 includes = {}
619 for commit_time, git_rev in history:
620 content = get_file_from_revision(git_repo, git_rev, path)
Kuang-che Wu7d0c7592019-09-16 09:59:28 +0800621 parse_result = parser_callback(path, content)
622 if parse_result is None:
623 continue
624 for include_name in parse_result:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800625 if include_name not in includes:
626 includes[include_name] = set()
627 includes[include_name].add(git_rev)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800628
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800629 # Analyze the start time and end time of each include.
630 dependencies = []
631 for include in includes:
632 appeared = None
633 for commit_time, git_rev in history:
634 if git_rev in includes[include]:
635 if not appeared:
636 appeared = commit_time
637 else:
638 if appeared:
Zheng-Jie Chang4d617a42020-02-15 06:46:00 +0800639 # dependency file exists in time range [appeared, commit_time)
640 dependencies.append((include, appeared, commit_time - 1))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800641 appeared = None
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800642
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800643 if appeared is not None:
644 dependencies.append((include, appeared, before))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800645
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800646 # Recursion and merge.
647 result = list(history)
648 for include, appeared, disappeared in dependencies:
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800649 result += get_history_recursively(
650 git_repo,
651 include,
652 appeared,
653 disappeared,
654 parser_callback,
655 branch=branch)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800656
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800657 # Sort and dedup.
658 result2 = []
Kuang-che Wuebb023c2018-11-29 15:49:32 +0800659 for x in sorted(result, key=lambda x: x[0]):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800660 if result2 and result2[-1] == x:
661 continue
662 result2.append(x)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800663
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800664 return result2
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800665
666
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800667def get_branches(git_repo, all_branches=True, commit=None):
668 """Get branches of a repository.
669
670 Args:
671 git_repo: path of git repo
672 all_branches: return remote branches if is set to True
673 commit: return branches containing this commit if is not None
674
675 Returns:
676 list of branch names
677 """
678 cmd = ['git', 'branch', '--format=%(refname)']
679 if all_branches:
680 cmd += ['-a']
681 if commit:
682 cmd += ['--contains', commit]
683
684 result = []
685 for line in util.check_output(*cmd, cwd=git_repo).splitlines():
686 result.append(line.strip())
687 return result
688
689
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800690def list_commits_between_commits(git_repo, old, new):
691 """Get all commits between (old, new].
692
693 Args:
694 git_repo: path of git repo.
695 old: old commit hash (exclusive)
696 new: new commit hash (inclusive)
697
698 Returns:
699 list of (timestamp, rev)
700 """
701 assert old and new
702 assert old == new or is_ancestor_commit(git_repo, old, new)
703 commits = []
704 # --first-parent is necessary for Android, see following link for more
705 # discussion.
706 # https://docs.google.com/document/d/1c8qiq14_ObRRjLT62sk9r5V5cyCGHX66dLYab4MVnks/edit#heading=h.n3i6mt2n6xuu
707 for line in util.check_output(
708 'git',
709 'rev-list',
710 '--timestamp',
711 '--reverse',
712 '--first-parent',
713 '%s..%s' % (old, new),
714 cwd=git_repo).splitlines():
715 timestamp, git_rev = line.split()
716 commits.append([int(timestamp), git_rev])
717
718 # bisect-kit has a fundamental assumption that commit timestamps are
719 # increasing because we sort and bisect the commits by timestamp across git
720 # repos. If not increasing, we have to adjust the timestamp as workaround.
721 # This might lead to bad bisect result, however the bad probability is low in
722 # practice since most machines' clocks are good enough.
723 if commits != sorted(commits, key=lambda x: x[0]):
724 logger.warning('Commit timestamps are not increasing')
725 last_timestamp = -1
726 adjusted = 0
727 for commit in commits:
728 if commit[0] < last_timestamp:
729 commit[0] = last_timestamp
730 adjusted += 1
731
732 last_timestamp = commit[0]
733 logger.warning('%d timestamps adjusted', adjusted)
734
735 return commits