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