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