blob: 1e25c2c94e2fe7bbb40a10bbf09b42f3144a5f8e [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
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800431 rb = self.GetUploadableBranch(branch)
432 if rb:
433 ready.append(rb)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700434 return ready
435
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800436 def GetUploadableBranch(self, branch_name):
437 """Get a single uploadable branch, or None.
438 """
439 branch = self.GetBranch(branch_name)
440 base = branch.LocalMerge
441 if branch.LocalMerge:
442 rb = ReviewableBranch(self, branch, base)
443 if rb.commits:
444 return rb
445 return None
446
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700447 def UploadForReview(self, branch=None):
448 """Uploads the named branch for code review.
449 """
450 if branch is None:
451 branch = self.CurrentBranch
452 if branch is None:
453 raise GitError('not currently on a branch')
454
455 branch = self.GetBranch(branch)
456 if not branch.LocalMerge:
457 raise GitError('branch %s does not track a remote' % branch.name)
458 if not branch.remote.review:
459 raise GitError('remote %s has no review url' % branch.remote.name)
460
461 dest_branch = branch.merge
462 if not dest_branch.startswith(R_HEADS):
463 dest_branch = R_HEADS + dest_branch
464
465 base_list = []
466 for name, id in self._allrefs.iteritems():
467 if branch.remote.WritesTo(name):
468 base_list.append(not_rev(name))
469 if not base_list:
470 raise GitError('no base refs, cannot upload %s' % branch.name)
471
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800472 if not branch.remote.projectname:
473 branch.remote.projectname = self.name
474 branch.remote.Save()
475
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700476 print >>sys.stderr, ''
477 _info("Uploading %s to %s:", branch.name, self.name)
478 try:
479 UploadBundle(project = self,
480 server = branch.remote.review,
481 email = self.UserEmail,
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800482 dest_project = branch.remote.projectname,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700483 dest_branch = dest_branch,
484 src_branch = R_HEADS + branch.name,
485 bases = base_list)
486 except proto_client.ClientLoginError:
487 raise UploadError('Login failure')
488 except urllib2.HTTPError, e:
489 raise UploadError('HTTP error %d' % e.code)
490
491 msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
492 self.bare_git.UpdateRef(R_PUB + branch.name,
493 R_HEADS + branch.name,
494 message = msg)
495
496
497## Sync ##
498
499 def Sync_NetworkHalf(self):
500 """Perform only the network IO portion of the sync process.
501 Local working directory/branch state is not affected.
502 """
503 if not self.Exists:
504 print >>sys.stderr
505 print >>sys.stderr, 'Initializing project %s ...' % self.name
506 self._InitGitDir()
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800507
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700508 self._InitRemote()
509 for r in self.extraRemotes.values():
510 if not self._RemoteFetch(r.name):
511 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700512 if not self._RemoteFetch():
513 return False
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800514
515 if self.worktree:
516 self._RepairAndroidImportErrors()
517 self._InitMRef()
518 else:
519 self._InitMirrorHead()
520 try:
521 os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
522 except OSError:
523 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700524 return True
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800525
526 def PostRepoUpgrade(self):
527 self._InitHooks()
528
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700529 def _CopyFiles(self):
530 for file in self.copyfiles:
531 file._Copy()
532
Shawn O. Pearce329c31d2008-10-24 09:17:25 -0700533 def _RepairAndroidImportErrors(self):
534 if self.name in ['platform/external/iptables',
535 'platform/external/libpcap',
536 'platform/external/tcpdump',
537 'platform/external/webkit',
538 'platform/system/wlan/ti']:
539 # I hate myself for doing this...
540 #
541 # In the initial Android 1.0 release these projects were
542 # shipped, some users got them, and then the history had
543 # to be rewritten to correct problems with their imports.
544 # The 'android-1.0' tag may still be pointing at the old
545 # history, so we need to drop the tag and fetch it again.
546 #
547 try:
548 remote = self.GetRemote(self.remote.name)
549 relname = remote.ToLocal(R_HEADS + 'release-1.0')
550 tagname = R_TAGS + 'android-1.0'
551 if self._revlist(not_rev(relname), tagname):
552 cmd = ['fetch', remote.name, '+%s:%s' % (tagname, tagname)]
553 GitCommand(self, cmd, bare = True).Wait()
554 except GitError:
555 pass
556
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700557 def Sync_LocalHalf(self):
558 """Perform only the local IO portion of the sync process.
559 Network access is not required.
560
561 Return:
562 True: the sync was successful
563 False: the sync requires user input
564 """
565 self._InitWorkTree()
566 self.CleanPublishedCache()
567
568 rem = self.GetRemote(self.remote.name)
569 rev = rem.ToLocal(self.revision)
570 branch = self.CurrentBranch
571
572 if branch is None:
573 # Currently on a detached HEAD. The user is assumed to
574 # not have any local modifications worth worrying about.
575 #
576 lost = self._revlist(not_rev(rev), HEAD)
577 if lost:
578 _info("[%s] Discarding %d commits", self.name, len(lost))
579 try:
580 self._Checkout(rev, quiet=True)
581 except GitError:
582 return False
583 self._CopyFiles()
584 return True
585
586 branch = self.GetBranch(branch)
587 merge = branch.LocalMerge
588
589 if not merge:
590 # The current branch has no tracking configuration.
591 # Jump off it to a deatched HEAD.
592 #
593 _info("[%s] Leaving %s"
594 " (does not track any upstream)",
595 self.name,
596 branch.name)
597 try:
598 self._Checkout(rev, quiet=True)
599 except GitError:
600 return False
601 self._CopyFiles()
602 return True
603
604 upstream_gain = self._revlist(not_rev(HEAD), rev)
605 pub = self.WasPublished(branch.name)
606 if pub:
607 not_merged = self._revlist(not_rev(rev), pub)
608 if not_merged:
609 if upstream_gain:
610 # The user has published this branch and some of those
611 # commits are not yet merged upstream. We do not want
612 # to rewrite the published commits so we punt.
613 #
614 _info("[%s] Branch %s is published,"
615 " but is now %d commits behind.",
616 self.name, branch.name, len(upstream_gain))
617 _info("[%s] Consider merging or rebasing the"
618 " unpublished commits.", self.name)
619 return True
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700620 elif upstream_gain:
Shawn O. Pearcea54c5272008-10-30 11:03:00 -0700621 # We can fast-forward safely.
622 #
623 try:
624 self._FastForward(rev)
625 except GitError:
626 return False
627 self._CopyFiles()
628 return True
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700629 else:
630 # Trivially no changes in the upstream.
631 #
632 return True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700633
634 if merge == rev:
635 try:
636 old_merge = self.bare_git.rev_parse('%s@{1}' % merge)
637 except GitError:
638 old_merge = merge
Shawn O. Pearce07346002008-10-21 07:09:27 -0700639 if old_merge == '0000000000000000000000000000000000000000' \
640 or old_merge == '':
641 old_merge = merge
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700642 else:
643 # The upstream switched on us. Time to cross our fingers
644 # and pray that the old upstream also wasn't in the habit
645 # of rebasing itself.
646 #
647 _info("[%s] Manifest switched from %s to %s",
648 self.name, merge, rev)
649 old_merge = merge
650
651 if rev == old_merge:
652 upstream_lost = []
653 else:
654 upstream_lost = self._revlist(not_rev(rev), old_merge)
655
656 if not upstream_lost and not upstream_gain:
657 # Trivially no changes caused by the upstream.
658 #
659 return True
660
661 if self.IsDirty(consider_untracked=False):
662 _warn('[%s] commit (or discard) uncommitted changes'
663 ' before sync', self.name)
664 return False
665
666 if upstream_lost:
667 # Upstream rebased. Not everything in HEAD
668 # may have been caused by the user.
669 #
670 _info("[%s] Discarding %d commits removed from upstream",
671 self.name, len(upstream_lost))
672
673 branch.remote = rem
674 branch.merge = self.revision
675 branch.Save()
676
677 my_changes = self._revlist(not_rev(old_merge), HEAD)
678 if my_changes:
679 try:
680 self._Rebase(upstream = old_merge, onto = rev)
681 except GitError:
682 return False
683 elif upstream_lost:
684 try:
685 self._ResetHard(rev)
686 except GitError:
687 return False
688 else:
689 try:
690 self._FastForward(rev)
691 except GitError:
692 return False
693
694 self._CopyFiles()
695 return True
696
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700697 def AddCopyFile(self, src, dest):
698 # dest should already be an absolute path, but src is project relative
699 # make src an absolute path
700 src = os.path.join(self.worktree, src)
701 self.copyfiles.append(_CopyFile(src, dest))
702
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700703 def DownloadPatchSet(self, change_id, patch_id):
704 """Download a single patch set of a single change to FETCH_HEAD.
705 """
706 remote = self.GetRemote(self.remote.name)
707
708 cmd = ['fetch', remote.name]
709 cmd.append('refs/changes/%2.2d/%d/%d' \
710 % (change_id % 100, change_id, patch_id))
711 cmd.extend(map(lambda x: str(x), remote.fetch))
712 if GitCommand(self, cmd, bare=True).Wait() != 0:
713 return None
714 return DownloadedChange(self,
715 remote.ToLocal(self.revision),
716 change_id,
717 patch_id,
718 self.bare_git.rev_parse('FETCH_HEAD'))
719
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700720
721## Branch Management ##
722
723 def StartBranch(self, name):
724 """Create a new branch off the manifest's revision.
725 """
726 branch = self.GetBranch(name)
727 branch.remote = self.GetRemote(self.remote.name)
728 branch.merge = self.revision
729
730 rev = branch.LocalMerge
731 cmd = ['checkout', '-b', branch.name, rev]
732 if GitCommand(self, cmd).Wait() == 0:
733 branch.Save()
734 else:
735 raise GitError('%s checkout %s ' % (self.name, rev))
736
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800737 def AbandonBranch(self, name):
738 """Destroy a local topic branch.
739 """
740 try:
741 tip_rev = self.bare_git.rev_parse(R_HEADS + name)
742 except GitError:
743 return
744
745 if self.CurrentBranch == name:
746 self._Checkout(
747 self.GetRemote(self.remote.name).ToLocal(self.revision),
748 quiet=True)
749
750 cmd = ['branch', '-D', name]
751 GitCommand(self, cmd, capture_stdout=True).Wait()
752
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700753 def PruneHeads(self):
754 """Prune any topic branches already merged into upstream.
755 """
756 cb = self.CurrentBranch
757 kill = []
758 for name in self._allrefs.keys():
759 if name.startswith(R_HEADS):
760 name = name[len(R_HEADS):]
761 if cb is None or name != cb:
762 kill.append(name)
763
764 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
765 if cb is not None \
766 and not self._revlist(HEAD + '...' + rev) \
767 and not self.IsDirty(consider_untracked = False):
768 self.work_git.DetachHead(HEAD)
769 kill.append(cb)
770
771 deleted = set()
772 if kill:
773 try:
774 old = self.bare_git.GetHead()
775 except GitError:
776 old = 'refs/heads/please_never_use_this_as_a_branch_name'
777
778 rm_re = re.compile(r"^Deleted branch (.*)\.$")
779 try:
780 self.bare_git.DetachHead(rev)
781
782 b = ['branch', '-d']
783 b.extend(kill)
784 b = GitCommand(self, b, bare=True,
785 capture_stdout=True,
786 capture_stderr=True)
787 b.Wait()
788 finally:
789 self.bare_git.SetHead(old)
790
791 for line in b.stdout.split("\n"):
792 m = rm_re.match(line)
793 if m:
794 deleted.add(m.group(1))
795
796 if deleted:
797 self.CleanPublishedCache()
798
799 if cb and cb not in kill:
800 kill.append(cb)
801 kill.sort()
802
803 kept = []
804 for branch in kill:
805 if branch not in deleted:
806 branch = self.GetBranch(branch)
807 base = branch.LocalMerge
808 if not base:
809 base = rev
810 kept.append(ReviewableBranch(self, branch, base))
811 return kept
812
813
814## Direct Git Commands ##
815
816 def _RemoteFetch(self, name=None):
817 if not name:
818 name = self.remote.name
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800819 cmd = ['fetch']
820 if not self.worktree:
821 cmd.append('--update-head-ok')
822 cmd.append(name)
823 return GitCommand(self, cmd, bare = True).Wait() == 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700824
825 def _Checkout(self, rev, quiet=False):
826 cmd = ['checkout']
827 if quiet:
828 cmd.append('-q')
829 cmd.append(rev)
830 cmd.append('--')
831 if GitCommand(self, cmd).Wait() != 0:
832 if self._allrefs:
833 raise GitError('%s checkout %s ' % (self.name, rev))
834
835 def _ResetHard(self, rev, quiet=True):
836 cmd = ['reset', '--hard']
837 if quiet:
838 cmd.append('-q')
839 cmd.append(rev)
840 if GitCommand(self, cmd).Wait() != 0:
841 raise GitError('%s reset --hard %s ' % (self.name, rev))
842
843 def _Rebase(self, upstream, onto = None):
844 cmd = ['rebase', '-i']
845 if onto is not None:
846 cmd.extend(['--onto', onto])
847 cmd.append(upstream)
848 if GitCommand(self, cmd, disable_editor=True).Wait() != 0:
849 raise GitError('%s rebase %s ' % (self.name, upstream))
850
851 def _FastForward(self, head):
852 cmd = ['merge', head]
853 if GitCommand(self, cmd).Wait() != 0:
854 raise GitError('%s merge %s ' % (self.name, head))
855
856 def _InitGitDir(self):
857 if not os.path.exists(self.gitdir):
858 os.makedirs(self.gitdir)
859 self.bare_git.init()
860 self.config.SetString('core.bare', None)
861
862 hooks = self._gitdir_path('hooks')
Shawn O. Pearcede646812008-10-29 14:38:12 -0700863 try:
864 to_rm = os.listdir(hooks)
865 except OSError:
866 to_rm = []
867 for old_hook in to_rm:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700868 os.remove(os.path.join(hooks, old_hook))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800869 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700870
871 m = self.manifest.manifestProject.config
872 for key in ['user.name', 'user.email']:
873 if m.Has(key, include_defaults = False):
874 self.config.SetString(key, m.GetString(key))
875
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800876 def _InitHooks(self):
877 hooks = self._gitdir_path('hooks')
878 if not os.path.exists(hooks):
879 os.makedirs(hooks)
880 for stock_hook in repo_hooks():
881 dst = os.path.join(hooks, os.path.basename(stock_hook))
882 try:
883 os.symlink(relpath(stock_hook, dst), dst)
884 except OSError, e:
885 if e.errno == errno.EEXIST:
886 pass
887 elif e.errno == errno.EPERM:
888 raise GitError('filesystem must support symlinks')
889 else:
890 raise
891
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700892 def _InitRemote(self):
893 if self.remote.fetchUrl:
894 remote = self.GetRemote(self.remote.name)
895
896 url = self.remote.fetchUrl
897 while url.endswith('/'):
898 url = url[:-1]
899 url += '/%s.git' % self.name
900 remote.url = url
901 remote.review = self.remote.reviewUrl
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800902 if remote.projectname is None:
903 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700904
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800905 if self.worktree:
906 remote.ResetFetch(mirror=False)
907 else:
908 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700909 remote.Save()
910
911 for r in self.extraRemotes.values():
912 remote = self.GetRemote(r.name)
913 remote.url = r.fetchUrl
914 remote.review = r.reviewUrl
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800915 if r.projectName:
916 remote.projectname = r.projectName
917 elif remote.projectname is None:
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800918 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700919 remote.ResetFetch()
920 remote.Save()
921
922 def _InitMRef(self):
923 if self.manifest.branch:
924 msg = 'manifest set to %s' % self.revision
925 ref = R_M + self.manifest.branch
926
927 if IsId(self.revision):
928 dst = self.revision + '^0',
929 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
930 else:
931 remote = self.GetRemote(self.remote.name)
932 dst = remote.ToLocal(self.revision)
933 self.bare_git.symbolic_ref('-m', msg, ref, dst)
934
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800935 def _InitMirrorHead(self):
936 dst = self.GetRemote(self.remote.name).ToLocal(self.revision)
937 msg = 'manifest set to %s' % self.revision
938 self.bare_git.SetHead(dst, message=msg)
939
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700940 def _InitWorkTree(self):
941 dotgit = os.path.join(self.worktree, '.git')
942 if not os.path.exists(dotgit):
943 os.makedirs(dotgit)
944
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700945 for name in ['config',
946 'description',
947 'hooks',
948 'info',
949 'logs',
950 'objects',
951 'packed-refs',
952 'refs',
953 'rr-cache',
954 'svn']:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -0800955 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800956 src = os.path.join(self.gitdir, name)
957 dst = os.path.join(dotgit, name)
958 os.symlink(relpath(src, dst), dst)
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -0800959 except OSError, e:
960 if e.errno == errno.EPERM:
961 raise GitError('filesystem must support symlinks')
962 else:
963 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700964
965 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
966 rev = self.bare_git.rev_parse('%s^0' % rev)
967
968 f = open(os.path.join(dotgit, HEAD), 'wb')
969 f.write("%s\n" % rev)
970 f.close()
971
972 cmd = ['read-tree', '--reset', '-u']
973 cmd.append('-v')
974 cmd.append('HEAD')
975 if GitCommand(self, cmd).Wait() != 0:
976 raise GitError("cannot initialize work tree")
977
978 def _gitdir_path(self, path):
979 return os.path.join(self.gitdir, path)
980
981 def _revlist(self, *args):
982 cmd = []
983 cmd.extend(args)
984 cmd.append('--')
985 return self.work_git.rev_list(*args)
986
987 @property
988 def _allrefs(self):
989 return self.bare_git.ListRefs()
990
991 class _GitGetByExec(object):
992 def __init__(self, project, bare):
993 self._project = project
994 self._bare = bare
995
996 def ListRefs(self, *args):
997 cmdv = ['for-each-ref', '--format=%(objectname) %(refname)']
998 cmdv.extend(args)
999 p = GitCommand(self._project,
1000 cmdv,
1001 bare = self._bare,
1002 capture_stdout = True,
1003 capture_stderr = True)
1004 r = {}
1005 for line in p.process.stdout:
1006 id, name = line[:-1].split(' ', 2)
1007 r[name] = id
1008 if p.Wait() != 0:
1009 raise GitError('%s for-each-ref %s: %s' % (
1010 self._project.name,
1011 str(args),
1012 p.stderr))
1013 return r
1014
1015 def LsOthers(self):
1016 p = GitCommand(self._project,
1017 ['ls-files',
1018 '-z',
1019 '--others',
1020 '--exclude-standard'],
1021 bare = False,
1022 capture_stdout = True,
1023 capture_stderr = True)
1024 if p.Wait() == 0:
1025 out = p.stdout
1026 if out:
1027 return out[:-1].split("\0")
1028 return []
1029
1030 def DiffZ(self, name, *args):
1031 cmd = [name]
1032 cmd.append('-z')
1033 cmd.extend(args)
1034 p = GitCommand(self._project,
1035 cmd,
1036 bare = False,
1037 capture_stdout = True,
1038 capture_stderr = True)
1039 try:
1040 out = p.process.stdout.read()
1041 r = {}
1042 if out:
1043 out = iter(out[:-1].split('\0'))
1044 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07001045 try:
1046 info = out.next()
1047 path = out.next()
1048 except StopIteration:
1049 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001050
1051 class _Info(object):
1052 def __init__(self, path, omode, nmode, oid, nid, state):
1053 self.path = path
1054 self.src_path = None
1055 self.old_mode = omode
1056 self.new_mode = nmode
1057 self.old_id = oid
1058 self.new_id = nid
1059
1060 if len(state) == 1:
1061 self.status = state
1062 self.level = None
1063 else:
1064 self.status = state[:1]
1065 self.level = state[1:]
1066 while self.level.startswith('0'):
1067 self.level = self.level[1:]
1068
1069 info = info[1:].split(' ')
1070 info =_Info(path, *info)
1071 if info.status in ('R', 'C'):
1072 info.src_path = info.path
1073 info.path = out.next()
1074 r[info.path] = info
1075 return r
1076 finally:
1077 p.Wait()
1078
1079 def GetHead(self):
1080 return self.symbolic_ref(HEAD)
1081
1082 def SetHead(self, ref, message=None):
1083 cmdv = []
1084 if message is not None:
1085 cmdv.extend(['-m', message])
1086 cmdv.append(HEAD)
1087 cmdv.append(ref)
1088 self.symbolic_ref(*cmdv)
1089
1090 def DetachHead(self, new, message=None):
1091 cmdv = ['--no-deref']
1092 if message is not None:
1093 cmdv.extend(['-m', message])
1094 cmdv.append(HEAD)
1095 cmdv.append(new)
1096 self.update_ref(*cmdv)
1097
1098 def UpdateRef(self, name, new, old=None,
1099 message=None,
1100 detach=False):
1101 cmdv = []
1102 if message is not None:
1103 cmdv.extend(['-m', message])
1104 if detach:
1105 cmdv.append('--no-deref')
1106 cmdv.append(name)
1107 cmdv.append(new)
1108 if old is not None:
1109 cmdv.append(old)
1110 self.update_ref(*cmdv)
1111
1112 def DeleteRef(self, name, old=None):
1113 if not old:
1114 old = self.rev_parse(name)
1115 self.update_ref('-d', name, old)
1116
1117 def rev_list(self, *args):
1118 cmdv = ['rev-list']
1119 cmdv.extend(args)
1120 p = GitCommand(self._project,
1121 cmdv,
1122 bare = self._bare,
1123 capture_stdout = True,
1124 capture_stderr = True)
1125 r = []
1126 for line in p.process.stdout:
1127 r.append(line[:-1])
1128 if p.Wait() != 0:
1129 raise GitError('%s rev-list %s: %s' % (
1130 self._project.name,
1131 str(args),
1132 p.stderr))
1133 return r
1134
1135 def __getattr__(self, name):
1136 name = name.replace('_', '-')
1137 def runner(*args):
1138 cmdv = [name]
1139 cmdv.extend(args)
1140 p = GitCommand(self._project,
1141 cmdv,
1142 bare = self._bare,
1143 capture_stdout = True,
1144 capture_stderr = True)
1145 if p.Wait() != 0:
1146 raise GitError('%s %s: %s' % (
1147 self._project.name,
1148 name,
1149 p.stderr))
1150 r = p.stdout
1151 if r.endswith('\n') and r.index('\n') == len(r) - 1:
1152 return r[:-1]
1153 return r
1154 return runner
1155
1156
1157class MetaProject(Project):
1158 """A special project housed under .repo.
1159 """
1160 def __init__(self, manifest, name, gitdir, worktree):
1161 repodir = manifest.repodir
1162 Project.__init__(self,
1163 manifest = manifest,
1164 name = name,
1165 gitdir = gitdir,
1166 worktree = worktree,
1167 remote = Remote('origin'),
1168 relpath = '.repo/%s' % name,
1169 revision = 'refs/heads/master')
1170
1171 def PreSync(self):
1172 if self.Exists:
1173 cb = self.CurrentBranch
1174 if cb:
1175 base = self.GetBranch(cb).merge
1176 if base:
1177 self.revision = base
1178
1179 @property
1180 def HasChanges(self):
1181 """Has the remote received new commits not yet checked out?
1182 """
1183 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
1184 if self._revlist(not_rev(HEAD), rev):
1185 return True
1186 return False