The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 1 | # Copyright (C) 2008 The Android Open Source Project |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | import filecmp |
| 16 | import os |
| 17 | import re |
| 18 | import shutil |
| 19 | import stat |
| 20 | import sys |
| 21 | import urllib2 |
| 22 | |
| 23 | from color import Coloring |
| 24 | from git_command import GitCommand |
| 25 | from git_config import GitConfig, IsId |
| 26 | from gerrit_upload import UploadBundle |
| 27 | from error import GitError, ImportError, UploadError |
| 28 | from remote import Remote |
| 29 | from codereview import proto_client |
| 30 | |
| 31 | HEAD = 'HEAD' |
| 32 | R_HEADS = 'refs/heads/' |
| 33 | R_TAGS = 'refs/tags/' |
| 34 | R_PUB = 'refs/published/' |
| 35 | R_M = 'refs/remotes/m/' |
| 36 | |
| 37 | def _warn(fmt, *args): |
| 38 | msg = fmt % args |
| 39 | print >>sys.stderr, 'warn: %s' % msg |
| 40 | |
| 41 | def _info(fmt, *args): |
| 42 | msg = fmt % args |
| 43 | print >>sys.stderr, 'info: %s' % msg |
| 44 | |
| 45 | def not_rev(r): |
| 46 | return '^' + r |
| 47 | |
Shawn O. Pearce | 632768b | 2008-10-23 11:58:52 -0700 | [diff] [blame] | 48 | class DownloadedChange(object): |
| 49 | _commit_cache = None |
| 50 | |
| 51 | def __init__(self, project, base, change_id, ps_id, commit): |
| 52 | self.project = project |
| 53 | self.base = base |
| 54 | self.change_id = change_id |
| 55 | self.ps_id = ps_id |
| 56 | self.commit = commit |
| 57 | |
| 58 | @property |
| 59 | def commits(self): |
| 60 | if self._commit_cache is None: |
| 61 | self._commit_cache = self.project.bare_git.rev_list( |
| 62 | '--abbrev=8', |
| 63 | '--abbrev-commit', |
| 64 | '--pretty=oneline', |
| 65 | '--reverse', |
| 66 | '--date-order', |
| 67 | not_rev(self.base), |
| 68 | self.commit, |
| 69 | '--') |
| 70 | return self._commit_cache |
| 71 | |
| 72 | |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 73 | class ReviewableBranch(object): |
| 74 | _commit_cache = None |
| 75 | |
| 76 | def __init__(self, project, branch, base): |
| 77 | self.project = project |
| 78 | self.branch = branch |
| 79 | self.base = base |
| 80 | |
| 81 | @property |
| 82 | def name(self): |
| 83 | return self.branch.name |
| 84 | |
| 85 | @property |
| 86 | def commits(self): |
| 87 | if self._commit_cache is None: |
| 88 | self._commit_cache = self.project.bare_git.rev_list( |
| 89 | '--abbrev=8', |
| 90 | '--abbrev-commit', |
| 91 | '--pretty=oneline', |
| 92 | '--reverse', |
| 93 | '--date-order', |
| 94 | not_rev(self.base), |
| 95 | R_HEADS + self.name, |
| 96 | '--') |
| 97 | return self._commit_cache |
| 98 | |
| 99 | @property |
| 100 | def date(self): |
| 101 | return self.project.bare_git.log( |
| 102 | '--pretty=format:%cd', |
| 103 | '-n', '1', |
| 104 | R_HEADS + self.name, |
| 105 | '--') |
| 106 | |
| 107 | def UploadForReview(self): |
| 108 | self.project.UploadForReview(self.name) |
| 109 | |
| 110 | @property |
| 111 | def tip_url(self): |
| 112 | me = self.project.GetBranch(self.name) |
| 113 | commit = self.project.bare_git.rev_parse(R_HEADS + self.name) |
| 114 | return 'http://%s/r/%s' % (me.remote.review, commit[0:12]) |
| 115 | |
Shawn O. Pearce | 0758d2f | 2008-10-22 13:13:40 -0700 | [diff] [blame] | 116 | @property |
| 117 | def owner_email(self): |
| 118 | return self.project.UserEmail |
| 119 | |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 120 | |
| 121 | class StatusColoring(Coloring): |
| 122 | def __init__(self, config): |
| 123 | Coloring.__init__(self, config, 'status') |
| 124 | self.project = self.printer('header', attr = 'bold') |
| 125 | self.branch = self.printer('header', attr = 'bold') |
| 126 | self.nobranch = self.printer('nobranch', fg = 'red') |
| 127 | |
| 128 | self.added = self.printer('added', fg = 'green') |
| 129 | self.changed = self.printer('changed', fg = 'red') |
| 130 | self.untracked = self.printer('untracked', fg = 'red') |
| 131 | |
| 132 | |
| 133 | class DiffColoring(Coloring): |
| 134 | def __init__(self, config): |
| 135 | Coloring.__init__(self, config, 'diff') |
| 136 | self.project = self.printer('header', attr = 'bold') |
| 137 | |
| 138 | |
| 139 | class _CopyFile: |
| 140 | def __init__(self, src, dest): |
| 141 | self.src = src |
| 142 | self.dest = dest |
| 143 | |
| 144 | def _Copy(self): |
| 145 | src = self.src |
| 146 | dest = self.dest |
| 147 | # copy file if it does not exist or is out of date |
| 148 | if not os.path.exists(dest) or not filecmp.cmp(src, dest): |
| 149 | try: |
| 150 | # remove existing file first, since it might be read-only |
| 151 | if os.path.exists(dest): |
| 152 | os.remove(dest) |
| 153 | shutil.copy(src, dest) |
| 154 | # make the file read-only |
| 155 | mode = os.stat(dest)[stat.ST_MODE] |
| 156 | mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH) |
| 157 | os.chmod(dest, mode) |
| 158 | except IOError: |
| 159 | print >>sys.stderr, \ |
| 160 | 'error: Cannot copy file %s to %s' \ |
| 161 | % (src, dest) |
| 162 | |
| 163 | |
| 164 | class Project(object): |
| 165 | def __init__(self, |
| 166 | manifest, |
| 167 | name, |
| 168 | remote, |
| 169 | gitdir, |
| 170 | worktree, |
| 171 | relpath, |
| 172 | revision): |
| 173 | self.manifest = manifest |
| 174 | self.name = name |
| 175 | self.remote = remote |
| 176 | self.gitdir = gitdir |
| 177 | self.worktree = worktree |
| 178 | self.relpath = relpath |
| 179 | self.revision = revision |
| 180 | self.snapshots = {} |
| 181 | self.extraRemotes = {} |
| 182 | self.copyfiles = [] |
| 183 | self.config = GitConfig.ForRepository( |
| 184 | gitdir = self.gitdir, |
| 185 | defaults = self.manifest.globalConfig) |
| 186 | |
| 187 | self.work_git = self._GitGetByExec(self, bare=False) |
| 188 | self.bare_git = self._GitGetByExec(self, bare=True) |
| 189 | |
| 190 | @property |
| 191 | def Exists(self): |
| 192 | return os.path.isdir(self.gitdir) |
| 193 | |
| 194 | @property |
| 195 | def CurrentBranch(self): |
| 196 | """Obtain the name of the currently checked out branch. |
| 197 | The branch name omits the 'refs/heads/' prefix. |
| 198 | None is returned if the project is on a detached HEAD. |
| 199 | """ |
| 200 | try: |
| 201 | b = self.work_git.GetHead() |
| 202 | except GitError: |
| 203 | return None |
| 204 | if b.startswith(R_HEADS): |
| 205 | return b[len(R_HEADS):] |
| 206 | return None |
| 207 | |
| 208 | def IsDirty(self, consider_untracked=True): |
| 209 | """Is the working directory modified in some way? |
| 210 | """ |
| 211 | self.work_git.update_index('-q', |
| 212 | '--unmerged', |
| 213 | '--ignore-missing', |
| 214 | '--refresh') |
| 215 | if self.work_git.DiffZ('diff-index','-M','--cached',HEAD): |
| 216 | return True |
| 217 | if self.work_git.DiffZ('diff-files'): |
| 218 | return True |
| 219 | if consider_untracked and self.work_git.LsOthers(): |
| 220 | return True |
| 221 | return False |
| 222 | |
| 223 | _userident_name = None |
| 224 | _userident_email = None |
| 225 | |
| 226 | @property |
| 227 | def UserName(self): |
| 228 | """Obtain the user's personal name. |
| 229 | """ |
| 230 | if self._userident_name is None: |
| 231 | self._LoadUserIdentity() |
| 232 | return self._userident_name |
| 233 | |
| 234 | @property |
| 235 | def UserEmail(self): |
| 236 | """Obtain the user's email address. This is very likely |
| 237 | to be their Gerrit login. |
| 238 | """ |
| 239 | if self._userident_email is None: |
| 240 | self._LoadUserIdentity() |
| 241 | return self._userident_email |
| 242 | |
| 243 | def _LoadUserIdentity(self): |
| 244 | u = self.bare_git.var('GIT_COMMITTER_IDENT') |
| 245 | m = re.compile("^(.*) <([^>]*)> ").match(u) |
| 246 | if m: |
| 247 | self._userident_name = m.group(1) |
| 248 | self._userident_email = m.group(2) |
| 249 | else: |
| 250 | self._userident_name = '' |
| 251 | self._userident_email = '' |
| 252 | |
| 253 | def GetRemote(self, name): |
| 254 | """Get the configuration for a single remote. |
| 255 | """ |
| 256 | return self.config.GetRemote(name) |
| 257 | |
| 258 | def GetBranch(self, name): |
| 259 | """Get the configuration for a single branch. |
| 260 | """ |
| 261 | return self.config.GetBranch(name) |
| 262 | |
| 263 | |
| 264 | ## Status Display ## |
| 265 | |
| 266 | def PrintWorkTreeStatus(self): |
| 267 | """Prints the status of the repository to stdout. |
| 268 | """ |
| 269 | if not os.path.isdir(self.worktree): |
| 270 | print '' |
| 271 | print 'project %s/' % self.relpath |
| 272 | print ' missing (run "repo sync")' |
| 273 | return |
| 274 | |
| 275 | self.work_git.update_index('-q', |
| 276 | '--unmerged', |
| 277 | '--ignore-missing', |
| 278 | '--refresh') |
| 279 | di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD) |
| 280 | df = self.work_git.DiffZ('diff-files') |
| 281 | do = self.work_git.LsOthers() |
| 282 | if not di and not df and not do: |
| 283 | return |
| 284 | |
| 285 | out = StatusColoring(self.config) |
| 286 | out.project('project %-40s', self.relpath + '/') |
| 287 | |
| 288 | branch = self.CurrentBranch |
| 289 | if branch is None: |
| 290 | out.nobranch('(*** NO BRANCH ***)') |
| 291 | else: |
| 292 | out.branch('branch %s', branch) |
| 293 | out.nl() |
| 294 | |
| 295 | paths = list() |
| 296 | paths.extend(di.keys()) |
| 297 | paths.extend(df.keys()) |
| 298 | paths.extend(do) |
| 299 | |
| 300 | paths = list(set(paths)) |
| 301 | paths.sort() |
| 302 | |
| 303 | for p in paths: |
| 304 | try: i = di[p] |
| 305 | except KeyError: i = None |
| 306 | |
| 307 | try: f = df[p] |
| 308 | except KeyError: f = None |
| 309 | |
| 310 | if i: i_status = i.status.upper() |
| 311 | else: i_status = '-' |
| 312 | |
| 313 | if f: f_status = f.status.lower() |
| 314 | else: f_status = '-' |
| 315 | |
| 316 | if i and i.src_path: |
| 317 | line = ' %s%s\t%s => (%s%%)' % (i_status, f_status, |
| 318 | i.src_path, p, i.level) |
| 319 | else: |
| 320 | line = ' %s%s\t%s' % (i_status, f_status, p) |
| 321 | |
| 322 | if i and not f: |
| 323 | out.added('%s', line) |
| 324 | elif (i and f) or (not i and f): |
| 325 | out.changed('%s', line) |
| 326 | elif not i and not f: |
| 327 | out.untracked('%s', line) |
| 328 | else: |
| 329 | out.write('%s', line) |
| 330 | out.nl() |
| 331 | |
| 332 | def PrintWorkTreeDiff(self): |
| 333 | """Prints the status of the repository to stdout. |
| 334 | """ |
| 335 | out = DiffColoring(self.config) |
| 336 | cmd = ['diff'] |
| 337 | if out.is_on: |
| 338 | cmd.append('--color') |
| 339 | cmd.append(HEAD) |
| 340 | cmd.append('--') |
| 341 | p = GitCommand(self, |
| 342 | cmd, |
| 343 | capture_stdout = True, |
| 344 | capture_stderr = True) |
| 345 | has_diff = False |
| 346 | for line in p.process.stdout: |
| 347 | if not has_diff: |
| 348 | out.nl() |
| 349 | out.project('project %s/' % self.relpath) |
| 350 | out.nl() |
| 351 | has_diff = True |
| 352 | print line[:-1] |
| 353 | p.Wait() |
| 354 | |
| 355 | |
| 356 | ## Publish / Upload ## |
| 357 | |
| 358 | def WasPublished(self, branch): |
| 359 | """Was the branch published (uploaded) for code review? |
| 360 | If so, returns the SHA-1 hash of the last published |
| 361 | state for the branch. |
| 362 | """ |
| 363 | try: |
| 364 | return self.bare_git.rev_parse(R_PUB + branch) |
| 365 | except GitError: |
| 366 | return None |
| 367 | |
| 368 | def CleanPublishedCache(self): |
| 369 | """Prunes any stale published refs. |
| 370 | """ |
| 371 | heads = set() |
| 372 | canrm = {} |
| 373 | for name, id in self._allrefs.iteritems(): |
| 374 | if name.startswith(R_HEADS): |
| 375 | heads.add(name) |
| 376 | elif name.startswith(R_PUB): |
| 377 | canrm[name] = id |
| 378 | |
| 379 | for name, id in canrm.iteritems(): |
| 380 | n = name[len(R_PUB):] |
| 381 | if R_HEADS + n not in heads: |
| 382 | self.bare_git.DeleteRef(name, id) |
| 383 | |
| 384 | def GetUploadableBranches(self): |
| 385 | """List any branches which can be uploaded for review. |
| 386 | """ |
| 387 | heads = {} |
| 388 | pubed = {} |
| 389 | |
| 390 | for name, id in self._allrefs.iteritems(): |
| 391 | if name.startswith(R_HEADS): |
| 392 | heads[name[len(R_HEADS):]] = id |
| 393 | elif name.startswith(R_PUB): |
| 394 | pubed[name[len(R_PUB):]] = id |
| 395 | |
| 396 | ready = [] |
| 397 | for branch, id in heads.iteritems(): |
| 398 | if branch in pubed and pubed[branch] == id: |
| 399 | continue |
| 400 | |
| 401 | branch = self.GetBranch(branch) |
| 402 | base = branch.LocalMerge |
| 403 | if branch.LocalMerge: |
| 404 | rb = ReviewableBranch(self, branch, base) |
| 405 | if rb.commits: |
| 406 | ready.append(rb) |
| 407 | return ready |
| 408 | |
| 409 | def UploadForReview(self, branch=None): |
| 410 | """Uploads the named branch for code review. |
| 411 | """ |
| 412 | if branch is None: |
| 413 | branch = self.CurrentBranch |
| 414 | if branch is None: |
| 415 | raise GitError('not currently on a branch') |
| 416 | |
| 417 | branch = self.GetBranch(branch) |
| 418 | if not branch.LocalMerge: |
| 419 | raise GitError('branch %s does not track a remote' % branch.name) |
| 420 | if not branch.remote.review: |
| 421 | raise GitError('remote %s has no review url' % branch.remote.name) |
| 422 | |
| 423 | dest_branch = branch.merge |
| 424 | if not dest_branch.startswith(R_HEADS): |
| 425 | dest_branch = R_HEADS + dest_branch |
| 426 | |
| 427 | base_list = [] |
| 428 | for name, id in self._allrefs.iteritems(): |
| 429 | if branch.remote.WritesTo(name): |
| 430 | base_list.append(not_rev(name)) |
| 431 | if not base_list: |
| 432 | raise GitError('no base refs, cannot upload %s' % branch.name) |
| 433 | |
| 434 | print >>sys.stderr, '' |
| 435 | _info("Uploading %s to %s:", branch.name, self.name) |
| 436 | try: |
| 437 | UploadBundle(project = self, |
| 438 | server = branch.remote.review, |
| 439 | email = self.UserEmail, |
| 440 | dest_project = self.name, |
| 441 | dest_branch = dest_branch, |
| 442 | src_branch = R_HEADS + branch.name, |
| 443 | bases = base_list) |
| 444 | except proto_client.ClientLoginError: |
| 445 | raise UploadError('Login failure') |
| 446 | except urllib2.HTTPError, e: |
| 447 | raise UploadError('HTTP error %d' % e.code) |
| 448 | |
| 449 | msg = "posted to %s for %s" % (branch.remote.review, dest_branch) |
| 450 | self.bare_git.UpdateRef(R_PUB + branch.name, |
| 451 | R_HEADS + branch.name, |
| 452 | message = msg) |
| 453 | |
| 454 | |
| 455 | ## Sync ## |
| 456 | |
| 457 | def Sync_NetworkHalf(self): |
| 458 | """Perform only the network IO portion of the sync process. |
| 459 | Local working directory/branch state is not affected. |
| 460 | """ |
| 461 | if not self.Exists: |
| 462 | print >>sys.stderr |
| 463 | print >>sys.stderr, 'Initializing project %s ...' % self.name |
| 464 | self._InitGitDir() |
| 465 | self._InitRemote() |
| 466 | for r in self.extraRemotes.values(): |
| 467 | if not self._RemoteFetch(r.name): |
| 468 | return False |
| 469 | if not self._SnapshotDownload(): |
| 470 | return False |
| 471 | if not self._RemoteFetch(): |
| 472 | return False |
| 473 | self._InitMRef() |
| 474 | return True |
| 475 | |
| 476 | def _CopyFiles(self): |
| 477 | for file in self.copyfiles: |
| 478 | file._Copy() |
| 479 | |
| 480 | def Sync_LocalHalf(self): |
| 481 | """Perform only the local IO portion of the sync process. |
| 482 | Network access is not required. |
| 483 | |
| 484 | Return: |
| 485 | True: the sync was successful |
| 486 | False: the sync requires user input |
| 487 | """ |
| 488 | self._InitWorkTree() |
| 489 | self.CleanPublishedCache() |
| 490 | |
| 491 | rem = self.GetRemote(self.remote.name) |
| 492 | rev = rem.ToLocal(self.revision) |
| 493 | branch = self.CurrentBranch |
| 494 | |
| 495 | if branch is None: |
| 496 | # Currently on a detached HEAD. The user is assumed to |
| 497 | # not have any local modifications worth worrying about. |
| 498 | # |
| 499 | lost = self._revlist(not_rev(rev), HEAD) |
| 500 | if lost: |
| 501 | _info("[%s] Discarding %d commits", self.name, len(lost)) |
| 502 | try: |
| 503 | self._Checkout(rev, quiet=True) |
| 504 | except GitError: |
| 505 | return False |
| 506 | self._CopyFiles() |
| 507 | return True |
| 508 | |
| 509 | branch = self.GetBranch(branch) |
| 510 | merge = branch.LocalMerge |
| 511 | |
| 512 | if not merge: |
| 513 | # The current branch has no tracking configuration. |
| 514 | # Jump off it to a deatched HEAD. |
| 515 | # |
| 516 | _info("[%s] Leaving %s" |
| 517 | " (does not track any upstream)", |
| 518 | self.name, |
| 519 | branch.name) |
| 520 | try: |
| 521 | self._Checkout(rev, quiet=True) |
| 522 | except GitError: |
| 523 | return False |
| 524 | self._CopyFiles() |
| 525 | return True |
| 526 | |
| 527 | upstream_gain = self._revlist(not_rev(HEAD), rev) |
| 528 | pub = self.WasPublished(branch.name) |
| 529 | if pub: |
| 530 | not_merged = self._revlist(not_rev(rev), pub) |
| 531 | if not_merged: |
| 532 | if upstream_gain: |
| 533 | # The user has published this branch and some of those |
| 534 | # commits are not yet merged upstream. We do not want |
| 535 | # to rewrite the published commits so we punt. |
| 536 | # |
| 537 | _info("[%s] Branch %s is published," |
| 538 | " but is now %d commits behind.", |
| 539 | self.name, branch.name, len(upstream_gain)) |
| 540 | _info("[%s] Consider merging or rebasing the" |
| 541 | " unpublished commits.", self.name) |
| 542 | return True |
| 543 | |
| 544 | if merge == rev: |
| 545 | try: |
| 546 | old_merge = self.bare_git.rev_parse('%s@{1}' % merge) |
| 547 | except GitError: |
| 548 | old_merge = merge |
Shawn O. Pearce | 0734600 | 2008-10-21 07:09:27 -0700 | [diff] [blame] | 549 | if old_merge == '0000000000000000000000000000000000000000' \ |
| 550 | or old_merge == '': |
| 551 | old_merge = merge |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 552 | else: |
| 553 | # The upstream switched on us. Time to cross our fingers |
| 554 | # and pray that the old upstream also wasn't in the habit |
| 555 | # of rebasing itself. |
| 556 | # |
| 557 | _info("[%s] Manifest switched from %s to %s", |
| 558 | self.name, merge, rev) |
| 559 | old_merge = merge |
| 560 | |
| 561 | if rev == old_merge: |
| 562 | upstream_lost = [] |
| 563 | else: |
| 564 | upstream_lost = self._revlist(not_rev(rev), old_merge) |
| 565 | |
| 566 | if not upstream_lost and not upstream_gain: |
| 567 | # Trivially no changes caused by the upstream. |
| 568 | # |
| 569 | return True |
| 570 | |
| 571 | if self.IsDirty(consider_untracked=False): |
| 572 | _warn('[%s] commit (or discard) uncommitted changes' |
| 573 | ' before sync', self.name) |
| 574 | return False |
| 575 | |
| 576 | if upstream_lost: |
| 577 | # Upstream rebased. Not everything in HEAD |
| 578 | # may have been caused by the user. |
| 579 | # |
| 580 | _info("[%s] Discarding %d commits removed from upstream", |
| 581 | self.name, len(upstream_lost)) |
| 582 | |
| 583 | branch.remote = rem |
| 584 | branch.merge = self.revision |
| 585 | branch.Save() |
| 586 | |
| 587 | my_changes = self._revlist(not_rev(old_merge), HEAD) |
| 588 | if my_changes: |
| 589 | try: |
| 590 | self._Rebase(upstream = old_merge, onto = rev) |
| 591 | except GitError: |
| 592 | return False |
| 593 | elif upstream_lost: |
| 594 | try: |
| 595 | self._ResetHard(rev) |
| 596 | except GitError: |
| 597 | return False |
| 598 | else: |
| 599 | try: |
| 600 | self._FastForward(rev) |
| 601 | except GitError: |
| 602 | return False |
| 603 | |
| 604 | self._CopyFiles() |
| 605 | return True |
| 606 | |
| 607 | def _SnapshotDownload(self): |
| 608 | if self.snapshots: |
| 609 | have = set(self._allrefs.keys()) |
| 610 | need = [] |
| 611 | |
| 612 | for tag, sn in self.snapshots.iteritems(): |
| 613 | if tag not in have: |
| 614 | need.append(sn) |
| 615 | |
| 616 | if need: |
| 617 | print >>sys.stderr, """ |
| 618 | *** Downloading source(s) from a mirror site. *** |
| 619 | *** If the network hangs, kill and restart repo. *** |
| 620 | """ |
| 621 | for sn in need: |
| 622 | try: |
| 623 | sn.Import() |
| 624 | except ImportError, e: |
| 625 | print >>sys.stderr, \ |
| 626 | 'error: Cannot import %s: %s' \ |
| 627 | % (self.name, e) |
| 628 | return False |
| 629 | cmd = ['repack', '-a', '-d', '-f', '-l'] |
| 630 | if GitCommand(self, cmd, bare = True).Wait() != 0: |
| 631 | return False |
| 632 | return True |
| 633 | |
| 634 | def AddCopyFile(self, src, dest): |
| 635 | # dest should already be an absolute path, but src is project relative |
| 636 | # make src an absolute path |
| 637 | src = os.path.join(self.worktree, src) |
| 638 | self.copyfiles.append(_CopyFile(src, dest)) |
| 639 | |
Shawn O. Pearce | 632768b | 2008-10-23 11:58:52 -0700 | [diff] [blame] | 640 | def DownloadPatchSet(self, change_id, patch_id): |
| 641 | """Download a single patch set of a single change to FETCH_HEAD. |
| 642 | """ |
| 643 | remote = self.GetRemote(self.remote.name) |
| 644 | |
| 645 | cmd = ['fetch', remote.name] |
| 646 | cmd.append('refs/changes/%2.2d/%d/%d' \ |
| 647 | % (change_id % 100, change_id, patch_id)) |
| 648 | cmd.extend(map(lambda x: str(x), remote.fetch)) |
| 649 | if GitCommand(self, cmd, bare=True).Wait() != 0: |
| 650 | return None |
| 651 | return DownloadedChange(self, |
| 652 | remote.ToLocal(self.revision), |
| 653 | change_id, |
| 654 | patch_id, |
| 655 | self.bare_git.rev_parse('FETCH_HEAD')) |
| 656 | |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 657 | |
| 658 | ## Branch Management ## |
| 659 | |
| 660 | def StartBranch(self, name): |
| 661 | """Create a new branch off the manifest's revision. |
| 662 | """ |
| 663 | branch = self.GetBranch(name) |
| 664 | branch.remote = self.GetRemote(self.remote.name) |
| 665 | branch.merge = self.revision |
| 666 | |
| 667 | rev = branch.LocalMerge |
| 668 | cmd = ['checkout', '-b', branch.name, rev] |
| 669 | if GitCommand(self, cmd).Wait() == 0: |
| 670 | branch.Save() |
| 671 | else: |
| 672 | raise GitError('%s checkout %s ' % (self.name, rev)) |
| 673 | |
| 674 | def PruneHeads(self): |
| 675 | """Prune any topic branches already merged into upstream. |
| 676 | """ |
| 677 | cb = self.CurrentBranch |
| 678 | kill = [] |
| 679 | for name in self._allrefs.keys(): |
| 680 | if name.startswith(R_HEADS): |
| 681 | name = name[len(R_HEADS):] |
| 682 | if cb is None or name != cb: |
| 683 | kill.append(name) |
| 684 | |
| 685 | rev = self.GetRemote(self.remote.name).ToLocal(self.revision) |
| 686 | if cb is not None \ |
| 687 | and not self._revlist(HEAD + '...' + rev) \ |
| 688 | and not self.IsDirty(consider_untracked = False): |
| 689 | self.work_git.DetachHead(HEAD) |
| 690 | kill.append(cb) |
| 691 | |
| 692 | deleted = set() |
| 693 | if kill: |
| 694 | try: |
| 695 | old = self.bare_git.GetHead() |
| 696 | except GitError: |
| 697 | old = 'refs/heads/please_never_use_this_as_a_branch_name' |
| 698 | |
| 699 | rm_re = re.compile(r"^Deleted branch (.*)\.$") |
| 700 | try: |
| 701 | self.bare_git.DetachHead(rev) |
| 702 | |
| 703 | b = ['branch', '-d'] |
| 704 | b.extend(kill) |
| 705 | b = GitCommand(self, b, bare=True, |
| 706 | capture_stdout=True, |
| 707 | capture_stderr=True) |
| 708 | b.Wait() |
| 709 | finally: |
| 710 | self.bare_git.SetHead(old) |
| 711 | |
| 712 | for line in b.stdout.split("\n"): |
| 713 | m = rm_re.match(line) |
| 714 | if m: |
| 715 | deleted.add(m.group(1)) |
| 716 | |
| 717 | if deleted: |
| 718 | self.CleanPublishedCache() |
| 719 | |
| 720 | if cb and cb not in kill: |
| 721 | kill.append(cb) |
| 722 | kill.sort() |
| 723 | |
| 724 | kept = [] |
| 725 | for branch in kill: |
| 726 | if branch not in deleted: |
| 727 | branch = self.GetBranch(branch) |
| 728 | base = branch.LocalMerge |
| 729 | if not base: |
| 730 | base = rev |
| 731 | kept.append(ReviewableBranch(self, branch, base)) |
| 732 | return kept |
| 733 | |
| 734 | |
| 735 | ## Direct Git Commands ## |
| 736 | |
| 737 | def _RemoteFetch(self, name=None): |
| 738 | if not name: |
| 739 | name = self.remote.name |
| 740 | |
| 741 | hide_errors = False |
| 742 | if self.extraRemotes or self.snapshots: |
| 743 | hide_errors = True |
| 744 | |
| 745 | proc = GitCommand(self, |
| 746 | ['fetch', name], |
| 747 | bare = True, |
| 748 | capture_stderr = hide_errors) |
| 749 | if hide_errors: |
| 750 | err = proc.process.stderr.fileno() |
| 751 | buf = '' |
| 752 | while True: |
| 753 | b = os.read(err, 256) |
| 754 | if b: |
| 755 | buf += b |
| 756 | while buf: |
| 757 | r = buf.find('remote: error: unable to find ') |
| 758 | if r >= 0: |
| 759 | lf = buf.find('\n') |
| 760 | if lf < 0: |
| 761 | break |
| 762 | buf = buf[lf + 1:] |
| 763 | continue |
| 764 | |
| 765 | cr = buf.find('\r') |
| 766 | if cr < 0: |
| 767 | break |
| 768 | os.write(2, buf[0:cr + 1]) |
| 769 | buf = buf[cr + 1:] |
| 770 | if not b: |
| 771 | if buf: |
| 772 | os.write(2, buf) |
| 773 | break |
| 774 | return proc.Wait() == 0 |
| 775 | |
| 776 | def _Checkout(self, rev, quiet=False): |
| 777 | cmd = ['checkout'] |
| 778 | if quiet: |
| 779 | cmd.append('-q') |
| 780 | cmd.append(rev) |
| 781 | cmd.append('--') |
| 782 | if GitCommand(self, cmd).Wait() != 0: |
| 783 | if self._allrefs: |
| 784 | raise GitError('%s checkout %s ' % (self.name, rev)) |
| 785 | |
| 786 | def _ResetHard(self, rev, quiet=True): |
| 787 | cmd = ['reset', '--hard'] |
| 788 | if quiet: |
| 789 | cmd.append('-q') |
| 790 | cmd.append(rev) |
| 791 | if GitCommand(self, cmd).Wait() != 0: |
| 792 | raise GitError('%s reset --hard %s ' % (self.name, rev)) |
| 793 | |
| 794 | def _Rebase(self, upstream, onto = None): |
| 795 | cmd = ['rebase', '-i'] |
| 796 | if onto is not None: |
| 797 | cmd.extend(['--onto', onto]) |
| 798 | cmd.append(upstream) |
| 799 | if GitCommand(self, cmd, disable_editor=True).Wait() != 0: |
| 800 | raise GitError('%s rebase %s ' % (self.name, upstream)) |
| 801 | |
| 802 | def _FastForward(self, head): |
| 803 | cmd = ['merge', head] |
| 804 | if GitCommand(self, cmd).Wait() != 0: |
| 805 | raise GitError('%s merge %s ' % (self.name, head)) |
| 806 | |
| 807 | def _InitGitDir(self): |
| 808 | if not os.path.exists(self.gitdir): |
| 809 | os.makedirs(self.gitdir) |
| 810 | self.bare_git.init() |
| 811 | self.config.SetString('core.bare', None) |
| 812 | |
| 813 | hooks = self._gitdir_path('hooks') |
| 814 | for old_hook in os.listdir(hooks): |
| 815 | os.remove(os.path.join(hooks, old_hook)) |
| 816 | |
| 817 | # TODO(sop) install custom repo hooks |
| 818 | |
| 819 | m = self.manifest.manifestProject.config |
| 820 | for key in ['user.name', 'user.email']: |
| 821 | if m.Has(key, include_defaults = False): |
| 822 | self.config.SetString(key, m.GetString(key)) |
| 823 | |
| 824 | def _InitRemote(self): |
| 825 | if self.remote.fetchUrl: |
| 826 | remote = self.GetRemote(self.remote.name) |
| 827 | |
| 828 | url = self.remote.fetchUrl |
| 829 | while url.endswith('/'): |
| 830 | url = url[:-1] |
| 831 | url += '/%s.git' % self.name |
| 832 | remote.url = url |
| 833 | remote.review = self.remote.reviewUrl |
| 834 | |
| 835 | remote.ResetFetch() |
| 836 | remote.Save() |
| 837 | |
| 838 | for r in self.extraRemotes.values(): |
| 839 | remote = self.GetRemote(r.name) |
| 840 | remote.url = r.fetchUrl |
| 841 | remote.review = r.reviewUrl |
| 842 | remote.ResetFetch() |
| 843 | remote.Save() |
| 844 | |
| 845 | def _InitMRef(self): |
| 846 | if self.manifest.branch: |
| 847 | msg = 'manifest set to %s' % self.revision |
| 848 | ref = R_M + self.manifest.branch |
| 849 | |
| 850 | if IsId(self.revision): |
| 851 | dst = self.revision + '^0', |
| 852 | self.bare_git.UpdateRef(ref, dst, message = msg, detach = True) |
| 853 | else: |
| 854 | remote = self.GetRemote(self.remote.name) |
| 855 | dst = remote.ToLocal(self.revision) |
| 856 | self.bare_git.symbolic_ref('-m', msg, ref, dst) |
| 857 | |
| 858 | def _InitWorkTree(self): |
| 859 | dotgit = os.path.join(self.worktree, '.git') |
| 860 | if not os.path.exists(dotgit): |
| 861 | os.makedirs(dotgit) |
| 862 | |
| 863 | topdir = os.path.commonprefix([self.gitdir, dotgit]) |
| 864 | if topdir.endswith('/'): |
| 865 | topdir = topdir[:-1] |
| 866 | else: |
| 867 | topdir = os.path.dirname(topdir) |
| 868 | |
| 869 | tmpdir = dotgit |
| 870 | relgit = '' |
| 871 | while topdir != tmpdir: |
| 872 | relgit += '../' |
| 873 | tmpdir = os.path.dirname(tmpdir) |
| 874 | relgit += self.gitdir[len(topdir) + 1:] |
| 875 | |
| 876 | for name in ['config', |
| 877 | 'description', |
| 878 | 'hooks', |
| 879 | 'info', |
| 880 | 'logs', |
| 881 | 'objects', |
| 882 | 'packed-refs', |
| 883 | 'refs', |
| 884 | 'rr-cache', |
| 885 | 'svn']: |
| 886 | os.symlink(os.path.join(relgit, name), |
| 887 | os.path.join(dotgit, name)) |
| 888 | |
| 889 | rev = self.GetRemote(self.remote.name).ToLocal(self.revision) |
| 890 | rev = self.bare_git.rev_parse('%s^0' % rev) |
| 891 | |
| 892 | f = open(os.path.join(dotgit, HEAD), 'wb') |
| 893 | f.write("%s\n" % rev) |
| 894 | f.close() |
| 895 | |
| 896 | cmd = ['read-tree', '--reset', '-u'] |
| 897 | cmd.append('-v') |
| 898 | cmd.append('HEAD') |
| 899 | if GitCommand(self, cmd).Wait() != 0: |
| 900 | raise GitError("cannot initialize work tree") |
| 901 | |
| 902 | def _gitdir_path(self, path): |
| 903 | return os.path.join(self.gitdir, path) |
| 904 | |
| 905 | def _revlist(self, *args): |
| 906 | cmd = [] |
| 907 | cmd.extend(args) |
| 908 | cmd.append('--') |
| 909 | return self.work_git.rev_list(*args) |
| 910 | |
| 911 | @property |
| 912 | def _allrefs(self): |
| 913 | return self.bare_git.ListRefs() |
| 914 | |
| 915 | class _GitGetByExec(object): |
| 916 | def __init__(self, project, bare): |
| 917 | self._project = project |
| 918 | self._bare = bare |
| 919 | |
| 920 | def ListRefs(self, *args): |
| 921 | cmdv = ['for-each-ref', '--format=%(objectname) %(refname)'] |
| 922 | cmdv.extend(args) |
| 923 | p = GitCommand(self._project, |
| 924 | cmdv, |
| 925 | bare = self._bare, |
| 926 | capture_stdout = True, |
| 927 | capture_stderr = True) |
| 928 | r = {} |
| 929 | for line in p.process.stdout: |
| 930 | id, name = line[:-1].split(' ', 2) |
| 931 | r[name] = id |
| 932 | if p.Wait() != 0: |
| 933 | raise GitError('%s for-each-ref %s: %s' % ( |
| 934 | self._project.name, |
| 935 | str(args), |
| 936 | p.stderr)) |
| 937 | return r |
| 938 | |
| 939 | def LsOthers(self): |
| 940 | p = GitCommand(self._project, |
| 941 | ['ls-files', |
| 942 | '-z', |
| 943 | '--others', |
| 944 | '--exclude-standard'], |
| 945 | bare = False, |
| 946 | capture_stdout = True, |
| 947 | capture_stderr = True) |
| 948 | if p.Wait() == 0: |
| 949 | out = p.stdout |
| 950 | if out: |
| 951 | return out[:-1].split("\0") |
| 952 | return [] |
| 953 | |
| 954 | def DiffZ(self, name, *args): |
| 955 | cmd = [name] |
| 956 | cmd.append('-z') |
| 957 | cmd.extend(args) |
| 958 | p = GitCommand(self._project, |
| 959 | cmd, |
| 960 | bare = False, |
| 961 | capture_stdout = True, |
| 962 | capture_stderr = True) |
| 963 | try: |
| 964 | out = p.process.stdout.read() |
| 965 | r = {} |
| 966 | if out: |
| 967 | out = iter(out[:-1].split('\0')) |
| 968 | while out: |
Shawn O. Pearce | 02dbb6d | 2008-10-21 13:59:08 -0700 | [diff] [blame] | 969 | try: |
| 970 | info = out.next() |
| 971 | path = out.next() |
| 972 | except StopIteration: |
| 973 | break |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 974 | |
| 975 | class _Info(object): |
| 976 | def __init__(self, path, omode, nmode, oid, nid, state): |
| 977 | self.path = path |
| 978 | self.src_path = None |
| 979 | self.old_mode = omode |
| 980 | self.new_mode = nmode |
| 981 | self.old_id = oid |
| 982 | self.new_id = nid |
| 983 | |
| 984 | if len(state) == 1: |
| 985 | self.status = state |
| 986 | self.level = None |
| 987 | else: |
| 988 | self.status = state[:1] |
| 989 | self.level = state[1:] |
| 990 | while self.level.startswith('0'): |
| 991 | self.level = self.level[1:] |
| 992 | |
| 993 | info = info[1:].split(' ') |
| 994 | info =_Info(path, *info) |
| 995 | if info.status in ('R', 'C'): |
| 996 | info.src_path = info.path |
| 997 | info.path = out.next() |
| 998 | r[info.path] = info |
| 999 | return r |
| 1000 | finally: |
| 1001 | p.Wait() |
| 1002 | |
| 1003 | def GetHead(self): |
| 1004 | return self.symbolic_ref(HEAD) |
| 1005 | |
| 1006 | def SetHead(self, ref, message=None): |
| 1007 | cmdv = [] |
| 1008 | if message is not None: |
| 1009 | cmdv.extend(['-m', message]) |
| 1010 | cmdv.append(HEAD) |
| 1011 | cmdv.append(ref) |
| 1012 | self.symbolic_ref(*cmdv) |
| 1013 | |
| 1014 | def DetachHead(self, new, message=None): |
| 1015 | cmdv = ['--no-deref'] |
| 1016 | if message is not None: |
| 1017 | cmdv.extend(['-m', message]) |
| 1018 | cmdv.append(HEAD) |
| 1019 | cmdv.append(new) |
| 1020 | self.update_ref(*cmdv) |
| 1021 | |
| 1022 | def UpdateRef(self, name, new, old=None, |
| 1023 | message=None, |
| 1024 | detach=False): |
| 1025 | cmdv = [] |
| 1026 | if message is not None: |
| 1027 | cmdv.extend(['-m', message]) |
| 1028 | if detach: |
| 1029 | cmdv.append('--no-deref') |
| 1030 | cmdv.append(name) |
| 1031 | cmdv.append(new) |
| 1032 | if old is not None: |
| 1033 | cmdv.append(old) |
| 1034 | self.update_ref(*cmdv) |
| 1035 | |
| 1036 | def DeleteRef(self, name, old=None): |
| 1037 | if not old: |
| 1038 | old = self.rev_parse(name) |
| 1039 | self.update_ref('-d', name, old) |
| 1040 | |
| 1041 | def rev_list(self, *args): |
| 1042 | cmdv = ['rev-list'] |
| 1043 | cmdv.extend(args) |
| 1044 | p = GitCommand(self._project, |
| 1045 | cmdv, |
| 1046 | bare = self._bare, |
| 1047 | capture_stdout = True, |
| 1048 | capture_stderr = True) |
| 1049 | r = [] |
| 1050 | for line in p.process.stdout: |
| 1051 | r.append(line[:-1]) |
| 1052 | if p.Wait() != 0: |
| 1053 | raise GitError('%s rev-list %s: %s' % ( |
| 1054 | self._project.name, |
| 1055 | str(args), |
| 1056 | p.stderr)) |
| 1057 | return r |
| 1058 | |
| 1059 | def __getattr__(self, name): |
| 1060 | name = name.replace('_', '-') |
| 1061 | def runner(*args): |
| 1062 | cmdv = [name] |
| 1063 | cmdv.extend(args) |
| 1064 | p = GitCommand(self._project, |
| 1065 | cmdv, |
| 1066 | bare = self._bare, |
| 1067 | capture_stdout = True, |
| 1068 | capture_stderr = True) |
| 1069 | if p.Wait() != 0: |
| 1070 | raise GitError('%s %s: %s' % ( |
| 1071 | self._project.name, |
| 1072 | name, |
| 1073 | p.stderr)) |
| 1074 | r = p.stdout |
| 1075 | if r.endswith('\n') and r.index('\n') == len(r) - 1: |
| 1076 | return r[:-1] |
| 1077 | return r |
| 1078 | return runner |
| 1079 | |
| 1080 | |
| 1081 | class MetaProject(Project): |
| 1082 | """A special project housed under .repo. |
| 1083 | """ |
| 1084 | def __init__(self, manifest, name, gitdir, worktree): |
| 1085 | repodir = manifest.repodir |
| 1086 | Project.__init__(self, |
| 1087 | manifest = manifest, |
| 1088 | name = name, |
| 1089 | gitdir = gitdir, |
| 1090 | worktree = worktree, |
| 1091 | remote = Remote('origin'), |
| 1092 | relpath = '.repo/%s' % name, |
| 1093 | revision = 'refs/heads/master') |
| 1094 | |
| 1095 | def PreSync(self): |
| 1096 | if self.Exists: |
| 1097 | cb = self.CurrentBranch |
| 1098 | if cb: |
| 1099 | base = self.GetBranch(cb).merge |
| 1100 | if base: |
| 1101 | self.revision = base |
| 1102 | |
| 1103 | @property |
| 1104 | def HasChanges(self): |
| 1105 | """Has the remote received new commits not yet checked out? |
| 1106 | """ |
| 1107 | rev = self.GetRemote(self.remote.name).ToLocal(self.revision) |
| 1108 | if self._revlist(not_rev(HEAD), rev): |
| 1109 | return True |
| 1110 | return False |