blob: 1cfaaae5e9588899e1e1c357029c403dfdc46416 [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
27from gerrit_upload import UploadBundle
28from error import GitError, ImportError, UploadError
29from remote import Remote
30from codereview import proto_client
31
32HEAD = 'HEAD'
33R_HEADS = 'refs/heads/'
34R_TAGS = 'refs/tags/'
35R_PUB = 'refs/published/'
36R_M = 'refs/remotes/m/'
37
38def _warn(fmt, *args):
39 msg = fmt % args
40 print >>sys.stderr, 'warn: %s' % msg
41
42def _info(fmt, *args):
43 msg = fmt % args
44 print >>sys.stderr, 'info: %s' % msg
45
46def not_rev(r):
47 return '^' + r
48
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080049
50hook_list = None
51def repo_hooks():
52 global hook_list
53 if hook_list is None:
54 d = os.path.abspath(os.path.dirname(__file__))
55 d = os.path.join(d , 'hooks')
56 hook_list = map(lambda x: os.path.join(d, x), os.listdir(d))
57 return hook_list
58
59def relpath(dst, src):
60 src = os.path.dirname(src)
61 top = os.path.commonprefix([dst, src])
62 if top.endswith('/'):
63 top = top[:-1]
64 else:
65 top = os.path.dirname(top)
66
67 tmp = src
68 rel = ''
69 while top != tmp:
70 rel += '../'
71 tmp = os.path.dirname(tmp)
72 return rel + dst[len(top) + 1:]
73
74
Shawn O. Pearce632768b2008-10-23 11:58:52 -070075class DownloadedChange(object):
76 _commit_cache = None
77
78 def __init__(self, project, base, change_id, ps_id, commit):
79 self.project = project
80 self.base = base
81 self.change_id = change_id
82 self.ps_id = ps_id
83 self.commit = commit
84
85 @property
86 def commits(self):
87 if self._commit_cache is None:
88 self._commit_cache = self.project.bare_git.rev_list(
89 '--abbrev=8',
90 '--abbrev-commit',
91 '--pretty=oneline',
92 '--reverse',
93 '--date-order',
94 not_rev(self.base),
95 self.commit,
96 '--')
97 return self._commit_cache
98
99
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700100class ReviewableBranch(object):
101 _commit_cache = None
102
103 def __init__(self, project, branch, base):
104 self.project = project
105 self.branch = branch
106 self.base = base
107
108 @property
109 def name(self):
110 return self.branch.name
111
112 @property
113 def commits(self):
114 if self._commit_cache is None:
115 self._commit_cache = self.project.bare_git.rev_list(
116 '--abbrev=8',
117 '--abbrev-commit',
118 '--pretty=oneline',
119 '--reverse',
120 '--date-order',
121 not_rev(self.base),
122 R_HEADS + self.name,
123 '--')
124 return self._commit_cache
125
126 @property
127 def date(self):
128 return self.project.bare_git.log(
129 '--pretty=format:%cd',
130 '-n', '1',
131 R_HEADS + self.name,
132 '--')
133
134 def UploadForReview(self):
135 self.project.UploadForReview(self.name)
136
137 @property
138 def tip_url(self):
139 me = self.project.GetBranch(self.name)
140 commit = self.project.bare_git.rev_parse(R_HEADS + self.name)
141 return 'http://%s/r/%s' % (me.remote.review, commit[0:12])
142
Shawn O. Pearce0758d2f2008-10-22 13:13:40 -0700143 @property
144 def owner_email(self):
145 return self.project.UserEmail
146
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700147
148class StatusColoring(Coloring):
149 def __init__(self, config):
150 Coloring.__init__(self, config, 'status')
151 self.project = self.printer('header', attr = 'bold')
152 self.branch = self.printer('header', attr = 'bold')
153 self.nobranch = self.printer('nobranch', fg = 'red')
154
155 self.added = self.printer('added', fg = 'green')
156 self.changed = self.printer('changed', fg = 'red')
157 self.untracked = self.printer('untracked', fg = 'red')
158
159
160class DiffColoring(Coloring):
161 def __init__(self, config):
162 Coloring.__init__(self, config, 'diff')
163 self.project = self.printer('header', attr = 'bold')
164
165
166class _CopyFile:
167 def __init__(self, src, dest):
168 self.src = src
169 self.dest = dest
170
171 def _Copy(self):
172 src = self.src
173 dest = self.dest
174 # copy file if it does not exist or is out of date
175 if not os.path.exists(dest) or not filecmp.cmp(src, dest):
176 try:
177 # remove existing file first, since it might be read-only
178 if os.path.exists(dest):
179 os.remove(dest)
180 shutil.copy(src, dest)
181 # make the file read-only
182 mode = os.stat(dest)[stat.ST_MODE]
183 mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
184 os.chmod(dest, mode)
185 except IOError:
186 print >>sys.stderr, \
187 'error: Cannot copy file %s to %s' \
188 % (src, dest)
189
190
191class Project(object):
192 def __init__(self,
193 manifest,
194 name,
195 remote,
196 gitdir,
197 worktree,
198 relpath,
199 revision):
200 self.manifest = manifest
201 self.name = name
202 self.remote = remote
203 self.gitdir = gitdir
204 self.worktree = worktree
205 self.relpath = relpath
206 self.revision = revision
207 self.snapshots = {}
208 self.extraRemotes = {}
209 self.copyfiles = []
210 self.config = GitConfig.ForRepository(
211 gitdir = self.gitdir,
212 defaults = self.manifest.globalConfig)
213
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800214 if self.worktree:
215 self.work_git = self._GitGetByExec(self, bare=False)
216 else:
217 self.work_git = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218 self.bare_git = self._GitGetByExec(self, bare=True)
219
220 @property
221 def Exists(self):
222 return os.path.isdir(self.gitdir)
223
224 @property
225 def CurrentBranch(self):
226 """Obtain the name of the currently checked out branch.
227 The branch name omits the 'refs/heads/' prefix.
228 None is returned if the project is on a detached HEAD.
229 """
230 try:
231 b = self.work_git.GetHead()
232 except GitError:
233 return None
234 if b.startswith(R_HEADS):
235 return b[len(R_HEADS):]
236 return None
237
238 def IsDirty(self, consider_untracked=True):
239 """Is the working directory modified in some way?
240 """
241 self.work_git.update_index('-q',
242 '--unmerged',
243 '--ignore-missing',
244 '--refresh')
245 if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
246 return True
247 if self.work_git.DiffZ('diff-files'):
248 return True
249 if consider_untracked and self.work_git.LsOthers():
250 return True
251 return False
252
253 _userident_name = None
254 _userident_email = None
255
256 @property
257 def UserName(self):
258 """Obtain the user's personal name.
259 """
260 if self._userident_name is None:
261 self._LoadUserIdentity()
262 return self._userident_name
263
264 @property
265 def UserEmail(self):
266 """Obtain the user's email address. This is very likely
267 to be their Gerrit login.
268 """
269 if self._userident_email is None:
270 self._LoadUserIdentity()
271 return self._userident_email
272
273 def _LoadUserIdentity(self):
274 u = self.bare_git.var('GIT_COMMITTER_IDENT')
275 m = re.compile("^(.*) <([^>]*)> ").match(u)
276 if m:
277 self._userident_name = m.group(1)
278 self._userident_email = m.group(2)
279 else:
280 self._userident_name = ''
281 self._userident_email = ''
282
283 def GetRemote(self, name):
284 """Get the configuration for a single remote.
285 """
286 return self.config.GetRemote(name)
287
288 def GetBranch(self, name):
289 """Get the configuration for a single branch.
290 """
291 return self.config.GetBranch(name)
292
293
294## Status Display ##
295
296 def PrintWorkTreeStatus(self):
297 """Prints the status of the repository to stdout.
298 """
299 if not os.path.isdir(self.worktree):
300 print ''
301 print 'project %s/' % self.relpath
302 print ' missing (run "repo sync")'
303 return
304
305 self.work_git.update_index('-q',
306 '--unmerged',
307 '--ignore-missing',
308 '--refresh')
309 di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
310 df = self.work_git.DiffZ('diff-files')
311 do = self.work_git.LsOthers()
312 if not di and not df and not do:
313 return
314
315 out = StatusColoring(self.config)
316 out.project('project %-40s', self.relpath + '/')
317
318 branch = self.CurrentBranch
319 if branch is None:
320 out.nobranch('(*** NO BRANCH ***)')
321 else:
322 out.branch('branch %s', branch)
323 out.nl()
324
325 paths = list()
326 paths.extend(di.keys())
327 paths.extend(df.keys())
328 paths.extend(do)
329
330 paths = list(set(paths))
331 paths.sort()
332
333 for p in paths:
334 try: i = di[p]
335 except KeyError: i = None
336
337 try: f = df[p]
338 except KeyError: f = None
339
340 if i: i_status = i.status.upper()
341 else: i_status = '-'
342
343 if f: f_status = f.status.lower()
344 else: f_status = '-'
345
346 if i and i.src_path:
347 line = ' %s%s\t%s => (%s%%)' % (i_status, f_status,
348 i.src_path, p, i.level)
349 else:
350 line = ' %s%s\t%s' % (i_status, f_status, p)
351
352 if i and not f:
353 out.added('%s', line)
354 elif (i and f) or (not i and f):
355 out.changed('%s', line)
356 elif not i and not f:
357 out.untracked('%s', line)
358 else:
359 out.write('%s', line)
360 out.nl()
361
362 def PrintWorkTreeDiff(self):
363 """Prints the status of the repository to stdout.
364 """
365 out = DiffColoring(self.config)
366 cmd = ['diff']
367 if out.is_on:
368 cmd.append('--color')
369 cmd.append(HEAD)
370 cmd.append('--')
371 p = GitCommand(self,
372 cmd,
373 capture_stdout = True,
374 capture_stderr = True)
375 has_diff = False
376 for line in p.process.stdout:
377 if not has_diff:
378 out.nl()
379 out.project('project %s/' % self.relpath)
380 out.nl()
381 has_diff = True
382 print line[:-1]
383 p.Wait()
384
385
386## Publish / Upload ##
387
388 def WasPublished(self, branch):
389 """Was the branch published (uploaded) for code review?
390 If so, returns the SHA-1 hash of the last published
391 state for the branch.
392 """
393 try:
394 return self.bare_git.rev_parse(R_PUB + branch)
395 except GitError:
396 return None
397
398 def CleanPublishedCache(self):
399 """Prunes any stale published refs.
400 """
401 heads = set()
402 canrm = {}
403 for name, id in self._allrefs.iteritems():
404 if name.startswith(R_HEADS):
405 heads.add(name)
406 elif name.startswith(R_PUB):
407 canrm[name] = id
408
409 for name, id in canrm.iteritems():
410 n = name[len(R_PUB):]
411 if R_HEADS + n not in heads:
412 self.bare_git.DeleteRef(name, id)
413
414 def GetUploadableBranches(self):
415 """List any branches which can be uploaded for review.
416 """
417 heads = {}
418 pubed = {}
419
420 for name, id in self._allrefs.iteritems():
421 if name.startswith(R_HEADS):
422 heads[name[len(R_HEADS):]] = id
423 elif name.startswith(R_PUB):
424 pubed[name[len(R_PUB):]] = id
425
426 ready = []
427 for branch, id in heads.iteritems():
428 if branch in pubed and pubed[branch] == id:
429 continue
430
431 branch = self.GetBranch(branch)
432 base = branch.LocalMerge
433 if branch.LocalMerge:
434 rb = ReviewableBranch(self, branch, base)
435 if rb.commits:
436 ready.append(rb)
437 return ready
438
439 def UploadForReview(self, branch=None):
440 """Uploads the named branch for code review.
441 """
442 if branch is None:
443 branch = self.CurrentBranch
444 if branch is None:
445 raise GitError('not currently on a branch')
446
447 branch = self.GetBranch(branch)
448 if not branch.LocalMerge:
449 raise GitError('branch %s does not track a remote' % branch.name)
450 if not branch.remote.review:
451 raise GitError('remote %s has no review url' % branch.remote.name)
452
453 dest_branch = branch.merge
454 if not dest_branch.startswith(R_HEADS):
455 dest_branch = R_HEADS + dest_branch
456
457 base_list = []
458 for name, id in self._allrefs.iteritems():
459 if branch.remote.WritesTo(name):
460 base_list.append(not_rev(name))
461 if not base_list:
462 raise GitError('no base refs, cannot upload %s' % branch.name)
463
464 print >>sys.stderr, ''
465 _info("Uploading %s to %s:", branch.name, self.name)
466 try:
467 UploadBundle(project = self,
468 server = branch.remote.review,
469 email = self.UserEmail,
470 dest_project = self.name,
471 dest_branch = dest_branch,
472 src_branch = R_HEADS + branch.name,
473 bases = base_list)
474 except proto_client.ClientLoginError:
475 raise UploadError('Login failure')
476 except urllib2.HTTPError, e:
477 raise UploadError('HTTP error %d' % e.code)
478
479 msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
480 self.bare_git.UpdateRef(R_PUB + branch.name,
481 R_HEADS + branch.name,
482 message = msg)
483
484
485## Sync ##
486
487 def Sync_NetworkHalf(self):
488 """Perform only the network IO portion of the sync process.
489 Local working directory/branch state is not affected.
490 """
491 if not self.Exists:
492 print >>sys.stderr
493 print >>sys.stderr, 'Initializing project %s ...' % self.name
494 self._InitGitDir()
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800495
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700496 self._InitRemote()
497 for r in self.extraRemotes.values():
498 if not self._RemoteFetch(r.name):
499 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700500 if not self._RemoteFetch():
501 return False
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800502
503 if self.worktree:
504 self._RepairAndroidImportErrors()
505 self._InitMRef()
506 else:
507 self._InitMirrorHead()
508 try:
509 os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
510 except OSError:
511 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700512 return True
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800513
514 def PostRepoUpgrade(self):
515 self._InitHooks()
516
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700517 def _CopyFiles(self):
518 for file in self.copyfiles:
519 file._Copy()
520
Shawn O. Pearce329c31d2008-10-24 09:17:25 -0700521 def _RepairAndroidImportErrors(self):
522 if self.name in ['platform/external/iptables',
523 'platform/external/libpcap',
524 'platform/external/tcpdump',
525 'platform/external/webkit',
526 'platform/system/wlan/ti']:
527 # I hate myself for doing this...
528 #
529 # In the initial Android 1.0 release these projects were
530 # shipped, some users got them, and then the history had
531 # to be rewritten to correct problems with their imports.
532 # The 'android-1.0' tag may still be pointing at the old
533 # history, so we need to drop the tag and fetch it again.
534 #
535 try:
536 remote = self.GetRemote(self.remote.name)
537 relname = remote.ToLocal(R_HEADS + 'release-1.0')
538 tagname = R_TAGS + 'android-1.0'
539 if self._revlist(not_rev(relname), tagname):
540 cmd = ['fetch', remote.name, '+%s:%s' % (tagname, tagname)]
541 GitCommand(self, cmd, bare = True).Wait()
542 except GitError:
543 pass
544
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700545 def Sync_LocalHalf(self):
546 """Perform only the local IO portion of the sync process.
547 Network access is not required.
548
549 Return:
550 True: the sync was successful
551 False: the sync requires user input
552 """
553 self._InitWorkTree()
554 self.CleanPublishedCache()
555
556 rem = self.GetRemote(self.remote.name)
557 rev = rem.ToLocal(self.revision)
558 branch = self.CurrentBranch
559
560 if branch is None:
561 # Currently on a detached HEAD. The user is assumed to
562 # not have any local modifications worth worrying about.
563 #
564 lost = self._revlist(not_rev(rev), HEAD)
565 if lost:
566 _info("[%s] Discarding %d commits", self.name, len(lost))
567 try:
568 self._Checkout(rev, quiet=True)
569 except GitError:
570 return False
571 self._CopyFiles()
572 return True
573
574 branch = self.GetBranch(branch)
575 merge = branch.LocalMerge
576
577 if not merge:
578 # The current branch has no tracking configuration.
579 # Jump off it to a deatched HEAD.
580 #
581 _info("[%s] Leaving %s"
582 " (does not track any upstream)",
583 self.name,
584 branch.name)
585 try:
586 self._Checkout(rev, quiet=True)
587 except GitError:
588 return False
589 self._CopyFiles()
590 return True
591
592 upstream_gain = self._revlist(not_rev(HEAD), rev)
593 pub = self.WasPublished(branch.name)
594 if pub:
595 not_merged = self._revlist(not_rev(rev), pub)
596 if not_merged:
597 if upstream_gain:
598 # The user has published this branch and some of those
599 # commits are not yet merged upstream. We do not want
600 # to rewrite the published commits so we punt.
601 #
602 _info("[%s] Branch %s is published,"
603 " but is now %d commits behind.",
604 self.name, branch.name, len(upstream_gain))
605 _info("[%s] Consider merging or rebasing the"
606 " unpublished commits.", self.name)
607 return True
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700608 elif upstream_gain:
Shawn O. Pearcea54c5272008-10-30 11:03:00 -0700609 # We can fast-forward safely.
610 #
611 try:
612 self._FastForward(rev)
613 except GitError:
614 return False
615 self._CopyFiles()
616 return True
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700617 else:
618 # Trivially no changes in the upstream.
619 #
620 return True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700621
622 if merge == rev:
623 try:
624 old_merge = self.bare_git.rev_parse('%s@{1}' % merge)
625 except GitError:
626 old_merge = merge
Shawn O. Pearce07346002008-10-21 07:09:27 -0700627 if old_merge == '0000000000000000000000000000000000000000' \
628 or old_merge == '':
629 old_merge = merge
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700630 else:
631 # The upstream switched on us. Time to cross our fingers
632 # and pray that the old upstream also wasn't in the habit
633 # of rebasing itself.
634 #
635 _info("[%s] Manifest switched from %s to %s",
636 self.name, merge, rev)
637 old_merge = merge
638
639 if rev == old_merge:
640 upstream_lost = []
641 else:
642 upstream_lost = self._revlist(not_rev(rev), old_merge)
643
644 if not upstream_lost and not upstream_gain:
645 # Trivially no changes caused by the upstream.
646 #
647 return True
648
649 if self.IsDirty(consider_untracked=False):
650 _warn('[%s] commit (or discard) uncommitted changes'
651 ' before sync', self.name)
652 return False
653
654 if upstream_lost:
655 # Upstream rebased. Not everything in HEAD
656 # may have been caused by the user.
657 #
658 _info("[%s] Discarding %d commits removed from upstream",
659 self.name, len(upstream_lost))
660
661 branch.remote = rem
662 branch.merge = self.revision
663 branch.Save()
664
665 my_changes = self._revlist(not_rev(old_merge), HEAD)
666 if my_changes:
667 try:
668 self._Rebase(upstream = old_merge, onto = rev)
669 except GitError:
670 return False
671 elif upstream_lost:
672 try:
673 self._ResetHard(rev)
674 except GitError:
675 return False
676 else:
677 try:
678 self._FastForward(rev)
679 except GitError:
680 return False
681
682 self._CopyFiles()
683 return True
684
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700685 def AddCopyFile(self, src, dest):
686 # dest should already be an absolute path, but src is project relative
687 # make src an absolute path
688 src = os.path.join(self.worktree, src)
689 self.copyfiles.append(_CopyFile(src, dest))
690
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700691 def DownloadPatchSet(self, change_id, patch_id):
692 """Download a single patch set of a single change to FETCH_HEAD.
693 """
694 remote = self.GetRemote(self.remote.name)
695
696 cmd = ['fetch', remote.name]
697 cmd.append('refs/changes/%2.2d/%d/%d' \
698 % (change_id % 100, change_id, patch_id))
699 cmd.extend(map(lambda x: str(x), remote.fetch))
700 if GitCommand(self, cmd, bare=True).Wait() != 0:
701 return None
702 return DownloadedChange(self,
703 remote.ToLocal(self.revision),
704 change_id,
705 patch_id,
706 self.bare_git.rev_parse('FETCH_HEAD'))
707
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700708
709## Branch Management ##
710
711 def StartBranch(self, name):
712 """Create a new branch off the manifest's revision.
713 """
714 branch = self.GetBranch(name)
715 branch.remote = self.GetRemote(self.remote.name)
716 branch.merge = self.revision
717
718 rev = branch.LocalMerge
719 cmd = ['checkout', '-b', branch.name, rev]
720 if GitCommand(self, cmd).Wait() == 0:
721 branch.Save()
722 else:
723 raise GitError('%s checkout %s ' % (self.name, rev))
724
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800725 def AbandonBranch(self, name):
726 """Destroy a local topic branch.
727 """
728 try:
729 tip_rev = self.bare_git.rev_parse(R_HEADS + name)
730 except GitError:
731 return
732
733 if self.CurrentBranch == name:
734 self._Checkout(
735 self.GetRemote(self.remote.name).ToLocal(self.revision),
736 quiet=True)
737
738 cmd = ['branch', '-D', name]
739 GitCommand(self, cmd, capture_stdout=True).Wait()
740
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700741 def PruneHeads(self):
742 """Prune any topic branches already merged into upstream.
743 """
744 cb = self.CurrentBranch
745 kill = []
746 for name in self._allrefs.keys():
747 if name.startswith(R_HEADS):
748 name = name[len(R_HEADS):]
749 if cb is None or name != cb:
750 kill.append(name)
751
752 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
753 if cb is not None \
754 and not self._revlist(HEAD + '...' + rev) \
755 and not self.IsDirty(consider_untracked = False):
756 self.work_git.DetachHead(HEAD)
757 kill.append(cb)
758
759 deleted = set()
760 if kill:
761 try:
762 old = self.bare_git.GetHead()
763 except GitError:
764 old = 'refs/heads/please_never_use_this_as_a_branch_name'
765
766 rm_re = re.compile(r"^Deleted branch (.*)\.$")
767 try:
768 self.bare_git.DetachHead(rev)
769
770 b = ['branch', '-d']
771 b.extend(kill)
772 b = GitCommand(self, b, bare=True,
773 capture_stdout=True,
774 capture_stderr=True)
775 b.Wait()
776 finally:
777 self.bare_git.SetHead(old)
778
779 for line in b.stdout.split("\n"):
780 m = rm_re.match(line)
781 if m:
782 deleted.add(m.group(1))
783
784 if deleted:
785 self.CleanPublishedCache()
786
787 if cb and cb not in kill:
788 kill.append(cb)
789 kill.sort()
790
791 kept = []
792 for branch in kill:
793 if branch not in deleted:
794 branch = self.GetBranch(branch)
795 base = branch.LocalMerge
796 if not base:
797 base = rev
798 kept.append(ReviewableBranch(self, branch, base))
799 return kept
800
801
802## Direct Git Commands ##
803
804 def _RemoteFetch(self, name=None):
805 if not name:
806 name = self.remote.name
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800807 cmd = ['fetch']
808 if not self.worktree:
809 cmd.append('--update-head-ok')
810 cmd.append(name)
811 return GitCommand(self, cmd, bare = True).Wait() == 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700812
813 def _Checkout(self, rev, quiet=False):
814 cmd = ['checkout']
815 if quiet:
816 cmd.append('-q')
817 cmd.append(rev)
818 cmd.append('--')
819 if GitCommand(self, cmd).Wait() != 0:
820 if self._allrefs:
821 raise GitError('%s checkout %s ' % (self.name, rev))
822
823 def _ResetHard(self, rev, quiet=True):
824 cmd = ['reset', '--hard']
825 if quiet:
826 cmd.append('-q')
827 cmd.append(rev)
828 if GitCommand(self, cmd).Wait() != 0:
829 raise GitError('%s reset --hard %s ' % (self.name, rev))
830
831 def _Rebase(self, upstream, onto = None):
832 cmd = ['rebase', '-i']
833 if onto is not None:
834 cmd.extend(['--onto', onto])
835 cmd.append(upstream)
836 if GitCommand(self, cmd, disable_editor=True).Wait() != 0:
837 raise GitError('%s rebase %s ' % (self.name, upstream))
838
839 def _FastForward(self, head):
840 cmd = ['merge', head]
841 if GitCommand(self, cmd).Wait() != 0:
842 raise GitError('%s merge %s ' % (self.name, head))
843
844 def _InitGitDir(self):
845 if not os.path.exists(self.gitdir):
846 os.makedirs(self.gitdir)
847 self.bare_git.init()
848 self.config.SetString('core.bare', None)
849
850 hooks = self._gitdir_path('hooks')
Shawn O. Pearcede646812008-10-29 14:38:12 -0700851 try:
852 to_rm = os.listdir(hooks)
853 except OSError:
854 to_rm = []
855 for old_hook in to_rm:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700856 os.remove(os.path.join(hooks, old_hook))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800857 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700858
859 m = self.manifest.manifestProject.config
860 for key in ['user.name', 'user.email']:
861 if m.Has(key, include_defaults = False):
862 self.config.SetString(key, m.GetString(key))
863
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800864 def _InitHooks(self):
865 hooks = self._gitdir_path('hooks')
866 if not os.path.exists(hooks):
867 os.makedirs(hooks)
868 for stock_hook in repo_hooks():
869 dst = os.path.join(hooks, os.path.basename(stock_hook))
870 try:
871 os.symlink(relpath(stock_hook, dst), dst)
872 except OSError, e:
873 if e.errno == errno.EEXIST:
874 pass
875 elif e.errno == errno.EPERM:
876 raise GitError('filesystem must support symlinks')
877 else:
878 raise
879
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700880 def _InitRemote(self):
881 if self.remote.fetchUrl:
882 remote = self.GetRemote(self.remote.name)
883
884 url = self.remote.fetchUrl
885 while url.endswith('/'):
886 url = url[:-1]
887 url += '/%s.git' % self.name
888 remote.url = url
889 remote.review = self.remote.reviewUrl
890
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800891 if self.worktree:
892 remote.ResetFetch(mirror=False)
893 else:
894 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700895 remote.Save()
896
897 for r in self.extraRemotes.values():
898 remote = self.GetRemote(r.name)
899 remote.url = r.fetchUrl
900 remote.review = r.reviewUrl
901 remote.ResetFetch()
902 remote.Save()
903
904 def _InitMRef(self):
905 if self.manifest.branch:
906 msg = 'manifest set to %s' % self.revision
907 ref = R_M + self.manifest.branch
908
909 if IsId(self.revision):
910 dst = self.revision + '^0',
911 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
912 else:
913 remote = self.GetRemote(self.remote.name)
914 dst = remote.ToLocal(self.revision)
915 self.bare_git.symbolic_ref('-m', msg, ref, dst)
916
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800917 def _InitMirrorHead(self):
918 dst = self.GetRemote(self.remote.name).ToLocal(self.revision)
919 msg = 'manifest set to %s' % self.revision
920 self.bare_git.SetHead(dst, message=msg)
921
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700922 def _InitWorkTree(self):
923 dotgit = os.path.join(self.worktree, '.git')
924 if not os.path.exists(dotgit):
925 os.makedirs(dotgit)
926
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700927 for name in ['config',
928 'description',
929 'hooks',
930 'info',
931 'logs',
932 'objects',
933 'packed-refs',
934 'refs',
935 'rr-cache',
936 'svn']:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -0800937 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800938 src = os.path.join(self.gitdir, name)
939 dst = os.path.join(dotgit, name)
940 os.symlink(relpath(src, dst), dst)
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -0800941 except OSError, e:
942 if e.errno == errno.EPERM:
943 raise GitError('filesystem must support symlinks')
944 else:
945 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700946
947 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
948 rev = self.bare_git.rev_parse('%s^0' % rev)
949
950 f = open(os.path.join(dotgit, HEAD), 'wb')
951 f.write("%s\n" % rev)
952 f.close()
953
954 cmd = ['read-tree', '--reset', '-u']
955 cmd.append('-v')
956 cmd.append('HEAD')
957 if GitCommand(self, cmd).Wait() != 0:
958 raise GitError("cannot initialize work tree")
959
960 def _gitdir_path(self, path):
961 return os.path.join(self.gitdir, path)
962
963 def _revlist(self, *args):
964 cmd = []
965 cmd.extend(args)
966 cmd.append('--')
967 return self.work_git.rev_list(*args)
968
969 @property
970 def _allrefs(self):
971 return self.bare_git.ListRefs()
972
973 class _GitGetByExec(object):
974 def __init__(self, project, bare):
975 self._project = project
976 self._bare = bare
977
978 def ListRefs(self, *args):
979 cmdv = ['for-each-ref', '--format=%(objectname) %(refname)']
980 cmdv.extend(args)
981 p = GitCommand(self._project,
982 cmdv,
983 bare = self._bare,
984 capture_stdout = True,
985 capture_stderr = True)
986 r = {}
987 for line in p.process.stdout:
988 id, name = line[:-1].split(' ', 2)
989 r[name] = id
990 if p.Wait() != 0:
991 raise GitError('%s for-each-ref %s: %s' % (
992 self._project.name,
993 str(args),
994 p.stderr))
995 return r
996
997 def LsOthers(self):
998 p = GitCommand(self._project,
999 ['ls-files',
1000 '-z',
1001 '--others',
1002 '--exclude-standard'],
1003 bare = False,
1004 capture_stdout = True,
1005 capture_stderr = True)
1006 if p.Wait() == 0:
1007 out = p.stdout
1008 if out:
1009 return out[:-1].split("\0")
1010 return []
1011
1012 def DiffZ(self, name, *args):
1013 cmd = [name]
1014 cmd.append('-z')
1015 cmd.extend(args)
1016 p = GitCommand(self._project,
1017 cmd,
1018 bare = False,
1019 capture_stdout = True,
1020 capture_stderr = True)
1021 try:
1022 out = p.process.stdout.read()
1023 r = {}
1024 if out:
1025 out = iter(out[:-1].split('\0'))
1026 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07001027 try:
1028 info = out.next()
1029 path = out.next()
1030 except StopIteration:
1031 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001032
1033 class _Info(object):
1034 def __init__(self, path, omode, nmode, oid, nid, state):
1035 self.path = path
1036 self.src_path = None
1037 self.old_mode = omode
1038 self.new_mode = nmode
1039 self.old_id = oid
1040 self.new_id = nid
1041
1042 if len(state) == 1:
1043 self.status = state
1044 self.level = None
1045 else:
1046 self.status = state[:1]
1047 self.level = state[1:]
1048 while self.level.startswith('0'):
1049 self.level = self.level[1:]
1050
1051 info = info[1:].split(' ')
1052 info =_Info(path, *info)
1053 if info.status in ('R', 'C'):
1054 info.src_path = info.path
1055 info.path = out.next()
1056 r[info.path] = info
1057 return r
1058 finally:
1059 p.Wait()
1060
1061 def GetHead(self):
1062 return self.symbolic_ref(HEAD)
1063
1064 def SetHead(self, ref, message=None):
1065 cmdv = []
1066 if message is not None:
1067 cmdv.extend(['-m', message])
1068 cmdv.append(HEAD)
1069 cmdv.append(ref)
1070 self.symbolic_ref(*cmdv)
1071
1072 def DetachHead(self, new, message=None):
1073 cmdv = ['--no-deref']
1074 if message is not None:
1075 cmdv.extend(['-m', message])
1076 cmdv.append(HEAD)
1077 cmdv.append(new)
1078 self.update_ref(*cmdv)
1079
1080 def UpdateRef(self, name, new, old=None,
1081 message=None,
1082 detach=False):
1083 cmdv = []
1084 if message is not None:
1085 cmdv.extend(['-m', message])
1086 if detach:
1087 cmdv.append('--no-deref')
1088 cmdv.append(name)
1089 cmdv.append(new)
1090 if old is not None:
1091 cmdv.append(old)
1092 self.update_ref(*cmdv)
1093
1094 def DeleteRef(self, name, old=None):
1095 if not old:
1096 old = self.rev_parse(name)
1097 self.update_ref('-d', name, old)
1098
1099 def rev_list(self, *args):
1100 cmdv = ['rev-list']
1101 cmdv.extend(args)
1102 p = GitCommand(self._project,
1103 cmdv,
1104 bare = self._bare,
1105 capture_stdout = True,
1106 capture_stderr = True)
1107 r = []
1108 for line in p.process.stdout:
1109 r.append(line[:-1])
1110 if p.Wait() != 0:
1111 raise GitError('%s rev-list %s: %s' % (
1112 self._project.name,
1113 str(args),
1114 p.stderr))
1115 return r
1116
1117 def __getattr__(self, name):
1118 name = name.replace('_', '-')
1119 def runner(*args):
1120 cmdv = [name]
1121 cmdv.extend(args)
1122 p = GitCommand(self._project,
1123 cmdv,
1124 bare = self._bare,
1125 capture_stdout = True,
1126 capture_stderr = True)
1127 if p.Wait() != 0:
1128 raise GitError('%s %s: %s' % (
1129 self._project.name,
1130 name,
1131 p.stderr))
1132 r = p.stdout
1133 if r.endswith('\n') and r.index('\n') == len(r) - 1:
1134 return r[:-1]
1135 return r
1136 return runner
1137
1138
1139class MetaProject(Project):
1140 """A special project housed under .repo.
1141 """
1142 def __init__(self, manifest, name, gitdir, worktree):
1143 repodir = manifest.repodir
1144 Project.__init__(self,
1145 manifest = manifest,
1146 name = name,
1147 gitdir = gitdir,
1148 worktree = worktree,
1149 remote = Remote('origin'),
1150 relpath = '.repo/%s' % name,
1151 revision = 'refs/heads/master')
1152
1153 def PreSync(self):
1154 if self.Exists:
1155 cb = self.CurrentBranch
1156 if cb:
1157 base = self.GetBranch(cb).merge
1158 if base:
1159 self.revision = base
1160
1161 @property
1162 def HasChanges(self):
1163 """Has the remote received new commits not yet checked out?
1164 """
1165 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
1166 if self._revlist(not_rev(HEAD), rev):
1167 return True
1168 return False