blob: adb7f6699f54400adba0b3cd4cdfbe670865996c [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001# Copyright (C) 2008 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -080015import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070016import filecmp
17import os
18import re
19import shutil
20import stat
21import sys
22import urllib2
23
24from color import Coloring
25from git_command import GitCommand
26from git_config import GitConfig, IsId
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070027from error import GitError, ImportError, UploadError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080028from error import ManifestInvalidRevisionError
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070029from remote import Remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030
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. Pearceb54a3922009-01-05 16:18:58 -080048def sq(r):
49 return "'" + r.replace("'", "'\''") + "'"
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080050
51hook_list = None
52def repo_hooks():
53 global hook_list
54 if hook_list is None:
55 d = os.path.abspath(os.path.dirname(__file__))
56 d = os.path.join(d , 'hooks')
57 hook_list = map(lambda x: os.path.join(d, x), os.listdir(d))
58 return hook_list
59
60def relpath(dst, src):
61 src = os.path.dirname(src)
62 top = os.path.commonprefix([dst, src])
63 if top.endswith('/'):
64 top = top[:-1]
65 else:
66 top = os.path.dirname(top)
67
68 tmp = src
69 rel = ''
70 while top != tmp:
71 rel += '../'
72 tmp = os.path.dirname(tmp)
73 return rel + dst[len(top) + 1:]
74
75
Shawn O. Pearce632768b2008-10-23 11:58:52 -070076class DownloadedChange(object):
77 _commit_cache = None
78
79 def __init__(self, project, base, change_id, ps_id, commit):
80 self.project = project
81 self.base = base
82 self.change_id = change_id
83 self.ps_id = ps_id
84 self.commit = commit
85
86 @property
87 def commits(self):
88 if self._commit_cache is None:
89 self._commit_cache = self.project.bare_git.rev_list(
90 '--abbrev=8',
91 '--abbrev-commit',
92 '--pretty=oneline',
93 '--reverse',
94 '--date-order',
95 not_rev(self.base),
96 self.commit,
97 '--')
98 return self._commit_cache
99
100
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700101class ReviewableBranch(object):
102 _commit_cache = None
103
104 def __init__(self, project, branch, base):
105 self.project = project
106 self.branch = branch
107 self.base = base
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800108 self.replace_changes = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700109
110 @property
111 def name(self):
112 return self.branch.name
113
114 @property
115 def commits(self):
116 if self._commit_cache is None:
117 self._commit_cache = self.project.bare_git.rev_list(
118 '--abbrev=8',
119 '--abbrev-commit',
120 '--pretty=oneline',
121 '--reverse',
122 '--date-order',
123 not_rev(self.base),
124 R_HEADS + self.name,
125 '--')
126 return self._commit_cache
127
128 @property
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800129 def unabbrev_commits(self):
130 r = dict()
131 for commit in self.project.bare_git.rev_list(
132 not_rev(self.base),
133 R_HEADS + self.name,
134 '--'):
135 r[commit[0:8]] = commit
136 return r
137
138 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700139 def date(self):
140 return self.project.bare_git.log(
141 '--pretty=format:%cd',
142 '-n', '1',
143 R_HEADS + self.name,
144 '--')
145
Joe Onorato2896a792008-11-17 16:56:36 -0500146 def UploadForReview(self, people):
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800147 self.project.UploadForReview(self.name,
Joe Onorato2896a792008-11-17 16:56:36 -0500148 self.replace_changes,
149 people)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700150
151 @property
152 def tip_url(self):
153 me = self.project.GetBranch(self.name)
154 commit = self.project.bare_git.rev_parse(R_HEADS + self.name)
155 return 'http://%s/r/%s' % (me.remote.review, commit[0:12])
156
Shawn O. Pearce0758d2f2008-10-22 13:13:40 -0700157 @property
158 def owner_email(self):
159 return self.project.UserEmail
160
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700161
162class StatusColoring(Coloring):
163 def __init__(self, config):
164 Coloring.__init__(self, config, 'status')
165 self.project = self.printer('header', attr = 'bold')
166 self.branch = self.printer('header', attr = 'bold')
167 self.nobranch = self.printer('nobranch', fg = 'red')
168
169 self.added = self.printer('added', fg = 'green')
170 self.changed = self.printer('changed', fg = 'red')
171 self.untracked = self.printer('untracked', fg = 'red')
172
173
174class DiffColoring(Coloring):
175 def __init__(self, config):
176 Coloring.__init__(self, config, 'diff')
177 self.project = self.printer('header', attr = 'bold')
178
179
180class _CopyFile:
181 def __init__(self, src, dest):
182 self.src = src
183 self.dest = dest
184
185 def _Copy(self):
186 src = self.src
187 dest = self.dest
188 # copy file if it does not exist or is out of date
189 if not os.path.exists(dest) or not filecmp.cmp(src, dest):
190 try:
191 # remove existing file first, since it might be read-only
192 if os.path.exists(dest):
193 os.remove(dest)
194 shutil.copy(src, dest)
195 # make the file read-only
196 mode = os.stat(dest)[stat.ST_MODE]
197 mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
198 os.chmod(dest, mode)
199 except IOError:
200 print >>sys.stderr, \
201 'error: Cannot copy file %s to %s' \
202 % (src, dest)
203
204
205class Project(object):
206 def __init__(self,
207 manifest,
208 name,
209 remote,
210 gitdir,
211 worktree,
212 relpath,
213 revision):
214 self.manifest = manifest
215 self.name = name
216 self.remote = remote
217 self.gitdir = gitdir
218 self.worktree = worktree
219 self.relpath = relpath
220 self.revision = revision
221 self.snapshots = {}
222 self.extraRemotes = {}
223 self.copyfiles = []
224 self.config = GitConfig.ForRepository(
225 gitdir = self.gitdir,
226 defaults = self.manifest.globalConfig)
227
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800228 if self.worktree:
229 self.work_git = self._GitGetByExec(self, bare=False)
230 else:
231 self.work_git = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700232 self.bare_git = self._GitGetByExec(self, bare=True)
233
234 @property
235 def Exists(self):
236 return os.path.isdir(self.gitdir)
237
238 @property
239 def CurrentBranch(self):
240 """Obtain the name of the currently checked out branch.
241 The branch name omits the 'refs/heads/' prefix.
242 None is returned if the project is on a detached HEAD.
243 """
244 try:
245 b = self.work_git.GetHead()
246 except GitError:
247 return None
248 if b.startswith(R_HEADS):
249 return b[len(R_HEADS):]
250 return None
251
252 def IsDirty(self, consider_untracked=True):
253 """Is the working directory modified in some way?
254 """
255 self.work_git.update_index('-q',
256 '--unmerged',
257 '--ignore-missing',
258 '--refresh')
259 if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
260 return True
261 if self.work_git.DiffZ('diff-files'):
262 return True
263 if consider_untracked and self.work_git.LsOthers():
264 return True
265 return False
266
267 _userident_name = None
268 _userident_email = None
269
270 @property
271 def UserName(self):
272 """Obtain the user's personal name.
273 """
274 if self._userident_name is None:
275 self._LoadUserIdentity()
276 return self._userident_name
277
278 @property
279 def UserEmail(self):
280 """Obtain the user's email address. This is very likely
281 to be their Gerrit login.
282 """
283 if self._userident_email is None:
284 self._LoadUserIdentity()
285 return self._userident_email
286
287 def _LoadUserIdentity(self):
288 u = self.bare_git.var('GIT_COMMITTER_IDENT')
289 m = re.compile("^(.*) <([^>]*)> ").match(u)
290 if m:
291 self._userident_name = m.group(1)
292 self._userident_email = m.group(2)
293 else:
294 self._userident_name = ''
295 self._userident_email = ''
296
297 def GetRemote(self, name):
298 """Get the configuration for a single remote.
299 """
300 return self.config.GetRemote(name)
301
302 def GetBranch(self, name):
303 """Get the configuration for a single branch.
304 """
305 return self.config.GetBranch(name)
306
307
308## Status Display ##
309
310 def PrintWorkTreeStatus(self):
311 """Prints the status of the repository to stdout.
312 """
313 if not os.path.isdir(self.worktree):
314 print ''
315 print 'project %s/' % self.relpath
316 print ' missing (run "repo sync")'
317 return
318
319 self.work_git.update_index('-q',
320 '--unmerged',
321 '--ignore-missing',
322 '--refresh')
323 di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
324 df = self.work_git.DiffZ('diff-files')
325 do = self.work_git.LsOthers()
326 if not di and not df and not do:
327 return
328
329 out = StatusColoring(self.config)
330 out.project('project %-40s', self.relpath + '/')
331
332 branch = self.CurrentBranch
333 if branch is None:
334 out.nobranch('(*** NO BRANCH ***)')
335 else:
336 out.branch('branch %s', branch)
337 out.nl()
338
339 paths = list()
340 paths.extend(di.keys())
341 paths.extend(df.keys())
342 paths.extend(do)
343
344 paths = list(set(paths))
345 paths.sort()
346
347 for p in paths:
348 try: i = di[p]
349 except KeyError: i = None
350
351 try: f = df[p]
352 except KeyError: f = None
353
354 if i: i_status = i.status.upper()
355 else: i_status = '-'
356
357 if f: f_status = f.status.lower()
358 else: f_status = '-'
359
360 if i and i.src_path:
Shawn O. Pearcefe086752009-03-03 13:49:48 -0800361 line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700362 i.src_path, p, i.level)
363 else:
364 line = ' %s%s\t%s' % (i_status, f_status, p)
365
366 if i and not f:
367 out.added('%s', line)
368 elif (i and f) or (not i and f):
369 out.changed('%s', line)
370 elif not i and not f:
371 out.untracked('%s', line)
372 else:
373 out.write('%s', line)
374 out.nl()
375
376 def PrintWorkTreeDiff(self):
377 """Prints the status of the repository to stdout.
378 """
379 out = DiffColoring(self.config)
380 cmd = ['diff']
381 if out.is_on:
382 cmd.append('--color')
383 cmd.append(HEAD)
384 cmd.append('--')
385 p = GitCommand(self,
386 cmd,
387 capture_stdout = True,
388 capture_stderr = True)
389 has_diff = False
390 for line in p.process.stdout:
391 if not has_diff:
392 out.nl()
393 out.project('project %s/' % self.relpath)
394 out.nl()
395 has_diff = True
396 print line[:-1]
397 p.Wait()
398
399
400## Publish / Upload ##
401
402 def WasPublished(self, branch):
403 """Was the branch published (uploaded) for code review?
404 If so, returns the SHA-1 hash of the last published
405 state for the branch.
406 """
407 try:
408 return self.bare_git.rev_parse(R_PUB + branch)
409 except GitError:
410 return None
411
412 def CleanPublishedCache(self):
413 """Prunes any stale published refs.
414 """
415 heads = set()
416 canrm = {}
417 for name, id in self._allrefs.iteritems():
418 if name.startswith(R_HEADS):
419 heads.add(name)
420 elif name.startswith(R_PUB):
421 canrm[name] = id
422
423 for name, id in canrm.iteritems():
424 n = name[len(R_PUB):]
425 if R_HEADS + n not in heads:
426 self.bare_git.DeleteRef(name, id)
427
428 def GetUploadableBranches(self):
429 """List any branches which can be uploaded for review.
430 """
431 heads = {}
432 pubed = {}
433
434 for name, id in self._allrefs.iteritems():
435 if name.startswith(R_HEADS):
436 heads[name[len(R_HEADS):]] = id
437 elif name.startswith(R_PUB):
438 pubed[name[len(R_PUB):]] = id
439
440 ready = []
441 for branch, id in heads.iteritems():
442 if branch in pubed and pubed[branch] == id:
443 continue
444
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800445 rb = self.GetUploadableBranch(branch)
446 if rb:
447 ready.append(rb)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700448 return ready
449
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800450 def GetUploadableBranch(self, branch_name):
451 """Get a single uploadable branch, or None.
452 """
453 branch = self.GetBranch(branch_name)
454 base = branch.LocalMerge
455 if branch.LocalMerge:
456 rb = ReviewableBranch(self, branch, base)
457 if rb.commits:
458 return rb
459 return None
460
Joe Onorato2896a792008-11-17 16:56:36 -0500461 def UploadForReview(self, branch=None, replace_changes=None, people=([],[])):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700462 """Uploads the named branch for code review.
463 """
464 if branch is None:
465 branch = self.CurrentBranch
466 if branch is None:
467 raise GitError('not currently on a branch')
468
469 branch = self.GetBranch(branch)
470 if not branch.LocalMerge:
471 raise GitError('branch %s does not track a remote' % branch.name)
472 if not branch.remote.review:
473 raise GitError('remote %s has no review url' % branch.remote.name)
474
475 dest_branch = branch.merge
476 if not dest_branch.startswith(R_HEADS):
477 dest_branch = R_HEADS + dest_branch
478
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800479 if not branch.remote.projectname:
480 branch.remote.projectname = self.name
481 branch.remote.Save()
482
Shawn O. Pearce370e3fa2009-01-26 10:55:39 -0800483 if branch.remote.ReviewProtocol == 'ssh':
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800484 if dest_branch.startswith(R_HEADS):
485 dest_branch = dest_branch[len(R_HEADS):]
486
487 rp = ['gerrit receive-pack']
488 for e in people[0]:
489 rp.append('--reviewer=%s' % sq(e))
490 for e in people[1]:
491 rp.append('--cc=%s' % sq(e))
492
493 cmd = ['push']
494 cmd.append('--receive-pack=%s' % " ".join(rp))
495 cmd.append(branch.remote.SshReviewUrl(self.UserEmail))
496 cmd.append('%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch))
497 if replace_changes:
498 for change_id,commit_id in replace_changes.iteritems():
499 cmd.append('%s:refs/changes/%s/new' % (commit_id, change_id))
500 if GitCommand(self, cmd, bare = True).Wait() != 0:
501 raise UploadError('Upload failed')
502
503 else:
504 raise UploadError('Unsupported protocol %s' \
505 % branch.remote.review)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700506
507 msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
508 self.bare_git.UpdateRef(R_PUB + branch.name,
509 R_HEADS + branch.name,
510 message = msg)
511
512
513## Sync ##
514
515 def Sync_NetworkHalf(self):
516 """Perform only the network IO portion of the sync process.
517 Local working directory/branch state is not affected.
518 """
519 if not self.Exists:
520 print >>sys.stderr
521 print >>sys.stderr, 'Initializing project %s ...' % self.name
522 self._InitGitDir()
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800523
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700524 self._InitRemote()
525 for r in self.extraRemotes.values():
526 if not self._RemoteFetch(r.name):
527 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700528 if not self._RemoteFetch():
529 return False
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800530
531 if self.worktree:
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800532 self._InitMRef()
533 else:
534 self._InitMirrorHead()
535 try:
536 os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
537 except OSError:
538 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700539 return True
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800540
541 def PostRepoUpgrade(self):
542 self._InitHooks()
543
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700544 def _CopyFiles(self):
545 for file in self.copyfiles:
546 file._Copy()
547
548 def Sync_LocalHalf(self):
549 """Perform only the local IO portion of the sync process.
550 Network access is not required.
551
552 Return:
553 True: the sync was successful
554 False: the sync requires user input
555 """
556 self._InitWorkTree()
557 self.CleanPublishedCache()
558
559 rem = self.GetRemote(self.remote.name)
560 rev = rem.ToLocal(self.revision)
Shawn O. Pearce559b8462009-03-02 12:56:08 -0800561 try:
562 self.bare_git.rev_parse('--verify', '%s^0' % rev)
563 except GitError:
564 raise ManifestInvalidRevisionError(
565 'revision %s in %s not found' % (self.revision, self.name))
566
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700567 branch = self.CurrentBranch
568
569 if branch is None:
570 # Currently on a detached HEAD. The user is assumed to
571 # not have any local modifications worth worrying about.
572 #
573 lost = self._revlist(not_rev(rev), HEAD)
574 if lost:
575 _info("[%s] Discarding %d commits", self.name, len(lost))
576 try:
577 self._Checkout(rev, quiet=True)
578 except GitError:
579 return False
580 self._CopyFiles()
581 return True
582
583 branch = self.GetBranch(branch)
584 merge = branch.LocalMerge
585
586 if not merge:
587 # The current branch has no tracking configuration.
588 # Jump off it to a deatched HEAD.
589 #
590 _info("[%s] Leaving %s"
591 " (does not track any upstream)",
592 self.name,
593 branch.name)
594 try:
595 self._Checkout(rev, quiet=True)
596 except GitError:
597 return False
598 self._CopyFiles()
599 return True
600
601 upstream_gain = self._revlist(not_rev(HEAD), rev)
602 pub = self.WasPublished(branch.name)
603 if pub:
604 not_merged = self._revlist(not_rev(rev), pub)
605 if not_merged:
606 if upstream_gain:
607 # The user has published this branch and some of those
608 # commits are not yet merged upstream. We do not want
609 # to rewrite the published commits so we punt.
610 #
611 _info("[%s] Branch %s is published,"
612 " but is now %d commits behind.",
613 self.name, branch.name, len(upstream_gain))
614 _info("[%s] Consider merging or rebasing the"
615 " unpublished commits.", self.name)
616 return True
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700617 elif upstream_gain:
Shawn O. Pearcea54c5272008-10-30 11:03:00 -0700618 # We can fast-forward safely.
619 #
620 try:
621 self._FastForward(rev)
622 except GitError:
623 return False
624 self._CopyFiles()
625 return True
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700626 else:
627 # Trivially no changes in the upstream.
628 #
629 return True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700630
631 if merge == rev:
632 try:
633 old_merge = self.bare_git.rev_parse('%s@{1}' % merge)
634 except GitError:
635 old_merge = merge
Shawn O. Pearce07346002008-10-21 07:09:27 -0700636 if old_merge == '0000000000000000000000000000000000000000' \
637 or old_merge == '':
638 old_merge = merge
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700639 else:
640 # The upstream switched on us. Time to cross our fingers
641 # and pray that the old upstream also wasn't in the habit
642 # of rebasing itself.
643 #
644 _info("[%s] Manifest switched from %s to %s",
645 self.name, merge, rev)
646 old_merge = merge
647
648 if rev == old_merge:
649 upstream_lost = []
650 else:
651 upstream_lost = self._revlist(not_rev(rev), old_merge)
652
653 if not upstream_lost and not upstream_gain:
654 # Trivially no changes caused by the upstream.
655 #
656 return True
657
658 if self.IsDirty(consider_untracked=False):
659 _warn('[%s] commit (or discard) uncommitted changes'
660 ' before sync', self.name)
661 return False
662
663 if upstream_lost:
664 # Upstream rebased. Not everything in HEAD
665 # may have been caused by the user.
666 #
667 _info("[%s] Discarding %d commits removed from upstream",
668 self.name, len(upstream_lost))
669
670 branch.remote = rem
671 branch.merge = self.revision
672 branch.Save()
673
674 my_changes = self._revlist(not_rev(old_merge), HEAD)
675 if my_changes:
676 try:
677 self._Rebase(upstream = old_merge, onto = rev)
678 except GitError:
679 return False
680 elif upstream_lost:
681 try:
682 self._ResetHard(rev)
683 except GitError:
684 return False
685 else:
686 try:
687 self._FastForward(rev)
688 except GitError:
689 return False
690
691 self._CopyFiles()
692 return True
693
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700694 def AddCopyFile(self, src, dest):
695 # dest should already be an absolute path, but src is project relative
696 # make src an absolute path
697 src = os.path.join(self.worktree, src)
698 self.copyfiles.append(_CopyFile(src, dest))
699
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700700 def DownloadPatchSet(self, change_id, patch_id):
701 """Download a single patch set of a single change to FETCH_HEAD.
702 """
703 remote = self.GetRemote(self.remote.name)
704
705 cmd = ['fetch', remote.name]
706 cmd.append('refs/changes/%2.2d/%d/%d' \
707 % (change_id % 100, change_id, patch_id))
708 cmd.extend(map(lambda x: str(x), remote.fetch))
709 if GitCommand(self, cmd, bare=True).Wait() != 0:
710 return None
711 return DownloadedChange(self,
712 remote.ToLocal(self.revision),
713 change_id,
714 patch_id,
715 self.bare_git.rev_parse('FETCH_HEAD'))
716
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700717
718## Branch Management ##
719
720 def StartBranch(self, name):
721 """Create a new branch off the manifest's revision.
722 """
723 branch = self.GetBranch(name)
724 branch.remote = self.GetRemote(self.remote.name)
725 branch.merge = self.revision
726
727 rev = branch.LocalMerge
728 cmd = ['checkout', '-b', branch.name, rev]
729 if GitCommand(self, cmd).Wait() == 0:
730 branch.Save()
731 else:
732 raise GitError('%s checkout %s ' % (self.name, rev))
733
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800734 def AbandonBranch(self, name):
735 """Destroy a local topic branch.
736 """
737 try:
738 tip_rev = self.bare_git.rev_parse(R_HEADS + name)
739 except GitError:
740 return
741
742 if self.CurrentBranch == name:
743 self._Checkout(
744 self.GetRemote(self.remote.name).ToLocal(self.revision),
745 quiet=True)
746
747 cmd = ['branch', '-D', name]
748 GitCommand(self, cmd, capture_stdout=True).Wait()
749
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700750 def PruneHeads(self):
751 """Prune any topic branches already merged into upstream.
752 """
753 cb = self.CurrentBranch
754 kill = []
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800755 left = self._allrefs
756 for name in left.keys():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700757 if name.startswith(R_HEADS):
758 name = name[len(R_HEADS):]
759 if cb is None or name != cb:
760 kill.append(name)
761
762 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
763 if cb is not None \
764 and not self._revlist(HEAD + '...' + rev) \
765 and not self.IsDirty(consider_untracked = False):
766 self.work_git.DetachHead(HEAD)
767 kill.append(cb)
768
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700769 if kill:
770 try:
771 old = self.bare_git.GetHead()
772 except GitError:
773 old = 'refs/heads/please_never_use_this_as_a_branch_name'
774
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700775 try:
776 self.bare_git.DetachHead(rev)
777
778 b = ['branch', '-d']
779 b.extend(kill)
780 b = GitCommand(self, b, bare=True,
781 capture_stdout=True,
782 capture_stderr=True)
783 b.Wait()
784 finally:
785 self.bare_git.SetHead(old)
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800786 left = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700787
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800788 for branch in kill:
789 if (R_HEADS + branch) not in left:
790 self.CleanPublishedCache()
791 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700792
793 if cb and cb not in kill:
794 kill.append(cb)
Shawn O. Pearce7c6c64d2009-03-02 12:38:13 -0800795 kill.sort()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700796
797 kept = []
798 for branch in kill:
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800799 if (R_HEADS + branch) in left:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700800 branch = self.GetBranch(branch)
801 base = branch.LocalMerge
802 if not base:
803 base = rev
804 kept.append(ReviewableBranch(self, branch, base))
805 return kept
806
807
808## Direct Git Commands ##
809
810 def _RemoteFetch(self, name=None):
811 if not name:
812 name = self.remote.name
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800813 cmd = ['fetch']
814 if not self.worktree:
815 cmd.append('--update-head-ok')
816 cmd.append(name)
817 return GitCommand(self, cmd, bare = True).Wait() == 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700818
819 def _Checkout(self, rev, quiet=False):
820 cmd = ['checkout']
821 if quiet:
822 cmd.append('-q')
823 cmd.append(rev)
824 cmd.append('--')
825 if GitCommand(self, cmd).Wait() != 0:
826 if self._allrefs:
827 raise GitError('%s checkout %s ' % (self.name, rev))
828
829 def _ResetHard(self, rev, quiet=True):
830 cmd = ['reset', '--hard']
831 if quiet:
832 cmd.append('-q')
833 cmd.append(rev)
834 if GitCommand(self, cmd).Wait() != 0:
835 raise GitError('%s reset --hard %s ' % (self.name, rev))
836
837 def _Rebase(self, upstream, onto = None):
838 cmd = ['rebase', '-i']
839 if onto is not None:
840 cmd.extend(['--onto', onto])
841 cmd.append(upstream)
842 if GitCommand(self, cmd, disable_editor=True).Wait() != 0:
843 raise GitError('%s rebase %s ' % (self.name, upstream))
844
845 def _FastForward(self, head):
846 cmd = ['merge', head]
847 if GitCommand(self, cmd).Wait() != 0:
848 raise GitError('%s merge %s ' % (self.name, head))
849
850 def _InitGitDir(self):
851 if not os.path.exists(self.gitdir):
852 os.makedirs(self.gitdir)
853 self.bare_git.init()
854 self.config.SetString('core.bare', None)
855
856 hooks = self._gitdir_path('hooks')
Shawn O. Pearcede646812008-10-29 14:38:12 -0700857 try:
858 to_rm = os.listdir(hooks)
859 except OSError:
860 to_rm = []
861 for old_hook in to_rm:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700862 os.remove(os.path.join(hooks, old_hook))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800863 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700864
865 m = self.manifest.manifestProject.config
866 for key in ['user.name', 'user.email']:
867 if m.Has(key, include_defaults = False):
868 self.config.SetString(key, m.GetString(key))
869
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800870 def _InitHooks(self):
871 hooks = self._gitdir_path('hooks')
872 if not os.path.exists(hooks):
873 os.makedirs(hooks)
874 for stock_hook in repo_hooks():
875 dst = os.path.join(hooks, os.path.basename(stock_hook))
876 try:
877 os.symlink(relpath(stock_hook, dst), dst)
878 except OSError, e:
879 if e.errno == errno.EEXIST:
880 pass
881 elif e.errno == errno.EPERM:
882 raise GitError('filesystem must support symlinks')
883 else:
884 raise
885
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700886 def _InitRemote(self):
887 if self.remote.fetchUrl:
888 remote = self.GetRemote(self.remote.name)
889
890 url = self.remote.fetchUrl
891 while url.endswith('/'):
892 url = url[:-1]
893 url += '/%s.git' % self.name
894 remote.url = url
895 remote.review = self.remote.reviewUrl
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800896 if remote.projectname is None:
897 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700898
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800899 if self.worktree:
900 remote.ResetFetch(mirror=False)
901 else:
902 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700903 remote.Save()
904
905 for r in self.extraRemotes.values():
906 remote = self.GetRemote(r.name)
907 remote.url = r.fetchUrl
908 remote.review = r.reviewUrl
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800909 if r.projectName:
910 remote.projectname = r.projectName
911 elif remote.projectname is None:
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800912 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700913 remote.ResetFetch()
914 remote.Save()
915
916 def _InitMRef(self):
917 if self.manifest.branch:
918 msg = 'manifest set to %s' % self.revision
919 ref = R_M + self.manifest.branch
920
921 if IsId(self.revision):
Marcelo E. Magallon21f73852008-12-31 04:44:37 +0000922 dst = self.revision + '^0'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700923 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
924 else:
925 remote = self.GetRemote(self.remote.name)
926 dst = remote.ToLocal(self.revision)
927 self.bare_git.symbolic_ref('-m', msg, ref, dst)
928
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800929 def _InitMirrorHead(self):
930 dst = self.GetRemote(self.remote.name).ToLocal(self.revision)
931 msg = 'manifest set to %s' % self.revision
932 self.bare_git.SetHead(dst, message=msg)
933
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700934 def _InitWorkTree(self):
935 dotgit = os.path.join(self.worktree, '.git')
936 if not os.path.exists(dotgit):
937 os.makedirs(dotgit)
938
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700939 for name in ['config',
940 'description',
941 'hooks',
942 'info',
943 'logs',
944 'objects',
945 'packed-refs',
946 'refs',
947 'rr-cache',
948 'svn']:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -0800949 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800950 src = os.path.join(self.gitdir, name)
951 dst = os.path.join(dotgit, name)
952 os.symlink(relpath(src, dst), dst)
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -0800953 except OSError, e:
954 if e.errno == errno.EPERM:
955 raise GitError('filesystem must support symlinks')
956 else:
957 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700958
959 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
960 rev = self.bare_git.rev_parse('%s^0' % rev)
961
962 f = open(os.path.join(dotgit, HEAD), 'wb')
963 f.write("%s\n" % rev)
964 f.close()
965
966 cmd = ['read-tree', '--reset', '-u']
967 cmd.append('-v')
968 cmd.append('HEAD')
969 if GitCommand(self, cmd).Wait() != 0:
970 raise GitError("cannot initialize work tree")
971
972 def _gitdir_path(self, path):
973 return os.path.join(self.gitdir, path)
974
975 def _revlist(self, *args):
976 cmd = []
977 cmd.extend(args)
978 cmd.append('--')
979 return self.work_git.rev_list(*args)
980
981 @property
982 def _allrefs(self):
983 return self.bare_git.ListRefs()
984
985 class _GitGetByExec(object):
986 def __init__(self, project, bare):
987 self._project = project
988 self._bare = bare
989
990 def ListRefs(self, *args):
991 cmdv = ['for-each-ref', '--format=%(objectname) %(refname)']
992 cmdv.extend(args)
993 p = GitCommand(self._project,
994 cmdv,
995 bare = self._bare,
996 capture_stdout = True,
997 capture_stderr = True)
998 r = {}
999 for line in p.process.stdout:
1000 id, name = line[:-1].split(' ', 2)
1001 r[name] = id
1002 if p.Wait() != 0:
1003 raise GitError('%s for-each-ref %s: %s' % (
1004 self._project.name,
1005 str(args),
1006 p.stderr))
1007 return r
1008
1009 def LsOthers(self):
1010 p = GitCommand(self._project,
1011 ['ls-files',
1012 '-z',
1013 '--others',
1014 '--exclude-standard'],
1015 bare = False,
1016 capture_stdout = True,
1017 capture_stderr = True)
1018 if p.Wait() == 0:
1019 out = p.stdout
1020 if out:
1021 return out[:-1].split("\0")
1022 return []
1023
1024 def DiffZ(self, name, *args):
1025 cmd = [name]
1026 cmd.append('-z')
1027 cmd.extend(args)
1028 p = GitCommand(self._project,
1029 cmd,
1030 bare = False,
1031 capture_stdout = True,
1032 capture_stderr = True)
1033 try:
1034 out = p.process.stdout.read()
1035 r = {}
1036 if out:
1037 out = iter(out[:-1].split('\0'))
1038 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07001039 try:
1040 info = out.next()
1041 path = out.next()
1042 except StopIteration:
1043 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001044
1045 class _Info(object):
1046 def __init__(self, path, omode, nmode, oid, nid, state):
1047 self.path = path
1048 self.src_path = None
1049 self.old_mode = omode
1050 self.new_mode = nmode
1051 self.old_id = oid
1052 self.new_id = nid
1053
1054 if len(state) == 1:
1055 self.status = state
1056 self.level = None
1057 else:
1058 self.status = state[:1]
1059 self.level = state[1:]
1060 while self.level.startswith('0'):
1061 self.level = self.level[1:]
1062
1063 info = info[1:].split(' ')
1064 info =_Info(path, *info)
1065 if info.status in ('R', 'C'):
1066 info.src_path = info.path
1067 info.path = out.next()
1068 r[info.path] = info
1069 return r
1070 finally:
1071 p.Wait()
1072
1073 def GetHead(self):
1074 return self.symbolic_ref(HEAD)
1075
1076 def SetHead(self, ref, message=None):
1077 cmdv = []
1078 if message is not None:
1079 cmdv.extend(['-m', message])
1080 cmdv.append(HEAD)
1081 cmdv.append(ref)
1082 self.symbolic_ref(*cmdv)
1083
1084 def DetachHead(self, new, message=None):
1085 cmdv = ['--no-deref']
1086 if message is not None:
1087 cmdv.extend(['-m', message])
1088 cmdv.append(HEAD)
1089 cmdv.append(new)
1090 self.update_ref(*cmdv)
1091
1092 def UpdateRef(self, name, new, old=None,
1093 message=None,
1094 detach=False):
1095 cmdv = []
1096 if message is not None:
1097 cmdv.extend(['-m', message])
1098 if detach:
1099 cmdv.append('--no-deref')
1100 cmdv.append(name)
1101 cmdv.append(new)
1102 if old is not None:
1103 cmdv.append(old)
1104 self.update_ref(*cmdv)
1105
1106 def DeleteRef(self, name, old=None):
1107 if not old:
1108 old = self.rev_parse(name)
1109 self.update_ref('-d', name, old)
1110
1111 def rev_list(self, *args):
1112 cmdv = ['rev-list']
1113 cmdv.extend(args)
1114 p = GitCommand(self._project,
1115 cmdv,
1116 bare = self._bare,
1117 capture_stdout = True,
1118 capture_stderr = True)
1119 r = []
1120 for line in p.process.stdout:
1121 r.append(line[:-1])
1122 if p.Wait() != 0:
1123 raise GitError('%s rev-list %s: %s' % (
1124 self._project.name,
1125 str(args),
1126 p.stderr))
1127 return r
1128
1129 def __getattr__(self, name):
1130 name = name.replace('_', '-')
1131 def runner(*args):
1132 cmdv = [name]
1133 cmdv.extend(args)
1134 p = GitCommand(self._project,
1135 cmdv,
1136 bare = self._bare,
1137 capture_stdout = True,
1138 capture_stderr = True)
1139 if p.Wait() != 0:
1140 raise GitError('%s %s: %s' % (
1141 self._project.name,
1142 name,
1143 p.stderr))
1144 r = p.stdout
1145 if r.endswith('\n') and r.index('\n') == len(r) - 1:
1146 return r[:-1]
1147 return r
1148 return runner
1149
1150
1151class MetaProject(Project):
1152 """A special project housed under .repo.
1153 """
1154 def __init__(self, manifest, name, gitdir, worktree):
1155 repodir = manifest.repodir
1156 Project.__init__(self,
1157 manifest = manifest,
1158 name = name,
1159 gitdir = gitdir,
1160 worktree = worktree,
1161 remote = Remote('origin'),
1162 relpath = '.repo/%s' % name,
1163 revision = 'refs/heads/master')
1164
1165 def PreSync(self):
1166 if self.Exists:
1167 cb = self.CurrentBranch
1168 if cb:
1169 base = self.GetBranch(cb).merge
1170 if base:
1171 self.revision = base
1172
1173 @property
1174 def HasChanges(self):
1175 """Has the remote received new commits not yet checked out?
1176 """
1177 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
1178 if self._revlist(not_rev(HEAD), rev):
1179 return True
1180 return False