blob: 1d565d70dea65cf484f8d6207c09e5baacbd54f7 [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 Wu5bea88a2020-03-16 10:55:24 +0800154 tries = 0
155 while True:
156 tries += 1
Kuang-che Wu2b1286b2019-05-20 20:37:26 +0800157 stderr_lines = []
158 try:
159 util.check_call(
160 'git',
161 'fetch',
162 *args,
163 cwd=git_repo,
164 stderr_callback=stderr_lines.append)
Kuang-che Wu5bea88a2020-03-16 10:55:24 +0800165 return
Kuang-che Wu2b1286b2019-05-20 20:37:26 +0800166 except subprocess.CalledProcessError:
Kuang-che Wu5bea88a2020-03-16 10:55:24 +0800167 if tries >= 5:
168 logger.error('git fetch failed too much times')
169 raise
Kuang-che Wu2b1286b2019-05-20 20:37:26 +0800170 stderr = ''.join(stderr_lines)
171 # only retry 5xx internal server error
Kuang-che Wu5bea88a2020-03-16 10:55:24 +0800172 if 'The requested URL returned error: 5' in stderr:
173 delay = min(60, 10 * 2**tries)
174 logger.warning('git fetch failed, will retry %s seconds later', delay)
175 time.sleep(delay)
176 continue
177 raise
Kuang-che Wu1e49f512018-12-06 15:27:42 +0800178
179
Kuang-che Wue41e0062017-09-01 19:04:14 +0800180def is_containing_commit(git_repo, rev):
181 """Determines given commit exists.
182
183 Args:
184 git_repo: path of git repo.
185 rev: git commit revision in query.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800186
187 Returns:
188 True if rev is inside given git repo. If git_repo is not a git folder,
189 returns False as well.
Kuang-che Wue41e0062017-09-01 19:04:14 +0800190 """
191 try:
192 return util.check_output(
193 'git', 'cat-file', '-t', rev, cwd=git_repo) == 'commit\n'
194 except subprocess.CalledProcessError:
195 return False
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800196 except OSError:
197 return False
Kuang-che Wue41e0062017-09-01 19:04:14 +0800198
199
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800200def is_ancestor_commit(git_repo, old, new):
201 """Determines `old` commit is ancestor of `new` commit.
202
203 Args:
204 git_repo: path of git repo.
205 old: the ancestor commit.
206 new: the descendant commit.
207
208 Returns:
209 True only if `old` is the ancestor of `new`. One commit is not considered
210 as ancestor of itself.
211 """
212 return util.check_output(
213 'git',
214 'rev-list',
215 '--ancestry-path',
216 '-1',
217 '%s..%s' % (old, new),
218 cwd=git_repo) != ''
219
220
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800221def get_commit_metadata(git_repo, rev):
222 """Get metadata of given commit.
223
224 Args:
225 git_repo: path of git repo.
226 rev: git commit revision in query.
227
228 Returns:
229 dict of metadata, including (if available):
230 tree: hash of git tree object
231 parent: list of parent commits; this field is unavailable for the very
232 first commit of git repo.
233 author: name and email of author
234 author_time: author timestamp (without timezone information)
235 committer: name and email of committer
236 committer_time: commit timestamp (without timezone information)
237 message: commit message text
238 """
239 meta = {}
240 data = util.check_output(
Kuang-che Wubcafc552019-08-15 15:27:02 +0800241 'git', 'cat-file', '-p', rev, cwd=git_repo, log_stdout=False)
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800242 header, meta['message'] = data.split('\n\n', 1)
243 for line in header.splitlines():
244 m = re.match(r'^tree (\w+)', line)
245 if m:
246 meta['tree'] = m.group(1)
247 continue
248
249 m = re.match(r'^parent (\w+)', line)
250 if m:
251 meta['parent'] = line.split()[1:]
252 continue
253
254 m = re.match(r'^(author|committer) (.*) (\d+) (\S+)$', line)
255 if m:
256 meta[m.group(1)] = m.group(2)
257 meta['%s_time' % m.group(1)] = int(m.group(3))
258 continue
259 return meta
260
261
Kuang-che Wue41e0062017-09-01 19:04:14 +0800262def get_revlist(git_repo, old, new):
263 """Enumerates git commit between two revisions (inclusive).
264
265 Args:
266 git_repo: path of git repo.
267 old: git commit revision.
268 new: git commit revision.
269
270 Returns:
271 list of git revisions. The list contains the input revisions, old and new.
272 """
273 assert old
274 assert new
275 cmd = ['git', 'rev-list', '--reverse', '%s^..%s' % (old, new)]
276 revlist = util.check_output(*cmd, cwd=git_repo).splitlines()
277 return revlist
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800278
279
280def get_commit_log(git_repo, rev):
281 """Get git commit log.
282
283 Args:
284 git_repo: path of git repo.
285 rev: git commit revision.
286
287 Returns:
288 commit log message
289 """
290 cmd = ['git', 'log', '-1', '--format=%B', rev]
291 msg = util.check_output(*cmd, cwd=git_repo)
292 return msg
293
294
Kuang-che Wu68db08a2018-03-30 11:50:34 +0800295def get_commit_hash(git_repo, rev):
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800296 """Get git commit hash.
297
298 Args:
299 git_repo: path of git repo.
300 rev: could be git tag, branch, or (shortened) commit hash
301
302 Returns:
303 full git commit hash
Kuang-che Wu5e7c9b02019-01-03 21:16:01 +0800304
305 Raises:
306 ValueError: `rev` is not unique or doesn't exist
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800307 """
Kuang-che Wu5e7c9b02019-01-03 21:16:01 +0800308 try:
309 # Use '^{commit}' to restrict search only commits.
310 # Use '--' to avoid ambiguity, like matching rev against path name.
311 output = util.check_output(
312 'git', 'rev-parse', '%s^{commit}' % rev, '--', cwd=git_repo)
313 git_rev = output.rstrip('-\n')
314 except subprocess.CalledProcessError:
315 # Do not use 'git rev-parse --disambiguate' to determine uniqueness
316 # because it searches objects other than commits as well.
317 raise ValueError('%s is not unique or does not exist' % rev)
318 assert is_git_rev(git_rev)
Kuang-che Wue2563ea2018-01-05 20:30:28 +0800319 return git_rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800320
321
Zheng-Jie Chang868c1752020-01-21 14:42:41 +0800322def get_commit_time(git_repo, rev, path=None):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800323 """Get git commit timestamp.
324
325 Args:
326 git_repo: path of git repo
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800327 rev: git commit id, branch name, tag name, or other git object
328 path: path, relative to git_repo
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800329
330 Returns:
331 timestamp (int)
332 """
Zheng-Jie Chang868c1752020-01-21 14:42:41 +0800333 cmd = ['git', 'log', '-1', '--format=%ct', rev]
334 if path:
335 cmd += ['--', path]
336 line = util.check_output(*cmd, cwd=git_repo)
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800337 return int(line)
338
339
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800340def is_symbolic_link(git_repo, rev, path):
341 """Check if a file is symbolic link.
342
343 Args:
344 git_repo: path of git repo
345 rev: git commit id
346 path: file path
347
348 Returns:
349 True if the specified file is a symbolic link in repo.
Zheng-Jie Chang29144442020-02-18 11:53:25 +0800350
351 Raises:
352 ValueError if not found
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800353 """
Zheng-Jie Chang29144442020-02-18 11:53:25 +0800354 # format: 120000 blob 8735a8c1dd96ede39a21d983d5c96792fd15c1a5 default.xml
355 splitted = util.check_output(
356 'git', 'ls-tree', rev, '--full-name', path, cwd=git_repo).split()
357 if len(splitted) >= 4 and splitted[3] == path:
358 return stat.S_ISLNK(int(splitted[0], 8))
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800359
Kuang-che Wud1b74152020-05-20 08:46:46 +0800360 raise ValueError('file %s is not found in repo:%s rev:%s' %
361 (path, git_repo, rev))
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800362
363
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800364def get_file_from_revision(git_repo, rev, path):
365 """Get file content of given revision.
366
367 Args:
368 git_repo: path of git repo
369 rev: git commit id
370 path: file path
371
372 Returns:
373 file content (str)
374 """
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800375 result = util.check_output(
Kuang-che Wubcafc552019-08-15 15:27:02 +0800376 'git', 'show', '%s:%s' % (rev, path), cwd=git_repo, log_stdout=False)
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +0800377 if is_symbolic_link(git_repo, rev, path):
378 return get_file_from_revision(git_repo, rev, result)
379 return result
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800380
381
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800382def list_dir_from_revision(git_repo, rev, path):
383 """Lists entries of directory of given revision.
384
385 Args:
386 git_repo: path of git repo
387 rev: git commit id
388 path: directory path, relative to git root
389
390 Returns:
391 list of names
392
393 Raises:
394 subprocess.CalledProcessError: if `path` doesn't exists in `rev`
395 """
396 return util.check_output(
397 'git',
398 'ls-tree',
399 '--name-only',
400 '%s:%s' % (rev, path),
401 cwd=git_repo,
Kuang-che Wubcafc552019-08-15 15:27:02 +0800402 log_stdout=False).splitlines()
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800403
404
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800405def get_rev_by_time(git_repo, timestamp, branch, path=None):
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800406 """Query commit of given time.
407
408 Args:
409 git_repo: path of git repo.
410 timestamp: timestamp
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800411 branch: only query parent of the `branch`. If branch=None, it means 'HEAD'
412 (current branch, usually).
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800413 path: only query history of path, relative to git_repo
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800414
415 Returns:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800416 git commit hash. None if path didn't exist at the given time.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800417 """
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800418 if not branch:
419 branch = 'HEAD'
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800420
421 cmd = [
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800422 'git',
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800423 'rev-list',
424 '--first-parent',
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800425 '-1',
426 '--before',
427 str(timestamp),
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800428 branch,
429 ]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800430 if path:
431 cmd += ['--', path]
432
433 result = util.check_output(*cmd, cwd=git_repo).strip()
434 return result or None
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800435
436
Kuang-che Wu3d04eda2019-09-05 23:56:40 +0800437def reset_hard(git_repo):
438 """Restore modified and deleted files.
439
440 This is simply wrapper of "git reset --hard".
441
442 Args:
443 git_repo: path of git repo.
444 """
445 util.check_call('git', 'reset', '--hard', cwd=git_repo)
446
447
448def list_untracked(git_repo, excludes=None):
449 """List untracked files and directories.
450
451 Args:
452 git_repo: path of git repo.
453 excludes: files and/or directories to ignore, relative to git_repo
454
455 Returns:
456 list of paths, relative to git_repo
457 """
458 exclude_flags = []
459 if excludes:
460 for exclude in excludes:
461 assert not os.path.isabs(exclude), 'should be relative'
462 exclude_flags += ['--exclude', '/' + re.escape(exclude)]
463
464 result = []
465 for path in util.check_output(
466 'git',
467 'ls-files',
468 '--others',
469 '--exclude-standard',
470 *exclude_flags,
471 cwd=git_repo).splitlines():
472 # Remove the trailing slash, which means directory.
473 path = path.rstrip('/')
474 result.append(path)
475 return result
476
477
478def distclean(git_repo, excludes=None):
479 """Clean up git repo directory.
480
481 Restore modified and deleted files. Delete untracked files.
482
483 Args:
484 git_repo: path of git repo.
485 excludes: files and/or directories to ignore, relative to git_repo
486 """
487 reset_hard(git_repo)
488
489 # Delete untracked files.
490 for untracked in list_untracked(git_repo, excludes=excludes):
491 path = os.path.join(git_repo, untracked)
492 logger.debug('delete untracked: %s', path)
Zheng-Jie Chang42fd2e42020-04-10 07:21:23 +0800493 if os.path.islink(path):
494 os.unlink(path)
495 elif os.path.isdir(path):
Kuang-che Wu3d04eda2019-09-05 23:56:40 +0800496 shutil.rmtree(path)
497 else:
498 os.unlink(path)
499
500
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800501def get_history(git_repo,
Zheng-Jie Chang0fc704b2019-12-09 18:43:38 +0800502 path=None,
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800503 branch=None,
504 after=None,
505 before=None,
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800506 padding_begin=False,
507 padding_end=False,
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800508 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)
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800520 padding_begin: If True, pads returned result with dummy record at exact
521 'after' time, if 'path' existed at that time.
522 padding_end: If True, pads returned result with dummy record at exact
523 'before' time, if 'path' existed at that time.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800524 with_subject: If True, return commit subject together
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800525
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800526 Returns:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800527 List of (timestamp, git hash, subject); or (timestamp, git hash) depends
528 on with_subject flag. They are all events when `path` was added, removed,
529 modified, and start and end time if `padding` is true. If `padding` and
530 `with_subject` are both true, 'dummy subject' will be returned as padding
531 history's subject.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800532
533 For each pair, at `timestamp`, the repo state is `git hash`. In other
534 words, `timestamp` is not necessary the commit time of `git hash` for the
535 padded entries.
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800536 """
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800537 log_format = '%ct %H' if not with_subject else '%ct %H %s'
538 cmd = ['git', 'log', '--reverse', '--first-parent', '--format=' + log_format]
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800539 if after:
540 cmd += ['--after', str(after)]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800541 if before:
542 cmd += ['--before', str(before)]
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800543 if branch:
544 assert not is_git_rev(branch)
545 cmd += [branch]
Zheng-Jie Chang0fc704b2019-12-09 18:43:38 +0800546 if path:
547 # '--' is necessary otherwise if `path` is removed in current revision, git
548 # will complain it's an ambiguous argument which may be path or something
549 # else (like git branch name, tag name, etc.)
550 cmd += ['--', path]
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800551
552 result = []
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800553 for line in util.check_output(*cmd, cwd=git_repo).splitlines():
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800554 # array = [timestamp, git_rev, subject] or [timestamp, git_rev]
555 array = line.split(' ', 2)
556 array[0] = int(array[0])
557 result.append(tuple(array))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800558
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800559 if padding_begin or padding_end:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800560 history = [0, '']
561 if with_subject:
562 history.append('dummy subject')
563
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800564 if padding_end:
565 assert before, 'padding_end=True make no sense if before=None'
566 if get_rev_by_time(git_repo, before, branch, path=path):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800567 before = int(before)
568 if not result or result[-1][0] != before:
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800569 git_rev = get_rev_by_time(git_repo, before, branch)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800570 assert git_rev
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800571 history[0:2] = [before, git_rev]
572 result.append(tuple(history))
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800573
574 if padding_begin:
575 assert after, 'padding_begin=True make no sense if after=None'
576 if get_rev_by_time(git_repo, after, branch, path=path):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800577 after = int(after)
578 if not result or result[0][0] != after:
Kuang-che Wu8a28a9d2018-09-11 17:43:36 +0800579 git_rev = get_rev_by_time(git_repo, after, branch)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800580 assert git_rev
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800581 history[0:2] = [after, git_rev]
582 result.insert(0, tuple(history))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800583
584 return result
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800585
586
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800587def get_history_recursively(git_repo,
588 path,
589 after,
590 before,
591 parser_callback,
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800592 padding_end=True,
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800593 branch=None):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800594 """Get commit history of given path and its dependencies.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800595
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800596 In comparison to get_history(), get_history_recursively also takes
597 dependencies into consideration. For example, if file A referenced file B,
598 get_history_recursively(A) will return commits of B in addition to A. This
599 applies recursively, so commits of C will be included if file B referenced
600 file C, and so on.
601
602 This function is file type neutral. `parser_callback(filename, content)` will
603 be invoked to parse file content and should return list of filename of
Kuang-che Wu7d0c7592019-09-16 09:59:28 +0800604 dependencies. If `parser_callback` returns None (usually syntax error), the
605 commit is omitted.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800606
607 Args:
608 git_repo: path of git repo
609 path: path to query, relative to git_repo
610 after: limit history after given time (inclusive)
611 before: limit history before given time (inclusive)
612 parser_callback: callback to parse file content. See above comment.
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800613 padding_end: If True, pads returned result with dummy record at exact
614 'after' time, if 'path' existed at that time.
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800615 branch: branch name or ref name
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800616
617 Returns:
618 list of (commit timestamp, git hash)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800619 """
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800620 history = get_history(
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800621 git_repo,
622 path,
623 after=after,
624 before=before,
625 padding_begin=True,
626 branch=branch)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800627
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800628 # Collect include information of each commit.
629 includes = {}
630 for commit_time, git_rev in history:
631 content = get_file_from_revision(git_repo, git_rev, path)
Kuang-che Wu7d0c7592019-09-16 09:59:28 +0800632 parse_result = parser_callback(path, content)
633 if parse_result is None:
634 continue
635 for include_name in parse_result:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800636 if include_name not in includes:
637 includes[include_name] = set()
638 includes[include_name].add(git_rev)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800639
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800640 # Analyze the start time and end time of each include.
641 dependencies = []
642 for include in includes:
643 appeared = None
644 for commit_time, git_rev in history:
645 if git_rev in includes[include]:
646 if not appeared:
647 appeared = commit_time
648 else:
649 if appeared:
Zheng-Jie Chang4d617a42020-02-15 06:46:00 +0800650 # dependency file exists in time range [appeared, commit_time)
651 dependencies.append((include, appeared, commit_time - 1))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800652 appeared = None
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800653
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800654 if appeared is not None:
655 dependencies.append((include, appeared, before))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800656
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800657 # Recursion and merge.
658 result = list(history)
659 for include, appeared, disappeared in dependencies:
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800660 result += get_history_recursively(
661 git_repo,
662 include,
663 appeared,
664 disappeared,
665 parser_callback,
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800666 padding_end=False,
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800667 branch=branch)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800668
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800669 # Sort and padding.
670 result.sort(key=lambda x: x[0])
671 if padding_end:
672 pad = (before,)
673 pad += result[-1][1:]
674 result.append(pad)
675
676 # Dedup.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800677 result2 = []
Zheng-Jie Chang313eec32020-02-18 16:17:07 +0800678 for x in result:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800679 if result2 and result2[-1] == x:
680 continue
681 result2.append(x)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800682
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800683 return result2
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800684
685
Zheng-Jie Changd968f552020-01-16 13:31:57 +0800686def get_branches(git_repo, all_branches=True, commit=None):
687 """Get branches of a repository.
688
689 Args:
690 git_repo: path of git repo
691 all_branches: return remote branches if is set to True
692 commit: return branches containing this commit if is not None
693
694 Returns:
695 list of branch names
696 """
697 cmd = ['git', 'branch', '--format=%(refname)']
698 if all_branches:
699 cmd += ['-a']
700 if commit:
701 cmd += ['--contains', commit]
702
703 result = []
704 for line in util.check_output(*cmd, cwd=git_repo).splitlines():
705 result.append(line.strip())
706 return result
707
708
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800709def list_commits_between_commits(git_repo, old, new):
710 """Get all commits between (old, new].
711
712 Args:
713 git_repo: path of git repo.
714 old: old commit hash (exclusive)
715 new: new commit hash (inclusive)
716
717 Returns:
718 list of (timestamp, rev)
719 """
720 assert old and new
721 assert old == new or is_ancestor_commit(git_repo, old, new)
722 commits = []
723 # --first-parent is necessary for Android, see following link for more
724 # discussion.
725 # https://docs.google.com/document/d/1c8qiq14_ObRRjLT62sk9r5V5cyCGHX66dLYab4MVnks/edit#heading=h.n3i6mt2n6xuu
726 for line in util.check_output(
727 'git',
728 'rev-list',
729 '--timestamp',
730 '--reverse',
731 '--first-parent',
732 '%s..%s' % (old, new),
733 cwd=git_repo).splitlines():
734 timestamp, git_rev = line.split()
735 commits.append([int(timestamp), git_rev])
736
737 # bisect-kit has a fundamental assumption that commit timestamps are
738 # increasing because we sort and bisect the commits by timestamp across git
739 # repos. If not increasing, we have to adjust the timestamp as workaround.
740 # This might lead to bad bisect result, however the bad probability is low in
741 # practice since most machines' clocks are good enough.
742 if commits != sorted(commits, key=lambda x: x[0]):
743 logger.warning('Commit timestamps are not increasing')
744 last_timestamp = -1
745 adjusted = 0
746 for commit in commits:
747 if commit[0] < last_timestamp:
748 commit[0] = last_timestamp
749 adjusted += 1
750
751 last_timestamp = commit[0]
752 logger.warning('%d timestamps adjusted', adjusted)
753
754 return commits