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 |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 469 | if not self._RemoteFetch(): |
| 470 | return False |
Shawn O. Pearce | 329c31d | 2008-10-24 09:17:25 -0700 | [diff] [blame] | 471 | self._RepairAndroidImportErrors() |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 472 | self._InitMRef() |
| 473 | return True |
| 474 | |
| 475 | def _CopyFiles(self): |
| 476 | for file in self.copyfiles: |
| 477 | file._Copy() |
| 478 | |
Shawn O. Pearce | 329c31d | 2008-10-24 09:17:25 -0700 | [diff] [blame] | 479 | def _RepairAndroidImportErrors(self): |
| 480 | if self.name in ['platform/external/iptables', |
| 481 | 'platform/external/libpcap', |
| 482 | 'platform/external/tcpdump', |
| 483 | 'platform/external/webkit', |
| 484 | 'platform/system/wlan/ti']: |
| 485 | # I hate myself for doing this... |
| 486 | # |
| 487 | # In the initial Android 1.0 release these projects were |
| 488 | # shipped, some users got them, and then the history had |
| 489 | # to be rewritten to correct problems with their imports. |
| 490 | # The 'android-1.0' tag may still be pointing at the old |
| 491 | # history, so we need to drop the tag and fetch it again. |
| 492 | # |
| 493 | try: |
| 494 | remote = self.GetRemote(self.remote.name) |
| 495 | relname = remote.ToLocal(R_HEADS + 'release-1.0') |
| 496 | tagname = R_TAGS + 'android-1.0' |
| 497 | if self._revlist(not_rev(relname), tagname): |
| 498 | cmd = ['fetch', remote.name, '+%s:%s' % (tagname, tagname)] |
| 499 | GitCommand(self, cmd, bare = True).Wait() |
| 500 | except GitError: |
| 501 | pass |
| 502 | |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 503 | def Sync_LocalHalf(self): |
| 504 | """Perform only the local IO portion of the sync process. |
| 505 | Network access is not required. |
| 506 | |
| 507 | Return: |
| 508 | True: the sync was successful |
| 509 | False: the sync requires user input |
| 510 | """ |
| 511 | self._InitWorkTree() |
| 512 | self.CleanPublishedCache() |
| 513 | |
| 514 | rem = self.GetRemote(self.remote.name) |
| 515 | rev = rem.ToLocal(self.revision) |
| 516 | branch = self.CurrentBranch |
| 517 | |
| 518 | if branch is None: |
| 519 | # Currently on a detached HEAD. The user is assumed to |
| 520 | # not have any local modifications worth worrying about. |
| 521 | # |
| 522 | lost = self._revlist(not_rev(rev), HEAD) |
| 523 | if lost: |
| 524 | _info("[%s] Discarding %d commits", self.name, len(lost)) |
| 525 | try: |
| 526 | self._Checkout(rev, quiet=True) |
| 527 | except GitError: |
| 528 | return False |
| 529 | self._CopyFiles() |
| 530 | return True |
| 531 | |
| 532 | branch = self.GetBranch(branch) |
| 533 | merge = branch.LocalMerge |
| 534 | |
| 535 | if not merge: |
| 536 | # The current branch has no tracking configuration. |
| 537 | # Jump off it to a deatched HEAD. |
| 538 | # |
| 539 | _info("[%s] Leaving %s" |
| 540 | " (does not track any upstream)", |
| 541 | self.name, |
| 542 | branch.name) |
| 543 | try: |
| 544 | self._Checkout(rev, quiet=True) |
| 545 | except GitError: |
| 546 | return False |
| 547 | self._CopyFiles() |
| 548 | return True |
| 549 | |
| 550 | upstream_gain = self._revlist(not_rev(HEAD), rev) |
| 551 | pub = self.WasPublished(branch.name) |
| 552 | if pub: |
| 553 | not_merged = self._revlist(not_rev(rev), pub) |
| 554 | if not_merged: |
| 555 | if upstream_gain: |
| 556 | # The user has published this branch and some of those |
| 557 | # commits are not yet merged upstream. We do not want |
| 558 | # to rewrite the published commits so we punt. |
| 559 | # |
| 560 | _info("[%s] Branch %s is published," |
| 561 | " but is now %d commits behind.", |
| 562 | self.name, branch.name, len(upstream_gain)) |
| 563 | _info("[%s] Consider merging or rebasing the" |
| 564 | " unpublished commits.", self.name) |
| 565 | return True |
Shawn O. Pearce | 23d7781 | 2008-10-30 11:06:57 -0700 | [diff] [blame^] | 566 | elif upstream_gain: |
Shawn O. Pearce | a54c527 | 2008-10-30 11:03:00 -0700 | [diff] [blame] | 567 | # We can fast-forward safely. |
| 568 | # |
| 569 | try: |
| 570 | self._FastForward(rev) |
| 571 | except GitError: |
| 572 | return False |
| 573 | self._CopyFiles() |
| 574 | return True |
Shawn O. Pearce | 23d7781 | 2008-10-30 11:06:57 -0700 | [diff] [blame^] | 575 | else: |
| 576 | # Trivially no changes in the upstream. |
| 577 | # |
| 578 | return True |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 579 | |
| 580 | if merge == rev: |
| 581 | try: |
| 582 | old_merge = self.bare_git.rev_parse('%s@{1}' % merge) |
| 583 | except GitError: |
| 584 | old_merge = merge |
Shawn O. Pearce | 0734600 | 2008-10-21 07:09:27 -0700 | [diff] [blame] | 585 | if old_merge == '0000000000000000000000000000000000000000' \ |
| 586 | or old_merge == '': |
| 587 | old_merge = merge |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 588 | else: |
| 589 | # The upstream switched on us. Time to cross our fingers |
| 590 | # and pray that the old upstream also wasn't in the habit |
| 591 | # of rebasing itself. |
| 592 | # |
| 593 | _info("[%s] Manifest switched from %s to %s", |
| 594 | self.name, merge, rev) |
| 595 | old_merge = merge |
| 596 | |
| 597 | if rev == old_merge: |
| 598 | upstream_lost = [] |
| 599 | else: |
| 600 | upstream_lost = self._revlist(not_rev(rev), old_merge) |
| 601 | |
| 602 | if not upstream_lost and not upstream_gain: |
| 603 | # Trivially no changes caused by the upstream. |
| 604 | # |
| 605 | return True |
| 606 | |
| 607 | if self.IsDirty(consider_untracked=False): |
| 608 | _warn('[%s] commit (or discard) uncommitted changes' |
| 609 | ' before sync', self.name) |
| 610 | return False |
| 611 | |
| 612 | if upstream_lost: |
| 613 | # Upstream rebased. Not everything in HEAD |
| 614 | # may have been caused by the user. |
| 615 | # |
| 616 | _info("[%s] Discarding %d commits removed from upstream", |
| 617 | self.name, len(upstream_lost)) |
| 618 | |
| 619 | branch.remote = rem |
| 620 | branch.merge = self.revision |
| 621 | branch.Save() |
| 622 | |
| 623 | my_changes = self._revlist(not_rev(old_merge), HEAD) |
| 624 | if my_changes: |
| 625 | try: |
| 626 | self._Rebase(upstream = old_merge, onto = rev) |
| 627 | except GitError: |
| 628 | return False |
| 629 | elif upstream_lost: |
| 630 | try: |
| 631 | self._ResetHard(rev) |
| 632 | except GitError: |
| 633 | return False |
| 634 | else: |
| 635 | try: |
| 636 | self._FastForward(rev) |
| 637 | except GitError: |
| 638 | return False |
| 639 | |
| 640 | self._CopyFiles() |
| 641 | return True |
| 642 | |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 643 | def AddCopyFile(self, src, dest): |
| 644 | # dest should already be an absolute path, but src is project relative |
| 645 | # make src an absolute path |
| 646 | src = os.path.join(self.worktree, src) |
| 647 | self.copyfiles.append(_CopyFile(src, dest)) |
| 648 | |
Shawn O. Pearce | 632768b | 2008-10-23 11:58:52 -0700 | [diff] [blame] | 649 | def DownloadPatchSet(self, change_id, patch_id): |
| 650 | """Download a single patch set of a single change to FETCH_HEAD. |
| 651 | """ |
| 652 | remote = self.GetRemote(self.remote.name) |
| 653 | |
| 654 | cmd = ['fetch', remote.name] |
| 655 | cmd.append('refs/changes/%2.2d/%d/%d' \ |
| 656 | % (change_id % 100, change_id, patch_id)) |
| 657 | cmd.extend(map(lambda x: str(x), remote.fetch)) |
| 658 | if GitCommand(self, cmd, bare=True).Wait() != 0: |
| 659 | return None |
| 660 | return DownloadedChange(self, |
| 661 | remote.ToLocal(self.revision), |
| 662 | change_id, |
| 663 | patch_id, |
| 664 | self.bare_git.rev_parse('FETCH_HEAD')) |
| 665 | |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 666 | |
| 667 | ## Branch Management ## |
| 668 | |
| 669 | def StartBranch(self, name): |
| 670 | """Create a new branch off the manifest's revision. |
| 671 | """ |
| 672 | branch = self.GetBranch(name) |
| 673 | branch.remote = self.GetRemote(self.remote.name) |
| 674 | branch.merge = self.revision |
| 675 | |
| 676 | rev = branch.LocalMerge |
| 677 | cmd = ['checkout', '-b', branch.name, rev] |
| 678 | if GitCommand(self, cmd).Wait() == 0: |
| 679 | branch.Save() |
| 680 | else: |
| 681 | raise GitError('%s checkout %s ' % (self.name, rev)) |
| 682 | |
| 683 | def PruneHeads(self): |
| 684 | """Prune any topic branches already merged into upstream. |
| 685 | """ |
| 686 | cb = self.CurrentBranch |
| 687 | kill = [] |
| 688 | for name in self._allrefs.keys(): |
| 689 | if name.startswith(R_HEADS): |
| 690 | name = name[len(R_HEADS):] |
| 691 | if cb is None or name != cb: |
| 692 | kill.append(name) |
| 693 | |
| 694 | rev = self.GetRemote(self.remote.name).ToLocal(self.revision) |
| 695 | if cb is not None \ |
| 696 | and not self._revlist(HEAD + '...' + rev) \ |
| 697 | and not self.IsDirty(consider_untracked = False): |
| 698 | self.work_git.DetachHead(HEAD) |
| 699 | kill.append(cb) |
| 700 | |
| 701 | deleted = set() |
| 702 | if kill: |
| 703 | try: |
| 704 | old = self.bare_git.GetHead() |
| 705 | except GitError: |
| 706 | old = 'refs/heads/please_never_use_this_as_a_branch_name' |
| 707 | |
| 708 | rm_re = re.compile(r"^Deleted branch (.*)\.$") |
| 709 | try: |
| 710 | self.bare_git.DetachHead(rev) |
| 711 | |
| 712 | b = ['branch', '-d'] |
| 713 | b.extend(kill) |
| 714 | b = GitCommand(self, b, bare=True, |
| 715 | capture_stdout=True, |
| 716 | capture_stderr=True) |
| 717 | b.Wait() |
| 718 | finally: |
| 719 | self.bare_git.SetHead(old) |
| 720 | |
| 721 | for line in b.stdout.split("\n"): |
| 722 | m = rm_re.match(line) |
| 723 | if m: |
| 724 | deleted.add(m.group(1)) |
| 725 | |
| 726 | if deleted: |
| 727 | self.CleanPublishedCache() |
| 728 | |
| 729 | if cb and cb not in kill: |
| 730 | kill.append(cb) |
| 731 | kill.sort() |
| 732 | |
| 733 | kept = [] |
| 734 | for branch in kill: |
| 735 | if branch not in deleted: |
| 736 | branch = self.GetBranch(branch) |
| 737 | base = branch.LocalMerge |
| 738 | if not base: |
| 739 | base = rev |
| 740 | kept.append(ReviewableBranch(self, branch, base)) |
| 741 | return kept |
| 742 | |
| 743 | |
| 744 | ## Direct Git Commands ## |
| 745 | |
| 746 | def _RemoteFetch(self, name=None): |
| 747 | if not name: |
| 748 | name = self.remote.name |
Shawn O. Pearce | ce03a40 | 2008-10-28 16:12:03 -0700 | [diff] [blame] | 749 | return GitCommand(self, |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 750 | ['fetch', name], |
Shawn O. Pearce | ce03a40 | 2008-10-28 16:12:03 -0700 | [diff] [blame] | 751 | bare = True).Wait() == 0 |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 752 | |
| 753 | def _Checkout(self, rev, quiet=False): |
| 754 | cmd = ['checkout'] |
| 755 | if quiet: |
| 756 | cmd.append('-q') |
| 757 | cmd.append(rev) |
| 758 | cmd.append('--') |
| 759 | if GitCommand(self, cmd).Wait() != 0: |
| 760 | if self._allrefs: |
| 761 | raise GitError('%s checkout %s ' % (self.name, rev)) |
| 762 | |
| 763 | def _ResetHard(self, rev, quiet=True): |
| 764 | cmd = ['reset', '--hard'] |
| 765 | if quiet: |
| 766 | cmd.append('-q') |
| 767 | cmd.append(rev) |
| 768 | if GitCommand(self, cmd).Wait() != 0: |
| 769 | raise GitError('%s reset --hard %s ' % (self.name, rev)) |
| 770 | |
| 771 | def _Rebase(self, upstream, onto = None): |
| 772 | cmd = ['rebase', '-i'] |
| 773 | if onto is not None: |
| 774 | cmd.extend(['--onto', onto]) |
| 775 | cmd.append(upstream) |
| 776 | if GitCommand(self, cmd, disable_editor=True).Wait() != 0: |
| 777 | raise GitError('%s rebase %s ' % (self.name, upstream)) |
| 778 | |
| 779 | def _FastForward(self, head): |
| 780 | cmd = ['merge', head] |
| 781 | if GitCommand(self, cmd).Wait() != 0: |
| 782 | raise GitError('%s merge %s ' % (self.name, head)) |
| 783 | |
| 784 | def _InitGitDir(self): |
| 785 | if not os.path.exists(self.gitdir): |
| 786 | os.makedirs(self.gitdir) |
| 787 | self.bare_git.init() |
| 788 | self.config.SetString('core.bare', None) |
| 789 | |
| 790 | hooks = self._gitdir_path('hooks') |
Shawn O. Pearce | de64681 | 2008-10-29 14:38:12 -0700 | [diff] [blame] | 791 | try: |
| 792 | to_rm = os.listdir(hooks) |
| 793 | except OSError: |
| 794 | to_rm = [] |
| 795 | for old_hook in to_rm: |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 796 | os.remove(os.path.join(hooks, old_hook)) |
| 797 | |
| 798 | # TODO(sop) install custom repo hooks |
| 799 | |
| 800 | m = self.manifest.manifestProject.config |
| 801 | for key in ['user.name', 'user.email']: |
| 802 | if m.Has(key, include_defaults = False): |
| 803 | self.config.SetString(key, m.GetString(key)) |
| 804 | |
| 805 | def _InitRemote(self): |
| 806 | if self.remote.fetchUrl: |
| 807 | remote = self.GetRemote(self.remote.name) |
| 808 | |
| 809 | url = self.remote.fetchUrl |
| 810 | while url.endswith('/'): |
| 811 | url = url[:-1] |
| 812 | url += '/%s.git' % self.name |
| 813 | remote.url = url |
| 814 | remote.review = self.remote.reviewUrl |
| 815 | |
| 816 | remote.ResetFetch() |
| 817 | remote.Save() |
| 818 | |
| 819 | for r in self.extraRemotes.values(): |
| 820 | remote = self.GetRemote(r.name) |
| 821 | remote.url = r.fetchUrl |
| 822 | remote.review = r.reviewUrl |
| 823 | remote.ResetFetch() |
| 824 | remote.Save() |
| 825 | |
| 826 | def _InitMRef(self): |
| 827 | if self.manifest.branch: |
| 828 | msg = 'manifest set to %s' % self.revision |
| 829 | ref = R_M + self.manifest.branch |
| 830 | |
| 831 | if IsId(self.revision): |
| 832 | dst = self.revision + '^0', |
| 833 | self.bare_git.UpdateRef(ref, dst, message = msg, detach = True) |
| 834 | else: |
| 835 | remote = self.GetRemote(self.remote.name) |
| 836 | dst = remote.ToLocal(self.revision) |
| 837 | self.bare_git.symbolic_ref('-m', msg, ref, dst) |
| 838 | |
| 839 | def _InitWorkTree(self): |
| 840 | dotgit = os.path.join(self.worktree, '.git') |
| 841 | if not os.path.exists(dotgit): |
| 842 | os.makedirs(dotgit) |
| 843 | |
| 844 | topdir = os.path.commonprefix([self.gitdir, dotgit]) |
| 845 | if topdir.endswith('/'): |
| 846 | topdir = topdir[:-1] |
| 847 | else: |
| 848 | topdir = os.path.dirname(topdir) |
| 849 | |
| 850 | tmpdir = dotgit |
| 851 | relgit = '' |
| 852 | while topdir != tmpdir: |
| 853 | relgit += '../' |
| 854 | tmpdir = os.path.dirname(tmpdir) |
| 855 | relgit += self.gitdir[len(topdir) + 1:] |
| 856 | |
| 857 | for name in ['config', |
| 858 | 'description', |
| 859 | 'hooks', |
| 860 | 'info', |
| 861 | 'logs', |
| 862 | 'objects', |
| 863 | 'packed-refs', |
| 864 | 'refs', |
| 865 | 'rr-cache', |
| 866 | 'svn']: |
| 867 | os.symlink(os.path.join(relgit, name), |
| 868 | os.path.join(dotgit, name)) |
| 869 | |
| 870 | rev = self.GetRemote(self.remote.name).ToLocal(self.revision) |
| 871 | rev = self.bare_git.rev_parse('%s^0' % rev) |
| 872 | |
| 873 | f = open(os.path.join(dotgit, HEAD), 'wb') |
| 874 | f.write("%s\n" % rev) |
| 875 | f.close() |
| 876 | |
| 877 | cmd = ['read-tree', '--reset', '-u'] |
| 878 | cmd.append('-v') |
| 879 | cmd.append('HEAD') |
| 880 | if GitCommand(self, cmd).Wait() != 0: |
| 881 | raise GitError("cannot initialize work tree") |
| 882 | |
| 883 | def _gitdir_path(self, path): |
| 884 | return os.path.join(self.gitdir, path) |
| 885 | |
| 886 | def _revlist(self, *args): |
| 887 | cmd = [] |
| 888 | cmd.extend(args) |
| 889 | cmd.append('--') |
| 890 | return self.work_git.rev_list(*args) |
| 891 | |
| 892 | @property |
| 893 | def _allrefs(self): |
| 894 | return self.bare_git.ListRefs() |
| 895 | |
| 896 | class _GitGetByExec(object): |
| 897 | def __init__(self, project, bare): |
| 898 | self._project = project |
| 899 | self._bare = bare |
| 900 | |
| 901 | def ListRefs(self, *args): |
| 902 | cmdv = ['for-each-ref', '--format=%(objectname) %(refname)'] |
| 903 | cmdv.extend(args) |
| 904 | p = GitCommand(self._project, |
| 905 | cmdv, |
| 906 | bare = self._bare, |
| 907 | capture_stdout = True, |
| 908 | capture_stderr = True) |
| 909 | r = {} |
| 910 | for line in p.process.stdout: |
| 911 | id, name = line[:-1].split(' ', 2) |
| 912 | r[name] = id |
| 913 | if p.Wait() != 0: |
| 914 | raise GitError('%s for-each-ref %s: %s' % ( |
| 915 | self._project.name, |
| 916 | str(args), |
| 917 | p.stderr)) |
| 918 | return r |
| 919 | |
| 920 | def LsOthers(self): |
| 921 | p = GitCommand(self._project, |
| 922 | ['ls-files', |
| 923 | '-z', |
| 924 | '--others', |
| 925 | '--exclude-standard'], |
| 926 | bare = False, |
| 927 | capture_stdout = True, |
| 928 | capture_stderr = True) |
| 929 | if p.Wait() == 0: |
| 930 | out = p.stdout |
| 931 | if out: |
| 932 | return out[:-1].split("\0") |
| 933 | return [] |
| 934 | |
| 935 | def DiffZ(self, name, *args): |
| 936 | cmd = [name] |
| 937 | cmd.append('-z') |
| 938 | cmd.extend(args) |
| 939 | p = GitCommand(self._project, |
| 940 | cmd, |
| 941 | bare = False, |
| 942 | capture_stdout = True, |
| 943 | capture_stderr = True) |
| 944 | try: |
| 945 | out = p.process.stdout.read() |
| 946 | r = {} |
| 947 | if out: |
| 948 | out = iter(out[:-1].split('\0')) |
| 949 | while out: |
Shawn O. Pearce | 02dbb6d | 2008-10-21 13:59:08 -0700 | [diff] [blame] | 950 | try: |
| 951 | info = out.next() |
| 952 | path = out.next() |
| 953 | except StopIteration: |
| 954 | break |
The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 955 | |
| 956 | class _Info(object): |
| 957 | def __init__(self, path, omode, nmode, oid, nid, state): |
| 958 | self.path = path |
| 959 | self.src_path = None |
| 960 | self.old_mode = omode |
| 961 | self.new_mode = nmode |
| 962 | self.old_id = oid |
| 963 | self.new_id = nid |
| 964 | |
| 965 | if len(state) == 1: |
| 966 | self.status = state |
| 967 | self.level = None |
| 968 | else: |
| 969 | self.status = state[:1] |
| 970 | self.level = state[1:] |
| 971 | while self.level.startswith('0'): |
| 972 | self.level = self.level[1:] |
| 973 | |
| 974 | info = info[1:].split(' ') |
| 975 | info =_Info(path, *info) |
| 976 | if info.status in ('R', 'C'): |
| 977 | info.src_path = info.path |
| 978 | info.path = out.next() |
| 979 | r[info.path] = info |
| 980 | return r |
| 981 | finally: |
| 982 | p.Wait() |
| 983 | |
| 984 | def GetHead(self): |
| 985 | return self.symbolic_ref(HEAD) |
| 986 | |
| 987 | def SetHead(self, ref, message=None): |
| 988 | cmdv = [] |
| 989 | if message is not None: |
| 990 | cmdv.extend(['-m', message]) |
| 991 | cmdv.append(HEAD) |
| 992 | cmdv.append(ref) |
| 993 | self.symbolic_ref(*cmdv) |
| 994 | |
| 995 | def DetachHead(self, new, message=None): |
| 996 | cmdv = ['--no-deref'] |
| 997 | if message is not None: |
| 998 | cmdv.extend(['-m', message]) |
| 999 | cmdv.append(HEAD) |
| 1000 | cmdv.append(new) |
| 1001 | self.update_ref(*cmdv) |
| 1002 | |
| 1003 | def UpdateRef(self, name, new, old=None, |
| 1004 | message=None, |
| 1005 | detach=False): |
| 1006 | cmdv = [] |
| 1007 | if message is not None: |
| 1008 | cmdv.extend(['-m', message]) |
| 1009 | if detach: |
| 1010 | cmdv.append('--no-deref') |
| 1011 | cmdv.append(name) |
| 1012 | cmdv.append(new) |
| 1013 | if old is not None: |
| 1014 | cmdv.append(old) |
| 1015 | self.update_ref(*cmdv) |
| 1016 | |
| 1017 | def DeleteRef(self, name, old=None): |
| 1018 | if not old: |
| 1019 | old = self.rev_parse(name) |
| 1020 | self.update_ref('-d', name, old) |
| 1021 | |
| 1022 | def rev_list(self, *args): |
| 1023 | cmdv = ['rev-list'] |
| 1024 | cmdv.extend(args) |
| 1025 | p = GitCommand(self._project, |
| 1026 | cmdv, |
| 1027 | bare = self._bare, |
| 1028 | capture_stdout = True, |
| 1029 | capture_stderr = True) |
| 1030 | r = [] |
| 1031 | for line in p.process.stdout: |
| 1032 | r.append(line[:-1]) |
| 1033 | if p.Wait() != 0: |
| 1034 | raise GitError('%s rev-list %s: %s' % ( |
| 1035 | self._project.name, |
| 1036 | str(args), |
| 1037 | p.stderr)) |
| 1038 | return r |
| 1039 | |
| 1040 | def __getattr__(self, name): |
| 1041 | name = name.replace('_', '-') |
| 1042 | def runner(*args): |
| 1043 | cmdv = [name] |
| 1044 | cmdv.extend(args) |
| 1045 | p = GitCommand(self._project, |
| 1046 | cmdv, |
| 1047 | bare = self._bare, |
| 1048 | capture_stdout = True, |
| 1049 | capture_stderr = True) |
| 1050 | if p.Wait() != 0: |
| 1051 | raise GitError('%s %s: %s' % ( |
| 1052 | self._project.name, |
| 1053 | name, |
| 1054 | p.stderr)) |
| 1055 | r = p.stdout |
| 1056 | if r.endswith('\n') and r.index('\n') == len(r) - 1: |
| 1057 | return r[:-1] |
| 1058 | return r |
| 1059 | return runner |
| 1060 | |
| 1061 | |
| 1062 | class MetaProject(Project): |
| 1063 | """A special project housed under .repo. |
| 1064 | """ |
| 1065 | def __init__(self, manifest, name, gitdir, worktree): |
| 1066 | repodir = manifest.repodir |
| 1067 | Project.__init__(self, |
| 1068 | manifest = manifest, |
| 1069 | name = name, |
| 1070 | gitdir = gitdir, |
| 1071 | worktree = worktree, |
| 1072 | remote = Remote('origin'), |
| 1073 | relpath = '.repo/%s' % name, |
| 1074 | revision = 'refs/heads/master') |
| 1075 | |
| 1076 | def PreSync(self): |
| 1077 | if self.Exists: |
| 1078 | cb = self.CurrentBranch |
| 1079 | if cb: |
| 1080 | base = self.GetBranch(cb).merge |
| 1081 | if base: |
| 1082 | self.revision = base |
| 1083 | |
| 1084 | @property |
| 1085 | def HasChanges(self): |
| 1086 | """Has the remote received new commits not yet checked out? |
| 1087 | """ |
| 1088 | rev = self.GetRemote(self.remote.name).ToLocal(self.revision) |
| 1089 | if self._revlist(not_rev(HEAD), rev): |
| 1090 | return True |
| 1091 | return False |