blob: 1b5d9a67d032d9bf7e4aae8811063607a261c75c [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 -070029
Shawn O. Pearced237b692009-04-17 18:49:50 -070030from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070031
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -070032def _lwrite(path, content):
33 lock = '%s.lock' % path
34
35 fd = open(lock, 'wb')
36 try:
37 fd.write(content)
38 finally:
39 fd.close()
40
41 try:
42 os.rename(lock, path)
43 except OSError:
44 os.remove(lock)
45 raise
46
Shawn O. Pearce48244782009-04-16 08:25:57 -070047def _error(fmt, *args):
48 msg = fmt % args
49 print >>sys.stderr, 'error: %s' % msg
50
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070051def not_rev(r):
52 return '^' + r
53
Shawn O. Pearceb54a3922009-01-05 16:18:58 -080054def sq(r):
55 return "'" + r.replace("'", "'\''") + "'"
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080056
57hook_list = None
58def repo_hooks():
59 global hook_list
60 if hook_list is None:
61 d = os.path.abspath(os.path.dirname(__file__))
62 d = os.path.join(d , 'hooks')
63 hook_list = map(lambda x: os.path.join(d, x), os.listdir(d))
64 return hook_list
65
66def relpath(dst, src):
67 src = os.path.dirname(src)
68 top = os.path.commonprefix([dst, src])
69 if top.endswith('/'):
70 top = top[:-1]
71 else:
72 top = os.path.dirname(top)
73
74 tmp = src
75 rel = ''
76 while top != tmp:
77 rel += '../'
78 tmp = os.path.dirname(tmp)
79 return rel + dst[len(top) + 1:]
80
81
Shawn O. Pearce632768b2008-10-23 11:58:52 -070082class DownloadedChange(object):
83 _commit_cache = None
84
85 def __init__(self, project, base, change_id, ps_id, commit):
86 self.project = project
87 self.base = base
88 self.change_id = change_id
89 self.ps_id = ps_id
90 self.commit = commit
91
92 @property
93 def commits(self):
94 if self._commit_cache is None:
95 self._commit_cache = self.project.bare_git.rev_list(
96 '--abbrev=8',
97 '--abbrev-commit',
98 '--pretty=oneline',
99 '--reverse',
100 '--date-order',
101 not_rev(self.base),
102 self.commit,
103 '--')
104 return self._commit_cache
105
106
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700107class ReviewableBranch(object):
108 _commit_cache = None
109
110 def __init__(self, project, branch, base):
111 self.project = project
112 self.branch = branch
113 self.base = base
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800114 self.replace_changes = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700115
116 @property
117 def name(self):
118 return self.branch.name
119
120 @property
121 def commits(self):
122 if self._commit_cache is None:
123 self._commit_cache = self.project.bare_git.rev_list(
124 '--abbrev=8',
125 '--abbrev-commit',
126 '--pretty=oneline',
127 '--reverse',
128 '--date-order',
129 not_rev(self.base),
130 R_HEADS + self.name,
131 '--')
132 return self._commit_cache
133
134 @property
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800135 def unabbrev_commits(self):
136 r = dict()
137 for commit in self.project.bare_git.rev_list(
138 not_rev(self.base),
139 R_HEADS + self.name,
140 '--'):
141 r[commit[0:8]] = commit
142 return r
143
144 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700145 def date(self):
146 return self.project.bare_git.log(
147 '--pretty=format:%cd',
148 '-n', '1',
149 R_HEADS + self.name,
150 '--')
151
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700152 def UploadForReview(self, people, auto_topic=False):
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800153 self.project.UploadForReview(self.name,
Joe Onorato2896a792008-11-17 16:56:36 -0500154 self.replace_changes,
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700155 people,
156 auto_topic=auto_topic)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700157
Ficus Kirkpatrickbc7ef672009-05-04 12:45:11 -0700158 def GetPublishedRefs(self):
159 refs = {}
160 output = self.project.bare_git.ls_remote(
161 self.branch.remote.SshReviewUrl(self.project.UserEmail),
162 'refs/changes/*')
163 for line in output.split('\n'):
164 try:
165 (sha, ref) = line.split()
166 refs[sha] = ref
167 except ValueError:
168 pass
169
170 return refs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700171
172class StatusColoring(Coloring):
173 def __init__(self, config):
174 Coloring.__init__(self, config, 'status')
175 self.project = self.printer('header', attr = 'bold')
176 self.branch = self.printer('header', attr = 'bold')
177 self.nobranch = self.printer('nobranch', fg = 'red')
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700178 self.important = self.printer('important', fg = 'red')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700179
180 self.added = self.printer('added', fg = 'green')
181 self.changed = self.printer('changed', fg = 'red')
182 self.untracked = self.printer('untracked', fg = 'red')
183
184
185class DiffColoring(Coloring):
186 def __init__(self, config):
187 Coloring.__init__(self, config, 'diff')
188 self.project = self.printer('header', attr = 'bold')
189
190
191class _CopyFile:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800192 def __init__(self, src, dest, abssrc, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700193 self.src = src
194 self.dest = dest
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800195 self.abs_src = abssrc
196 self.abs_dest = absdest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700197
198 def _Copy(self):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800199 src = self.abs_src
200 dest = self.abs_dest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700201 # copy file if it does not exist or is out of date
202 if not os.path.exists(dest) or not filecmp.cmp(src, dest):
203 try:
204 # remove existing file first, since it might be read-only
205 if os.path.exists(dest):
206 os.remove(dest)
Matthew Buckett2daf6672009-07-11 09:43:47 -0400207 else:
208 dir = os.path.dirname(dest)
209 if not os.path.isdir(dir):
210 os.makedirs(dir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700211 shutil.copy(src, dest)
212 # make the file read-only
213 mode = os.stat(dest)[stat.ST_MODE]
214 mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
215 os.chmod(dest, mode)
216 except IOError:
Shawn O. Pearce48244782009-04-16 08:25:57 -0700217 _error('Cannot copy file %s to %s', src, dest)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700219class RemoteSpec(object):
220 def __init__(self,
221 name,
222 url = None,
223 review = None):
224 self.name = name
225 self.url = url
226 self.review = review
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700227
228class Project(object):
229 def __init__(self,
230 manifest,
231 name,
232 remote,
233 gitdir,
234 worktree,
235 relpath,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700236 revisionExpr,
237 revisionId):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700238 self.manifest = manifest
239 self.name = name
240 self.remote = remote
241 self.gitdir = gitdir
242 self.worktree = worktree
243 self.relpath = relpath
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700244 self.revisionExpr = revisionExpr
245
246 if revisionId is None \
247 and revisionExpr \
248 and IsId(revisionExpr):
249 self.revisionId = revisionExpr
250 else:
251 self.revisionId = revisionId
252
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700253 self.snapshots = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700254 self.copyfiles = []
255 self.config = GitConfig.ForRepository(
256 gitdir = self.gitdir,
257 defaults = self.manifest.globalConfig)
258
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800259 if self.worktree:
260 self.work_git = self._GitGetByExec(self, bare=False)
261 else:
262 self.work_git = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700263 self.bare_git = self._GitGetByExec(self, bare=True)
Shawn O. Pearced237b692009-04-17 18:49:50 -0700264 self.bare_ref = GitRefs(gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700265
266 @property
267 def Exists(self):
268 return os.path.isdir(self.gitdir)
269
270 @property
271 def CurrentBranch(self):
272 """Obtain the name of the currently checked out branch.
273 The branch name omits the 'refs/heads/' prefix.
274 None is returned if the project is on a detached HEAD.
275 """
Shawn O. Pearce5b23f242009-04-17 18:43:33 -0700276 b = self.work_git.GetHead()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700277 if b.startswith(R_HEADS):
278 return b[len(R_HEADS):]
279 return None
280
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700281 def IsRebaseInProgress(self):
282 w = self.worktree
283 g = os.path.join(w, '.git')
284 return os.path.exists(os.path.join(g, 'rebase-apply')) \
285 or os.path.exists(os.path.join(g, 'rebase-merge')) \
286 or os.path.exists(os.path.join(w, '.dotest'))
Julius Gustavsson0cb1b3f2010-06-17 17:55:02 +0200287
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700288 def IsDirty(self, consider_untracked=True):
289 """Is the working directory modified in some way?
290 """
291 self.work_git.update_index('-q',
292 '--unmerged',
293 '--ignore-missing',
294 '--refresh')
295 if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
296 return True
297 if self.work_git.DiffZ('diff-files'):
298 return True
299 if consider_untracked and self.work_git.LsOthers():
300 return True
301 return False
302
303 _userident_name = None
304 _userident_email = None
305
306 @property
307 def UserName(self):
308 """Obtain the user's personal name.
309 """
310 if self._userident_name is None:
311 self._LoadUserIdentity()
312 return self._userident_name
313
314 @property
315 def UserEmail(self):
316 """Obtain the user's email address. This is very likely
317 to be their Gerrit login.
318 """
319 if self._userident_email is None:
320 self._LoadUserIdentity()
321 return self._userident_email
322
323 def _LoadUserIdentity(self):
324 u = self.bare_git.var('GIT_COMMITTER_IDENT')
325 m = re.compile("^(.*) <([^>]*)> ").match(u)
326 if m:
327 self._userident_name = m.group(1)
328 self._userident_email = m.group(2)
329 else:
330 self._userident_name = ''
331 self._userident_email = ''
332
333 def GetRemote(self, name):
334 """Get the configuration for a single remote.
335 """
336 return self.config.GetRemote(name)
337
338 def GetBranch(self, name):
339 """Get the configuration for a single branch.
340 """
341 return self.config.GetBranch(name)
342
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700343 def GetBranches(self):
344 """Get all existing local branches.
345 """
346 current = self.CurrentBranch
Shawn O. Pearced237b692009-04-17 18:49:50 -0700347 all = self._allrefs
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700348 heads = {}
349 pubd = {}
350
351 for name, id in all.iteritems():
352 if name.startswith(R_HEADS):
353 name = name[len(R_HEADS):]
354 b = self.GetBranch(name)
355 b.current = name == current
356 b.published = None
357 b.revision = id
358 heads[name] = b
359
360 for name, id in all.iteritems():
361 if name.startswith(R_PUB):
362 name = name[len(R_PUB):]
363 b = heads.get(name)
364 if b:
365 b.published = id
366
367 return heads
368
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700369
370## Status Display ##
371
Anthony Newnamcc50bac2010-04-08 10:28:59 -0500372 def HasChanges(self):
373 """Returns true if there are uncommitted changes.
374 """
375 self.work_git.update_index('-q',
376 '--unmerged',
377 '--ignore-missing',
378 '--refresh')
379 if self.IsRebaseInProgress():
380 return True
381
382 if self.work_git.DiffZ('diff-index', '--cached', HEAD):
383 return True
384
385 if self.work_git.DiffZ('diff-files'):
386 return True
387
388 if self.work_git.LsOthers():
389 return True
390
391 return False
392
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700393 def PrintWorkTreeStatus(self):
394 """Prints the status of the repository to stdout.
395 """
396 if not os.path.isdir(self.worktree):
397 print ''
398 print 'project %s/' % self.relpath
399 print ' missing (run "repo sync")'
400 return
401
402 self.work_git.update_index('-q',
403 '--unmerged',
404 '--ignore-missing',
405 '--refresh')
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700406 rb = self.IsRebaseInProgress()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700407 di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
408 df = self.work_git.DiffZ('diff-files')
409 do = self.work_git.LsOthers()
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700410 if not rb and not di and not df and not do:
Shawn O. Pearce161f4452009-04-10 17:41:44 -0700411 return 'CLEAN'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700412
413 out = StatusColoring(self.config)
414 out.project('project %-40s', self.relpath + '/')
415
416 branch = self.CurrentBranch
417 if branch is None:
418 out.nobranch('(*** NO BRANCH ***)')
419 else:
420 out.branch('branch %s', branch)
421 out.nl()
422
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700423 if rb:
424 out.important('prior sync failed; rebase still in progress')
425 out.nl()
426
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700427 paths = list()
428 paths.extend(di.keys())
429 paths.extend(df.keys())
430 paths.extend(do)
431
432 paths = list(set(paths))
433 paths.sort()
434
435 for p in paths:
436 try: i = di[p]
437 except KeyError: i = None
438
439 try: f = df[p]
440 except KeyError: f = None
Julius Gustavsson0cb1b3f2010-06-17 17:55:02 +0200441
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700442 if i: i_status = i.status.upper()
443 else: i_status = '-'
444
445 if f: f_status = f.status.lower()
446 else: f_status = '-'
447
448 if i and i.src_path:
Shawn O. Pearcefe086752009-03-03 13:49:48 -0800449 line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700450 i.src_path, p, i.level)
451 else:
452 line = ' %s%s\t%s' % (i_status, f_status, p)
453
454 if i and not f:
455 out.added('%s', line)
456 elif (i and f) or (not i and f):
457 out.changed('%s', line)
458 elif not i and not f:
459 out.untracked('%s', line)
460 else:
461 out.write('%s', line)
462 out.nl()
Shawn O. Pearce161f4452009-04-10 17:41:44 -0700463 return 'DIRTY'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700464
465 def PrintWorkTreeDiff(self):
466 """Prints the status of the repository to stdout.
467 """
468 out = DiffColoring(self.config)
469 cmd = ['diff']
470 if out.is_on:
471 cmd.append('--color')
472 cmd.append(HEAD)
473 cmd.append('--')
474 p = GitCommand(self,
475 cmd,
476 capture_stdout = True,
477 capture_stderr = True)
478 has_diff = False
479 for line in p.process.stdout:
480 if not has_diff:
481 out.nl()
482 out.project('project %s/' % self.relpath)
483 out.nl()
484 has_diff = True
485 print line[:-1]
486 p.Wait()
487
488
489## Publish / Upload ##
490
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700491 def WasPublished(self, branch, all=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700492 """Was the branch published (uploaded) for code review?
493 If so, returns the SHA-1 hash of the last published
494 state for the branch.
495 """
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700496 key = R_PUB + branch
497 if all is None:
498 try:
499 return self.bare_git.rev_parse(key)
500 except GitError:
501 return None
502 else:
503 try:
504 return all[key]
505 except KeyError:
506 return None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700507
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700508 def CleanPublishedCache(self, all=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700509 """Prunes any stale published refs.
510 """
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700511 if all is None:
512 all = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700513 heads = set()
514 canrm = {}
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700515 for name, id in all.iteritems():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700516 if name.startswith(R_HEADS):
517 heads.add(name)
518 elif name.startswith(R_PUB):
519 canrm[name] = id
520
521 for name, id in canrm.iteritems():
522 n = name[len(R_PUB):]
523 if R_HEADS + n not in heads:
524 self.bare_git.DeleteRef(name, id)
525
526 def GetUploadableBranches(self):
527 """List any branches which can be uploaded for review.
528 """
529 heads = {}
530 pubed = {}
531
532 for name, id in self._allrefs.iteritems():
533 if name.startswith(R_HEADS):
534 heads[name[len(R_HEADS):]] = id
535 elif name.startswith(R_PUB):
536 pubed[name[len(R_PUB):]] = id
537
538 ready = []
539 for branch, id in heads.iteritems():
540 if branch in pubed and pubed[branch] == id:
541 continue
542
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800543 rb = self.GetUploadableBranch(branch)
544 if rb:
545 ready.append(rb)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700546 return ready
547
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800548 def GetUploadableBranch(self, branch_name):
549 """Get a single uploadable branch, or None.
550 """
551 branch = self.GetBranch(branch_name)
552 base = branch.LocalMerge
553 if branch.LocalMerge:
554 rb = ReviewableBranch(self, branch, base)
555 if rb.commits:
556 return rb
557 return None
558
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700559 def UploadForReview(self, branch=None,
560 replace_changes=None,
561 people=([],[]),
562 auto_topic=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700563 """Uploads the named branch for code review.
564 """
565 if branch is None:
566 branch = self.CurrentBranch
567 if branch is None:
568 raise GitError('not currently on a branch')
569
570 branch = self.GetBranch(branch)
571 if not branch.LocalMerge:
572 raise GitError('branch %s does not track a remote' % branch.name)
573 if not branch.remote.review:
574 raise GitError('remote %s has no review url' % branch.remote.name)
575
576 dest_branch = branch.merge
577 if not dest_branch.startswith(R_HEADS):
578 dest_branch = R_HEADS + dest_branch
579
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800580 if not branch.remote.projectname:
581 branch.remote.projectname = self.name
582 branch.remote.Save()
583
Shawn O. Pearce370e3fa2009-01-26 10:55:39 -0800584 if branch.remote.ReviewProtocol == 'ssh':
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800585 if dest_branch.startswith(R_HEADS):
586 dest_branch = dest_branch[len(R_HEADS):]
587
588 rp = ['gerrit receive-pack']
589 for e in people[0]:
590 rp.append('--reviewer=%s' % sq(e))
591 for e in people[1]:
592 rp.append('--cc=%s' % sq(e))
593
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700594 ref_spec = '%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch)
595 if auto_topic:
596 ref_spec = ref_spec + '/' + branch.name
597
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800598 cmd = ['push']
599 cmd.append('--receive-pack=%s' % " ".join(rp))
600 cmd.append(branch.remote.SshReviewUrl(self.UserEmail))
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700601 cmd.append(ref_spec)
602
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800603 if replace_changes:
604 for change_id,commit_id in replace_changes.iteritems():
605 cmd.append('%s:refs/changes/%s/new' % (commit_id, change_id))
606 if GitCommand(self, cmd, bare = True).Wait() != 0:
607 raise UploadError('Upload failed')
608
609 else:
610 raise UploadError('Unsupported protocol %s' \
611 % branch.remote.review)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700612
613 msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
614 self.bare_git.UpdateRef(R_PUB + branch.name,
615 R_HEADS + branch.name,
616 message = msg)
617
618
619## Sync ##
620
621 def Sync_NetworkHalf(self):
622 """Perform only the network IO portion of the sync process.
623 Local working directory/branch state is not affected.
624 """
625 if not self.Exists:
626 print >>sys.stderr
627 print >>sys.stderr, 'Initializing project %s ...' % self.name
628 self._InitGitDir()
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800629
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700630 self._InitRemote()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700631 if not self._RemoteFetch():
632 return False
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800633
Julius Gustavsson0cb1b3f2010-06-17 17:55:02 +0200634 #Check that the requested ref was found after fetch
635 #
636 try:
637 self.GetRevisionId()
638 except ManifestInvalidRevisionError:
639 # if the ref is a tag. We can try fetching
640 # the tag manually as a last resort
641 #
642 rev = self.revisionExpr
643 if rev.startswith(R_TAGS):
644 self._RemoteFetch(None, rev[len(R_TAGS):])
645
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800646 if self.worktree:
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800647 self._InitMRef()
648 else:
649 self._InitMirrorHead()
650 try:
651 os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
652 except OSError:
653 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700654 return True
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800655
656 def PostRepoUpgrade(self):
657 self._InitHooks()
658
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700659 def _CopyFiles(self):
660 for file in self.copyfiles:
661 file._Copy()
662
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700663 def GetRevisionId(self, all=None):
664 if self.revisionId:
665 return self.revisionId
666
667 rem = self.GetRemote(self.remote.name)
668 rev = rem.ToLocal(self.revisionExpr)
669
670 if all is not None and rev in all:
671 return all[rev]
672
673 try:
674 return self.bare_git.rev_parse('--verify', '%s^0' % rev)
675 except GitError:
676 raise ManifestInvalidRevisionError(
677 'revision %s in %s not found' % (self.revisionExpr,
678 self.name))
679
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700680 def Sync_LocalHalf(self, syncbuf):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700681 """Perform only the local IO portion of the sync process.
682 Network access is not required.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700683 """
684 self._InitWorkTree()
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700685 all = self.bare_ref.all
686 self.CleanPublishedCache(all)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700687
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700688 revid = self.GetRevisionId(all)
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700689 head = self.work_git.GetHead()
690 if head.startswith(R_HEADS):
691 branch = head[len(R_HEADS):]
692 try:
693 head = all[head]
694 except KeyError:
695 head = None
696 else:
697 branch = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700698
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700699 if branch is None or syncbuf.detach_head:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700700 # Currently on a detached HEAD. The user is assumed to
701 # not have any local modifications worth worrying about.
702 #
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700703 if self.IsRebaseInProgress():
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700704 syncbuf.fail(self, _PriorSyncFailedError())
705 return
706
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700707 if head == revid:
708 # No changes; don't do anything further.
709 #
710 return
711
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700712 lost = self._revlist(not_rev(revid), HEAD)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700713 if lost:
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700714 syncbuf.info(self, "discarding %d commits", len(lost))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700715 try:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700716 self._Checkout(revid, quiet=True)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700717 except GitError, e:
718 syncbuf.fail(self, e)
719 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700720 self._CopyFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700721 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700722
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700723 if head == revid:
724 # No changes; don't do anything further.
725 #
726 return
727
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700728 branch = self.GetBranch(branch)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700729
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700730 if not branch.LocalMerge:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700731 # The current branch has no tracking configuration.
732 # Jump off it to a deatched HEAD.
733 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700734 syncbuf.info(self,
735 "leaving %s; does not track upstream",
736 branch.name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700737 try:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700738 self._Checkout(revid, quiet=True)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700739 except GitError, e:
740 syncbuf.fail(self, e)
741 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700742 self._CopyFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700743 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700744
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700745 upstream_gain = self._revlist(not_rev(HEAD), revid)
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700746 pub = self.WasPublished(branch.name, all)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700747 if pub:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700748 not_merged = self._revlist(not_rev(revid), pub)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700749 if not_merged:
750 if upstream_gain:
751 # The user has published this branch and some of those
752 # commits are not yet merged upstream. We do not want
753 # to rewrite the published commits so we punt.
754 #
Daniel Sandler4c50dee2010-03-02 15:38:03 -0500755 syncbuf.fail(self,
756 "branch %s is published (but not merged) and is now %d commits behind"
757 % (branch.name, len(upstream_gain)))
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700758 return
Shawn O. Pearce05f66b62009-04-21 08:26:32 -0700759 elif pub == head:
760 # All published commits are merged, and thus we are a
761 # strict subset. We can fast-forward safely.
Shawn O. Pearcea54c5272008-10-30 11:03:00 -0700762 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700763 def _doff():
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700764 self._FastForward(revid)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700765 self._CopyFiles()
766 syncbuf.later1(self, _doff)
767 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700768
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -0700769 # Examine the local commits not in the remote. Find the
770 # last one attributed to this user, if any.
771 #
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700772 local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -0700773 last_mine = None
774 cnt_mine = 0
775 for commit in local_changes:
Shawn O. Pearceaa4982e2009-12-30 18:38:27 -0800776 commit_id, committer_email = commit.split(' ', 1)
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -0700777 if committer_email == self.UserEmail:
778 last_mine = commit_id
779 cnt_mine += 1
780
Shawn O. Pearceda88ff42009-06-03 11:09:12 -0700781 if not upstream_gain and cnt_mine == len(local_changes):
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700782 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700783
784 if self.IsDirty(consider_untracked=False):
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700785 syncbuf.fail(self, _DirtyError())
786 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700787
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700788 # If the upstream switched on us, warn the user.
789 #
790 if branch.merge != self.revisionExpr:
791 if branch.merge and self.revisionExpr:
792 syncbuf.info(self,
793 'manifest switched %s...%s',
794 branch.merge,
795 self.revisionExpr)
796 elif branch.merge:
797 syncbuf.info(self,
798 'manifest no longer tracks %s',
799 branch.merge)
800
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -0700801 if cnt_mine < len(local_changes):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700802 # Upstream rebased. Not everything in HEAD
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -0700803 # was created by this user.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700804 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700805 syncbuf.info(self,
806 "discarding %d commits removed from upstream",
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -0700807 len(local_changes) - cnt_mine)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700808
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700809 branch.remote = self.GetRemote(self.remote.name)
810 branch.merge = self.revisionExpr
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700811 branch.Save()
812
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -0700813 if cnt_mine > 0:
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700814 def _dorebase():
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700815 self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700816 self._CopyFiles()
817 syncbuf.later2(self, _dorebase)
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -0700818 elif local_changes:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700819 try:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700820 self._ResetHard(revid)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700821 self._CopyFiles()
822 except GitError, e:
823 syncbuf.fail(self, e)
824 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700825 else:
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700826 def _doff():
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700827 self._FastForward(revid)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700828 self._CopyFiles()
829 syncbuf.later1(self, _doff)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700830
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800831 def AddCopyFile(self, src, dest, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700832 # dest should already be an absolute path, but src is project relative
833 # make src an absolute path
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800834 abssrc = os.path.join(self.worktree, src)
835 self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700836
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700837 def DownloadPatchSet(self, change_id, patch_id):
838 """Download a single patch set of a single change to FETCH_HEAD.
839 """
840 remote = self.GetRemote(self.remote.name)
841
842 cmd = ['fetch', remote.name]
843 cmd.append('refs/changes/%2.2d/%d/%d' \
844 % (change_id % 100, change_id, patch_id))
845 cmd.extend(map(lambda x: str(x), remote.fetch))
846 if GitCommand(self, cmd, bare=True).Wait() != 0:
847 return None
848 return DownloadedChange(self,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700849 self.GetRevisionId(),
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700850 change_id,
851 patch_id,
852 self.bare_git.rev_parse('FETCH_HEAD'))
853
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700854
855## Branch Management ##
856
857 def StartBranch(self, name):
858 """Create a new branch off the manifest's revision.
859 """
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700860 head = self.work_git.GetHead()
861 if head == (R_HEADS + name):
862 return True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700863
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700864 all = self.bare_ref.all
865 if (R_HEADS + name) in all:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700866 return GitCommand(self,
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700867 ['checkout', name, '--'],
Shawn O. Pearce0f0dfa32009-04-18 14:53:39 -0700868 capture_stdout = True,
869 capture_stderr = True).Wait() == 0
Shawn O. Pearce0a389e92009-04-10 16:21:18 -0700870
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700871 branch = self.GetBranch(name)
872 branch.remote = self.GetRemote(self.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700873 branch.merge = self.revisionExpr
874 revid = self.GetRevisionId(all)
Shawn O. Pearce0a389e92009-04-10 16:21:18 -0700875
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700876 if head.startswith(R_HEADS):
877 try:
878 head = all[head]
879 except KeyError:
880 head = None
881
882 if revid and head and revid == head:
883 ref = os.path.join(self.gitdir, R_HEADS + name)
884 try:
885 os.makedirs(os.path.dirname(ref))
886 except OSError:
887 pass
888 _lwrite(ref, '%s\n' % revid)
889 _lwrite(os.path.join(self.worktree, '.git', HEAD),
890 'ref: %s%s\n' % (R_HEADS, name))
891 branch.Save()
892 return True
893
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700894 if GitCommand(self,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700895 ['checkout', '-b', branch.name, revid],
Shawn O. Pearce0f0dfa32009-04-18 14:53:39 -0700896 capture_stdout = True,
897 capture_stderr = True).Wait() == 0:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700898 branch.Save()
899 return True
900 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700901
Wink Saville02d79452009-04-10 13:01:24 -0700902 def CheckoutBranch(self, name):
903 """Checkout a local topic branch.
904 """
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700905 rev = R_HEADS + name
906 head = self.work_git.GetHead()
907 if head == rev:
908 # Already on the branch
909 #
910 return True
Wink Saville02d79452009-04-10 13:01:24 -0700911
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700912 all = self.bare_ref.all
Wink Saville02d79452009-04-10 13:01:24 -0700913 try:
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700914 revid = all[rev]
915 except KeyError:
916 # Branch does not exist in this project
917 #
918 return False
919
920 if head.startswith(R_HEADS):
921 try:
922 head = all[head]
923 except KeyError:
924 head = None
925
926 if head == revid:
927 # Same revision; just update HEAD to point to the new
928 # target branch, but otherwise take no other action.
929 #
930 _lwrite(os.path.join(self.worktree, '.git', HEAD),
931 'ref: %s%s\n' % (R_HEADS, name))
932 return True
Wink Saville02d79452009-04-10 13:01:24 -0700933
Shawn O. Pearce89e717d2009-04-18 15:04:41 -0700934 return GitCommand(self,
935 ['checkout', name, '--'],
936 capture_stdout = True,
937 capture_stderr = True).Wait() == 0
Wink Saville02d79452009-04-10 13:01:24 -0700938
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800939 def AbandonBranch(self, name):
940 """Destroy a local topic branch.
941 """
Shawn O. Pearce552ac892009-04-18 15:15:24 -0700942 rev = R_HEADS + name
943 all = self.bare_ref.all
944 if rev not in all:
945 # Doesn't exist; assume already abandoned.
946 #
947 return True
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800948
Shawn O. Pearce552ac892009-04-18 15:15:24 -0700949 head = self.work_git.GetHead()
950 if head == rev:
951 # We can't destroy the branch while we are sitting
952 # on it. Switch to a detached HEAD.
953 #
954 head = all[head]
955
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700956 revid = self.GetRevisionId(all)
957 if head == revid:
Shawn O. Pearce552ac892009-04-18 15:15:24 -0700958 _lwrite(os.path.join(self.worktree, '.git', HEAD),
959 '%s\n' % revid)
960 else:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700961 self._Checkout(revid, quiet=True)
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800962
Shawn O. Pearce552ac892009-04-18 15:15:24 -0700963 return GitCommand(self,
964 ['branch', '-D', name],
965 capture_stdout = True,
966 capture_stderr = True).Wait() == 0
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -0800967
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700968 def PruneHeads(self):
969 """Prune any topic branches already merged into upstream.
970 """
971 cb = self.CurrentBranch
972 kill = []
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -0800973 left = self._allrefs
974 for name in left.keys():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700975 if name.startswith(R_HEADS):
976 name = name[len(R_HEADS):]
977 if cb is None or name != cb:
978 kill.append(name)
979
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700980 rev = self.GetRevisionId(left)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700981 if cb is not None \
982 and not self._revlist(HEAD + '...' + rev) \
983 and not self.IsDirty(consider_untracked = False):
984 self.work_git.DetachHead(HEAD)
985 kill.append(cb)
986
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700987 if kill:
Shawn O. Pearce5b23f242009-04-17 18:43:33 -0700988 old = self.bare_git.GetHead()
989 if old is None:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700990 old = 'refs/heads/please_never_use_this_as_a_branch_name'
991
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700992 try:
993 self.bare_git.DetachHead(rev)
994
995 b = ['branch', '-d']
996 b.extend(kill)
997 b = GitCommand(self, b, bare=True,
998 capture_stdout=True,
999 capture_stderr=True)
1000 b.Wait()
1001 finally:
1002 self.bare_git.SetHead(old)
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001003 left = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001004
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001005 for branch in kill:
1006 if (R_HEADS + branch) not in left:
1007 self.CleanPublishedCache()
1008 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001009
1010 if cb and cb not in kill:
1011 kill.append(cb)
Shawn O. Pearce7c6c64d2009-03-02 12:38:13 -08001012 kill.sort()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001013
1014 kept = []
1015 for branch in kill:
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001016 if (R_HEADS + branch) in left:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001017 branch = self.GetBranch(branch)
1018 base = branch.LocalMerge
1019 if not base:
1020 base = rev
1021 kept.append(ReviewableBranch(self, branch, base))
1022 return kept
1023
1024
1025## Direct Git Commands ##
1026
Julius Gustavsson0cb1b3f2010-06-17 17:55:02 +02001027 def _RemoteFetch(self, name=None, tag=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001028 if not name:
1029 name = self.remote.name
Shawn O. Pearcefb231612009-04-10 18:53:46 -07001030
1031 ssh_proxy = False
1032 if self.GetRemote(name).PreConnectFetch():
1033 ssh_proxy = True
1034
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001035 cmd = ['fetch']
1036 if not self.worktree:
1037 cmd.append('--update-head-ok')
1038 cmd.append(name)
Julius Gustavsson0cb1b3f2010-06-17 17:55:02 +02001039 if tag is not None:
1040 cmd.append('tag')
1041 cmd.append(tag)
Shawn O. Pearcefb231612009-04-10 18:53:46 -07001042 return GitCommand(self,
1043 cmd,
1044 bare = True,
1045 ssh_proxy = ssh_proxy).Wait() == 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001046
1047 def _Checkout(self, rev, quiet=False):
1048 cmd = ['checkout']
1049 if quiet:
1050 cmd.append('-q')
1051 cmd.append(rev)
1052 cmd.append('--')
1053 if GitCommand(self, cmd).Wait() != 0:
1054 if self._allrefs:
1055 raise GitError('%s checkout %s ' % (self.name, rev))
1056
1057 def _ResetHard(self, rev, quiet=True):
1058 cmd = ['reset', '--hard']
1059 if quiet:
1060 cmd.append('-q')
1061 cmd.append(rev)
1062 if GitCommand(self, cmd).Wait() != 0:
1063 raise GitError('%s reset --hard %s ' % (self.name, rev))
1064
1065 def _Rebase(self, upstream, onto = None):
Shawn O. Pearce19a83d82009-04-16 08:14:26 -07001066 cmd = ['rebase']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001067 if onto is not None:
1068 cmd.extend(['--onto', onto])
1069 cmd.append(upstream)
Shawn O. Pearce19a83d82009-04-16 08:14:26 -07001070 if GitCommand(self, cmd).Wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001071 raise GitError('%s rebase %s ' % (self.name, upstream))
1072
1073 def _FastForward(self, head):
1074 cmd = ['merge', head]
1075 if GitCommand(self, cmd).Wait() != 0:
1076 raise GitError('%s merge %s ' % (self.name, head))
1077
1078 def _InitGitDir(self):
1079 if not os.path.exists(self.gitdir):
1080 os.makedirs(self.gitdir)
1081 self.bare_git.init()
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -08001082
1083 if self.manifest.IsMirror:
1084 self.config.SetString('core.bare', 'true')
1085 else:
1086 self.config.SetString('core.bare', None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001087
1088 hooks = self._gitdir_path('hooks')
Shawn O. Pearcede646812008-10-29 14:38:12 -07001089 try:
1090 to_rm = os.listdir(hooks)
1091 except OSError:
1092 to_rm = []
1093 for old_hook in to_rm:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001094 os.remove(os.path.join(hooks, old_hook))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001095 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001096
1097 m = self.manifest.manifestProject.config
1098 for key in ['user.name', 'user.email']:
1099 if m.Has(key, include_defaults = False):
1100 self.config.SetString(key, m.GetString(key))
1101
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001102 def _InitHooks(self):
1103 hooks = self._gitdir_path('hooks')
1104 if not os.path.exists(hooks):
1105 os.makedirs(hooks)
1106 for stock_hook in repo_hooks():
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07001107 name = os.path.basename(stock_hook)
1108
1109 if name in ('commit-msg') and not self.remote.review:
1110 # Don't install a Gerrit Code Review hook if this
1111 # project does not appear to use it for reviews.
1112 #
1113 continue
1114
1115 dst = os.path.join(hooks, name)
1116 if os.path.islink(dst):
1117 continue
1118 if os.path.exists(dst):
1119 if filecmp.cmp(stock_hook, dst, shallow=False):
1120 os.remove(dst)
1121 else:
1122 _error("%s: Not replacing %s hook", self.relpath, name)
1123 continue
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001124 try:
1125 os.symlink(relpath(stock_hook, dst), dst)
1126 except OSError, e:
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07001127 if e.errno == errno.EPERM:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001128 raise GitError('filesystem must support symlinks')
1129 else:
1130 raise
1131
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001132 def _InitRemote(self):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -07001133 if self.remote.url:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001134 remote = self.GetRemote(self.remote.name)
Shawn O. Pearced1f70d92009-05-19 14:58:02 -07001135 remote.url = self.remote.url
1136 remote.review = self.remote.review
1137 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001138
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001139 if self.worktree:
1140 remote.ResetFetch(mirror=False)
1141 else:
1142 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001143 remote.Save()
1144
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001145 def _InitMRef(self):
1146 if self.manifest.branch:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001147 self._InitAnyMRef(R_M + self.manifest.branch)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001148
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001149 def _InitMirrorHead(self):
Shawn O. Pearcefe200ee2009-06-01 15:28:21 -07001150 self._InitAnyMRef(HEAD)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001151
1152 def _InitAnyMRef(self, ref):
1153 cur = self.bare_ref.symref(ref)
1154
1155 if self.revisionId:
1156 if cur != '' or self.bare_ref.get(ref) != self.revisionId:
1157 msg = 'manifest set to %s' % self.revisionId
1158 dst = self.revisionId + '^0'
1159 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
1160 else:
1161 remote = self.GetRemote(self.remote.name)
1162 dst = remote.ToLocal(self.revisionExpr)
1163 if cur != dst:
1164 msg = 'manifest set to %s' % self.revisionExpr
1165 self.bare_git.symbolic_ref('-m', msg, ref, dst)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001166
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001167 def _InitWorkTree(self):
1168 dotgit = os.path.join(self.worktree, '.git')
1169 if not os.path.exists(dotgit):
1170 os.makedirs(dotgit)
1171
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001172 for name in ['config',
1173 'description',
1174 'hooks',
1175 'info',
1176 'logs',
1177 'objects',
1178 'packed-refs',
1179 'refs',
1180 'rr-cache',
1181 'svn']:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08001182 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001183 src = os.path.join(self.gitdir, name)
1184 dst = os.path.join(dotgit, name)
Nico Sallembiend63060f2010-01-20 10:27:50 -08001185 if os.path.islink(dst) or not os.path.exists(dst):
1186 os.symlink(relpath(src, dst), dst)
1187 else:
1188 raise GitError('cannot overwrite a local work tree')
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08001189 except OSError, e:
1190 if e.errno == errno.EPERM:
1191 raise GitError('filesystem must support symlinks')
1192 else:
1193 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001194
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001195 _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001196
1197 cmd = ['read-tree', '--reset', '-u']
1198 cmd.append('-v')
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001199 cmd.append(HEAD)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001200 if GitCommand(self, cmd).Wait() != 0:
1201 raise GitError("cannot initialize work tree")
Shawn O. Pearce93609662009-04-21 10:50:33 -07001202 self._CopyFiles()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001203
1204 def _gitdir_path(self, path):
1205 return os.path.join(self.gitdir, path)
1206
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001207 def _revlist(self, *args, **kw):
1208 a = []
1209 a.extend(args)
1210 a.append('--')
1211 return self.work_git.rev_list(*a, **kw)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001212
1213 @property
1214 def _allrefs(self):
Shawn O. Pearced237b692009-04-17 18:49:50 -07001215 return self.bare_ref.all
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001216
1217 class _GitGetByExec(object):
1218 def __init__(self, project, bare):
1219 self._project = project
1220 self._bare = bare
1221
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001222 def LsOthers(self):
1223 p = GitCommand(self._project,
1224 ['ls-files',
1225 '-z',
1226 '--others',
1227 '--exclude-standard'],
1228 bare = False,
1229 capture_stdout = True,
1230 capture_stderr = True)
1231 if p.Wait() == 0:
1232 out = p.stdout
1233 if out:
1234 return out[:-1].split("\0")
1235 return []
1236
1237 def DiffZ(self, name, *args):
1238 cmd = [name]
1239 cmd.append('-z')
1240 cmd.extend(args)
1241 p = GitCommand(self._project,
1242 cmd,
1243 bare = False,
1244 capture_stdout = True,
1245 capture_stderr = True)
1246 try:
1247 out = p.process.stdout.read()
1248 r = {}
1249 if out:
1250 out = iter(out[:-1].split('\0'))
1251 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07001252 try:
1253 info = out.next()
1254 path = out.next()
1255 except StopIteration:
1256 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001257
1258 class _Info(object):
1259 def __init__(self, path, omode, nmode, oid, nid, state):
1260 self.path = path
1261 self.src_path = None
1262 self.old_mode = omode
1263 self.new_mode = nmode
1264 self.old_id = oid
1265 self.new_id = nid
1266
1267 if len(state) == 1:
1268 self.status = state
1269 self.level = None
1270 else:
1271 self.status = state[:1]
1272 self.level = state[1:]
1273 while self.level.startswith('0'):
1274 self.level = self.level[1:]
1275
1276 info = info[1:].split(' ')
1277 info =_Info(path, *info)
1278 if info.status in ('R', 'C'):
1279 info.src_path = info.path
1280 info.path = out.next()
1281 r[info.path] = info
1282 return r
1283 finally:
1284 p.Wait()
1285
1286 def GetHead(self):
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07001287 if self._bare:
1288 path = os.path.join(self._project.gitdir, HEAD)
1289 else:
1290 path = os.path.join(self._project.worktree, '.git', HEAD)
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -07001291 fd = open(path, 'rb')
1292 try:
1293 line = fd.read()
1294 finally:
1295 fd.close()
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07001296 if line.startswith('ref: '):
1297 return line[5:-1]
1298 return line[:-1]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001299
1300 def SetHead(self, ref, message=None):
1301 cmdv = []
1302 if message is not None:
1303 cmdv.extend(['-m', message])
1304 cmdv.append(HEAD)
1305 cmdv.append(ref)
1306 self.symbolic_ref(*cmdv)
1307
1308 def DetachHead(self, new, message=None):
1309 cmdv = ['--no-deref']
1310 if message is not None:
1311 cmdv.extend(['-m', message])
1312 cmdv.append(HEAD)
1313 cmdv.append(new)
1314 self.update_ref(*cmdv)
1315
1316 def UpdateRef(self, name, new, old=None,
1317 message=None,
1318 detach=False):
1319 cmdv = []
1320 if message is not None:
1321 cmdv.extend(['-m', message])
1322 if detach:
1323 cmdv.append('--no-deref')
1324 cmdv.append(name)
1325 cmdv.append(new)
1326 if old is not None:
1327 cmdv.append(old)
1328 self.update_ref(*cmdv)
1329
1330 def DeleteRef(self, name, old=None):
1331 if not old:
1332 old = self.rev_parse(name)
1333 self.update_ref('-d', name, old)
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001334 self._project.bare_ref.deleted(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001335
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001336 def rev_list(self, *args, **kw):
1337 if 'format' in kw:
1338 cmdv = ['log', '--pretty=format:%s' % kw['format']]
1339 else:
1340 cmdv = ['rev-list']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001341 cmdv.extend(args)
1342 p = GitCommand(self._project,
1343 cmdv,
1344 bare = self._bare,
1345 capture_stdout = True,
1346 capture_stderr = True)
1347 r = []
1348 for line in p.process.stdout:
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001349 if line[-1] == '\n':
1350 line = line[:-1]
1351 r.append(line)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001352 if p.Wait() != 0:
1353 raise GitError('%s rev-list %s: %s' % (
1354 self._project.name,
1355 str(args),
1356 p.stderr))
1357 return r
1358
1359 def __getattr__(self, name):
1360 name = name.replace('_', '-')
1361 def runner(*args):
1362 cmdv = [name]
1363 cmdv.extend(args)
1364 p = GitCommand(self._project,
1365 cmdv,
1366 bare = self._bare,
1367 capture_stdout = True,
1368 capture_stderr = True)
1369 if p.Wait() != 0:
1370 raise GitError('%s %s: %s' % (
1371 self._project.name,
1372 name,
1373 p.stderr))
1374 r = p.stdout
1375 if r.endswith('\n') and r.index('\n') == len(r) - 1:
1376 return r[:-1]
1377 return r
1378 return runner
1379
1380
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001381class _PriorSyncFailedError(Exception):
1382 def __str__(self):
1383 return 'prior sync failed; rebase still in progress'
1384
1385class _DirtyError(Exception):
1386 def __str__(self):
1387 return 'contains uncommitted changes'
1388
1389class _InfoMessage(object):
1390 def __init__(self, project, text):
1391 self.project = project
1392 self.text = text
1393
1394 def Print(self, syncbuf):
1395 syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
1396 syncbuf.out.nl()
1397
1398class _Failure(object):
1399 def __init__(self, project, why):
1400 self.project = project
1401 self.why = why
1402
1403 def Print(self, syncbuf):
1404 syncbuf.out.fail('error: %s/: %s',
1405 self.project.relpath,
1406 str(self.why))
1407 syncbuf.out.nl()
1408
1409class _Later(object):
1410 def __init__(self, project, action):
1411 self.project = project
1412 self.action = action
1413
1414 def Run(self, syncbuf):
1415 out = syncbuf.out
1416 out.project('project %s/', self.project.relpath)
1417 out.nl()
1418 try:
1419 self.action()
1420 out.nl()
1421 return True
1422 except GitError, e:
1423 out.nl()
1424 return False
1425
1426class _SyncColoring(Coloring):
1427 def __init__(self, config):
1428 Coloring.__init__(self, config, 'reposync')
1429 self.project = self.printer('header', attr = 'bold')
1430 self.info = self.printer('info')
1431 self.fail = self.printer('fail', fg='red')
1432
1433class SyncBuffer(object):
1434 def __init__(self, config, detach_head=False):
1435 self._messages = []
1436 self._failures = []
1437 self._later_queue1 = []
1438 self._later_queue2 = []
1439
1440 self.out = _SyncColoring(config)
1441 self.out.redirect(sys.stderr)
1442
1443 self.detach_head = detach_head
1444 self.clean = True
1445
1446 def info(self, project, fmt, *args):
1447 self._messages.append(_InfoMessage(project, fmt % args))
1448
1449 def fail(self, project, err=None):
1450 self._failures.append(_Failure(project, err))
1451 self.clean = False
1452
1453 def later1(self, project, what):
1454 self._later_queue1.append(_Later(project, what))
1455
1456 def later2(self, project, what):
1457 self._later_queue2.append(_Later(project, what))
1458
1459 def Finish(self):
1460 self._PrintMessages()
1461 self._RunLater()
1462 self._PrintMessages()
1463 return self.clean
1464
1465 def _RunLater(self):
1466 for q in ['_later_queue1', '_later_queue2']:
1467 if not self._RunQueue(q):
1468 return
1469
1470 def _RunQueue(self, queue):
1471 for m in getattr(self, queue):
1472 if not m.Run(self):
1473 self.clean = False
1474 return False
1475 setattr(self, queue, [])
1476 return True
1477
1478 def _PrintMessages(self):
1479 for m in self._messages:
1480 m.Print(self)
1481 for m in self._failures:
1482 m.Print(self)
1483
1484 self._messages = []
1485 self._failures = []
1486
1487
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001488class MetaProject(Project):
1489 """A special project housed under .repo.
1490 """
1491 def __init__(self, manifest, name, gitdir, worktree):
1492 repodir = manifest.repodir
1493 Project.__init__(self,
1494 manifest = manifest,
1495 name = name,
1496 gitdir = gitdir,
1497 worktree = worktree,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -07001498 remote = RemoteSpec('origin'),
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001499 relpath = '.repo/%s' % name,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001500 revisionExpr = 'refs/heads/master',
1501 revisionId = None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001502
1503 def PreSync(self):
1504 if self.Exists:
1505 cb = self.CurrentBranch
1506 if cb:
1507 base = self.GetBranch(cb).merge
1508 if base:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001509 self.revisionExpr = base
1510 self.revisionId = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001511
1512 @property
Shawn O. Pearcef6906872009-04-18 10:49:00 -07001513 def LastFetch(self):
1514 try:
1515 fh = os.path.join(self.gitdir, 'FETCH_HEAD')
1516 return os.path.getmtime(fh)
1517 except OSError:
1518 return 0
1519
1520 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001521 def HasChanges(self):
1522 """Has the remote received new commits not yet checked out?
1523 """
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001524 if not self.remote or not self.revisionExpr:
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07001525 return False
1526
1527 all = self.bare_ref.all
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001528 revid = self.GetRevisionId(all)
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07001529 head = self.work_git.GetHead()
1530 if head.startswith(R_HEADS):
1531 try:
1532 head = all[head]
1533 except KeyError:
1534 head = None
1535
1536 if revid == head:
1537 return False
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001538 elif self._revlist(not_rev(HEAD), revid):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001539 return True
1540 return False