blob: 46d23f6288c62c641f384537a3a6c2b5d7498f4a [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')
778 for old_hook in os.listdir(hooks):
779 os.remove(os.path.join(hooks, old_hook))
780
781 # TODO(sop) install custom repo hooks
782
783 m = self.manifest.manifestProject.config
784 for key in ['user.name', 'user.email']:
785 if m.Has(key, include_defaults = False):
786 self.config.SetString(key, m.GetString(key))
787
788 def _InitRemote(self):
789 if self.remote.fetchUrl:
790 remote = self.GetRemote(self.remote.name)
791
792 url = self.remote.fetchUrl
793 while url.endswith('/'):
794 url = url[:-1]
795 url += '/%s.git' % self.name
796 remote.url = url
797 remote.review = self.remote.reviewUrl
798
799 remote.ResetFetch()
800 remote.Save()
801
802 for r in self.extraRemotes.values():
803 remote = self.GetRemote(r.name)
804 remote.url = r.fetchUrl
805 remote.review = r.reviewUrl
806 remote.ResetFetch()
807 remote.Save()
808
809 def _InitMRef(self):
810 if self.manifest.branch:
811 msg = 'manifest set to %s' % self.revision
812 ref = R_M + self.manifest.branch
813
814 if IsId(self.revision):
815 dst = self.revision + '^0',
816 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
817 else:
818 remote = self.GetRemote(self.remote.name)
819 dst = remote.ToLocal(self.revision)
820 self.bare_git.symbolic_ref('-m', msg, ref, dst)
821
822 def _InitWorkTree(self):
823 dotgit = os.path.join(self.worktree, '.git')
824 if not os.path.exists(dotgit):
825 os.makedirs(dotgit)
826
827 topdir = os.path.commonprefix([self.gitdir, dotgit])
828 if topdir.endswith('/'):
829 topdir = topdir[:-1]
830 else:
831 topdir = os.path.dirname(topdir)
832
833 tmpdir = dotgit
834 relgit = ''
835 while topdir != tmpdir:
836 relgit += '../'
837 tmpdir = os.path.dirname(tmpdir)
838 relgit += self.gitdir[len(topdir) + 1:]
839
840 for name in ['config',
841 'description',
842 'hooks',
843 'info',
844 'logs',
845 'objects',
846 'packed-refs',
847 'refs',
848 'rr-cache',
849 'svn']:
850 os.symlink(os.path.join(relgit, name),
851 os.path.join(dotgit, name))
852
853 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
854 rev = self.bare_git.rev_parse('%s^0' % rev)
855
856 f = open(os.path.join(dotgit, HEAD), 'wb')
857 f.write("%s\n" % rev)
858 f.close()
859
860 cmd = ['read-tree', '--reset', '-u']
861 cmd.append('-v')
862 cmd.append('HEAD')
863 if GitCommand(self, cmd).Wait() != 0:
864 raise GitError("cannot initialize work tree")
865
866 def _gitdir_path(self, path):
867 return os.path.join(self.gitdir, path)
868
869 def _revlist(self, *args):
870 cmd = []
871 cmd.extend(args)
872 cmd.append('--')
873 return self.work_git.rev_list(*args)
874
875 @property
876 def _allrefs(self):
877 return self.bare_git.ListRefs()
878
879 class _GitGetByExec(object):
880 def __init__(self, project, bare):
881 self._project = project
882 self._bare = bare
883
884 def ListRefs(self, *args):
885 cmdv = ['for-each-ref', '--format=%(objectname) %(refname)']
886 cmdv.extend(args)
887 p = GitCommand(self._project,
888 cmdv,
889 bare = self._bare,
890 capture_stdout = True,
891 capture_stderr = True)
892 r = {}
893 for line in p.process.stdout:
894 id, name = line[:-1].split(' ', 2)
895 r[name] = id
896 if p.Wait() != 0:
897 raise GitError('%s for-each-ref %s: %s' % (
898 self._project.name,
899 str(args),
900 p.stderr))
901 return r
902
903 def LsOthers(self):
904 p = GitCommand(self._project,
905 ['ls-files',
906 '-z',
907 '--others',
908 '--exclude-standard'],
909 bare = False,
910 capture_stdout = True,
911 capture_stderr = True)
912 if p.Wait() == 0:
913 out = p.stdout
914 if out:
915 return out[:-1].split("\0")
916 return []
917
918 def DiffZ(self, name, *args):
919 cmd = [name]
920 cmd.append('-z')
921 cmd.extend(args)
922 p = GitCommand(self._project,
923 cmd,
924 bare = False,
925 capture_stdout = True,
926 capture_stderr = True)
927 try:
928 out = p.process.stdout.read()
929 r = {}
930 if out:
931 out = iter(out[:-1].split('\0'))
932 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -0700933 try:
934 info = out.next()
935 path = out.next()
936 except StopIteration:
937 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700938
939 class _Info(object):
940 def __init__(self, path, omode, nmode, oid, nid, state):
941 self.path = path
942 self.src_path = None
943 self.old_mode = omode
944 self.new_mode = nmode
945 self.old_id = oid
946 self.new_id = nid
947
948 if len(state) == 1:
949 self.status = state
950 self.level = None
951 else:
952 self.status = state[:1]
953 self.level = state[1:]
954 while self.level.startswith('0'):
955 self.level = self.level[1:]
956
957 info = info[1:].split(' ')
958 info =_Info(path, *info)
959 if info.status in ('R', 'C'):
960 info.src_path = info.path
961 info.path = out.next()
962 r[info.path] = info
963 return r
964 finally:
965 p.Wait()
966
967 def GetHead(self):
968 return self.symbolic_ref(HEAD)
969
970 def SetHead(self, ref, message=None):
971 cmdv = []
972 if message is not None:
973 cmdv.extend(['-m', message])
974 cmdv.append(HEAD)
975 cmdv.append(ref)
976 self.symbolic_ref(*cmdv)
977
978 def DetachHead(self, new, message=None):
979 cmdv = ['--no-deref']
980 if message is not None:
981 cmdv.extend(['-m', message])
982 cmdv.append(HEAD)
983 cmdv.append(new)
984 self.update_ref(*cmdv)
985
986 def UpdateRef(self, name, new, old=None,
987 message=None,
988 detach=False):
989 cmdv = []
990 if message is not None:
991 cmdv.extend(['-m', message])
992 if detach:
993 cmdv.append('--no-deref')
994 cmdv.append(name)
995 cmdv.append(new)
996 if old is not None:
997 cmdv.append(old)
998 self.update_ref(*cmdv)
999
1000 def DeleteRef(self, name, old=None):
1001 if not old:
1002 old = self.rev_parse(name)
1003 self.update_ref('-d', name, old)
1004
1005 def rev_list(self, *args):
1006 cmdv = ['rev-list']
1007 cmdv.extend(args)
1008 p = GitCommand(self._project,
1009 cmdv,
1010 bare = self._bare,
1011 capture_stdout = True,
1012 capture_stderr = True)
1013 r = []
1014 for line in p.process.stdout:
1015 r.append(line[:-1])
1016 if p.Wait() != 0:
1017 raise GitError('%s rev-list %s: %s' % (
1018 self._project.name,
1019 str(args),
1020 p.stderr))
1021 return r
1022
1023 def __getattr__(self, name):
1024 name = name.replace('_', '-')
1025 def runner(*args):
1026 cmdv = [name]
1027 cmdv.extend(args)
1028 p = GitCommand(self._project,
1029 cmdv,
1030 bare = self._bare,
1031 capture_stdout = True,
1032 capture_stderr = True)
1033 if p.Wait() != 0:
1034 raise GitError('%s %s: %s' % (
1035 self._project.name,
1036 name,
1037 p.stderr))
1038 r = p.stdout
1039 if r.endswith('\n') and r.index('\n') == len(r) - 1:
1040 return r[:-1]
1041 return r
1042 return runner
1043
1044
1045class MetaProject(Project):
1046 """A special project housed under .repo.
1047 """
1048 def __init__(self, manifest, name, gitdir, worktree):
1049 repodir = manifest.repodir
1050 Project.__init__(self,
1051 manifest = manifest,
1052 name = name,
1053 gitdir = gitdir,
1054 worktree = worktree,
1055 remote = Remote('origin'),
1056 relpath = '.repo/%s' % name,
1057 revision = 'refs/heads/master')
1058
1059 def PreSync(self):
1060 if self.Exists:
1061 cb = self.CurrentBranch
1062 if cb:
1063 base = self.GetBranch(cb).merge
1064 if base:
1065 self.revision = base
1066
1067 @property
1068 def HasChanges(self):
1069 """Has the remote received new commits not yet checked out?
1070 """
1071 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
1072 if self._revlist(not_rev(HEAD), rev):
1073 return True
1074 return False