Kuang-che Wu | 6e4beca | 2018-06-27 17:45:02 +0800 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
Kuang-che Wu | e41e006 | 2017-09-01 19:04:14 +0800 | [diff] [blame] | 2 | # 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 | |
| 7 | from __future__ import print_function |
| 8 | import logging |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 9 | import os |
Kuang-che Wu | e41e006 | 2017-09-01 19:04:14 +0800 | [diff] [blame] | 10 | import re |
Kuang-che Wu | 3d04eda | 2019-09-05 23:56:40 +0800 | [diff] [blame] | 11 | import shutil |
Zheng-Jie Chang | 2914444 | 2020-02-18 11:53:25 +0800 | [diff] [blame^] | 12 | import stat |
Kuang-che Wu | e41e006 | 2017-09-01 19:04:14 +0800 | [diff] [blame] | 13 | import subprocess |
Kuang-che Wu | 2b1286b | 2019-05-20 20:37:26 +0800 | [diff] [blame] | 14 | import time |
Kuang-che Wu | e41e006 | 2017-09-01 19:04:14 +0800 | [diff] [blame] | 15 | |
| 16 | from bisect_kit import cli |
| 17 | from bisect_kit import util |
| 18 | |
| 19 | logger = logging.getLogger(__name__) |
| 20 | |
| 21 | GIT_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. |
| 30 | GIT_MIN_COMMIT_ID_LENGTH = 7 |
| 31 | |
| 32 | |
| 33 | def 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 | |
| 43 | def 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 Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 51 | def 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 Wu | 0836654 | 2019-01-12 12:37:49 +0800 | [diff] [blame] | 56 | def 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 Wu | 6948ecc | 2018-09-11 17:43:49 +0800 | [diff] [blame] | 67 | def 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 Wu | e41e006 | 2017-09-01 19:04:14 +0800 | [diff] [blame] | 76 | def 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 Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 86 | def 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 | |
| 100 | def 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 Wu | 1e49f51 | 2018-12-06 15:27:42 +0800 | [diff] [blame] | 137 | def 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 | |
| 147 | def fetch(git_repo, *args): |
Kuang-che Wu | 2b1286b | 2019-05-20 20:37:26 +0800 | [diff] [blame] | 148 | """Wrapper of 'git fetch' with retry support. |
Kuang-che Wu | 1e49f51 | 2018-12-06 15:27:42 +0800 | [diff] [blame] | 149 | |
| 150 | Args: |
| 151 | git_repo: path of git repo. |
| 152 | args: parameters pass to 'git fetch' |
| 153 | """ |
Kuang-che Wu | 2b1286b | 2019-05-20 20:37:26 +0800 | [diff] [blame] | 154 | 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 Wu | 1e49f51 | 2018-12-06 15:27:42 +0800 | [diff] [blame] | 181 | |
| 182 | |
Kuang-che Wu | e41e006 | 2017-09-01 19:04:14 +0800 | [diff] [blame] | 183 | def 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 Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 189 | |
| 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 Wu | e41e006 | 2017-09-01 19:04:14 +0800 | [diff] [blame] | 193 | """ |
| 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 Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 199 | except OSError: |
| 200 | return False |
Kuang-che Wu | e41e006 | 2017-09-01 19:04:14 +0800 | [diff] [blame] | 201 | |
| 202 | |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 203 | def 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 Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 224 | def 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 Wu | bcafc55 | 2019-08-15 15:27:02 +0800 | [diff] [blame] | 244 | 'git', 'cat-file', '-p', rev, cwd=git_repo, log_stdout=False) |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 245 | 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 Wu | e41e006 | 2017-09-01 19:04:14 +0800 | [diff] [blame] | 265 | def 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 Wu | e2563ea | 2018-01-05 20:30:28 +0800 | [diff] [blame] | 281 | |
| 282 | |
| 283 | def 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 Wu | 68db08a | 2018-03-30 11:50:34 +0800 | [diff] [blame] | 298 | def get_commit_hash(git_repo, rev): |
Kuang-che Wu | e2563ea | 2018-01-05 20:30:28 +0800 | [diff] [blame] | 299 | """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 Wu | 5e7c9b0 | 2019-01-03 21:16:01 +0800 | [diff] [blame] | 307 | |
| 308 | Raises: |
| 309 | ValueError: `rev` is not unique or doesn't exist |
Kuang-che Wu | e2563ea | 2018-01-05 20:30:28 +0800 | [diff] [blame] | 310 | """ |
Kuang-che Wu | 5e7c9b0 | 2019-01-03 21:16:01 +0800 | [diff] [blame] | 311 | 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 Wu | e2563ea | 2018-01-05 20:30:28 +0800 | [diff] [blame] | 322 | return git_rev |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 323 | |
| 324 | |
Zheng-Jie Chang | 868c175 | 2020-01-21 14:42:41 +0800 | [diff] [blame] | 325 | def get_commit_time(git_repo, rev, path=None): |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 326 | """Get git commit timestamp. |
| 327 | |
| 328 | Args: |
| 329 | git_repo: path of git repo |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 330 | rev: git commit id, branch name, tag name, or other git object |
| 331 | path: path, relative to git_repo |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 332 | |
| 333 | Returns: |
| 334 | timestamp (int) |
| 335 | """ |
Zheng-Jie Chang | 868c175 | 2020-01-21 14:42:41 +0800 | [diff] [blame] | 336 | cmd = ['git', 'log', '-1', '--format=%ct', rev] |
| 337 | if path: |
| 338 | cmd += ['--', path] |
| 339 | line = util.check_output(*cmd, cwd=git_repo) |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 340 | return int(line) |
| 341 | |
| 342 | |
Zheng-Jie Chang | 1ace301 | 2020-02-15 04:51:05 +0800 | [diff] [blame] | 343 | def 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 Chang | 2914444 | 2020-02-18 11:53:25 +0800 | [diff] [blame^] | 353 | |
| 354 | Raises: |
| 355 | ValueError if not found |
Zheng-Jie Chang | 1ace301 | 2020-02-15 04:51:05 +0800 | [diff] [blame] | 356 | """ |
Zheng-Jie Chang | 2914444 | 2020-02-18 11:53:25 +0800 | [diff] [blame^] | 357 | # 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 Chang | 1ace301 | 2020-02-15 04:51:05 +0800 | [diff] [blame] | 362 | |
| 363 | raise ValueError( |
| 364 | 'file %s is not found in repo:%s rev:%s' % (path, git_repo, rev)) |
| 365 | |
| 366 | |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 367 | def 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 Chang | 1ace301 | 2020-02-15 04:51:05 +0800 | [diff] [blame] | 378 | result = util.check_output( |
Kuang-che Wu | bcafc55 | 2019-08-15 15:27:02 +0800 | [diff] [blame] | 379 | 'git', 'show', '%s:%s' % (rev, path), cwd=git_repo, log_stdout=False) |
Zheng-Jie Chang | 1ace301 | 2020-02-15 04:51:05 +0800 | [diff] [blame] | 380 | if is_symbolic_link(git_repo, rev, path): |
| 381 | return get_file_from_revision(git_repo, rev, result) |
| 382 | return result |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 383 | |
| 384 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 385 | def 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 Wu | bcafc55 | 2019-08-15 15:27:02 +0800 | [diff] [blame] | 405 | log_stdout=False).splitlines() |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 406 | |
| 407 | |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 408 | def get_rev_by_time(git_repo, timestamp, branch, path=None): |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 409 | """Query commit of given time. |
| 410 | |
| 411 | Args: |
| 412 | git_repo: path of git repo. |
| 413 | timestamp: timestamp |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 414 | branch: only query parent of the `branch`. If branch=None, it means 'HEAD' |
| 415 | (current branch, usually). |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 416 | path: only query history of path, relative to git_repo |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 417 | |
| 418 | Returns: |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 419 | git commit hash. None if path didn't exist at the given time. |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 420 | """ |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 421 | if not branch: |
| 422 | branch = 'HEAD' |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 423 | |
| 424 | cmd = [ |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 425 | 'git', |
Kuang-che Wu | d1d45b4 | 2018-07-05 00:46:45 +0800 | [diff] [blame] | 426 | 'rev-list', |
| 427 | '--first-parent', |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 428 | '-1', |
| 429 | '--before', |
| 430 | str(timestamp), |
Kuang-che Wu | 89ac2e7 | 2018-07-25 17:39:07 +0800 | [diff] [blame] | 431 | branch, |
| 432 | ] |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 433 | if path: |
| 434 | cmd += ['--', path] |
| 435 | |
| 436 | result = util.check_output(*cmd, cwd=git_repo).strip() |
| 437 | return result or None |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 438 | |
| 439 | |
Kuang-che Wu | 3d04eda | 2019-09-05 23:56:40 +0800 | [diff] [blame] | 440 | def 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 | |
| 451 | def 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 | |
| 481 | def 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 Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 502 | def get_history(git_repo, |
Zheng-Jie Chang | 0fc704b | 2019-12-09 18:43:38 +0800 | [diff] [blame] | 503 | path=None, |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 504 | branch=None, |
| 505 | after=None, |
| 506 | before=None, |
Zheng-Jie Chang | 127c330 | 2019-09-10 17:17:04 +0800 | [diff] [blame] | 507 | padding=False, |
| 508 | with_subject=False): |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 509 | """Get commit history of given path. |
| 510 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 511 | `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 Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 514 | Args: |
| 515 | git_repo: path of git repo. |
| 516 | path: path to query, relative to git_repo |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 517 | branch: branch name or ref name |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 518 | 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 Chang | 127c330 | 2019-09-10 17:17:04 +0800 | [diff] [blame] | 523 | with_subject: If True, return commit subject together |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 524 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 525 | Returns: |
Zheng-Jie Chang | 127c330 | 2019-09-10 17:17:04 +0800 | [diff] [blame] | 526 | 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 Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 531 | |
| 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 Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 535 | """ |
Zheng-Jie Chang | 127c330 | 2019-09-10 17:17:04 +0800 | [diff] [blame] | 536 | log_format = '%ct %H' if not with_subject else '%ct %H %s' |
| 537 | cmd = ['git', 'log', '--reverse', '--first-parent', '--format=' + log_format] |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 538 | if after: |
| 539 | cmd += ['--after', str(after)] |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 540 | if before: |
| 541 | cmd += ['--before', str(before)] |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 542 | if branch: |
| 543 | assert not is_git_rev(branch) |
| 544 | cmd += [branch] |
Zheng-Jie Chang | 0fc704b | 2019-12-09 18:43:38 +0800 | [diff] [blame] | 545 | 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 Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 550 | |
| 551 | result = [] |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 552 | for line in util.check_output(*cmd, cwd=git_repo).splitlines(): |
Zheng-Jie Chang | 127c330 | 2019-09-10 17:17:04 +0800 | [diff] [blame] | 553 | # 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 Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 557 | |
| 558 | if padding: |
Kuang-che Wu | ae6824b | 2019-08-27 22:20:01 +0800 | [diff] [blame] | 559 | assert before or after, 'padding=True make no sense if they are both None' |
Zheng-Jie Chang | 127c330 | 2019-09-10 17:17:04 +0800 | [diff] [blame] | 560 | history = [0, ''] |
| 561 | if with_subject: |
| 562 | history.append('dummy subject') |
| 563 | |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 564 | if before is not None and get_rev_by_time( |
| 565 | git_repo, before, branch, path=path): |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 566 | before = int(before) |
| 567 | if not result or result[-1][0] != before: |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 568 | git_rev = get_rev_by_time(git_repo, before, branch) |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 569 | assert git_rev |
Zheng-Jie Chang | 127c330 | 2019-09-10 17:17:04 +0800 | [diff] [blame] | 570 | history[0:2] = [before, git_rev] |
| 571 | result.append(tuple(history)) |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 572 | if after is not None and get_rev_by_time( |
| 573 | git_repo, after, branch, path=path): |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 574 | after = int(after) |
| 575 | if not result or result[0][0] != after: |
Kuang-che Wu | 8a28a9d | 2018-09-11 17:43:36 +0800 | [diff] [blame] | 576 | git_rev = get_rev_by_time(git_repo, after, branch) |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 577 | assert git_rev |
Zheng-Jie Chang | 127c330 | 2019-09-10 17:17:04 +0800 | [diff] [blame] | 578 | history[0:2] = [after, git_rev] |
| 579 | result.insert(0, tuple(history)) |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 580 | |
| 581 | return result |
Kuang-che Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 582 | |
| 583 | |
Zheng-Jie Chang | d968f55 | 2020-01-16 13:31:57 +0800 | [diff] [blame] | 584 | def get_history_recursively(git_repo, |
| 585 | path, |
| 586 | after, |
| 587 | before, |
| 588 | parser_callback, |
| 589 | branch=None): |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 590 | """Get commit history of given path and its dependencies. |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 591 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 592 | 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 Wu | 7d0c759 | 2019-09-16 09:59:28 +0800 | [diff] [blame] | 600 | dependencies. If `parser_callback` returns None (usually syntax error), the |
| 601 | commit is omitted. |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 602 | |
| 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 Chang | d968f55 | 2020-01-16 13:31:57 +0800 | [diff] [blame] | 609 | branch: branch name or ref name |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 610 | |
| 611 | Returns: |
| 612 | list of (commit timestamp, git hash) |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 613 | """ |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 614 | history = get_history( |
Zheng-Jie Chang | d968f55 | 2020-01-16 13:31:57 +0800 | [diff] [blame] | 615 | git_repo, path, after=after, before=before, padding=True, branch=branch) |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 616 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 617 | # 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 Wu | 7d0c759 | 2019-09-16 09:59:28 +0800 | [diff] [blame] | 621 | parse_result = parser_callback(path, content) |
| 622 | if parse_result is None: |
| 623 | continue |
| 624 | for include_name in parse_result: |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 625 | if include_name not in includes: |
| 626 | includes[include_name] = set() |
| 627 | includes[include_name].add(git_rev) |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 628 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 629 | # 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 Chang | 4d617a4 | 2020-02-15 06:46:00 +0800 | [diff] [blame] | 639 | # dependency file exists in time range [appeared, commit_time) |
| 640 | dependencies.append((include, appeared, commit_time - 1)) |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 641 | appeared = None |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 642 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 643 | if appeared is not None: |
| 644 | dependencies.append((include, appeared, before)) |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 645 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 646 | # Recursion and merge. |
| 647 | result = list(history) |
| 648 | for include, appeared, disappeared in dependencies: |
Zheng-Jie Chang | d968f55 | 2020-01-16 13:31:57 +0800 | [diff] [blame] | 649 | result += get_history_recursively( |
| 650 | git_repo, |
| 651 | include, |
| 652 | appeared, |
| 653 | disappeared, |
| 654 | parser_callback, |
| 655 | branch=branch) |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 656 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 657 | # Sort and dedup. |
| 658 | result2 = [] |
Kuang-che Wu | ebb023c | 2018-11-29 15:49:32 +0800 | [diff] [blame] | 659 | for x in sorted(result, key=lambda x: x[0]): |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 660 | if result2 and result2[-1] == x: |
| 661 | continue |
| 662 | result2.append(x) |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 663 | |
Kuang-che Wu | e4bae0b | 2018-07-19 12:10:14 +0800 | [diff] [blame] | 664 | return result2 |
Kuang-che Wu | bfc4a64 | 2018-04-19 11:54:08 +0800 | [diff] [blame] | 665 | |
| 666 | |
Zheng-Jie Chang | d968f55 | 2020-01-16 13:31:57 +0800 | [diff] [blame] | 667 | def 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 Wu | 3eb6b50 | 2018-06-06 16:15:18 +0800 | [diff] [blame] | 690 | def 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 |