blob: 8d6e4b6cc73b48c583342dd6365e5c440c1aeed7 [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:
782 cmd = ['checkout', name, '--']
783 return GitCommand(self,
784 cmd,
785 capture_stdout = 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
817 cmd = ['checkout', '-b', branch.name, rev]
818 if GitCommand(self,
819 cmd,
820 capture_stdout = True).Wait() == 0:
821 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 """
828
829 # Be sure the branch exists
830 try:
831 tip_rev = self.bare_git.rev_parse(R_HEADS + name)
832 except GitError:
833 return False;
834
835 # Do the checkout
836 cmd = ['checkout', name, '--']
Shawn O. Pearce2675c3f2009-04-10 16:20:25 -0700837 return GitCommand(self, cmd).Wait() == 0
Wink Saville02d79452009-04-10 13:01:24 -0700838
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800839 def AbandonBranch(self, name):
840 """Destroy a local topic branch.
841 """
842 try:
843 tip_rev = self.bare_git.rev_parse(R_HEADS + name)
844 except GitError:
845 return
846
847 if self.CurrentBranch == name:
848 self._Checkout(
849 self.GetRemote(self.remote.name).ToLocal(self.revision),
850 quiet=True)
851
852 cmd = ['branch', '-D', name]
853 GitCommand(self, cmd, capture_stdout=True).Wait()
854
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700855 def PruneHeads(self):
856 """Prune any topic branches already merged into upstream.
857 """
858 cb = self.CurrentBranch
859 kill = []
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800860 left = self._allrefs
861 for name in left.keys():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700862 if name.startswith(R_HEADS):
863 name = name[len(R_HEADS):]
864 if cb is None or name != cb:
865 kill.append(name)
866
867 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
868 if cb is not None \
869 and not self._revlist(HEAD + '...' + rev) \
870 and not self.IsDirty(consider_untracked = False):
871 self.work_git.DetachHead(HEAD)
872 kill.append(cb)
873
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700874 if kill:
Shawn O. Pearce5b23f242009-04-17 18:43:33 -0700875 old = self.bare_git.GetHead()
876 if old is None:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700877 old = 'refs/heads/please_never_use_this_as_a_branch_name'
878
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700879 try:
880 self.bare_git.DetachHead(rev)
881
882 b = ['branch', '-d']
883 b.extend(kill)
884 b = GitCommand(self, b, bare=True,
885 capture_stdout=True,
886 capture_stderr=True)
887 b.Wait()
888 finally:
889 self.bare_git.SetHead(old)
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800890 left = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700891
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800892 for branch in kill:
893 if (R_HEADS + branch) not in left:
894 self.CleanPublishedCache()
895 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700896
897 if cb and cb not in kill:
898 kill.append(cb)
Shawn O. Pearce7c6c64d2009-03-02 12:38:13 -0800899 kill.sort()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700900
901 kept = []
902 for branch in kill:
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800903 if (R_HEADS + branch) in left:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700904 branch = self.GetBranch(branch)
905 base = branch.LocalMerge
906 if not base:
907 base = rev
908 kept.append(ReviewableBranch(self, branch, base))
909 return kept
910
911
912## Direct Git Commands ##
913
914 def _RemoteFetch(self, name=None):
915 if not name:
916 name = self.remote.name
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800917 cmd = ['fetch']
918 if not self.worktree:
919 cmd.append('--update-head-ok')
920 cmd.append(name)
921 return GitCommand(self, cmd, bare = True).Wait() == 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700922
923 def _Checkout(self, rev, quiet=False):
924 cmd = ['checkout']
925 if quiet:
926 cmd.append('-q')
927 cmd.append(rev)
928 cmd.append('--')
929 if GitCommand(self, cmd).Wait() != 0:
930 if self._allrefs:
931 raise GitError('%s checkout %s ' % (self.name, rev))
932
933 def _ResetHard(self, rev, quiet=True):
934 cmd = ['reset', '--hard']
935 if quiet:
936 cmd.append('-q')
937 cmd.append(rev)
938 if GitCommand(self, cmd).Wait() != 0:
939 raise GitError('%s reset --hard %s ' % (self.name, rev))
940
941 def _Rebase(self, upstream, onto = None):
Shawn O. Pearce19a83d82009-04-16 08:14:26 -0700942 cmd = ['rebase']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700943 if onto is not None:
944 cmd.extend(['--onto', onto])
945 cmd.append(upstream)
Shawn O. Pearce19a83d82009-04-16 08:14:26 -0700946 if GitCommand(self, cmd).Wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700947 raise GitError('%s rebase %s ' % (self.name, upstream))
948
949 def _FastForward(self, head):
950 cmd = ['merge', head]
951 if GitCommand(self, cmd).Wait() != 0:
952 raise GitError('%s merge %s ' % (self.name, head))
953
954 def _InitGitDir(self):
955 if not os.path.exists(self.gitdir):
956 os.makedirs(self.gitdir)
957 self.bare_git.init()
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -0800958
959 if self.manifest.IsMirror:
960 self.config.SetString('core.bare', 'true')
961 else:
962 self.config.SetString('core.bare', None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700963
964 hooks = self._gitdir_path('hooks')
Shawn O. Pearcede646812008-10-29 14:38:12 -0700965 try:
966 to_rm = os.listdir(hooks)
967 except OSError:
968 to_rm = []
969 for old_hook in to_rm:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700970 os.remove(os.path.join(hooks, old_hook))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800971 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700972
973 m = self.manifest.manifestProject.config
974 for key in ['user.name', 'user.email']:
975 if m.Has(key, include_defaults = False):
976 self.config.SetString(key, m.GetString(key))
977
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800978 def _InitHooks(self):
979 hooks = self._gitdir_path('hooks')
980 if not os.path.exists(hooks):
981 os.makedirs(hooks)
982 for stock_hook in repo_hooks():
983 dst = os.path.join(hooks, os.path.basename(stock_hook))
984 try:
985 os.symlink(relpath(stock_hook, dst), dst)
986 except OSError, e:
987 if e.errno == errno.EEXIST:
988 pass
989 elif e.errno == errno.EPERM:
990 raise GitError('filesystem must support symlinks')
991 else:
992 raise
993
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700994 def _InitRemote(self):
995 if self.remote.fetchUrl:
996 remote = self.GetRemote(self.remote.name)
997
998 url = self.remote.fetchUrl
999 while url.endswith('/'):
1000 url = url[:-1]
1001 url += '/%s.git' % self.name
1002 remote.url = url
1003 remote.review = self.remote.reviewUrl
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -08001004 if remote.projectname is None:
1005 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001006
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001007 if self.worktree:
1008 remote.ResetFetch(mirror=False)
1009 else:
1010 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001011 remote.Save()
1012
1013 for r in self.extraRemotes.values():
1014 remote = self.GetRemote(r.name)
1015 remote.url = r.fetchUrl
1016 remote.review = r.reviewUrl
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001017 if r.projectName:
1018 remote.projectname = r.projectName
1019 elif remote.projectname is None:
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -08001020 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001021 remote.ResetFetch()
1022 remote.Save()
1023
1024 def _InitMRef(self):
1025 if self.manifest.branch:
1026 msg = 'manifest set to %s' % self.revision
1027 ref = R_M + self.manifest.branch
Shawn O. Pearce0f3dd232009-04-17 20:32:44 -07001028 cur = self.bare_ref.symref(ref)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001029
1030 if IsId(self.revision):
Shawn O. Pearce0f3dd232009-04-17 20:32:44 -07001031 if cur != '' or self.bare_ref.get(ref) != self.revision:
1032 dst = self.revision + '^0'
1033 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001034 else:
1035 remote = self.GetRemote(self.remote.name)
1036 dst = remote.ToLocal(self.revision)
Shawn O. Pearce0f3dd232009-04-17 20:32:44 -07001037 if cur != dst:
1038 self.bare_git.symbolic_ref('-m', msg, ref, dst)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001039
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001040 def _InitMirrorHead(self):
1041 dst = self.GetRemote(self.remote.name).ToLocal(self.revision)
1042 msg = 'manifest set to %s' % self.revision
1043 self.bare_git.SetHead(dst, message=msg)
1044
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001045 def _InitWorkTree(self):
1046 dotgit = os.path.join(self.worktree, '.git')
1047 if not os.path.exists(dotgit):
1048 os.makedirs(dotgit)
1049
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001050 for name in ['config',
1051 'description',
1052 'hooks',
1053 'info',
1054 'logs',
1055 'objects',
1056 'packed-refs',
1057 'refs',
1058 'rr-cache',
1059 'svn']:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08001060 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001061 src = os.path.join(self.gitdir, name)
1062 dst = os.path.join(dotgit, name)
1063 os.symlink(relpath(src, dst), dst)
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08001064 except OSError, e:
1065 if e.errno == errno.EPERM:
1066 raise GitError('filesystem must support symlinks')
1067 else:
1068 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001069
1070 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
1071 rev = self.bare_git.rev_parse('%s^0' % rev)
1072
1073 f = open(os.path.join(dotgit, HEAD), 'wb')
1074 f.write("%s\n" % rev)
1075 f.close()
1076
1077 cmd = ['read-tree', '--reset', '-u']
1078 cmd.append('-v')
1079 cmd.append('HEAD')
1080 if GitCommand(self, cmd).Wait() != 0:
1081 raise GitError("cannot initialize work tree")
1082
1083 def _gitdir_path(self, path):
1084 return os.path.join(self.gitdir, path)
1085
1086 def _revlist(self, *args):
1087 cmd = []
1088 cmd.extend(args)
1089 cmd.append('--')
1090 return self.work_git.rev_list(*args)
1091
1092 @property
1093 def _allrefs(self):
Shawn O. Pearced237b692009-04-17 18:49:50 -07001094 return self.bare_ref.all
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001095
1096 class _GitGetByExec(object):
1097 def __init__(self, project, bare):
1098 self._project = project
1099 self._bare = bare
1100
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001101 def LsOthers(self):
1102 p = GitCommand(self._project,
1103 ['ls-files',
1104 '-z',
1105 '--others',
1106 '--exclude-standard'],
1107 bare = False,
1108 capture_stdout = True,
1109 capture_stderr = True)
1110 if p.Wait() == 0:
1111 out = p.stdout
1112 if out:
1113 return out[:-1].split("\0")
1114 return []
1115
1116 def DiffZ(self, name, *args):
1117 cmd = [name]
1118 cmd.append('-z')
1119 cmd.extend(args)
1120 p = GitCommand(self._project,
1121 cmd,
1122 bare = False,
1123 capture_stdout = True,
1124 capture_stderr = True)
1125 try:
1126 out = p.process.stdout.read()
1127 r = {}
1128 if out:
1129 out = iter(out[:-1].split('\0'))
1130 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07001131 try:
1132 info = out.next()
1133 path = out.next()
1134 except StopIteration:
1135 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001136
1137 class _Info(object):
1138 def __init__(self, path, omode, nmode, oid, nid, state):
1139 self.path = path
1140 self.src_path = None
1141 self.old_mode = omode
1142 self.new_mode = nmode
1143 self.old_id = oid
1144 self.new_id = nid
1145
1146 if len(state) == 1:
1147 self.status = state
1148 self.level = None
1149 else:
1150 self.status = state[:1]
1151 self.level = state[1:]
1152 while self.level.startswith('0'):
1153 self.level = self.level[1:]
1154
1155 info = info[1:].split(' ')
1156 info =_Info(path, *info)
1157 if info.status in ('R', 'C'):
1158 info.src_path = info.path
1159 info.path = out.next()
1160 r[info.path] = info
1161 return r
1162 finally:
1163 p.Wait()
1164
1165 def GetHead(self):
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07001166 if self._bare:
1167 path = os.path.join(self._project.gitdir, HEAD)
1168 else:
1169 path = os.path.join(self._project.worktree, '.git', HEAD)
1170 line = open(path, 'r').read()
1171 if line.startswith('ref: '):
1172 return line[5:-1]
1173 return line[:-1]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001174
1175 def SetHead(self, ref, message=None):
1176 cmdv = []
1177 if message is not None:
1178 cmdv.extend(['-m', message])
1179 cmdv.append(HEAD)
1180 cmdv.append(ref)
1181 self.symbolic_ref(*cmdv)
1182
1183 def DetachHead(self, new, message=None):
1184 cmdv = ['--no-deref']
1185 if message is not None:
1186 cmdv.extend(['-m', message])
1187 cmdv.append(HEAD)
1188 cmdv.append(new)
1189 self.update_ref(*cmdv)
1190
1191 def UpdateRef(self, name, new, old=None,
1192 message=None,
1193 detach=False):
1194 cmdv = []
1195 if message is not None:
1196 cmdv.extend(['-m', message])
1197 if detach:
1198 cmdv.append('--no-deref')
1199 cmdv.append(name)
1200 cmdv.append(new)
1201 if old is not None:
1202 cmdv.append(old)
1203 self.update_ref(*cmdv)
1204
1205 def DeleteRef(self, name, old=None):
1206 if not old:
1207 old = self.rev_parse(name)
1208 self.update_ref('-d', name, old)
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001209 self._project.bare_ref.deleted(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001210
1211 def rev_list(self, *args):
1212 cmdv = ['rev-list']
1213 cmdv.extend(args)
1214 p = GitCommand(self._project,
1215 cmdv,
1216 bare = self._bare,
1217 capture_stdout = True,
1218 capture_stderr = True)
1219 r = []
1220 for line in p.process.stdout:
1221 r.append(line[:-1])
1222 if p.Wait() != 0:
1223 raise GitError('%s rev-list %s: %s' % (
1224 self._project.name,
1225 str(args),
1226 p.stderr))
1227 return r
1228
1229 def __getattr__(self, name):
1230 name = name.replace('_', '-')
1231 def runner(*args):
1232 cmdv = [name]
1233 cmdv.extend(args)
1234 p = GitCommand(self._project,
1235 cmdv,
1236 bare = self._bare,
1237 capture_stdout = True,
1238 capture_stderr = True)
1239 if p.Wait() != 0:
1240 raise GitError('%s %s: %s' % (
1241 self._project.name,
1242 name,
1243 p.stderr))
1244 r = p.stdout
1245 if r.endswith('\n') and r.index('\n') == len(r) - 1:
1246 return r[:-1]
1247 return r
1248 return runner
1249
1250
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001251class _PriorSyncFailedError(Exception):
1252 def __str__(self):
1253 return 'prior sync failed; rebase still in progress'
1254
1255class _DirtyError(Exception):
1256 def __str__(self):
1257 return 'contains uncommitted changes'
1258
1259class _InfoMessage(object):
1260 def __init__(self, project, text):
1261 self.project = project
1262 self.text = text
1263
1264 def Print(self, syncbuf):
1265 syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
1266 syncbuf.out.nl()
1267
1268class _Failure(object):
1269 def __init__(self, project, why):
1270 self.project = project
1271 self.why = why
1272
1273 def Print(self, syncbuf):
1274 syncbuf.out.fail('error: %s/: %s',
1275 self.project.relpath,
1276 str(self.why))
1277 syncbuf.out.nl()
1278
1279class _Later(object):
1280 def __init__(self, project, action):
1281 self.project = project
1282 self.action = action
1283
1284 def Run(self, syncbuf):
1285 out = syncbuf.out
1286 out.project('project %s/', self.project.relpath)
1287 out.nl()
1288 try:
1289 self.action()
1290 out.nl()
1291 return True
1292 except GitError, e:
1293 out.nl()
1294 return False
1295
1296class _SyncColoring(Coloring):
1297 def __init__(self, config):
1298 Coloring.__init__(self, config, 'reposync')
1299 self.project = self.printer('header', attr = 'bold')
1300 self.info = self.printer('info')
1301 self.fail = self.printer('fail', fg='red')
1302
1303class SyncBuffer(object):
1304 def __init__(self, config, detach_head=False):
1305 self._messages = []
1306 self._failures = []
1307 self._later_queue1 = []
1308 self._later_queue2 = []
1309
1310 self.out = _SyncColoring(config)
1311 self.out.redirect(sys.stderr)
1312
1313 self.detach_head = detach_head
1314 self.clean = True
1315
1316 def info(self, project, fmt, *args):
1317 self._messages.append(_InfoMessage(project, fmt % args))
1318
1319 def fail(self, project, err=None):
1320 self._failures.append(_Failure(project, err))
1321 self.clean = False
1322
1323 def later1(self, project, what):
1324 self._later_queue1.append(_Later(project, what))
1325
1326 def later2(self, project, what):
1327 self._later_queue2.append(_Later(project, what))
1328
1329 def Finish(self):
1330 self._PrintMessages()
1331 self._RunLater()
1332 self._PrintMessages()
1333 return self.clean
1334
1335 def _RunLater(self):
1336 for q in ['_later_queue1', '_later_queue2']:
1337 if not self._RunQueue(q):
1338 return
1339
1340 def _RunQueue(self, queue):
1341 for m in getattr(self, queue):
1342 if not m.Run(self):
1343 self.clean = False
1344 return False
1345 setattr(self, queue, [])
1346 return True
1347
1348 def _PrintMessages(self):
1349 for m in self._messages:
1350 m.Print(self)
1351 for m in self._failures:
1352 m.Print(self)
1353
1354 self._messages = []
1355 self._failures = []
1356
1357
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001358class MetaProject(Project):
1359 """A special project housed under .repo.
1360 """
1361 def __init__(self, manifest, name, gitdir, worktree):
1362 repodir = manifest.repodir
1363 Project.__init__(self,
1364 manifest = manifest,
1365 name = name,
1366 gitdir = gitdir,
1367 worktree = worktree,
1368 remote = Remote('origin'),
1369 relpath = '.repo/%s' % name,
1370 revision = 'refs/heads/master')
1371
1372 def PreSync(self):
1373 if self.Exists:
1374 cb = self.CurrentBranch
1375 if cb:
1376 base = self.GetBranch(cb).merge
1377 if base:
1378 self.revision = base
1379
1380 @property
Shawn O. Pearcef6906872009-04-18 10:49:00 -07001381 def LastFetch(self):
1382 try:
1383 fh = os.path.join(self.gitdir, 'FETCH_HEAD')
1384 return os.path.getmtime(fh)
1385 except OSError:
1386 return 0
1387
1388 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001389 def HasChanges(self):
1390 """Has the remote received new commits not yet checked out?
1391 """
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07001392 if not self.remote or not self.revision:
1393 return False
1394
1395 all = self.bare_ref.all
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001396 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07001397 if rev in all:
1398 revid = all[rev]
1399 else:
1400 revid = rev
1401
1402 head = self.work_git.GetHead()
1403 if head.startswith(R_HEADS):
1404 try:
1405 head = all[head]
1406 except KeyError:
1407 head = None
1408
1409 if revid == head:
1410 return False
1411 elif self._revlist(not_rev(HEAD), rev):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001412 return True
1413 return False