blob: b9792523919940465a7620e1859a01c84a9c7d11 [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()
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -0800854
855 if self.manifest.IsMirror:
856 self.config.SetString('core.bare', 'true')
857 else:
858 self.config.SetString('core.bare', None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700859
860 hooks = self._gitdir_path('hooks')
Shawn O. Pearcede646812008-10-29 14:38:12 -0700861 try:
862 to_rm = os.listdir(hooks)
863 except OSError:
864 to_rm = []
865 for old_hook in to_rm:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700866 os.remove(os.path.join(hooks, old_hook))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800867 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700868
869 m = self.manifest.manifestProject.config
870 for key in ['user.name', 'user.email']:
871 if m.Has(key, include_defaults = False):
872 self.config.SetString(key, m.GetString(key))
873
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800874 def _InitHooks(self):
875 hooks = self._gitdir_path('hooks')
876 if not os.path.exists(hooks):
877 os.makedirs(hooks)
878 for stock_hook in repo_hooks():
879 dst = os.path.join(hooks, os.path.basename(stock_hook))
880 try:
881 os.symlink(relpath(stock_hook, dst), dst)
882 except OSError, e:
883 if e.errno == errno.EEXIST:
884 pass
885 elif e.errno == errno.EPERM:
886 raise GitError('filesystem must support symlinks')
887 else:
888 raise
889
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700890 def _InitRemote(self):
891 if self.remote.fetchUrl:
892 remote = self.GetRemote(self.remote.name)
893
894 url = self.remote.fetchUrl
895 while url.endswith('/'):
896 url = url[:-1]
897 url += '/%s.git' % self.name
898 remote.url = url
899 remote.review = self.remote.reviewUrl
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800900 if remote.projectname is None:
901 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700902
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800903 if self.worktree:
904 remote.ResetFetch(mirror=False)
905 else:
906 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700907 remote.Save()
908
909 for r in self.extraRemotes.values():
910 remote = self.GetRemote(r.name)
911 remote.url = r.fetchUrl
912 remote.review = r.reviewUrl
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800913 if r.projectName:
914 remote.projectname = r.projectName
915 elif remote.projectname is None:
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800916 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700917 remote.ResetFetch()
918 remote.Save()
919
920 def _InitMRef(self):
921 if self.manifest.branch:
922 msg = 'manifest set to %s' % self.revision
923 ref = R_M + self.manifest.branch
924
925 if IsId(self.revision):
Marcelo E. Magallon21f73852008-12-31 04:44:37 +0000926 dst = self.revision + '^0'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700927 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
928 else:
929 remote = self.GetRemote(self.remote.name)
930 dst = remote.ToLocal(self.revision)
931 self.bare_git.symbolic_ref('-m', msg, ref, dst)
932
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800933 def _InitMirrorHead(self):
934 dst = self.GetRemote(self.remote.name).ToLocal(self.revision)
935 msg = 'manifest set to %s' % self.revision
936 self.bare_git.SetHead(dst, message=msg)
937
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700938 def _InitWorkTree(self):
939 dotgit = os.path.join(self.worktree, '.git')
940 if not os.path.exists(dotgit):
941 os.makedirs(dotgit)
942
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700943 for name in ['config',
944 'description',
945 'hooks',
946 'info',
947 'logs',
948 'objects',
949 'packed-refs',
950 'refs',
951 'rr-cache',
952 'svn']:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -0800953 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800954 src = os.path.join(self.gitdir, name)
955 dst = os.path.join(dotgit, name)
956 os.symlink(relpath(src, dst), dst)
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -0800957 except OSError, e:
958 if e.errno == errno.EPERM:
959 raise GitError('filesystem must support symlinks')
960 else:
961 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700962
963 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
964 rev = self.bare_git.rev_parse('%s^0' % rev)
965
966 f = open(os.path.join(dotgit, HEAD), 'wb')
967 f.write("%s\n" % rev)
968 f.close()
969
970 cmd = ['read-tree', '--reset', '-u']
971 cmd.append('-v')
972 cmd.append('HEAD')
973 if GitCommand(self, cmd).Wait() != 0:
974 raise GitError("cannot initialize work tree")
975
976 def _gitdir_path(self, path):
977 return os.path.join(self.gitdir, path)
978
979 def _revlist(self, *args):
980 cmd = []
981 cmd.extend(args)
982 cmd.append('--')
983 return self.work_git.rev_list(*args)
984
985 @property
986 def _allrefs(self):
987 return self.bare_git.ListRefs()
988
989 class _GitGetByExec(object):
990 def __init__(self, project, bare):
991 self._project = project
992 self._bare = bare
993
994 def ListRefs(self, *args):
995 cmdv = ['for-each-ref', '--format=%(objectname) %(refname)']
996 cmdv.extend(args)
997 p = GitCommand(self._project,
998 cmdv,
999 bare = self._bare,
1000 capture_stdout = True,
1001 capture_stderr = True)
1002 r = {}
1003 for line in p.process.stdout:
1004 id, name = line[:-1].split(' ', 2)
1005 r[name] = id
1006 if p.Wait() != 0:
1007 raise GitError('%s for-each-ref %s: %s' % (
1008 self._project.name,
1009 str(args),
1010 p.stderr))
1011 return r
1012
1013 def LsOthers(self):
1014 p = GitCommand(self._project,
1015 ['ls-files',
1016 '-z',
1017 '--others',
1018 '--exclude-standard'],
1019 bare = False,
1020 capture_stdout = True,
1021 capture_stderr = True)
1022 if p.Wait() == 0:
1023 out = p.stdout
1024 if out:
1025 return out[:-1].split("\0")
1026 return []
1027
1028 def DiffZ(self, name, *args):
1029 cmd = [name]
1030 cmd.append('-z')
1031 cmd.extend(args)
1032 p = GitCommand(self._project,
1033 cmd,
1034 bare = False,
1035 capture_stdout = True,
1036 capture_stderr = True)
1037 try:
1038 out = p.process.stdout.read()
1039 r = {}
1040 if out:
1041 out = iter(out[:-1].split('\0'))
1042 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07001043 try:
1044 info = out.next()
1045 path = out.next()
1046 except StopIteration:
1047 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001048
1049 class _Info(object):
1050 def __init__(self, path, omode, nmode, oid, nid, state):
1051 self.path = path
1052 self.src_path = None
1053 self.old_mode = omode
1054 self.new_mode = nmode
1055 self.old_id = oid
1056 self.new_id = nid
1057
1058 if len(state) == 1:
1059 self.status = state
1060 self.level = None
1061 else:
1062 self.status = state[:1]
1063 self.level = state[1:]
1064 while self.level.startswith('0'):
1065 self.level = self.level[1:]
1066
1067 info = info[1:].split(' ')
1068 info =_Info(path, *info)
1069 if info.status in ('R', 'C'):
1070 info.src_path = info.path
1071 info.path = out.next()
1072 r[info.path] = info
1073 return r
1074 finally:
1075 p.Wait()
1076
1077 def GetHead(self):
1078 return self.symbolic_ref(HEAD)
1079
1080 def SetHead(self, ref, message=None):
1081 cmdv = []
1082 if message is not None:
1083 cmdv.extend(['-m', message])
1084 cmdv.append(HEAD)
1085 cmdv.append(ref)
1086 self.symbolic_ref(*cmdv)
1087
1088 def DetachHead(self, new, message=None):
1089 cmdv = ['--no-deref']
1090 if message is not None:
1091 cmdv.extend(['-m', message])
1092 cmdv.append(HEAD)
1093 cmdv.append(new)
1094 self.update_ref(*cmdv)
1095
1096 def UpdateRef(self, name, new, old=None,
1097 message=None,
1098 detach=False):
1099 cmdv = []
1100 if message is not None:
1101 cmdv.extend(['-m', message])
1102 if detach:
1103 cmdv.append('--no-deref')
1104 cmdv.append(name)
1105 cmdv.append(new)
1106 if old is not None:
1107 cmdv.append(old)
1108 self.update_ref(*cmdv)
1109
1110 def DeleteRef(self, name, old=None):
1111 if not old:
1112 old = self.rev_parse(name)
1113 self.update_ref('-d', name, old)
1114
1115 def rev_list(self, *args):
1116 cmdv = ['rev-list']
1117 cmdv.extend(args)
1118 p = GitCommand(self._project,
1119 cmdv,
1120 bare = self._bare,
1121 capture_stdout = True,
1122 capture_stderr = True)
1123 r = []
1124 for line in p.process.stdout:
1125 r.append(line[:-1])
1126 if p.Wait() != 0:
1127 raise GitError('%s rev-list %s: %s' % (
1128 self._project.name,
1129 str(args),
1130 p.stderr))
1131 return r
1132
1133 def __getattr__(self, name):
1134 name = name.replace('_', '-')
1135 def runner(*args):
1136 cmdv = [name]
1137 cmdv.extend(args)
1138 p = GitCommand(self._project,
1139 cmdv,
1140 bare = self._bare,
1141 capture_stdout = True,
1142 capture_stderr = True)
1143 if p.Wait() != 0:
1144 raise GitError('%s %s: %s' % (
1145 self._project.name,
1146 name,
1147 p.stderr))
1148 r = p.stdout
1149 if r.endswith('\n') and r.index('\n') == len(r) - 1:
1150 return r[:-1]
1151 return r
1152 return runner
1153
1154
1155class MetaProject(Project):
1156 """A special project housed under .repo.
1157 """
1158 def __init__(self, manifest, name, gitdir, worktree):
1159 repodir = manifest.repodir
1160 Project.__init__(self,
1161 manifest = manifest,
1162 name = name,
1163 gitdir = gitdir,
1164 worktree = worktree,
1165 remote = Remote('origin'),
1166 relpath = '.repo/%s' % name,
1167 revision = 'refs/heads/master')
1168
1169 def PreSync(self):
1170 if self.Exists:
1171 cb = self.CurrentBranch
1172 if cb:
1173 base = self.GetBranch(cb).merge
1174 if base:
1175 self.revision = base
1176
1177 @property
1178 def HasChanges(self):
1179 """Has the remote received new commits not yet checked out?
1180 """
1181 rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
1182 if self._revlist(not_rev(HEAD), rev):
1183 return True
1184 return False