blob: 029a80f40bbe7aac142fcad3cf41a12398f8bc41 [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
Shawn O. Pearced237b692009-04-17 18:49:50 -070031from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -070033def _lwrite(path, content):
34 lock = '%s.lock' % path
35
36 fd = open(lock, 'wb')
37 try:
38 fd.write(content)
39 finally:
40 fd.close()
41
42 try:
43 os.rename(lock, path)
44 except OSError:
45 os.remove(lock)
46 raise
47
Shawn O. Pearce48244782009-04-16 08:25:57 -070048def _error(fmt, *args):
49 msg = fmt % args
50 print >>sys.stderr, 'error: %s' % msg
51
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070052def not_rev(r):
53 return '^' + r
54
Shawn O. Pearceb54a3922009-01-05 16:18:58 -080055def sq(r):
56 return "'" + r.replace("'", "'\''") + "'"
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080057
58hook_list = None
59def repo_hooks():
60 global hook_list
61 if hook_list is None:
62 d = os.path.abspath(os.path.dirname(__file__))
63 d = os.path.join(d , 'hooks')
64 hook_list = map(lambda x: os.path.join(d, x), os.listdir(d))
65 return hook_list
66
67def relpath(dst, src):
68 src = os.path.dirname(src)
69 top = os.path.commonprefix([dst, src])
70 if top.endswith('/'):
71 top = top[:-1]
72 else:
73 top = os.path.dirname(top)
74
75 tmp = src
76 rel = ''
77 while top != tmp:
78 rel += '../'
79 tmp = os.path.dirname(tmp)
80 return rel + dst[len(top) + 1:]
81
82
Shawn O. Pearce632768b2008-10-23 11:58:52 -070083class DownloadedChange(object):
84 _commit_cache = None
85
86 def __init__(self, project, base, change_id, ps_id, commit):
87 self.project = project
88 self.base = base
89 self.change_id = change_id
90 self.ps_id = ps_id
91 self.commit = commit
92
93 @property
94 def commits(self):
95 if self._commit_cache is None:
96 self._commit_cache = self.project.bare_git.rev_list(
97 '--abbrev=8',
98 '--abbrev-commit',
99 '--pretty=oneline',
100 '--reverse',
101 '--date-order',
102 not_rev(self.base),
103 self.commit,
104 '--')
105 return self._commit_cache
106
107
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700108class ReviewableBranch(object):
109 _commit_cache = None
110
111 def __init__(self, project, branch, base):
112 self.project = project
113 self.branch = branch
114 self.base = base
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800115 self.replace_changes = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700116
117 @property
118 def name(self):
119 return self.branch.name
120
121 @property
122 def commits(self):
123 if self._commit_cache is None:
124 self._commit_cache = self.project.bare_git.rev_list(
125 '--abbrev=8',
126 '--abbrev-commit',
127 '--pretty=oneline',
128 '--reverse',
129 '--date-order',
130 not_rev(self.base),
131 R_HEADS + self.name,
132 '--')
133 return self._commit_cache
134
135 @property
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800136 def unabbrev_commits(self):
137 r = dict()
138 for commit in self.project.bare_git.rev_list(
139 not_rev(self.base),
140 R_HEADS + self.name,
141 '--'):
142 r[commit[0:8]] = commit
143 return r
144
145 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700146 def date(self):
147 return self.project.bare_git.log(
148 '--pretty=format:%cd',
149 '-n', '1',
150 R_HEADS + self.name,
151 '--')
152
Joe Onorato2896a792008-11-17 16:56:36 -0500153 def UploadForReview(self, people):
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800154 self.project.UploadForReview(self.name,
Joe Onorato2896a792008-11-17 16:56:36 -0500155 self.replace_changes,
156 people)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700157
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700158
159class StatusColoring(Coloring):
160 def __init__(self, config):
161 Coloring.__init__(self, config, 'status')
162 self.project = self.printer('header', attr = 'bold')
163 self.branch = self.printer('header', attr = 'bold')
164 self.nobranch = self.printer('nobranch', fg = 'red')
165
166 self.added = self.printer('added', fg = 'green')
167 self.changed = self.printer('changed', fg = 'red')
168 self.untracked = self.printer('untracked', fg = 'red')
169
170
171class DiffColoring(Coloring):
172 def __init__(self, config):
173 Coloring.__init__(self, config, 'diff')
174 self.project = self.printer('header', attr = 'bold')
175
176
177class _CopyFile:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800178 def __init__(self, src, dest, abssrc, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700179 self.src = src
180 self.dest = dest
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800181 self.abs_src = abssrc
182 self.abs_dest = absdest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700183
184 def _Copy(self):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800185 src = self.abs_src
186 dest = self.abs_dest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700187 # copy file if it does not exist or is out of date
188 if not os.path.exists(dest) or not filecmp.cmp(src, dest):
189 try:
190 # remove existing file first, since it might be read-only
191 if os.path.exists(dest):
192 os.remove(dest)
193 shutil.copy(src, dest)
194 # make the file read-only
195 mode = os.stat(dest)[stat.ST_MODE]
196 mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
197 os.chmod(dest, mode)
198 except IOError:
Shawn O. Pearce48244782009-04-16 08:25:57 -0700199 _error('Cannot copy file %s to %s', src, dest)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700200
201
202class Project(object):
203 def __init__(self,
204 manifest,
205 name,
206 remote,
207 gitdir,
208 worktree,
209 relpath,
210 revision):
211 self.manifest = manifest
212 self.name = name
213 self.remote = remote
214 self.gitdir = gitdir
215 self.worktree = worktree
216 self.relpath = relpath
217 self.revision = revision
218 self.snapshots = {}
219 self.extraRemotes = {}
220 self.copyfiles = []
221 self.config = GitConfig.ForRepository(
222 gitdir = self.gitdir,
223 defaults = self.manifest.globalConfig)
224
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800225 if self.worktree:
226 self.work_git = self._GitGetByExec(self, bare=False)
227 else:
228 self.work_git = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700229 self.bare_git = self._GitGetByExec(self, bare=True)
Shawn O. Pearced237b692009-04-17 18:49:50 -0700230 self.bare_ref = GitRefs(gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700231
232 @property
233 def Exists(self):
234 return os.path.isdir(self.gitdir)
235
236 @property
237 def CurrentBranch(self):
238 """Obtain the name of the currently checked out branch.
239 The branch name omits the 'refs/heads/' prefix.
240 None is returned if the project is on a detached HEAD.
241 """
Shawn O. Pearce5b23f242009-04-17 18:43:33 -0700242 b = self.work_git.GetHead()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700243 if b.startswith(R_HEADS):
244 return b[len(R_HEADS):]
245 return None
246
247 def IsDirty(self, consider_untracked=True):
248 """Is the working directory modified in some way?
249 """
250 self.work_git.update_index('-q',
251 '--unmerged',
252 '--ignore-missing',
253 '--refresh')
254 if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
255 return True
256 if self.work_git.DiffZ('diff-files'):
257 return True
258 if consider_untracked and self.work_git.LsOthers():
259 return True
260 return False
261
262 _userident_name = None
263 _userident_email = None
264
265 @property
266 def UserName(self):
267 """Obtain the user's personal name.
268 """
269 if self._userident_name is None:
270 self._LoadUserIdentity()
271 return self._userident_name
272
273 @property
274 def UserEmail(self):
275 """Obtain the user's email address. This is very likely
276 to be their Gerrit login.
277 """
278 if self._userident_email is None:
279 self._LoadUserIdentity()
280 return self._userident_email
281
282 def _LoadUserIdentity(self):
283 u = self.bare_git.var('GIT_COMMITTER_IDENT')
284 m = re.compile("^(.*) <([^>]*)> ").match(u)
285 if m:
286 self._userident_name = m.group(1)
287 self._userident_email = m.group(2)
288 else:
289 self._userident_name = ''
290 self._userident_email = ''
291
292 def GetRemote(self, name):
293 """Get the configuration for a single remote.
294 """
295 return self.config.GetRemote(name)
296
297 def GetBranch(self, name):
298 """Get the configuration for a single branch.
299 """
300 return self.config.GetBranch(name)
301
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700302 def GetBranches(self):
303 """Get all existing local branches.
304 """
305 current = self.CurrentBranch
Shawn O. Pearced237b692009-04-17 18:49:50 -0700306 all = self._allrefs
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700307 heads = {}
308 pubd = {}
309
310 for name, id in all.iteritems():
311 if name.startswith(R_HEADS):
312 name = name[len(R_HEADS):]
313 b = self.GetBranch(name)
314 b.current = name == current
315 b.published = None
316 b.revision = id
317 heads[name] = b
318
319 for name, id in all.iteritems():
320 if name.startswith(R_PUB):
321 name = name[len(R_PUB):]
322 b = heads.get(name)
323 if b:
324 b.published = id
325
326 return heads
327
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700328
329## Status Display ##
330
331 def PrintWorkTreeStatus(self):
332 """Prints the status of the repository to stdout.
333 """
334 if not os.path.isdir(self.worktree):
335 print ''
336 print 'project %s/' % self.relpath
337 print ' missing (run "repo sync")'
338 return
339
340 self.work_git.update_index('-q',
341 '--unmerged',
342 '--ignore-missing',
343 '--refresh')
344 di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
345 df = self.work_git.DiffZ('diff-files')
346 do = self.work_git.LsOthers()
347 if not di and not df and not do:
Shawn O. Pearce161f4452009-04-10 17:41:44 -0700348 return 'CLEAN'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700349
350 out = StatusColoring(self.config)
351 out.project('project %-40s', self.relpath + '/')
352
353 branch = self.CurrentBranch
354 if branch is None:
355 out.nobranch('(*** NO BRANCH ***)')
356 else:
357 out.branch('branch %s', branch)
358 out.nl()
359
360 paths = list()
361 paths.extend(di.keys())
362 paths.extend(df.keys())
363 paths.extend(do)
364
365 paths = list(set(paths))
366 paths.sort()
367
368 for p in paths:
369 try: i = di[p]
370 except KeyError: i = None
371
372 try: f = df[p]
373 except KeyError: f = None
374
375 if i: i_status = i.status.upper()
376 else: i_status = '-'
377
378 if f: f_status = f.status.lower()
379 else: f_status = '-'
380
381 if i and i.src_path:
Shawn O. Pearcefe086752009-03-03 13:49:48 -0800382 line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700383 i.src_path, p, i.level)
384 else:
385 line = ' %s%s\t%s' % (i_status, f_status, p)
386
387 if i and not f:
388 out.added('%s', line)
389 elif (i and f) or (not i and f):
390 out.changed('%s', line)
391 elif not i and not f:
392 out.untracked('%s', line)
393 else:
394 out.write('%s', line)
395 out.nl()
Shawn O. Pearce161f4452009-04-10 17:41:44 -0700396 return 'DIRTY'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700397
398 def PrintWorkTreeDiff(self):
399 """Prints the status of the repository to stdout.
400 """
401 out = DiffColoring(self.config)
402 cmd = ['diff']
403 if out.is_on:
404 cmd.append('--color')
405 cmd.append(HEAD)
406 cmd.append('--')
407 p = GitCommand(self,
408 cmd,
409 capture_stdout = True,
410 capture_stderr = True)
411 has_diff = False
412 for line in p.process.stdout:
413 if not has_diff:
414 out.nl()
415 out.project('project %s/' % self.relpath)
416 out.nl()
417 has_diff = True
418 print line[:-1]
419 p.Wait()
420
421
422## Publish / Upload ##
423
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700424 def WasPublished(self, branch, all=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700425 """Was the branch published (uploaded) for code review?
426 If so, returns the SHA-1 hash of the last published
427 state for the branch.
428 """
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700429 key = R_PUB + branch
430 if all is None:
431 try:
432 return self.bare_git.rev_parse(key)
433 except GitError:
434 return None
435 else:
436 try:
437 return all[key]
438 except KeyError:
439 return None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700440
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700441 def CleanPublishedCache(self, all=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700442 """Prunes any stale published refs.
443 """
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700444 if all is None:
445 all = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700446 heads = set()
447 canrm = {}
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700448 for name, id in all.iteritems():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700449 if name.startswith(R_HEADS):
450 heads.add(name)
451 elif name.startswith(R_PUB):
452 canrm[name] = id
453
454 for name, id in canrm.iteritems():
455 n = name[len(R_PUB):]
456 if R_HEADS + n not in heads:
457 self.bare_git.DeleteRef(name, id)
458
459 def GetUploadableBranches(self):
460 """List any branches which can be uploaded for review.
461 """
462 heads = {}
463 pubed = {}
464
465 for name, id in self._allrefs.iteritems():
466 if name.startswith(R_HEADS):
467 heads[name[len(R_HEADS):]] = id
468 elif name.startswith(R_PUB):
469 pubed[name[len(R_PUB):]] = id
470
471 ready = []
472 for branch, id in heads.iteritems():
473 if branch in pubed and pubed[branch] == id:
474 continue
475
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800476 rb = self.GetUploadableBranch(branch)
477 if rb:
478 ready.append(rb)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700479 return ready
480
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800481 def GetUploadableBranch(self, branch_name):
482 """Get a single uploadable branch, or None.
483 """
484 branch = self.GetBranch(branch_name)
485 base = branch.LocalMerge
486 if branch.LocalMerge:
487 rb = ReviewableBranch(self, branch, base)
488 if rb.commits:
489 return rb
490 return None
491
Joe Onorato2896a792008-11-17 16:56:36 -0500492 def UploadForReview(self, branch=None, replace_changes=None, people=([],[])):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700493 """Uploads the named branch for code review.
494 """
495 if branch is None:
496 branch = self.CurrentBranch
497 if branch is None:
498 raise GitError('not currently on a branch')
499
500 branch = self.GetBranch(branch)
501 if not branch.LocalMerge:
502 raise GitError('branch %s does not track a remote' % branch.name)
503 if not branch.remote.review:
504 raise GitError('remote %s has no review url' % branch.remote.name)
505
506 dest_branch = branch.merge
507 if not dest_branch.startswith(R_HEADS):
508 dest_branch = R_HEADS + dest_branch
509
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800510 if not branch.remote.projectname:
511 branch.remote.projectname = self.name
512 branch.remote.Save()
513
Shawn O. Pearce370e3fa2009-01-26 10:55:39 -0800514 if branch.remote.ReviewProtocol == 'ssh':
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800515 if dest_branch.startswith(R_HEADS):
516 dest_branch = dest_branch[len(R_HEADS):]
517
518 rp = ['gerrit receive-pack']
519 for e in people[0]:
520 rp.append('--reviewer=%s' % sq(e))
521 for e in people[1]:
522 rp.append('--cc=%s' % sq(e))
523
524 cmd = ['push']
525 cmd.append('--receive-pack=%s' % " ".join(rp))
526 cmd.append(branch.remote.SshReviewUrl(self.UserEmail))
527 cmd.append('%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch))
528 if replace_changes:
529 for change_id,commit_id in replace_changes.iteritems():
530 cmd.append('%s:refs/changes/%s/new' % (commit_id, change_id))
531 if GitCommand(self, cmd, bare = True).Wait() != 0:
532 raise UploadError('Upload failed')
533
534 else:
535 raise UploadError('Unsupported protocol %s' \
536 % branch.remote.review)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700537
538 msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
539 self.bare_git.UpdateRef(R_PUB + branch.name,
540 R_HEADS + branch.name,
541 message = msg)
542
543
544## Sync ##
545
546 def Sync_NetworkHalf(self):
547 """Perform only the network IO portion of the sync process.
548 Local working directory/branch state is not affected.
549 """
550 if not self.Exists:
551 print >>sys.stderr
552 print >>sys.stderr, 'Initializing project %s ...' % self.name
553 self._InitGitDir()
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800554
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700555 self._InitRemote()
556 for r in self.extraRemotes.values():
557 if not self._RemoteFetch(r.name):
558 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700559 if not self._RemoteFetch():
560 return False
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800561
562 if self.worktree:
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800563 self._InitMRef()
564 else:
565 self._InitMirrorHead()
566 try:
567 os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
568 except OSError:
569 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700570 return True
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800571
572 def PostRepoUpgrade(self):
573 self._InitHooks()
574
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700575 def _CopyFiles(self):
576 for file in self.copyfiles:
577 file._Copy()
578
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700579 def Sync_LocalHalf(self, syncbuf):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700580 """Perform only the local IO portion of the sync process.
581 Network access is not required.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700582 """
583 self._InitWorkTree()
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700584 all = self.bare_ref.all
585 self.CleanPublishedCache(all)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700586
587 rem = self.GetRemote(self.remote.name)
588 rev = rem.ToLocal(self.revision)
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700589 if rev in all:
590 revid = all[rev]
591 elif IsId(rev):
592 revid = rev
593 else:
594 try:
595 revid = self.bare_git.rev_parse('--verify', '%s^0' % rev)
596 except GitError:
597 raise ManifestInvalidRevisionError(
598 'revision %s in %s not found' % (self.revision, self.name))
Shawn O. Pearce559b8462009-03-02 12:56:08 -0800599
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700600 head = self.work_git.GetHead()
601 if head.startswith(R_HEADS):
602 branch = head[len(R_HEADS):]
603 try:
604 head = all[head]
605 except KeyError:
606 head = None
607 else:
608 branch = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700609
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700610 if branch is None or syncbuf.detach_head:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700611 # Currently on a detached HEAD. The user is assumed to
612 # not have any local modifications worth worrying about.
613 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700614 if os.path.exists(os.path.join(self.worktree, '.dotest')) \
615 or os.path.exists(os.path.join(self.worktree, '.git', 'rebase-apply')):
616 syncbuf.fail(self, _PriorSyncFailedError())
617 return
618
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700619 if head == revid:
620 # No changes; don't do anything further.
621 #
622 return
623
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700624 lost = self._revlist(not_rev(rev), HEAD)
625 if lost:
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700626 syncbuf.info(self, "discarding %d commits", len(lost))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700627 try:
628 self._Checkout(rev, quiet=True)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700629 except GitError, e:
630 syncbuf.fail(self, e)
631 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700632 self._CopyFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700633 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700634
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700635 if head == revid:
636 # No changes; don't do anything further.
637 #
638 return
639
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700640 branch = self.GetBranch(branch)
641 merge = branch.LocalMerge
642
643 if not merge:
644 # The current branch has no tracking configuration.
645 # Jump off it to a deatched HEAD.
646 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700647 syncbuf.info(self,
648 "leaving %s; does not track upstream",
649 branch.name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700650 try:
651 self._Checkout(rev, quiet=True)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700652 except GitError, e:
653 syncbuf.fail(self, e)
654 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700655 self._CopyFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700656 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700657
658 upstream_gain = self._revlist(not_rev(HEAD), rev)
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700659 pub = self.WasPublished(branch.name, all)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700660 if pub:
661 not_merged = self._revlist(not_rev(rev), pub)
662 if not_merged:
663 if upstream_gain:
664 # The user has published this branch and some of those
665 # commits are not yet merged upstream. We do not want
666 # to rewrite the published commits so we punt.
667 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700668 syncbuf.info(self,
669 "branch %s is published but is now %d commits behind",
670 branch.name,
671 len(upstream_gain))
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700672 return
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700673 elif upstream_gain:
Shawn O. Pearcea54c5272008-10-30 11:03:00 -0700674 # We can fast-forward safely.
675 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700676 def _doff():
Shawn O. Pearcea54c5272008-10-30 11:03:00 -0700677 self._FastForward(rev)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700678 self._CopyFiles()
679 syncbuf.later1(self, _doff)
680 return
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700681 else:
682 # Trivially no changes in the upstream.
683 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700684 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700685
686 if merge == rev:
687 try:
688 old_merge = self.bare_git.rev_parse('%s@{1}' % merge)
689 except GitError:
690 old_merge = merge
Shawn O. Pearce07346002008-10-21 07:09:27 -0700691 if old_merge == '0000000000000000000000000000000000000000' \
692 or old_merge == '':
693 old_merge = merge
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700694 else:
695 # The upstream switched on us. Time to cross our fingers
696 # and pray that the old upstream also wasn't in the habit
697 # of rebasing itself.
698 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700699 syncbuf.info(self, "manifest switched %s...%s", merge, rev)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700700 old_merge = merge
701
702 if rev == old_merge:
703 upstream_lost = []
704 else:
705 upstream_lost = self._revlist(not_rev(rev), old_merge)
706
707 if not upstream_lost and not upstream_gain:
708 # Trivially no changes caused by the upstream.
709 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700710 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700711
712 if self.IsDirty(consider_untracked=False):
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700713 syncbuf.fail(self, _DirtyError())
714 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700715
716 if upstream_lost:
717 # Upstream rebased. Not everything in HEAD
718 # may have been caused by the user.
719 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700720 syncbuf.info(self,
721 "discarding %d commits removed from upstream",
722 len(upstream_lost))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700723
724 branch.remote = rem
725 branch.merge = self.revision
726 branch.Save()
727
728 my_changes = self._revlist(not_rev(old_merge), HEAD)
729 if my_changes:
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700730 def _dorebase():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700731 self._Rebase(upstream = old_merge, onto = rev)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700732 self._CopyFiles()
733 syncbuf.later2(self, _dorebase)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700734 elif upstream_lost:
735 try:
736 self._ResetHard(rev)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700737 self._CopyFiles()
738 except GitError, e:
739 syncbuf.fail(self, e)
740 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700741 else:
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700742 def _doff():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700743 self._FastForward(rev)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700744 self._CopyFiles()
745 syncbuf.later1(self, _doff)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700746
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800747 def AddCopyFile(self, src, dest, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700748 # dest should already be an absolute path, but src is project relative
749 # make src an absolute path
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800750 abssrc = os.path.join(self.worktree, src)
751 self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700752
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700753 def DownloadPatchSet(self, change_id, patch_id):
754 """Download a single patch set of a single change to FETCH_HEAD.
755 """
756 remote = self.GetRemote(self.remote.name)
757
758 cmd = ['fetch', remote.name]
759 cmd.append('refs/changes/%2.2d/%d/%d' \
760 % (change_id % 100, change_id, patch_id))
761 cmd.extend(map(lambda x: str(x), remote.fetch))
762 if GitCommand(self, cmd, bare=True).Wait() != 0:
763 return None
764 return DownloadedChange(self,
765 remote.ToLocal(self.revision),
766 change_id,
767 patch_id,
768 self.bare_git.rev_parse('FETCH_HEAD'))
769
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700770
771## Branch Management ##
772
773 def StartBranch(self, name):
774 """Create a new branch off the manifest's revision.
775 """
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700776 head = self.work_git.GetHead()
777 if head == (R_HEADS + name):
778 return True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700779
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700780 all = self.bare_ref.all
781 if (R_HEADS + name) in all:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700782 return GitCommand(self,
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700783 ['checkout', name, '--'],
Shawn O. Pearce0f0dfa32009-04-18 14:53:39 -0700784 capture_stdout = True,
785 capture_stderr = True).Wait() == 0
Shawn O. Pearce0a389e92009-04-10 16:21:18 -0700786
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700787 branch = self.GetBranch(name)
788 branch.remote = self.GetRemote(self.remote.name)
789 branch.merge = self.revision
790
791 rev = branch.LocalMerge
792 if rev in all:
793 revid = all[rev]
794 elif IsId(rev):
795 revid = rev
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700796 else:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700797 revid = None
Shawn O. Pearce0a389e92009-04-10 16:21:18 -0700798
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700799 if head.startswith(R_HEADS):
800 try:
801 head = all[head]
802 except KeyError:
803 head = None
804
805 if revid and head and revid == head:
806 ref = os.path.join(self.gitdir, R_HEADS + name)
807 try:
808 os.makedirs(os.path.dirname(ref))
809 except OSError:
810 pass
811 _lwrite(ref, '%s\n' % revid)
812 _lwrite(os.path.join(self.worktree, '.git', HEAD),
813 'ref: %s%s\n' % (R_HEADS, name))
814 branch.Save()
815 return True
816
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700817 if GitCommand(self,
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700818 ['checkout', '-b', branch.name, rev],
Shawn O. Pearce0f0dfa32009-04-18 14:53:39 -0700819 capture_stdout = True,
820 capture_stderr = True).Wait() == 0:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700821 branch.Save()
822 return True
823 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700824
Wink Saville02d79452009-04-10 13:01:24 -0700825 def CheckoutBranch(self, name):
826 """Checkout a local topic branch.
827 """
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700828 rev = R_HEADS + name
829 head = self.work_git.GetHead()
830 if head == rev:
831 # Already on the branch
832 #
833 return True
Wink Saville02d79452009-04-10 13:01:24 -0700834
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700835 all = self.bare_ref.all
Wink Saville02d79452009-04-10 13:01:24 -0700836 try:
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700837 revid = all[rev]
838 except KeyError:
839 # Branch does not exist in this project
840 #
841 return False
842
843 if head.startswith(R_HEADS):
844 try:
845 head = all[head]
846 except KeyError:
847 head = None
848
849 if head == revid:
850 # Same revision; just update HEAD to point to the new
851 # target branch, but otherwise take no other action.
852 #
853 _lwrite(os.path.join(self.worktree, '.git', HEAD),
854 'ref: %s%s\n' % (R_HEADS, name))
855 return True
Wink Saville02d79452009-04-10 13:01:24 -0700856
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700857 return GitCommand(self,
858 ['checkout', name, '--'],
859 capture_stdout = True,
860 capture_stderr = True).Wait() == 0
Wink Saville02d79452009-04-10 13:01:24 -0700861
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800862 def AbandonBranch(self, name):
863 """Destroy a local topic branch.
864 """
865 try:
866 tip_rev = self.bare_git.rev_parse(R_HEADS + name)
867 except GitError:
868 return
869
870 if self.CurrentBranch == name:
871 self._Checkout(
872 self.GetRemote(self.remote.name).ToLocal(self.revision),
873 quiet=True)
874
875 cmd = ['branch', '-D', name]
876 GitCommand(self, cmd, capture_stdout=True).Wait()
877
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700878 def PruneHeads(self):
879 """Prune any topic branches already merged into upstream.
880 """
881 cb = self.CurrentBranch
882 kill = []
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800883 left = self._allrefs
884 for name in left.keys():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700885 if name.startswith(R_HEADS):
886 name = name[len(R_HEADS):]
887 if cb is None or name != cb:
888 kill.append(name)
889
890 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
891 if cb is not None \
892 and not self._revlist(HEAD + '...' + rev) \
893 and not self.IsDirty(consider_untracked = False):
894 self.work_git.DetachHead(HEAD)
895 kill.append(cb)
896
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700897 if kill:
Shawn O. Pearce5b23f242009-04-17 18:43:33 -0700898 old = self.bare_git.GetHead()
899 if old is None:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700900 old = 'refs/heads/please_never_use_this_as_a_branch_name'
901
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700902 try:
903 self.bare_git.DetachHead(rev)
904
905 b = ['branch', '-d']
906 b.extend(kill)
907 b = GitCommand(self, b, bare=True,
908 capture_stdout=True,
909 capture_stderr=True)
910 b.Wait()
911 finally:
912 self.bare_git.SetHead(old)
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800913 left = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700914
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800915 for branch in kill:
916 if (R_HEADS + branch) not in left:
917 self.CleanPublishedCache()
918 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700919
920 if cb and cb not in kill:
921 kill.append(cb)
Shawn O. Pearce7c6c64d2009-03-02 12:38:13 -0800922 kill.sort()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700923
924 kept = []
925 for branch in kill:
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800926 if (R_HEADS + branch) in left:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700927 branch = self.GetBranch(branch)
928 base = branch.LocalMerge
929 if not base:
930 base = rev
931 kept.append(ReviewableBranch(self, branch, base))
932 return kept
933
934
935## Direct Git Commands ##
936
937 def _RemoteFetch(self, name=None):
938 if not name:
939 name = self.remote.name
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800940 cmd = ['fetch']
941 if not self.worktree:
942 cmd.append('--update-head-ok')
943 cmd.append(name)
944 return GitCommand(self, cmd, bare = True).Wait() == 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700945
946 def _Checkout(self, rev, quiet=False):
947 cmd = ['checkout']
948 if quiet:
949 cmd.append('-q')
950 cmd.append(rev)
951 cmd.append('--')
952 if GitCommand(self, cmd).Wait() != 0:
953 if self._allrefs:
954 raise GitError('%s checkout %s ' % (self.name, rev))
955
956 def _ResetHard(self, rev, quiet=True):
957 cmd = ['reset', '--hard']
958 if quiet:
959 cmd.append('-q')
960 cmd.append(rev)
961 if GitCommand(self, cmd).Wait() != 0:
962 raise GitError('%s reset --hard %s ' % (self.name, rev))
963
964 def _Rebase(self, upstream, onto = None):
Shawn O. Pearce19a83d82009-04-16 08:14:26 -0700965 cmd = ['rebase']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700966 if onto is not None:
967 cmd.extend(['--onto', onto])
968 cmd.append(upstream)
Shawn O. Pearce19a83d82009-04-16 08:14:26 -0700969 if GitCommand(self, cmd).Wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700970 raise GitError('%s rebase %s ' % (self.name, upstream))
971
972 def _FastForward(self, head):
973 cmd = ['merge', head]
974 if GitCommand(self, cmd).Wait() != 0:
975 raise GitError('%s merge %s ' % (self.name, head))
976
977 def _InitGitDir(self):
978 if not os.path.exists(self.gitdir):
979 os.makedirs(self.gitdir)
980 self.bare_git.init()
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -0800981
982 if self.manifest.IsMirror:
983 self.config.SetString('core.bare', 'true')
984 else:
985 self.config.SetString('core.bare', None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700986
987 hooks = self._gitdir_path('hooks')
Shawn O. Pearcede646812008-10-29 14:38:12 -0700988 try:
989 to_rm = os.listdir(hooks)
990 except OSError:
991 to_rm = []
992 for old_hook in to_rm:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700993 os.remove(os.path.join(hooks, old_hook))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800994 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700995
996 m = self.manifest.manifestProject.config
997 for key in ['user.name', 'user.email']:
998 if m.Has(key, include_defaults = False):
999 self.config.SetString(key, m.GetString(key))
1000
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001001 def _InitHooks(self):
1002 hooks = self._gitdir_path('hooks')
1003 if not os.path.exists(hooks):
1004 os.makedirs(hooks)
1005 for stock_hook in repo_hooks():
1006 dst = os.path.join(hooks, os.path.basename(stock_hook))
1007 try:
1008 os.symlink(relpath(stock_hook, dst), dst)
1009 except OSError, e:
1010 if e.errno == errno.EEXIST:
1011 pass
1012 elif e.errno == errno.EPERM:
1013 raise GitError('filesystem must support symlinks')
1014 else:
1015 raise
1016
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001017 def _InitRemote(self):
1018 if self.remote.fetchUrl:
1019 remote = self.GetRemote(self.remote.name)
1020
1021 url = self.remote.fetchUrl
1022 while url.endswith('/'):
1023 url = url[:-1]
1024 url += '/%s.git' % self.name
1025 remote.url = url
1026 remote.review = self.remote.reviewUrl
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -08001027 if remote.projectname is None:
1028 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001029
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001030 if self.worktree:
1031 remote.ResetFetch(mirror=False)
1032 else:
1033 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001034 remote.Save()
1035
1036 for r in self.extraRemotes.values():
1037 remote = self.GetRemote(r.name)
1038 remote.url = r.fetchUrl
1039 remote.review = r.reviewUrl
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001040 if r.projectName:
1041 remote.projectname = r.projectName
1042 elif remote.projectname is None:
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -08001043 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001044 remote.ResetFetch()
1045 remote.Save()
1046
1047 def _InitMRef(self):
1048 if self.manifest.branch:
1049 msg = 'manifest set to %s' % self.revision
1050 ref = R_M + self.manifest.branch
Shawn O. Pearce0f3dd232009-04-17 20:32:44 -07001051 cur = self.bare_ref.symref(ref)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001052
1053 if IsId(self.revision):
Shawn O. Pearce0f3dd232009-04-17 20:32:44 -07001054 if cur != '' or self.bare_ref.get(ref) != self.revision:
1055 dst = self.revision + '^0'
1056 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001057 else:
1058 remote = self.GetRemote(self.remote.name)
1059 dst = remote.ToLocal(self.revision)
Shawn O. Pearce0f3dd232009-04-17 20:32:44 -07001060 if cur != dst:
1061 self.bare_git.symbolic_ref('-m', msg, ref, dst)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001062
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001063 def _InitMirrorHead(self):
1064 dst = self.GetRemote(self.remote.name).ToLocal(self.revision)
1065 msg = 'manifest set to %s' % self.revision
1066 self.bare_git.SetHead(dst, message=msg)
1067
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001068 def _InitWorkTree(self):
1069 dotgit = os.path.join(self.worktree, '.git')
1070 if not os.path.exists(dotgit):
1071 os.makedirs(dotgit)
1072
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001073 for name in ['config',
1074 'description',
1075 'hooks',
1076 'info',
1077 'logs',
1078 'objects',
1079 'packed-refs',
1080 'refs',
1081 'rr-cache',
1082 'svn']:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08001083 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001084 src = os.path.join(self.gitdir, name)
1085 dst = os.path.join(dotgit, name)
1086 os.symlink(relpath(src, dst), dst)
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08001087 except OSError, e:
1088 if e.errno == errno.EPERM:
1089 raise GitError('filesystem must support symlinks')
1090 else:
1091 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001092
1093 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
1094 rev = self.bare_git.rev_parse('%s^0' % rev)
1095
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -07001096 _lwrite(os.path.join(dotgit, HEAD), '%s\n' % rev)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001097
1098 cmd = ['read-tree', '--reset', '-u']
1099 cmd.append('-v')
1100 cmd.append('HEAD')
1101 if GitCommand(self, cmd).Wait() != 0:
1102 raise GitError("cannot initialize work tree")
1103
1104 def _gitdir_path(self, path):
1105 return os.path.join(self.gitdir, path)
1106
1107 def _revlist(self, *args):
1108 cmd = []
1109 cmd.extend(args)
1110 cmd.append('--')
1111 return self.work_git.rev_list(*args)
1112
1113 @property
1114 def _allrefs(self):
Shawn O. Pearced237b692009-04-17 18:49:50 -07001115 return self.bare_ref.all
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001116
1117 class _GitGetByExec(object):
1118 def __init__(self, project, bare):
1119 self._project = project
1120 self._bare = bare
1121
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001122 def LsOthers(self):
1123 p = GitCommand(self._project,
1124 ['ls-files',
1125 '-z',
1126 '--others',
1127 '--exclude-standard'],
1128 bare = False,
1129 capture_stdout = True,
1130 capture_stderr = True)
1131 if p.Wait() == 0:
1132 out = p.stdout
1133 if out:
1134 return out[:-1].split("\0")
1135 return []
1136
1137 def DiffZ(self, name, *args):
1138 cmd = [name]
1139 cmd.append('-z')
1140 cmd.extend(args)
1141 p = GitCommand(self._project,
1142 cmd,
1143 bare = False,
1144 capture_stdout = True,
1145 capture_stderr = True)
1146 try:
1147 out = p.process.stdout.read()
1148 r = {}
1149 if out:
1150 out = iter(out[:-1].split('\0'))
1151 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07001152 try:
1153 info = out.next()
1154 path = out.next()
1155 except StopIteration:
1156 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001157
1158 class _Info(object):
1159 def __init__(self, path, omode, nmode, oid, nid, state):
1160 self.path = path
1161 self.src_path = None
1162 self.old_mode = omode
1163 self.new_mode = nmode
1164 self.old_id = oid
1165 self.new_id = nid
1166
1167 if len(state) == 1:
1168 self.status = state
1169 self.level = None
1170 else:
1171 self.status = state[:1]
1172 self.level = state[1:]
1173 while self.level.startswith('0'):
1174 self.level = self.level[1:]
1175
1176 info = info[1:].split(' ')
1177 info =_Info(path, *info)
1178 if info.status in ('R', 'C'):
1179 info.src_path = info.path
1180 info.path = out.next()
1181 r[info.path] = info
1182 return r
1183 finally:
1184 p.Wait()
1185
1186 def GetHead(self):
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07001187 if self._bare:
1188 path = os.path.join(self._project.gitdir, HEAD)
1189 else:
1190 path = os.path.join(self._project.worktree, '.git', HEAD)
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -07001191 fd = open(path, 'rb')
1192 try:
1193 line = fd.read()
1194 finally:
1195 fd.close()
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07001196 if line.startswith('ref: '):
1197 return line[5:-1]
1198 return line[:-1]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001199
1200 def SetHead(self, ref, message=None):
1201 cmdv = []
1202 if message is not None:
1203 cmdv.extend(['-m', message])
1204 cmdv.append(HEAD)
1205 cmdv.append(ref)
1206 self.symbolic_ref(*cmdv)
1207
1208 def DetachHead(self, new, message=None):
1209 cmdv = ['--no-deref']
1210 if message is not None:
1211 cmdv.extend(['-m', message])
1212 cmdv.append(HEAD)
1213 cmdv.append(new)
1214 self.update_ref(*cmdv)
1215
1216 def UpdateRef(self, name, new, old=None,
1217 message=None,
1218 detach=False):
1219 cmdv = []
1220 if message is not None:
1221 cmdv.extend(['-m', message])
1222 if detach:
1223 cmdv.append('--no-deref')
1224 cmdv.append(name)
1225 cmdv.append(new)
1226 if old is not None:
1227 cmdv.append(old)
1228 self.update_ref(*cmdv)
1229
1230 def DeleteRef(self, name, old=None):
1231 if not old:
1232 old = self.rev_parse(name)
1233 self.update_ref('-d', name, old)
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001234 self._project.bare_ref.deleted(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001235
1236 def rev_list(self, *args):
1237 cmdv = ['rev-list']
1238 cmdv.extend(args)
1239 p = GitCommand(self._project,
1240 cmdv,
1241 bare = self._bare,
1242 capture_stdout = True,
1243 capture_stderr = True)
1244 r = []
1245 for line in p.process.stdout:
1246 r.append(line[:-1])
1247 if p.Wait() != 0:
1248 raise GitError('%s rev-list %s: %s' % (
1249 self._project.name,
1250 str(args),
1251 p.stderr))
1252 return r
1253
1254 def __getattr__(self, name):
1255 name = name.replace('_', '-')
1256 def runner(*args):
1257 cmdv = [name]
1258 cmdv.extend(args)
1259 p = GitCommand(self._project,
1260 cmdv,
1261 bare = self._bare,
1262 capture_stdout = True,
1263 capture_stderr = True)
1264 if p.Wait() != 0:
1265 raise GitError('%s %s: %s' % (
1266 self._project.name,
1267 name,
1268 p.stderr))
1269 r = p.stdout
1270 if r.endswith('\n') and r.index('\n') == len(r) - 1:
1271 return r[:-1]
1272 return r
1273 return runner
1274
1275
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001276class _PriorSyncFailedError(Exception):
1277 def __str__(self):
1278 return 'prior sync failed; rebase still in progress'
1279
1280class _DirtyError(Exception):
1281 def __str__(self):
1282 return 'contains uncommitted changes'
1283
1284class _InfoMessage(object):
1285 def __init__(self, project, text):
1286 self.project = project
1287 self.text = text
1288
1289 def Print(self, syncbuf):
1290 syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
1291 syncbuf.out.nl()
1292
1293class _Failure(object):
1294 def __init__(self, project, why):
1295 self.project = project
1296 self.why = why
1297
1298 def Print(self, syncbuf):
1299 syncbuf.out.fail('error: %s/: %s',
1300 self.project.relpath,
1301 str(self.why))
1302 syncbuf.out.nl()
1303
1304class _Later(object):
1305 def __init__(self, project, action):
1306 self.project = project
1307 self.action = action
1308
1309 def Run(self, syncbuf):
1310 out = syncbuf.out
1311 out.project('project %s/', self.project.relpath)
1312 out.nl()
1313 try:
1314 self.action()
1315 out.nl()
1316 return True
1317 except GitError, e:
1318 out.nl()
1319 return False
1320
1321class _SyncColoring(Coloring):
1322 def __init__(self, config):
1323 Coloring.__init__(self, config, 'reposync')
1324 self.project = self.printer('header', attr = 'bold')
1325 self.info = self.printer('info')
1326 self.fail = self.printer('fail', fg='red')
1327
1328class SyncBuffer(object):
1329 def __init__(self, config, detach_head=False):
1330 self._messages = []
1331 self._failures = []
1332 self._later_queue1 = []
1333 self._later_queue2 = []
1334
1335 self.out = _SyncColoring(config)
1336 self.out.redirect(sys.stderr)
1337
1338 self.detach_head = detach_head
1339 self.clean = True
1340
1341 def info(self, project, fmt, *args):
1342 self._messages.append(_InfoMessage(project, fmt % args))
1343
1344 def fail(self, project, err=None):
1345 self._failures.append(_Failure(project, err))
1346 self.clean = False
1347
1348 def later1(self, project, what):
1349 self._later_queue1.append(_Later(project, what))
1350
1351 def later2(self, project, what):
1352 self._later_queue2.append(_Later(project, what))
1353
1354 def Finish(self):
1355 self._PrintMessages()
1356 self._RunLater()
1357 self._PrintMessages()
1358 return self.clean
1359
1360 def _RunLater(self):
1361 for q in ['_later_queue1', '_later_queue2']:
1362 if not self._RunQueue(q):
1363 return
1364
1365 def _RunQueue(self, queue):
1366 for m in getattr(self, queue):
1367 if not m.Run(self):
1368 self.clean = False
1369 return False
1370 setattr(self, queue, [])
1371 return True
1372
1373 def _PrintMessages(self):
1374 for m in self._messages:
1375 m.Print(self)
1376 for m in self._failures:
1377 m.Print(self)
1378
1379 self._messages = []
1380 self._failures = []
1381
1382
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001383class MetaProject(Project):
1384 """A special project housed under .repo.
1385 """
1386 def __init__(self, manifest, name, gitdir, worktree):
1387 repodir = manifest.repodir
1388 Project.__init__(self,
1389 manifest = manifest,
1390 name = name,
1391 gitdir = gitdir,
1392 worktree = worktree,
1393 remote = Remote('origin'),
1394 relpath = '.repo/%s' % name,
1395 revision = 'refs/heads/master')
1396
1397 def PreSync(self):
1398 if self.Exists:
1399 cb = self.CurrentBranch
1400 if cb:
1401 base = self.GetBranch(cb).merge
1402 if base:
1403 self.revision = base
1404
1405 @property
Shawn O. Pearcef6906872009-04-18 10:49:00 -07001406 def LastFetch(self):
1407 try:
1408 fh = os.path.join(self.gitdir, 'FETCH_HEAD')
1409 return os.path.getmtime(fh)
1410 except OSError:
1411 return 0
1412
1413 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001414 def HasChanges(self):
1415 """Has the remote received new commits not yet checked out?
1416 """
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07001417 if not self.remote or not self.revision:
1418 return False
1419
1420 all = self.bare_ref.all
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001421 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07001422 if rev in all:
1423 revid = all[rev]
1424 else:
1425 revid = rev
1426
1427 head = self.work_git.GetHead()
1428 if head.startswith(R_HEADS):
1429 try:
1430 head = all[head]
1431 except KeyError:
1432 head = None
1433
1434 if revid == head:
1435 return False
1436 elif self._revlist(not_rev(HEAD), rev):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001437 return True
1438 return False