blob: 6621f1cb9d7621c52101a19121f5f2c82852b218 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001# 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
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -080015import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070016import filecmp
17import os
18import re
19import shutil
20import stat
21import sys
22import urllib2
23
24from color import Coloring
25from git_command import GitCommand
26from git_config import GitConfig, IsId
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070027from error import GitError, ImportError, UploadError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080028from error import ManifestInvalidRevisionError
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070029from remote import Remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030
31HEAD = 'HEAD'
32R_HEADS = 'refs/heads/'
33R_TAGS = 'refs/tags/'
34R_PUB = 'refs/published/'
35R_M = 'refs/remotes/m/'
36
Shawn O. Pearce48244782009-04-16 08:25:57 -070037def _error(fmt, *args):
38 msg = fmt % args
39 print >>sys.stderr, 'error: %s' % msg
40
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070041def not_rev(r):
42 return '^' + r
43
Shawn O. Pearceb54a3922009-01-05 16:18:58 -080044def sq(r):
45 return "'" + r.replace("'", "'\''") + "'"
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080046
47hook_list = None
48def repo_hooks():
49 global hook_list
50 if hook_list is None:
51 d = os.path.abspath(os.path.dirname(__file__))
52 d = os.path.join(d , 'hooks')
53 hook_list = map(lambda x: os.path.join(d, x), os.listdir(d))
54 return hook_list
55
56def relpath(dst, src):
57 src = os.path.dirname(src)
58 top = os.path.commonprefix([dst, src])
59 if top.endswith('/'):
60 top = top[:-1]
61 else:
62 top = os.path.dirname(top)
63
64 tmp = src
65 rel = ''
66 while top != tmp:
67 rel += '../'
68 tmp = os.path.dirname(tmp)
69 return rel + dst[len(top) + 1:]
70
71
Shawn O. Pearce632768b2008-10-23 11:58:52 -070072class DownloadedChange(object):
73 _commit_cache = None
74
75 def __init__(self, project, base, change_id, ps_id, commit):
76 self.project = project
77 self.base = base
78 self.change_id = change_id
79 self.ps_id = ps_id
80 self.commit = commit
81
82 @property
83 def commits(self):
84 if self._commit_cache is None:
85 self._commit_cache = self.project.bare_git.rev_list(
86 '--abbrev=8',
87 '--abbrev-commit',
88 '--pretty=oneline',
89 '--reverse',
90 '--date-order',
91 not_rev(self.base),
92 self.commit,
93 '--')
94 return self._commit_cache
95
96
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070097class ReviewableBranch(object):
98 _commit_cache = None
99
100 def __init__(self, project, branch, base):
101 self.project = project
102 self.branch = branch
103 self.base = base
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800104 self.replace_changes = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700105
106 @property
107 def name(self):
108 return self.branch.name
109
110 @property
111 def commits(self):
112 if self._commit_cache is None:
113 self._commit_cache = self.project.bare_git.rev_list(
114 '--abbrev=8',
115 '--abbrev-commit',
116 '--pretty=oneline',
117 '--reverse',
118 '--date-order',
119 not_rev(self.base),
120 R_HEADS + self.name,
121 '--')
122 return self._commit_cache
123
124 @property
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800125 def unabbrev_commits(self):
126 r = dict()
127 for commit in self.project.bare_git.rev_list(
128 not_rev(self.base),
129 R_HEADS + self.name,
130 '--'):
131 r[commit[0:8]] = commit
132 return r
133
134 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135 def date(self):
136 return self.project.bare_git.log(
137 '--pretty=format:%cd',
138 '-n', '1',
139 R_HEADS + self.name,
140 '--')
141
Joe Onorato2896a792008-11-17 16:56:36 -0500142 def UploadForReview(self, people):
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800143 self.project.UploadForReview(self.name,
Joe Onorato2896a792008-11-17 16:56:36 -0500144 self.replace_changes,
145 people)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700146
147 @property
148 def tip_url(self):
149 me = self.project.GetBranch(self.name)
150 commit = self.project.bare_git.rev_parse(R_HEADS + self.name)
151 return 'http://%s/r/%s' % (me.remote.review, commit[0:12])
152
Shawn O. Pearce0758d2f2008-10-22 13:13:40 -0700153 @property
154 def owner_email(self):
155 return self.project.UserEmail
156
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700157
158class StatusColoring(Coloring):
159 def __init__(self, config):
160 Coloring.__init__(self, config, 'status')
161 self.project = self.printer('header', attr = 'bold')
162 self.branch = self.printer('header', attr = 'bold')
163 self.nobranch = self.printer('nobranch', fg = 'red')
164
165 self.added = self.printer('added', fg = 'green')
166 self.changed = self.printer('changed', fg = 'red')
167 self.untracked = self.printer('untracked', fg = 'red')
168
169
170class DiffColoring(Coloring):
171 def __init__(self, config):
172 Coloring.__init__(self, config, 'diff')
173 self.project = self.printer('header', attr = 'bold')
174
175
176class _CopyFile:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800177 def __init__(self, src, dest, abssrc, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700178 self.src = src
179 self.dest = dest
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800180 self.abs_src = abssrc
181 self.abs_dest = absdest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700182
183 def _Copy(self):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800184 src = self.abs_src
185 dest = self.abs_dest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700186 # copy file if it does not exist or is out of date
187 if not os.path.exists(dest) or not filecmp.cmp(src, dest):
188 try:
189 # remove existing file first, since it might be read-only
190 if os.path.exists(dest):
191 os.remove(dest)
192 shutil.copy(src, dest)
193 # make the file read-only
194 mode = os.stat(dest)[stat.ST_MODE]
195 mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
196 os.chmod(dest, mode)
197 except IOError:
Shawn O. Pearce48244782009-04-16 08:25:57 -0700198 _error('Cannot copy file %s to %s', src, dest)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700199
200
201class Project(object):
202 def __init__(self,
203 manifest,
204 name,
205 remote,
206 gitdir,
207 worktree,
208 relpath,
209 revision):
210 self.manifest = manifest
211 self.name = name
212 self.remote = remote
213 self.gitdir = gitdir
214 self.worktree = worktree
215 self.relpath = relpath
216 self.revision = revision
217 self.snapshots = {}
218 self.extraRemotes = {}
219 self.copyfiles = []
220 self.config = GitConfig.ForRepository(
221 gitdir = self.gitdir,
222 defaults = self.manifest.globalConfig)
223
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800224 if self.worktree:
225 self.work_git = self._GitGetByExec(self, bare=False)
226 else:
227 self.work_git = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700228 self.bare_git = self._GitGetByExec(self, bare=True)
229
230 @property
231 def Exists(self):
232 return os.path.isdir(self.gitdir)
233
234 @property
235 def CurrentBranch(self):
236 """Obtain the name of the currently checked out branch.
237 The branch name omits the 'refs/heads/' prefix.
238 None is returned if the project is on a detached HEAD.
239 """
240 try:
241 b = self.work_git.GetHead()
242 except GitError:
243 return None
244 if b.startswith(R_HEADS):
245 return b[len(R_HEADS):]
246 return None
247
248 def IsDirty(self, consider_untracked=True):
249 """Is the working directory modified in some way?
250 """
251 self.work_git.update_index('-q',
252 '--unmerged',
253 '--ignore-missing',
254 '--refresh')
255 if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
256 return True
257 if self.work_git.DiffZ('diff-files'):
258 return True
259 if consider_untracked and self.work_git.LsOthers():
260 return True
261 return False
262
263 _userident_name = None
264 _userident_email = None
265
266 @property
267 def UserName(self):
268 """Obtain the user's personal name.
269 """
270 if self._userident_name is None:
271 self._LoadUserIdentity()
272 return self._userident_name
273
274 @property
275 def UserEmail(self):
276 """Obtain the user's email address. This is very likely
277 to be their Gerrit login.
278 """
279 if self._userident_email is None:
280 self._LoadUserIdentity()
281 return self._userident_email
282
283 def _LoadUserIdentity(self):
284 u = self.bare_git.var('GIT_COMMITTER_IDENT')
285 m = re.compile("^(.*) <([^>]*)> ").match(u)
286 if m:
287 self._userident_name = m.group(1)
288 self._userident_email = m.group(2)
289 else:
290 self._userident_name = ''
291 self._userident_email = ''
292
293 def GetRemote(self, name):
294 """Get the configuration for a single remote.
295 """
296 return self.config.GetRemote(name)
297
298 def GetBranch(self, name):
299 """Get the configuration for a single branch.
300 """
301 return self.config.GetBranch(name)
302
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700303 def GetBranches(self):
304 """Get all existing local branches.
305 """
306 current = self.CurrentBranch
307 all = self.bare_git.ListRefs()
308 heads = {}
309 pubd = {}
310
311 for name, id in all.iteritems():
312 if name.startswith(R_HEADS):
313 name = name[len(R_HEADS):]
314 b = self.GetBranch(name)
315 b.current = name == current
316 b.published = None
317 b.revision = id
318 heads[name] = b
319
320 for name, id in all.iteritems():
321 if name.startswith(R_PUB):
322 name = name[len(R_PUB):]
323 b = heads.get(name)
324 if b:
325 b.published = id
326
327 return heads
328
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700329
330## Status Display ##
331
332 def PrintWorkTreeStatus(self):
333 """Prints the status of the repository to stdout.
334 """
335 if not os.path.isdir(self.worktree):
336 print ''
337 print 'project %s/' % self.relpath
338 print ' missing (run "repo sync")'
339 return
340
341 self.work_git.update_index('-q',
342 '--unmerged',
343 '--ignore-missing',
344 '--refresh')
345 di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
346 df = self.work_git.DiffZ('diff-files')
347 do = self.work_git.LsOthers()
348 if not di and not df and not do:
Shawn O. Pearce161f4452009-04-10 17:41:44 -0700349 return 'CLEAN'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700350
351 out = StatusColoring(self.config)
352 out.project('project %-40s', self.relpath + '/')
353
354 branch = self.CurrentBranch
355 if branch is None:
356 out.nobranch('(*** NO BRANCH ***)')
357 else:
358 out.branch('branch %s', branch)
359 out.nl()
360
361 paths = list()
362 paths.extend(di.keys())
363 paths.extend(df.keys())
364 paths.extend(do)
365
366 paths = list(set(paths))
367 paths.sort()
368
369 for p in paths:
370 try: i = di[p]
371 except KeyError: i = None
372
373 try: f = df[p]
374 except KeyError: f = None
375
376 if i: i_status = i.status.upper()
377 else: i_status = '-'
378
379 if f: f_status = f.status.lower()
380 else: f_status = '-'
381
382 if i and i.src_path:
Shawn O. Pearcefe086752009-03-03 13:49:48 -0800383 line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700384 i.src_path, p, i.level)
385 else:
386 line = ' %s%s\t%s' % (i_status, f_status, p)
387
388 if i and not f:
389 out.added('%s', line)
390 elif (i and f) or (not i and f):
391 out.changed('%s', line)
392 elif not i and not f:
393 out.untracked('%s', line)
394 else:
395 out.write('%s', line)
396 out.nl()
Shawn O. Pearce161f4452009-04-10 17:41:44 -0700397 return 'DIRTY'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700398
399 def PrintWorkTreeDiff(self):
400 """Prints the status of the repository to stdout.
401 """
402 out = DiffColoring(self.config)
403 cmd = ['diff']
404 if out.is_on:
405 cmd.append('--color')
406 cmd.append(HEAD)
407 cmd.append('--')
408 p = GitCommand(self,
409 cmd,
410 capture_stdout = True,
411 capture_stderr = True)
412 has_diff = False
413 for line in p.process.stdout:
414 if not has_diff:
415 out.nl()
416 out.project('project %s/' % self.relpath)
417 out.nl()
418 has_diff = True
419 print line[:-1]
420 p.Wait()
421
422
423## Publish / Upload ##
424
425 def WasPublished(self, branch):
426 """Was the branch published (uploaded) for code review?
427 If so, returns the SHA-1 hash of the last published
428 state for the branch.
429 """
430 try:
431 return self.bare_git.rev_parse(R_PUB + branch)
432 except GitError:
433 return None
434
435 def CleanPublishedCache(self):
436 """Prunes any stale published refs.
437 """
438 heads = set()
439 canrm = {}
440 for name, id in self._allrefs.iteritems():
441 if name.startswith(R_HEADS):
442 heads.add(name)
443 elif name.startswith(R_PUB):
444 canrm[name] = id
445
446 for name, id in canrm.iteritems():
447 n = name[len(R_PUB):]
448 if R_HEADS + n not in heads:
449 self.bare_git.DeleteRef(name, id)
450
451 def GetUploadableBranches(self):
452 """List any branches which can be uploaded for review.
453 """
454 heads = {}
455 pubed = {}
456
457 for name, id in self._allrefs.iteritems():
458 if name.startswith(R_HEADS):
459 heads[name[len(R_HEADS):]] = id
460 elif name.startswith(R_PUB):
461 pubed[name[len(R_PUB):]] = id
462
463 ready = []
464 for branch, id in heads.iteritems():
465 if branch in pubed and pubed[branch] == id:
466 continue
467
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800468 rb = self.GetUploadableBranch(branch)
469 if rb:
470 ready.append(rb)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700471 return ready
472
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800473 def GetUploadableBranch(self, branch_name):
474 """Get a single uploadable branch, or None.
475 """
476 branch = self.GetBranch(branch_name)
477 base = branch.LocalMerge
478 if branch.LocalMerge:
479 rb = ReviewableBranch(self, branch, base)
480 if rb.commits:
481 return rb
482 return None
483
Joe Onorato2896a792008-11-17 16:56:36 -0500484 def UploadForReview(self, branch=None, replace_changes=None, people=([],[])):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700485 """Uploads the named branch for code review.
486 """
487 if branch is None:
488 branch = self.CurrentBranch
489 if branch is None:
490 raise GitError('not currently on a branch')
491
492 branch = self.GetBranch(branch)
493 if not branch.LocalMerge:
494 raise GitError('branch %s does not track a remote' % branch.name)
495 if not branch.remote.review:
496 raise GitError('remote %s has no review url' % branch.remote.name)
497
498 dest_branch = branch.merge
499 if not dest_branch.startswith(R_HEADS):
500 dest_branch = R_HEADS + dest_branch
501
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800502 if not branch.remote.projectname:
503 branch.remote.projectname = self.name
504 branch.remote.Save()
505
Shawn O. Pearce370e3fa2009-01-26 10:55:39 -0800506 if branch.remote.ReviewProtocol == 'ssh':
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800507 if dest_branch.startswith(R_HEADS):
508 dest_branch = dest_branch[len(R_HEADS):]
509
510 rp = ['gerrit receive-pack']
511 for e in people[0]:
512 rp.append('--reviewer=%s' % sq(e))
513 for e in people[1]:
514 rp.append('--cc=%s' % sq(e))
515
516 cmd = ['push']
517 cmd.append('--receive-pack=%s' % " ".join(rp))
518 cmd.append(branch.remote.SshReviewUrl(self.UserEmail))
519 cmd.append('%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch))
520 if replace_changes:
521 for change_id,commit_id in replace_changes.iteritems():
522 cmd.append('%s:refs/changes/%s/new' % (commit_id, change_id))
523 if GitCommand(self, cmd, bare = True).Wait() != 0:
524 raise UploadError('Upload failed')
525
526 else:
527 raise UploadError('Unsupported protocol %s' \
528 % branch.remote.review)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700529
530 msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
531 self.bare_git.UpdateRef(R_PUB + branch.name,
532 R_HEADS + branch.name,
533 message = msg)
534
535
536## Sync ##
537
538 def Sync_NetworkHalf(self):
539 """Perform only the network IO portion of the sync process.
540 Local working directory/branch state is not affected.
541 """
542 if not self.Exists:
543 print >>sys.stderr
544 print >>sys.stderr, 'Initializing project %s ...' % self.name
545 self._InitGitDir()
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800546
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700547 self._InitRemote()
548 for r in self.extraRemotes.values():
549 if not self._RemoteFetch(r.name):
550 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700551 if not self._RemoteFetch():
552 return False
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800553
554 if self.worktree:
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800555 self._InitMRef()
556 else:
557 self._InitMirrorHead()
558 try:
559 os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
560 except OSError:
561 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700562 return True
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800563
564 def PostRepoUpgrade(self):
565 self._InitHooks()
566
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700567 def _CopyFiles(self):
568 for file in self.copyfiles:
569 file._Copy()
570
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700571 def Sync_LocalHalf(self, syncbuf):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700572 """Perform only the local IO portion of the sync process.
573 Network access is not required.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700574 """
575 self._InitWorkTree()
576 self.CleanPublishedCache()
577
578 rem = self.GetRemote(self.remote.name)
579 rev = rem.ToLocal(self.revision)
Shawn O. Pearce559b8462009-03-02 12:56:08 -0800580 try:
581 self.bare_git.rev_parse('--verify', '%s^0' % rev)
582 except GitError:
583 raise ManifestInvalidRevisionError(
584 'revision %s in %s not found' % (self.revision, self.name))
585
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700586 branch = self.CurrentBranch
587
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700588 if branch is None or syncbuf.detach_head:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700589 # Currently on a detached HEAD. The user is assumed to
590 # not have any local modifications worth worrying about.
591 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700592 if os.path.exists(os.path.join(self.worktree, '.dotest')) \
593 or os.path.exists(os.path.join(self.worktree, '.git', 'rebase-apply')):
594 syncbuf.fail(self, _PriorSyncFailedError())
595 return
596
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700597 lost = self._revlist(not_rev(rev), HEAD)
598 if lost:
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700599 syncbuf.info(self, "discarding %d commits", len(lost))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700600 try:
601 self._Checkout(rev, quiet=True)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700602 except GitError, e:
603 syncbuf.fail(self, e)
604 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700605 self._CopyFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700606 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700607
608 branch = self.GetBranch(branch)
609 merge = branch.LocalMerge
610
611 if not merge:
612 # The current branch has no tracking configuration.
613 # Jump off it to a deatched HEAD.
614 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700615 syncbuf.info(self,
616 "leaving %s; does not track upstream",
617 branch.name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700618 try:
619 self._Checkout(rev, quiet=True)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700620 except GitError, e:
621 syncbuf.fail(self, e)
622 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700623 self._CopyFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700624 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700625
626 upstream_gain = self._revlist(not_rev(HEAD), rev)
627 pub = self.WasPublished(branch.name)
628 if pub:
629 not_merged = self._revlist(not_rev(rev), pub)
630 if not_merged:
631 if upstream_gain:
632 # The user has published this branch and some of those
633 # commits are not yet merged upstream. We do not want
634 # to rewrite the published commits so we punt.
635 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700636 syncbuf.info(self,
637 "branch %s is published but is now %d commits behind",
638 branch.name,
639 len(upstream_gain))
640 syncbuf.info(self, "consider merging or rebasing the unpublished commits")
641 return
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700642 elif upstream_gain:
Shawn O. Pearcea54c5272008-10-30 11:03:00 -0700643 # We can fast-forward safely.
644 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700645 def _doff():
Shawn O. Pearcea54c5272008-10-30 11:03:00 -0700646 self._FastForward(rev)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700647 self._CopyFiles()
648 syncbuf.later1(self, _doff)
649 return
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700650 else:
651 # Trivially no changes in the upstream.
652 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700653 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700654
655 if merge == rev:
656 try:
657 old_merge = self.bare_git.rev_parse('%s@{1}' % merge)
658 except GitError:
659 old_merge = merge
Shawn O. Pearce07346002008-10-21 07:09:27 -0700660 if old_merge == '0000000000000000000000000000000000000000' \
661 or old_merge == '':
662 old_merge = merge
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700663 else:
664 # The upstream switched on us. Time to cross our fingers
665 # and pray that the old upstream also wasn't in the habit
666 # of rebasing itself.
667 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700668 syncbuf.info(self, "manifest switched %s...%s", merge, rev)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700669 old_merge = merge
670
671 if rev == old_merge:
672 upstream_lost = []
673 else:
674 upstream_lost = self._revlist(not_rev(rev), old_merge)
675
676 if not upstream_lost and not upstream_gain:
677 # Trivially no changes caused by the upstream.
678 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700679 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700680
681 if self.IsDirty(consider_untracked=False):
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700682 syncbuf.fail(self, _DirtyError())
683 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700684
685 if upstream_lost:
686 # Upstream rebased. Not everything in HEAD
687 # may have been caused by the user.
688 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700689 syncbuf.info(self,
690 "discarding %d commits removed from upstream",
691 len(upstream_lost))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700692
693 branch.remote = rem
694 branch.merge = self.revision
695 branch.Save()
696
697 my_changes = self._revlist(not_rev(old_merge), HEAD)
698 if my_changes:
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700699 def _dorebase():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700700 self._Rebase(upstream = old_merge, onto = rev)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700701 self._CopyFiles()
702 syncbuf.later2(self, _dorebase)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700703 elif upstream_lost:
704 try:
705 self._ResetHard(rev)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700706 self._CopyFiles()
707 except GitError, e:
708 syncbuf.fail(self, e)
709 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700710 else:
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700711 def _doff():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700712 self._FastForward(rev)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700713 self._CopyFiles()
714 syncbuf.later1(self, _doff)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700715
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800716 def AddCopyFile(self, src, dest, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700717 # dest should already be an absolute path, but src is project relative
718 # make src an absolute path
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800719 abssrc = os.path.join(self.worktree, src)
720 self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700721
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700722 def DownloadPatchSet(self, change_id, patch_id):
723 """Download a single patch set of a single change to FETCH_HEAD.
724 """
725 remote = self.GetRemote(self.remote.name)
726
727 cmd = ['fetch', remote.name]
728 cmd.append('refs/changes/%2.2d/%d/%d' \
729 % (change_id % 100, change_id, patch_id))
730 cmd.extend(map(lambda x: str(x), remote.fetch))
731 if GitCommand(self, cmd, bare=True).Wait() != 0:
732 return None
733 return DownloadedChange(self,
734 remote.ToLocal(self.revision),
735 change_id,
736 patch_id,
737 self.bare_git.rev_parse('FETCH_HEAD'))
738
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700739
740## Branch Management ##
741
742 def StartBranch(self, name):
743 """Create a new branch off the manifest's revision.
744 """
Shawn O. Pearce0a389e92009-04-10 16:21:18 -0700745 try:
746 self.bare_git.rev_parse(R_HEADS + name)
747 exists = True
748 except GitError:
749 exists = False;
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700750
Shawn O. Pearce0a389e92009-04-10 16:21:18 -0700751 if exists:
752 if name == self.CurrentBranch:
753 return True
754 else:
755 cmd = ['checkout', name, '--']
756 return GitCommand(self, cmd).Wait() == 0
757
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700758 else:
Shawn O. Pearce0a389e92009-04-10 16:21:18 -0700759 branch = self.GetBranch(name)
760 branch.remote = self.GetRemote(self.remote.name)
761 branch.merge = self.revision
762
763 rev = branch.LocalMerge
764 cmd = ['checkout', '-b', branch.name, rev]
765 if GitCommand(self, cmd).Wait() == 0:
766 branch.Save()
767 return True
768 else:
769 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700770
Wink Saville02d79452009-04-10 13:01:24 -0700771 def CheckoutBranch(self, name):
772 """Checkout a local topic branch.
773 """
774
775 # Be sure the branch exists
776 try:
777 tip_rev = self.bare_git.rev_parse(R_HEADS + name)
778 except GitError:
779 return False;
780
781 # Do the checkout
782 cmd = ['checkout', name, '--']
Shawn O. Pearce2675c3f2009-04-10 16:20:25 -0700783 return GitCommand(self, cmd).Wait() == 0
Wink Saville02d79452009-04-10 13:01:24 -0700784
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800785 def AbandonBranch(self, name):
786 """Destroy a local topic branch.
787 """
788 try:
789 tip_rev = self.bare_git.rev_parse(R_HEADS + name)
790 except GitError:
791 return
792
793 if self.CurrentBranch == name:
794 self._Checkout(
795 self.GetRemote(self.remote.name).ToLocal(self.revision),
796 quiet=True)
797
798 cmd = ['branch', '-D', name]
799 GitCommand(self, cmd, capture_stdout=True).Wait()
800
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700801 def PruneHeads(self):
802 """Prune any topic branches already merged into upstream.
803 """
804 cb = self.CurrentBranch
805 kill = []
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800806 left = self._allrefs
807 for name in left.keys():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700808 if name.startswith(R_HEADS):
809 name = name[len(R_HEADS):]
810 if cb is None or name != cb:
811 kill.append(name)
812
813 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
814 if cb is not None \
815 and not self._revlist(HEAD + '...' + rev) \
816 and not self.IsDirty(consider_untracked = False):
817 self.work_git.DetachHead(HEAD)
818 kill.append(cb)
819
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700820 if kill:
821 try:
822 old = self.bare_git.GetHead()
823 except GitError:
824 old = 'refs/heads/please_never_use_this_as_a_branch_name'
825
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700826 try:
827 self.bare_git.DetachHead(rev)
828
829 b = ['branch', '-d']
830 b.extend(kill)
831 b = GitCommand(self, b, bare=True,
832 capture_stdout=True,
833 capture_stderr=True)
834 b.Wait()
835 finally:
836 self.bare_git.SetHead(old)
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800837 left = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700838
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800839 for branch in kill:
840 if (R_HEADS + branch) not in left:
841 self.CleanPublishedCache()
842 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700843
844 if cb and cb not in kill:
845 kill.append(cb)
Shawn O. Pearce7c6c64d2009-03-02 12:38:13 -0800846 kill.sort()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700847
848 kept = []
849 for branch in kill:
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800850 if (R_HEADS + branch) in left:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700851 branch = self.GetBranch(branch)
852 base = branch.LocalMerge
853 if not base:
854 base = rev
855 kept.append(ReviewableBranch(self, branch, base))
856 return kept
857
858
859## Direct Git Commands ##
860
861 def _RemoteFetch(self, name=None):
862 if not name:
863 name = self.remote.name
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800864 cmd = ['fetch']
865 if not self.worktree:
866 cmd.append('--update-head-ok')
867 cmd.append(name)
868 return GitCommand(self, cmd, bare = True).Wait() == 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700869
870 def _Checkout(self, rev, quiet=False):
871 cmd = ['checkout']
872 if quiet:
873 cmd.append('-q')
874 cmd.append(rev)
875 cmd.append('--')
876 if GitCommand(self, cmd).Wait() != 0:
877 if self._allrefs:
878 raise GitError('%s checkout %s ' % (self.name, rev))
879
880 def _ResetHard(self, rev, quiet=True):
881 cmd = ['reset', '--hard']
882 if quiet:
883 cmd.append('-q')
884 cmd.append(rev)
885 if GitCommand(self, cmd).Wait() != 0:
886 raise GitError('%s reset --hard %s ' % (self.name, rev))
887
888 def _Rebase(self, upstream, onto = None):
Shawn O. Pearce19a83d82009-04-16 08:14:26 -0700889 cmd = ['rebase']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700890 if onto is not None:
891 cmd.extend(['--onto', onto])
892 cmd.append(upstream)
Shawn O. Pearce19a83d82009-04-16 08:14:26 -0700893 if GitCommand(self, cmd).Wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700894 raise GitError('%s rebase %s ' % (self.name, upstream))
895
896 def _FastForward(self, head):
897 cmd = ['merge', head]
898 if GitCommand(self, cmd).Wait() != 0:
899 raise GitError('%s merge %s ' % (self.name, head))
900
901 def _InitGitDir(self):
902 if not os.path.exists(self.gitdir):
903 os.makedirs(self.gitdir)
904 self.bare_git.init()
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -0800905
906 if self.manifest.IsMirror:
907 self.config.SetString('core.bare', 'true')
908 else:
909 self.config.SetString('core.bare', None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700910
911 hooks = self._gitdir_path('hooks')
Shawn O. Pearcede646812008-10-29 14:38:12 -0700912 try:
913 to_rm = os.listdir(hooks)
914 except OSError:
915 to_rm = []
916 for old_hook in to_rm:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700917 os.remove(os.path.join(hooks, old_hook))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800918 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700919
920 m = self.manifest.manifestProject.config
921 for key in ['user.name', 'user.email']:
922 if m.Has(key, include_defaults = False):
923 self.config.SetString(key, m.GetString(key))
924
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800925 def _InitHooks(self):
926 hooks = self._gitdir_path('hooks')
927 if not os.path.exists(hooks):
928 os.makedirs(hooks)
929 for stock_hook in repo_hooks():
930 dst = os.path.join(hooks, os.path.basename(stock_hook))
931 try:
932 os.symlink(relpath(stock_hook, dst), dst)
933 except OSError, e:
934 if e.errno == errno.EEXIST:
935 pass
936 elif e.errno == errno.EPERM:
937 raise GitError('filesystem must support symlinks')
938 else:
939 raise
940
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700941 def _InitRemote(self):
942 if self.remote.fetchUrl:
943 remote = self.GetRemote(self.remote.name)
944
945 url = self.remote.fetchUrl
946 while url.endswith('/'):
947 url = url[:-1]
948 url += '/%s.git' % self.name
949 remote.url = url
950 remote.review = self.remote.reviewUrl
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800951 if remote.projectname is None:
952 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700953
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800954 if self.worktree:
955 remote.ResetFetch(mirror=False)
956 else:
957 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700958 remote.Save()
959
960 for r in self.extraRemotes.values():
961 remote = self.GetRemote(r.name)
962 remote.url = r.fetchUrl
963 remote.review = r.reviewUrl
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800964 if r.projectName:
965 remote.projectname = r.projectName
966 elif remote.projectname is None:
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800967 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700968 remote.ResetFetch()
969 remote.Save()
970
971 def _InitMRef(self):
972 if self.manifest.branch:
973 msg = 'manifest set to %s' % self.revision
974 ref = R_M + self.manifest.branch
975
976 if IsId(self.revision):
Marcelo E. Magallon21f73852008-12-31 04:44:37 +0000977 dst = self.revision + '^0'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700978 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
979 else:
980 remote = self.GetRemote(self.remote.name)
981 dst = remote.ToLocal(self.revision)
982 self.bare_git.symbolic_ref('-m', msg, ref, dst)
983
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800984 def _InitMirrorHead(self):
985 dst = self.GetRemote(self.remote.name).ToLocal(self.revision)
986 msg = 'manifest set to %s' % self.revision
987 self.bare_git.SetHead(dst, message=msg)
988
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700989 def _InitWorkTree(self):
990 dotgit = os.path.join(self.worktree, '.git')
991 if not os.path.exists(dotgit):
992 os.makedirs(dotgit)
993
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700994 for name in ['config',
995 'description',
996 'hooks',
997 'info',
998 'logs',
999 'objects',
1000 'packed-refs',
1001 'refs',
1002 'rr-cache',
1003 'svn']:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08001004 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001005 src = os.path.join(self.gitdir, name)
1006 dst = os.path.join(dotgit, name)
1007 os.symlink(relpath(src, dst), dst)
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08001008 except OSError, e:
1009 if e.errno == errno.EPERM:
1010 raise GitError('filesystem must support symlinks')
1011 else:
1012 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001013
1014 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
1015 rev = self.bare_git.rev_parse('%s^0' % rev)
1016
1017 f = open(os.path.join(dotgit, HEAD), 'wb')
1018 f.write("%s\n" % rev)
1019 f.close()
1020
1021 cmd = ['read-tree', '--reset', '-u']
1022 cmd.append('-v')
1023 cmd.append('HEAD')
1024 if GitCommand(self, cmd).Wait() != 0:
1025 raise GitError("cannot initialize work tree")
1026
1027 def _gitdir_path(self, path):
1028 return os.path.join(self.gitdir, path)
1029
1030 def _revlist(self, *args):
1031 cmd = []
1032 cmd.extend(args)
1033 cmd.append('--')
1034 return self.work_git.rev_list(*args)
1035
1036 @property
1037 def _allrefs(self):
1038 return self.bare_git.ListRefs()
1039
1040 class _GitGetByExec(object):
1041 def __init__(self, project, bare):
1042 self._project = project
1043 self._bare = bare
1044
1045 def ListRefs(self, *args):
1046 cmdv = ['for-each-ref', '--format=%(objectname) %(refname)']
1047 cmdv.extend(args)
1048 p = GitCommand(self._project,
1049 cmdv,
1050 bare = self._bare,
1051 capture_stdout = True,
1052 capture_stderr = True)
1053 r = {}
1054 for line in p.process.stdout:
1055 id, name = line[:-1].split(' ', 2)
1056 r[name] = id
1057 if p.Wait() != 0:
1058 raise GitError('%s for-each-ref %s: %s' % (
1059 self._project.name,
1060 str(args),
1061 p.stderr))
1062 return r
1063
1064 def LsOthers(self):
1065 p = GitCommand(self._project,
1066 ['ls-files',
1067 '-z',
1068 '--others',
1069 '--exclude-standard'],
1070 bare = False,
1071 capture_stdout = True,
1072 capture_stderr = True)
1073 if p.Wait() == 0:
1074 out = p.stdout
1075 if out:
1076 return out[:-1].split("\0")
1077 return []
1078
1079 def DiffZ(self, name, *args):
1080 cmd = [name]
1081 cmd.append('-z')
1082 cmd.extend(args)
1083 p = GitCommand(self._project,
1084 cmd,
1085 bare = False,
1086 capture_stdout = True,
1087 capture_stderr = True)
1088 try:
1089 out = p.process.stdout.read()
1090 r = {}
1091 if out:
1092 out = iter(out[:-1].split('\0'))
1093 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07001094 try:
1095 info = out.next()
1096 path = out.next()
1097 except StopIteration:
1098 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001099
1100 class _Info(object):
1101 def __init__(self, path, omode, nmode, oid, nid, state):
1102 self.path = path
1103 self.src_path = None
1104 self.old_mode = omode
1105 self.new_mode = nmode
1106 self.old_id = oid
1107 self.new_id = nid
1108
1109 if len(state) == 1:
1110 self.status = state
1111 self.level = None
1112 else:
1113 self.status = state[:1]
1114 self.level = state[1:]
1115 while self.level.startswith('0'):
1116 self.level = self.level[1:]
1117
1118 info = info[1:].split(' ')
1119 info =_Info(path, *info)
1120 if info.status in ('R', 'C'):
1121 info.src_path = info.path
1122 info.path = out.next()
1123 r[info.path] = info
1124 return r
1125 finally:
1126 p.Wait()
1127
1128 def GetHead(self):
1129 return self.symbolic_ref(HEAD)
1130
1131 def SetHead(self, ref, message=None):
1132 cmdv = []
1133 if message is not None:
1134 cmdv.extend(['-m', message])
1135 cmdv.append(HEAD)
1136 cmdv.append(ref)
1137 self.symbolic_ref(*cmdv)
1138
1139 def DetachHead(self, new, message=None):
1140 cmdv = ['--no-deref']
1141 if message is not None:
1142 cmdv.extend(['-m', message])
1143 cmdv.append(HEAD)
1144 cmdv.append(new)
1145 self.update_ref(*cmdv)
1146
1147 def UpdateRef(self, name, new, old=None,
1148 message=None,
1149 detach=False):
1150 cmdv = []
1151 if message is not None:
1152 cmdv.extend(['-m', message])
1153 if detach:
1154 cmdv.append('--no-deref')
1155 cmdv.append(name)
1156 cmdv.append(new)
1157 if old is not None:
1158 cmdv.append(old)
1159 self.update_ref(*cmdv)
1160
1161 def DeleteRef(self, name, old=None):
1162 if not old:
1163 old = self.rev_parse(name)
1164 self.update_ref('-d', name, old)
1165
1166 def rev_list(self, *args):
1167 cmdv = ['rev-list']
1168 cmdv.extend(args)
1169 p = GitCommand(self._project,
1170 cmdv,
1171 bare = self._bare,
1172 capture_stdout = True,
1173 capture_stderr = True)
1174 r = []
1175 for line in p.process.stdout:
1176 r.append(line[:-1])
1177 if p.Wait() != 0:
1178 raise GitError('%s rev-list %s: %s' % (
1179 self._project.name,
1180 str(args),
1181 p.stderr))
1182 return r
1183
1184 def __getattr__(self, name):
1185 name = name.replace('_', '-')
1186 def runner(*args):
1187 cmdv = [name]
1188 cmdv.extend(args)
1189 p = GitCommand(self._project,
1190 cmdv,
1191 bare = self._bare,
1192 capture_stdout = True,
1193 capture_stderr = True)
1194 if p.Wait() != 0:
1195 raise GitError('%s %s: %s' % (
1196 self._project.name,
1197 name,
1198 p.stderr))
1199 r = p.stdout
1200 if r.endswith('\n') and r.index('\n') == len(r) - 1:
1201 return r[:-1]
1202 return r
1203 return runner
1204
1205
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001206class _PriorSyncFailedError(Exception):
1207 def __str__(self):
1208 return 'prior sync failed; rebase still in progress'
1209
1210class _DirtyError(Exception):
1211 def __str__(self):
1212 return 'contains uncommitted changes'
1213
1214class _InfoMessage(object):
1215 def __init__(self, project, text):
1216 self.project = project
1217 self.text = text
1218
1219 def Print(self, syncbuf):
1220 syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
1221 syncbuf.out.nl()
1222
1223class _Failure(object):
1224 def __init__(self, project, why):
1225 self.project = project
1226 self.why = why
1227
1228 def Print(self, syncbuf):
1229 syncbuf.out.fail('error: %s/: %s',
1230 self.project.relpath,
1231 str(self.why))
1232 syncbuf.out.nl()
1233
1234class _Later(object):
1235 def __init__(self, project, action):
1236 self.project = project
1237 self.action = action
1238
1239 def Run(self, syncbuf):
1240 out = syncbuf.out
1241 out.project('project %s/', self.project.relpath)
1242 out.nl()
1243 try:
1244 self.action()
1245 out.nl()
1246 return True
1247 except GitError, e:
1248 out.nl()
1249 return False
1250
1251class _SyncColoring(Coloring):
1252 def __init__(self, config):
1253 Coloring.__init__(self, config, 'reposync')
1254 self.project = self.printer('header', attr = 'bold')
1255 self.info = self.printer('info')
1256 self.fail = self.printer('fail', fg='red')
1257
1258class SyncBuffer(object):
1259 def __init__(self, config, detach_head=False):
1260 self._messages = []
1261 self._failures = []
1262 self._later_queue1 = []
1263 self._later_queue2 = []
1264
1265 self.out = _SyncColoring(config)
1266 self.out.redirect(sys.stderr)
1267
1268 self.detach_head = detach_head
1269 self.clean = True
1270
1271 def info(self, project, fmt, *args):
1272 self._messages.append(_InfoMessage(project, fmt % args))
1273
1274 def fail(self, project, err=None):
1275 self._failures.append(_Failure(project, err))
1276 self.clean = False
1277
1278 def later1(self, project, what):
1279 self._later_queue1.append(_Later(project, what))
1280
1281 def later2(self, project, what):
1282 self._later_queue2.append(_Later(project, what))
1283
1284 def Finish(self):
1285 self._PrintMessages()
1286 self._RunLater()
1287 self._PrintMessages()
1288 return self.clean
1289
1290 def _RunLater(self):
1291 for q in ['_later_queue1', '_later_queue2']:
1292 if not self._RunQueue(q):
1293 return
1294
1295 def _RunQueue(self, queue):
1296 for m in getattr(self, queue):
1297 if not m.Run(self):
1298 self.clean = False
1299 return False
1300 setattr(self, queue, [])
1301 return True
1302
1303 def _PrintMessages(self):
1304 for m in self._messages:
1305 m.Print(self)
1306 for m in self._failures:
1307 m.Print(self)
1308
1309 self._messages = []
1310 self._failures = []
1311
1312
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001313class MetaProject(Project):
1314 """A special project housed under .repo.
1315 """
1316 def __init__(self, manifest, name, gitdir, worktree):
1317 repodir = manifest.repodir
1318 Project.__init__(self,
1319 manifest = manifest,
1320 name = name,
1321 gitdir = gitdir,
1322 worktree = worktree,
1323 remote = Remote('origin'),
1324 relpath = '.repo/%s' % name,
1325 revision = 'refs/heads/master')
1326
1327 def PreSync(self):
1328 if self.Exists:
1329 cb = self.CurrentBranch
1330 if cb:
1331 base = self.GetBranch(cb).merge
1332 if base:
1333 self.revision = base
1334
1335 @property
1336 def HasChanges(self):
1337 """Has the remote received new commits not yet checked out?
1338 """
1339 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
1340 if self._revlist(not_rev(HEAD), rev):
1341 return True
1342 return False