blob: 8ed61551f470cf8fb5734175fd9767ea5120c8d7 [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:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800181 def __init__(self, src, dest, abssrc, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700182 self.src = src
183 self.dest = dest
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800184 self.abs_src = abssrc
185 self.abs_dest = absdest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700186
187 def _Copy(self):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800188 src = self.abs_src
189 dest = self.abs_dest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700190 # copy file if it does not exist or is out of date
191 if not os.path.exists(dest) or not filecmp.cmp(src, dest):
192 try:
193 # remove existing file first, since it might be read-only
194 if os.path.exists(dest):
195 os.remove(dest)
196 shutil.copy(src, dest)
197 # make the file read-only
198 mode = os.stat(dest)[stat.ST_MODE]
199 mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
200 os.chmod(dest, mode)
201 except IOError:
202 print >>sys.stderr, \
203 'error: Cannot copy file %s to %s' \
204 % (src, dest)
205
206
207class Project(object):
208 def __init__(self,
209 manifest,
210 name,
211 remote,
212 gitdir,
213 worktree,
214 relpath,
215 revision):
216 self.manifest = manifest
217 self.name = name
218 self.remote = remote
219 self.gitdir = gitdir
220 self.worktree = worktree
221 self.relpath = relpath
222 self.revision = revision
223 self.snapshots = {}
224 self.extraRemotes = {}
225 self.copyfiles = []
226 self.config = GitConfig.ForRepository(
227 gitdir = self.gitdir,
228 defaults = self.manifest.globalConfig)
229
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800230 if self.worktree:
231 self.work_git = self._GitGetByExec(self, bare=False)
232 else:
233 self.work_git = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700234 self.bare_git = self._GitGetByExec(self, bare=True)
235
236 @property
237 def Exists(self):
238 return os.path.isdir(self.gitdir)
239
240 @property
241 def CurrentBranch(self):
242 """Obtain the name of the currently checked out branch.
243 The branch name omits the 'refs/heads/' prefix.
244 None is returned if the project is on a detached HEAD.
245 """
246 try:
247 b = self.work_git.GetHead()
248 except GitError:
249 return None
250 if b.startswith(R_HEADS):
251 return b[len(R_HEADS):]
252 return None
253
254 def IsDirty(self, consider_untracked=True):
255 """Is the working directory modified in some way?
256 """
257 self.work_git.update_index('-q',
258 '--unmerged',
259 '--ignore-missing',
260 '--refresh')
261 if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
262 return True
263 if self.work_git.DiffZ('diff-files'):
264 return True
265 if consider_untracked and self.work_git.LsOthers():
266 return True
267 return False
268
269 _userident_name = None
270 _userident_email = None
271
272 @property
273 def UserName(self):
274 """Obtain the user's personal name.
275 """
276 if self._userident_name is None:
277 self._LoadUserIdentity()
278 return self._userident_name
279
280 @property
281 def UserEmail(self):
282 """Obtain the user's email address. This is very likely
283 to be their Gerrit login.
284 """
285 if self._userident_email is None:
286 self._LoadUserIdentity()
287 return self._userident_email
288
289 def _LoadUserIdentity(self):
290 u = self.bare_git.var('GIT_COMMITTER_IDENT')
291 m = re.compile("^(.*) <([^>]*)> ").match(u)
292 if m:
293 self._userident_name = m.group(1)
294 self._userident_email = m.group(2)
295 else:
296 self._userident_name = ''
297 self._userident_email = ''
298
299 def GetRemote(self, name):
300 """Get the configuration for a single remote.
301 """
302 return self.config.GetRemote(name)
303
304 def GetBranch(self, name):
305 """Get the configuration for a single branch.
306 """
307 return self.config.GetBranch(name)
308
309
310## Status Display ##
311
312 def PrintWorkTreeStatus(self):
313 """Prints the status of the repository to stdout.
314 """
315 if not os.path.isdir(self.worktree):
316 print ''
317 print 'project %s/' % self.relpath
318 print ' missing (run "repo sync")'
319 return
320
321 self.work_git.update_index('-q',
322 '--unmerged',
323 '--ignore-missing',
324 '--refresh')
325 di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
326 df = self.work_git.DiffZ('diff-files')
327 do = self.work_git.LsOthers()
328 if not di and not df and not do:
329 return
330
331 out = StatusColoring(self.config)
332 out.project('project %-40s', self.relpath + '/')
333
334 branch = self.CurrentBranch
335 if branch is None:
336 out.nobranch('(*** NO BRANCH ***)')
337 else:
338 out.branch('branch %s', branch)
339 out.nl()
340
341 paths = list()
342 paths.extend(di.keys())
343 paths.extend(df.keys())
344 paths.extend(do)
345
346 paths = list(set(paths))
347 paths.sort()
348
349 for p in paths:
350 try: i = di[p]
351 except KeyError: i = None
352
353 try: f = df[p]
354 except KeyError: f = None
355
356 if i: i_status = i.status.upper()
357 else: i_status = '-'
358
359 if f: f_status = f.status.lower()
360 else: f_status = '-'
361
362 if i and i.src_path:
Shawn O. Pearcefe086752009-03-03 13:49:48 -0800363 line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700364 i.src_path, p, i.level)
365 else:
366 line = ' %s%s\t%s' % (i_status, f_status, p)
367
368 if i and not f:
369 out.added('%s', line)
370 elif (i and f) or (not i and f):
371 out.changed('%s', line)
372 elif not i and not f:
373 out.untracked('%s', line)
374 else:
375 out.write('%s', line)
376 out.nl()
377
378 def PrintWorkTreeDiff(self):
379 """Prints the status of the repository to stdout.
380 """
381 out = DiffColoring(self.config)
382 cmd = ['diff']
383 if out.is_on:
384 cmd.append('--color')
385 cmd.append(HEAD)
386 cmd.append('--')
387 p = GitCommand(self,
388 cmd,
389 capture_stdout = True,
390 capture_stderr = True)
391 has_diff = False
392 for line in p.process.stdout:
393 if not has_diff:
394 out.nl()
395 out.project('project %s/' % self.relpath)
396 out.nl()
397 has_diff = True
398 print line[:-1]
399 p.Wait()
400
401
402## Publish / Upload ##
403
404 def WasPublished(self, branch):
405 """Was the branch published (uploaded) for code review?
406 If so, returns the SHA-1 hash of the last published
407 state for the branch.
408 """
409 try:
410 return self.bare_git.rev_parse(R_PUB + branch)
411 except GitError:
412 return None
413
414 def CleanPublishedCache(self):
415 """Prunes any stale published refs.
416 """
417 heads = set()
418 canrm = {}
419 for name, id in self._allrefs.iteritems():
420 if name.startswith(R_HEADS):
421 heads.add(name)
422 elif name.startswith(R_PUB):
423 canrm[name] = id
424
425 for name, id in canrm.iteritems():
426 n = name[len(R_PUB):]
427 if R_HEADS + n not in heads:
428 self.bare_git.DeleteRef(name, id)
429
430 def GetUploadableBranches(self):
431 """List any branches which can be uploaded for review.
432 """
433 heads = {}
434 pubed = {}
435
436 for name, id in self._allrefs.iteritems():
437 if name.startswith(R_HEADS):
438 heads[name[len(R_HEADS):]] = id
439 elif name.startswith(R_PUB):
440 pubed[name[len(R_PUB):]] = id
441
442 ready = []
443 for branch, id in heads.iteritems():
444 if branch in pubed and pubed[branch] == id:
445 continue
446
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800447 rb = self.GetUploadableBranch(branch)
448 if rb:
449 ready.append(rb)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700450 return ready
451
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800452 def GetUploadableBranch(self, branch_name):
453 """Get a single uploadable branch, or None.
454 """
455 branch = self.GetBranch(branch_name)
456 base = branch.LocalMerge
457 if branch.LocalMerge:
458 rb = ReviewableBranch(self, branch, base)
459 if rb.commits:
460 return rb
461 return None
462
Joe Onorato2896a792008-11-17 16:56:36 -0500463 def UploadForReview(self, branch=None, replace_changes=None, people=([],[])):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700464 """Uploads the named branch for code review.
465 """
466 if branch is None:
467 branch = self.CurrentBranch
468 if branch is None:
469 raise GitError('not currently on a branch')
470
471 branch = self.GetBranch(branch)
472 if not branch.LocalMerge:
473 raise GitError('branch %s does not track a remote' % branch.name)
474 if not branch.remote.review:
475 raise GitError('remote %s has no review url' % branch.remote.name)
476
477 dest_branch = branch.merge
478 if not dest_branch.startswith(R_HEADS):
479 dest_branch = R_HEADS + dest_branch
480
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800481 if not branch.remote.projectname:
482 branch.remote.projectname = self.name
483 branch.remote.Save()
484
Shawn O. Pearce370e3fa2009-01-26 10:55:39 -0800485 if branch.remote.ReviewProtocol == 'ssh':
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800486 if dest_branch.startswith(R_HEADS):
487 dest_branch = dest_branch[len(R_HEADS):]
488
489 rp = ['gerrit receive-pack']
490 for e in people[0]:
491 rp.append('--reviewer=%s' % sq(e))
492 for e in people[1]:
493 rp.append('--cc=%s' % sq(e))
494
495 cmd = ['push']
496 cmd.append('--receive-pack=%s' % " ".join(rp))
497 cmd.append(branch.remote.SshReviewUrl(self.UserEmail))
498 cmd.append('%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch))
499 if replace_changes:
500 for change_id,commit_id in replace_changes.iteritems():
501 cmd.append('%s:refs/changes/%s/new' % (commit_id, change_id))
502 if GitCommand(self, cmd, bare = True).Wait() != 0:
503 raise UploadError('Upload failed')
504
505 else:
506 raise UploadError('Unsupported protocol %s' \
507 % branch.remote.review)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700508
509 msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
510 self.bare_git.UpdateRef(R_PUB + branch.name,
511 R_HEADS + branch.name,
512 message = msg)
513
514
515## Sync ##
516
517 def Sync_NetworkHalf(self):
518 """Perform only the network IO portion of the sync process.
519 Local working directory/branch state is not affected.
520 """
521 if not self.Exists:
522 print >>sys.stderr
523 print >>sys.stderr, 'Initializing project %s ...' % self.name
524 self._InitGitDir()
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800525
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700526 self._InitRemote()
527 for r in self.extraRemotes.values():
528 if not self._RemoteFetch(r.name):
529 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700530 if not self._RemoteFetch():
531 return False
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800532
533 if self.worktree:
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800534 self._InitMRef()
535 else:
536 self._InitMirrorHead()
537 try:
538 os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
539 except OSError:
540 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700541 return True
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800542
543 def PostRepoUpgrade(self):
544 self._InitHooks()
545
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700546 def _CopyFiles(self):
547 for file in self.copyfiles:
548 file._Copy()
549
550 def Sync_LocalHalf(self):
551 """Perform only the local IO portion of the sync process.
552 Network access is not required.
553
554 Return:
555 True: the sync was successful
556 False: the sync requires user input
557 """
558 self._InitWorkTree()
559 self.CleanPublishedCache()
560
561 rem = self.GetRemote(self.remote.name)
562 rev = rem.ToLocal(self.revision)
Shawn O. Pearce559b8462009-03-02 12:56:08 -0800563 try:
564 self.bare_git.rev_parse('--verify', '%s^0' % rev)
565 except GitError:
566 raise ManifestInvalidRevisionError(
567 'revision %s in %s not found' % (self.revision, self.name))
568
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700569 branch = self.CurrentBranch
570
571 if branch is None:
572 # Currently on a detached HEAD. The user is assumed to
573 # not have any local modifications worth worrying about.
574 #
575 lost = self._revlist(not_rev(rev), HEAD)
576 if lost:
577 _info("[%s] Discarding %d commits", self.name, len(lost))
578 try:
579 self._Checkout(rev, quiet=True)
580 except GitError:
581 return False
582 self._CopyFiles()
583 return True
584
585 branch = self.GetBranch(branch)
586 merge = branch.LocalMerge
587
588 if not merge:
589 # The current branch has no tracking configuration.
590 # Jump off it to a deatched HEAD.
591 #
592 _info("[%s] Leaving %s"
593 " (does not track any upstream)",
594 self.name,
595 branch.name)
596 try:
597 self._Checkout(rev, quiet=True)
598 except GitError:
599 return False
600 self._CopyFiles()
601 return True
602
603 upstream_gain = self._revlist(not_rev(HEAD), rev)
604 pub = self.WasPublished(branch.name)
605 if pub:
606 not_merged = self._revlist(not_rev(rev), pub)
607 if not_merged:
608 if upstream_gain:
609 # The user has published this branch and some of those
610 # commits are not yet merged upstream. We do not want
611 # to rewrite the published commits so we punt.
612 #
613 _info("[%s] Branch %s is published,"
614 " but is now %d commits behind.",
615 self.name, branch.name, len(upstream_gain))
616 _info("[%s] Consider merging or rebasing the"
617 " unpublished commits.", self.name)
618 return True
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700619 elif upstream_gain:
Shawn O. Pearcea54c5272008-10-30 11:03:00 -0700620 # We can fast-forward safely.
621 #
622 try:
623 self._FastForward(rev)
624 except GitError:
625 return False
626 self._CopyFiles()
627 return True
Shawn O. Pearce23d77812008-10-30 11:06:57 -0700628 else:
629 # Trivially no changes in the upstream.
630 #
631 return True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700632
633 if merge == rev:
634 try:
635 old_merge = self.bare_git.rev_parse('%s@{1}' % merge)
636 except GitError:
637 old_merge = merge
Shawn O. Pearce07346002008-10-21 07:09:27 -0700638 if old_merge == '0000000000000000000000000000000000000000' \
639 or old_merge == '':
640 old_merge = merge
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700641 else:
642 # The upstream switched on us. Time to cross our fingers
643 # and pray that the old upstream also wasn't in the habit
644 # of rebasing itself.
645 #
646 _info("[%s] Manifest switched from %s to %s",
647 self.name, merge, rev)
648 old_merge = merge
649
650 if rev == old_merge:
651 upstream_lost = []
652 else:
653 upstream_lost = self._revlist(not_rev(rev), old_merge)
654
655 if not upstream_lost and not upstream_gain:
656 # Trivially no changes caused by the upstream.
657 #
658 return True
659
660 if self.IsDirty(consider_untracked=False):
661 _warn('[%s] commit (or discard) uncommitted changes'
662 ' before sync', self.name)
663 return False
664
665 if upstream_lost:
666 # Upstream rebased. Not everything in HEAD
667 # may have been caused by the user.
668 #
669 _info("[%s] Discarding %d commits removed from upstream",
670 self.name, len(upstream_lost))
671
672 branch.remote = rem
673 branch.merge = self.revision
674 branch.Save()
675
676 my_changes = self._revlist(not_rev(old_merge), HEAD)
677 if my_changes:
678 try:
679 self._Rebase(upstream = old_merge, onto = rev)
680 except GitError:
681 return False
682 elif upstream_lost:
683 try:
684 self._ResetHard(rev)
685 except GitError:
686 return False
687 else:
688 try:
689 self._FastForward(rev)
690 except GitError:
691 return False
692
693 self._CopyFiles()
694 return True
695
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800696 def AddCopyFile(self, src, dest, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700697 # dest should already be an absolute path, but src is project relative
698 # make src an absolute path
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800699 abssrc = os.path.join(self.worktree, src)
700 self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700701
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700702 def DownloadPatchSet(self, change_id, patch_id):
703 """Download a single patch set of a single change to FETCH_HEAD.
704 """
705 remote = self.GetRemote(self.remote.name)
706
707 cmd = ['fetch', remote.name]
708 cmd.append('refs/changes/%2.2d/%d/%d' \
709 % (change_id % 100, change_id, patch_id))
710 cmd.extend(map(lambda x: str(x), remote.fetch))
711 if GitCommand(self, cmd, bare=True).Wait() != 0:
712 return None
713 return DownloadedChange(self,
714 remote.ToLocal(self.revision),
715 change_id,
716 patch_id,
717 self.bare_git.rev_parse('FETCH_HEAD'))
718
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700719
720## Branch Management ##
721
722 def StartBranch(self, name):
723 """Create a new branch off the manifest's revision.
724 """
725 branch = self.GetBranch(name)
726 branch.remote = self.GetRemote(self.remote.name)
727 branch.merge = self.revision
728
729 rev = branch.LocalMerge
730 cmd = ['checkout', '-b', branch.name, rev]
731 if GitCommand(self, cmd).Wait() == 0:
732 branch.Save()
733 else:
734 raise GitError('%s checkout %s ' % (self.name, rev))
735
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800736 def AbandonBranch(self, name):
737 """Destroy a local topic branch.
738 """
739 try:
740 tip_rev = self.bare_git.rev_parse(R_HEADS + name)
741 except GitError:
742 return
743
744 if self.CurrentBranch == name:
745 self._Checkout(
746 self.GetRemote(self.remote.name).ToLocal(self.revision),
747 quiet=True)
748
749 cmd = ['branch', '-D', name]
750 GitCommand(self, cmd, capture_stdout=True).Wait()
751
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700752 def PruneHeads(self):
753 """Prune any topic branches already merged into upstream.
754 """
755 cb = self.CurrentBranch
756 kill = []
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800757 left = self._allrefs
758 for name in left.keys():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700759 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
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700771 if kill:
772 try:
773 old = self.bare_git.GetHead()
774 except GitError:
775 old = 'refs/heads/please_never_use_this_as_a_branch_name'
776
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700777 try:
778 self.bare_git.DetachHead(rev)
779
780 b = ['branch', '-d']
781 b.extend(kill)
782 b = GitCommand(self, b, bare=True,
783 capture_stdout=True,
784 capture_stderr=True)
785 b.Wait()
786 finally:
787 self.bare_git.SetHead(old)
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800788 left = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700789
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800790 for branch in kill:
791 if (R_HEADS + branch) not in left:
792 self.CleanPublishedCache()
793 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700794
795 if cb and cb not in kill:
796 kill.append(cb)
Shawn O. Pearce7c6c64d2009-03-02 12:38:13 -0800797 kill.sort()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700798
799 kept = []
800 for branch in kill:
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800801 if (R_HEADS + branch) in left:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700802 branch = self.GetBranch(branch)
803 base = branch.LocalMerge
804 if not base:
805 base = rev
806 kept.append(ReviewableBranch(self, branch, base))
807 return kept
808
809
810## Direct Git Commands ##
811
812 def _RemoteFetch(self, name=None):
813 if not name:
814 name = self.remote.name
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800815 cmd = ['fetch']
816 if not self.worktree:
817 cmd.append('--update-head-ok')
818 cmd.append(name)
819 return GitCommand(self, cmd, bare = True).Wait() == 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700820
821 def _Checkout(self, rev, quiet=False):
822 cmd = ['checkout']
823 if quiet:
824 cmd.append('-q')
825 cmd.append(rev)
826 cmd.append('--')
827 if GitCommand(self, cmd).Wait() != 0:
828 if self._allrefs:
829 raise GitError('%s checkout %s ' % (self.name, rev))
830
831 def _ResetHard(self, rev, quiet=True):
832 cmd = ['reset', '--hard']
833 if quiet:
834 cmd.append('-q')
835 cmd.append(rev)
836 if GitCommand(self, cmd).Wait() != 0:
837 raise GitError('%s reset --hard %s ' % (self.name, rev))
838
839 def _Rebase(self, upstream, onto = None):
840 cmd = ['rebase', '-i']
841 if onto is not None:
842 cmd.extend(['--onto', onto])
843 cmd.append(upstream)
844 if GitCommand(self, cmd, disable_editor=True).Wait() != 0:
845 raise GitError('%s rebase %s ' % (self.name, upstream))
846
847 def _FastForward(self, head):
848 cmd = ['merge', head]
849 if GitCommand(self, cmd).Wait() != 0:
850 raise GitError('%s merge %s ' % (self.name, head))
851
852 def _InitGitDir(self):
853 if not os.path.exists(self.gitdir):
854 os.makedirs(self.gitdir)
855 self.bare_git.init()
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -0800856
857 if self.manifest.IsMirror:
858 self.config.SetString('core.bare', 'true')
859 else:
860 self.config.SetString('core.bare', None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700861
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):
Marcelo E. Magallon21f73852008-12-31 04:44:37 +0000928 dst = self.revision + '^0'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700929 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