blob: 679dccc1bfffadda704aa0890fa5b27ed42fb53b [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
Sarah Owenscecd1d82012-11-01 22:59:27 -070015from __future__ import print_function
Doug Anderson37282b42011-03-04 11:54:18 -080016import traceback
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -080017import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070018import filecmp
19import os
Shawn O. Pearcec325dc32011-10-03 08:30:24 -070020import random
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070021import re
22import shutil
23import stat
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -070024import subprocess
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070025import sys
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +080026import tempfile
Shawn O. Pearcec325dc32011-10-03 08:30:24 -070027import time
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -070028
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070029from color import Coloring
Dave Borowitzb42b4742012-10-31 12:27:27 -070030from git_command import GitCommand, git_require
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -070031from git_config import GitConfig, IsId, GetSchemeFromUrl, ID_RE
David Pursehousee15c65a2012-08-22 10:46:11 +090032from error import GitError, HookError, UploadError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080033from error import ManifestInvalidRevisionError
Conley Owens75ee0572012-11-15 17:33:11 -080034from error import NoManifestException
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -070035from trace import IsTrace, Trace
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070036
Shawn O. Pearced237b692009-04-17 18:49:50 -070037from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070038
David Pursehouse59bbb582013-05-17 10:49:33 +090039from pyversion import is_python3
40if not is_python3():
41 # pylint:disable=W0622
Chirayu Desai217ea7d2013-03-01 19:14:38 +053042 input = raw_input
David Pursehouse59bbb582013-05-17 10:49:33 +090043 # pylint:enable=W0622
Chirayu Desai217ea7d2013-03-01 19:14:38 +053044
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -070045def _lwrite(path, content):
46 lock = '%s.lock' % path
47
48 fd = open(lock, 'wb')
49 try:
50 fd.write(content)
51 finally:
52 fd.close()
53
54 try:
55 os.rename(lock, path)
56 except OSError:
57 os.remove(lock)
58 raise
59
Shawn O. Pearce48244782009-04-16 08:25:57 -070060def _error(fmt, *args):
61 msg = fmt % args
Sarah Owenscecd1d82012-11-01 22:59:27 -070062 print('error: %s' % msg, file=sys.stderr)
Shawn O. Pearce48244782009-04-16 08:25:57 -070063
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070064def not_rev(r):
65 return '^' + r
66
Shawn O. Pearceb54a3922009-01-05 16:18:58 -080067def sq(r):
68 return "'" + r.replace("'", "'\''") + "'"
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080069
Doug Anderson8ced8642011-01-10 14:16:30 -080070_project_hook_list = None
71def _ProjectHooks():
72 """List the hooks present in the 'hooks' directory.
73
74 These hooks are project hooks and are copied to the '.git/hooks' directory
75 of all subprojects.
76
77 This function caches the list of hooks (based on the contents of the
78 'repo/hooks' directory) on the first call.
79
80 Returns:
81 A list of absolute paths to all of the files in the hooks directory.
82 """
83 global _project_hook_list
84 if _project_hook_list is None:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080085 d = os.path.abspath(os.path.dirname(__file__))
86 d = os.path.join(d , 'hooks')
Chirayu Desai217ea7d2013-03-01 19:14:38 +053087 _project_hook_list = [os.path.join(d, x) for x in os.listdir(d)]
Doug Anderson8ced8642011-01-10 14:16:30 -080088 return _project_hook_list
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080089
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080090
Shawn O. Pearce632768b2008-10-23 11:58:52 -070091class DownloadedChange(object):
92 _commit_cache = None
93
94 def __init__(self, project, base, change_id, ps_id, commit):
95 self.project = project
96 self.base = base
97 self.change_id = change_id
98 self.ps_id = ps_id
99 self.commit = commit
100
101 @property
102 def commits(self):
103 if self._commit_cache is None:
104 self._commit_cache = self.project.bare_git.rev_list(
105 '--abbrev=8',
106 '--abbrev-commit',
107 '--pretty=oneline',
108 '--reverse',
109 '--date-order',
110 not_rev(self.base),
111 self.commit,
112 '--')
113 return self._commit_cache
114
115
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700116class ReviewableBranch(object):
117 _commit_cache = None
118
119 def __init__(self, project, branch, base):
120 self.project = project
121 self.branch = branch
122 self.base = base
123
124 @property
125 def name(self):
126 return self.branch.name
127
128 @property
129 def commits(self):
130 if self._commit_cache is None:
131 self._commit_cache = self.project.bare_git.rev_list(
132 '--abbrev=8',
133 '--abbrev-commit',
134 '--pretty=oneline',
135 '--reverse',
136 '--date-order',
137 not_rev(self.base),
138 R_HEADS + self.name,
139 '--')
140 return self._commit_cache
141
142 @property
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800143 def unabbrev_commits(self):
144 r = dict()
145 for commit in self.project.bare_git.rev_list(
146 not_rev(self.base),
147 R_HEADS + self.name,
148 '--'):
149 r[commit[0:8]] = commit
150 return r
151
152 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700153 def date(self):
154 return self.project.bare_git.log(
155 '--pretty=format:%cd',
156 '-n', '1',
157 R_HEADS + self.name,
158 '--')
159
Bryan Jacobsf609f912013-05-06 13:36:24 -0400160 def UploadForReview(self, people, auto_topic=False, draft=False, dest_branch=None):
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800161 self.project.UploadForReview(self.name,
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700162 people,
Brian Harring435370c2012-07-28 15:37:04 -0700163 auto_topic=auto_topic,
Bryan Jacobsf609f912013-05-06 13:36:24 -0400164 draft=draft,
165 dest_branch=dest_branch)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700166
Ficus Kirkpatrickbc7ef672009-05-04 12:45:11 -0700167 def GetPublishedRefs(self):
168 refs = {}
169 output = self.project.bare_git.ls_remote(
170 self.branch.remote.SshReviewUrl(self.project.UserEmail),
171 'refs/changes/*')
172 for line in output.split('\n'):
173 try:
174 (sha, ref) = line.split()
175 refs[sha] = ref
176 except ValueError:
177 pass
178
179 return refs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700180
181class StatusColoring(Coloring):
182 def __init__(self, config):
183 Coloring.__init__(self, config, 'status')
184 self.project = self.printer('header', attr = 'bold')
185 self.branch = self.printer('header', attr = 'bold')
186 self.nobranch = self.printer('nobranch', fg = 'red')
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700187 self.important = self.printer('important', fg = 'red')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700188
189 self.added = self.printer('added', fg = 'green')
190 self.changed = self.printer('changed', fg = 'red')
191 self.untracked = self.printer('untracked', fg = 'red')
192
193
194class DiffColoring(Coloring):
195 def __init__(self, config):
196 Coloring.__init__(self, config, 'diff')
197 self.project = self.printer('header', attr = 'bold')
198
James W. Mills24c13082012-04-12 15:04:13 -0500199class _Annotation:
200 def __init__(self, name, value, keep):
201 self.name = name
202 self.value = value
203 self.keep = keep
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700204
205class _CopyFile:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800206 def __init__(self, src, dest, abssrc, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700207 self.src = src
208 self.dest = dest
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800209 self.abs_src = abssrc
210 self.abs_dest = absdest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700211
212 def _Copy(self):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800213 src = self.abs_src
214 dest = self.abs_dest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700215 # copy file if it does not exist or is out of date
216 if not os.path.exists(dest) or not filecmp.cmp(src, dest):
217 try:
218 # remove existing file first, since it might be read-only
219 if os.path.exists(dest):
220 os.remove(dest)
Matthew Buckett2daf6672009-07-11 09:43:47 -0400221 else:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200222 dest_dir = os.path.dirname(dest)
223 if not os.path.isdir(dest_dir):
224 os.makedirs(dest_dir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700225 shutil.copy(src, dest)
226 # make the file read-only
227 mode = os.stat(dest)[stat.ST_MODE]
228 mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
229 os.chmod(dest, mode)
230 except IOError:
Shawn O. Pearce48244782009-04-16 08:25:57 -0700231 _error('Cannot copy file %s to %s', src, dest)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700232
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700233class RemoteSpec(object):
234 def __init__(self,
235 name,
236 url = None,
237 review = None):
238 self.name = name
239 self.url = url
240 self.review = review
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700241
Doug Anderson37282b42011-03-04 11:54:18 -0800242class RepoHook(object):
243 """A RepoHook contains information about a script to run as a hook.
244
245 Hooks are used to run a python script before running an upload (for instance,
246 to run presubmit checks). Eventually, we may have hooks for other actions.
247
248 This shouldn't be confused with files in the 'repo/hooks' directory. Those
249 files are copied into each '.git/hooks' folder for each project. Repo-level
250 hooks are associated instead with repo actions.
251
252 Hooks are always python. When a hook is run, we will load the hook into the
253 interpreter and execute its main() function.
254 """
255 def __init__(self,
256 hook_type,
257 hooks_project,
258 topdir,
259 abort_if_user_denies=False):
260 """RepoHook constructor.
261
262 Params:
263 hook_type: A string representing the type of hook. This is also used
264 to figure out the name of the file containing the hook. For
265 example: 'pre-upload'.
266 hooks_project: The project containing the repo hooks. If you have a
267 manifest, this is manifest.repo_hooks_project. OK if this is None,
268 which will make the hook a no-op.
269 topdir: Repo's top directory (the one containing the .repo directory).
270 Scripts will run with CWD as this directory. If you have a manifest,
271 this is manifest.topdir
272 abort_if_user_denies: If True, we'll throw a HookError() if the user
273 doesn't allow us to run the hook.
274 """
275 self._hook_type = hook_type
276 self._hooks_project = hooks_project
277 self._topdir = topdir
278 self._abort_if_user_denies = abort_if_user_denies
279
280 # Store the full path to the script for convenience.
281 if self._hooks_project:
282 self._script_fullpath = os.path.join(self._hooks_project.worktree,
283 self._hook_type + '.py')
284 else:
285 self._script_fullpath = None
286
287 def _GetHash(self):
288 """Return a hash of the contents of the hooks directory.
289
290 We'll just use git to do this. This hash has the property that if anything
291 changes in the directory we will return a different has.
292
293 SECURITY CONSIDERATION:
294 This hash only represents the contents of files in the hook directory, not
295 any other files imported or called by hooks. Changes to imported files
296 can change the script behavior without affecting the hash.
297
298 Returns:
299 A string representing the hash. This will always be ASCII so that it can
300 be printed to the user easily.
301 """
302 assert self._hooks_project, "Must have hooks to calculate their hash."
303
304 # We will use the work_git object rather than just calling GetRevisionId().
305 # That gives us a hash of the latest checked in version of the files that
306 # the user will actually be executing. Specifically, GetRevisionId()
307 # doesn't appear to change even if a user checks out a different version
308 # of the hooks repo (via git checkout) nor if a user commits their own revs.
309 #
310 # NOTE: Local (non-committed) changes will not be factored into this hash.
311 # I think this is OK, since we're really only worried about warning the user
312 # about upstream changes.
313 return self._hooks_project.work_git.rev_parse('HEAD')
314
315 def _GetMustVerb(self):
316 """Return 'must' if the hook is required; 'should' if not."""
317 if self._abort_if_user_denies:
318 return 'must'
319 else:
320 return 'should'
321
322 def _CheckForHookApproval(self):
323 """Check to see whether this hook has been approved.
324
325 We'll look at the hash of all of the hooks. If this matches the hash that
326 the user last approved, we're done. If it doesn't, we'll ask the user
327 about approval.
328
329 Note that we ask permission for each individual hook even though we use
330 the hash of all hooks when detecting changes. We'd like the user to be
331 able to approve / deny each hook individually. We only use the hash of all
332 hooks because there is no other easy way to detect changes to local imports.
333
334 Returns:
335 True if this hook is approved to run; False otherwise.
336
337 Raises:
338 HookError: Raised if the user doesn't approve and abort_if_user_denies
339 was passed to the consturctor.
340 """
Doug Anderson37282b42011-03-04 11:54:18 -0800341 hooks_config = self._hooks_project.config
342 git_approval_key = 'repo.hooks.%s.approvedhash' % self._hook_type
343
344 # Get the last hash that the user approved for this hook; may be None.
345 old_hash = hooks_config.GetString(git_approval_key)
346
347 # Get the current hash so we can tell if scripts changed since approval.
348 new_hash = self._GetHash()
349
350 if old_hash is not None:
351 # User previously approved hook and asked not to be prompted again.
352 if new_hash == old_hash:
353 # Approval matched. We're done.
354 return True
355 else:
356 # Give the user a reason why we're prompting, since they last told
357 # us to "never ask again".
358 prompt = 'WARNING: Scripts have changed since %s was allowed.\n\n' % (
359 self._hook_type)
360 else:
361 prompt = ''
362
363 # Prompt the user if we're not on a tty; on a tty we'll assume "no".
364 if sys.stdout.isatty():
365 prompt += ('Repo %s run the script:\n'
366 ' %s\n'
367 '\n'
368 'Do you want to allow this script to run '
369 '(yes/yes-never-ask-again/NO)? ') % (
370 self._GetMustVerb(), self._script_fullpath)
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530371 response = input(prompt).lower()
David Pursehouse98ffba12012-11-14 11:18:00 +0900372 print()
Doug Anderson37282b42011-03-04 11:54:18 -0800373
374 # User is doing a one-time approval.
375 if response in ('y', 'yes'):
376 return True
377 elif response == 'yes-never-ask-again':
378 hooks_config.SetString(git_approval_key, new_hash)
379 return True
380
381 # For anything else, we'll assume no approval.
382 if self._abort_if_user_denies:
383 raise HookError('You must allow the %s hook or use --no-verify.' %
384 self._hook_type)
385
386 return False
387
388 def _ExecuteHook(self, **kwargs):
389 """Actually execute the given hook.
390
391 This will run the hook's 'main' function in our python interpreter.
392
393 Args:
394 kwargs: Keyword arguments to pass to the hook. These are often specific
395 to the hook type. For instance, pre-upload hooks will contain
396 a project_list.
397 """
398 # Keep sys.path and CWD stashed away so that we can always restore them
399 # upon function exit.
400 orig_path = os.getcwd()
401 orig_syspath = sys.path
402
403 try:
404 # Always run hooks with CWD as topdir.
405 os.chdir(self._topdir)
406
407 # Put the hook dir as the first item of sys.path so hooks can do
408 # relative imports. We want to replace the repo dir as [0] so
409 # hooks can't import repo files.
410 sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
411
412 # Exec, storing global context in the context dict. We catch exceptions
413 # and convert to a HookError w/ just the failing traceback.
414 context = {}
415 try:
416 execfile(self._script_fullpath, context)
417 except Exception:
418 raise HookError('%s\nFailed to import %s hook; see traceback above.' % (
419 traceback.format_exc(), self._hook_type))
420
421 # Running the script should have defined a main() function.
422 if 'main' not in context:
423 raise HookError('Missing main() in: "%s"' % self._script_fullpath)
424
425
426 # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
427 # We don't actually want hooks to define their main with this argument--
428 # it's there to remind them that their hook should always take **kwargs.
429 # For instance, a pre-upload hook should be defined like:
430 # def main(project_list, **kwargs):
431 #
432 # This allows us to later expand the API without breaking old hooks.
433 kwargs = kwargs.copy()
434 kwargs['hook_should_take_kwargs'] = True
435
436 # Call the main function in the hook. If the hook should cause the
437 # build to fail, it will raise an Exception. We'll catch that convert
438 # to a HookError w/ just the failing traceback.
439 try:
440 context['main'](**kwargs)
441 except Exception:
442 raise HookError('%s\nFailed to run main() for %s hook; see traceback '
443 'above.' % (
444 traceback.format_exc(), self._hook_type))
445 finally:
446 # Restore sys.path and CWD.
447 sys.path = orig_syspath
448 os.chdir(orig_path)
449
450 def Run(self, user_allows_all_hooks, **kwargs):
451 """Run the hook.
452
453 If the hook doesn't exist (because there is no hooks project or because
454 this particular hook is not enabled), this is a no-op.
455
456 Args:
457 user_allows_all_hooks: If True, we will never prompt about running the
458 hook--we'll just assume it's OK to run it.
459 kwargs: Keyword arguments to pass to the hook. These are often specific
460 to the hook type. For instance, pre-upload hooks will contain
461 a project_list.
462
463 Raises:
464 HookError: If there was a problem finding the hook or the user declined
465 to run a required hook (from _CheckForHookApproval).
466 """
467 # No-op if there is no hooks project or if hook is disabled.
468 if ((not self._hooks_project) or
469 (self._hook_type not in self._hooks_project.enabled_repo_hooks)):
470 return
471
472 # Bail with a nice error if we can't find the hook.
473 if not os.path.isfile(self._script_fullpath):
474 raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
475
476 # Make sure the user is OK with running the hook.
477 if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
478 return
479
480 # Run the hook with the same version of python we're using.
481 self._ExecuteHook(**kwargs)
482
483
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700484class Project(object):
485 def __init__(self,
486 manifest,
487 name,
488 remote,
489 gitdir,
490 worktree,
491 relpath,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700492 revisionExpr,
Mike Pontillod3153822012-02-28 11:53:24 -0800493 revisionId,
Colin Cross5acde752012-03-28 20:15:45 -0700494 rebase = True,
Anatol Pomazau79770d22012-04-20 14:41:59 -0700495 groups = None,
Brian Harring14a66742012-09-28 20:21:57 -0700496 sync_c = False,
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800497 sync_s = False,
David Pursehouseede7f122012-11-27 22:25:30 +0900498 clone_depth = None,
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800499 upstream = None,
500 parent = None,
Bryan Jacobsf609f912013-05-06 13:36:24 -0400501 is_derived = False,
502 dest_branch = None):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800503 """Init a Project object.
504
505 Args:
506 manifest: The XmlManifest object.
507 name: The `name` attribute of manifest.xml's project element.
508 remote: RemoteSpec object specifying its remote's properties.
509 gitdir: Absolute path of git directory.
510 worktree: Absolute path of git working tree.
511 relpath: Relative path of git working tree to repo's top directory.
512 revisionExpr: The `revision` attribute of manifest.xml's project element.
513 revisionId: git commit id for checking out.
514 rebase: The `rebase` attribute of manifest.xml's project element.
515 groups: The `groups` attribute of manifest.xml's project element.
516 sync_c: The `sync-c` attribute of manifest.xml's project element.
517 sync_s: The `sync-s` attribute of manifest.xml's project element.
518 upstream: The `upstream` attribute of manifest.xml's project element.
519 parent: The parent Project object.
520 is_derived: False if the project was explicitly defined in the manifest;
521 True if the project is a discovered submodule.
Bryan Jacobsf609f912013-05-06 13:36:24 -0400522 dest_branch: The branch to which to push changes for review by default.
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800523 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700524 self.manifest = manifest
525 self.name = name
526 self.remote = remote
Anthony Newnamdf14a702011-01-09 17:31:57 -0800527 self.gitdir = gitdir.replace('\\', '/')
Shawn O. Pearce0ce6ca92011-01-10 13:26:01 -0800528 if worktree:
529 self.worktree = worktree.replace('\\', '/')
530 else:
531 self.worktree = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700532 self.relpath = relpath
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700533 self.revisionExpr = revisionExpr
534
535 if revisionId is None \
536 and revisionExpr \
537 and IsId(revisionExpr):
538 self.revisionId = revisionExpr
539 else:
540 self.revisionId = revisionId
541
Mike Pontillod3153822012-02-28 11:53:24 -0800542 self.rebase = rebase
Colin Cross5acde752012-03-28 20:15:45 -0700543 self.groups = groups
Anatol Pomazau79770d22012-04-20 14:41:59 -0700544 self.sync_c = sync_c
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800545 self.sync_s = sync_s
David Pursehouseede7f122012-11-27 22:25:30 +0900546 self.clone_depth = clone_depth
Brian Harring14a66742012-09-28 20:21:57 -0700547 self.upstream = upstream
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800548 self.parent = parent
549 self.is_derived = is_derived
550 self.subprojects = []
Mike Pontillod3153822012-02-28 11:53:24 -0800551
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700552 self.snapshots = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700553 self.copyfiles = []
James W. Mills24c13082012-04-12 15:04:13 -0500554 self.annotations = []
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700555 self.config = GitConfig.ForRepository(
556 gitdir = self.gitdir,
557 defaults = self.manifest.globalConfig)
558
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800559 if self.worktree:
560 self.work_git = self._GitGetByExec(self, bare=False)
561 else:
562 self.work_git = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700563 self.bare_git = self._GitGetByExec(self, bare=True)
Shawn O. Pearced237b692009-04-17 18:49:50 -0700564 self.bare_ref = GitRefs(gitdir)
Bryan Jacobsf609f912013-05-06 13:36:24 -0400565 self.dest_branch = dest_branch
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700566
Doug Anderson37282b42011-03-04 11:54:18 -0800567 # This will be filled in if a project is later identified to be the
568 # project containing repo hooks.
569 self.enabled_repo_hooks = []
570
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700571 @property
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800572 def Derived(self):
573 return self.is_derived
574
575 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700576 def Exists(self):
577 return os.path.isdir(self.gitdir)
578
579 @property
580 def CurrentBranch(self):
581 """Obtain the name of the currently checked out branch.
582 The branch name omits the 'refs/heads/' prefix.
583 None is returned if the project is on a detached HEAD.
584 """
Shawn O. Pearce5b23f242009-04-17 18:43:33 -0700585 b = self.work_git.GetHead()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700586 if b.startswith(R_HEADS):
587 return b[len(R_HEADS):]
588 return None
589
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700590 def IsRebaseInProgress(self):
591 w = self.worktree
592 g = os.path.join(w, '.git')
593 return os.path.exists(os.path.join(g, 'rebase-apply')) \
594 or os.path.exists(os.path.join(g, 'rebase-merge')) \
595 or os.path.exists(os.path.join(w, '.dotest'))
Julius Gustavsson0cb1b3f2010-06-17 17:55:02 +0200596
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700597 def IsDirty(self, consider_untracked=True):
598 """Is the working directory modified in some way?
599 """
600 self.work_git.update_index('-q',
601 '--unmerged',
602 '--ignore-missing',
603 '--refresh')
David Pursehouse8f62fb72012-11-14 12:09:38 +0900604 if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700605 return True
606 if self.work_git.DiffZ('diff-files'):
607 return True
608 if consider_untracked and self.work_git.LsOthers():
609 return True
610 return False
611
612 _userident_name = None
613 _userident_email = None
614
615 @property
616 def UserName(self):
617 """Obtain the user's personal name.
618 """
619 if self._userident_name is None:
620 self._LoadUserIdentity()
621 return self._userident_name
622
623 @property
624 def UserEmail(self):
625 """Obtain the user's email address. This is very likely
626 to be their Gerrit login.
627 """
628 if self._userident_email is None:
629 self._LoadUserIdentity()
630 return self._userident_email
631
632 def _LoadUserIdentity(self):
David Pursehousec1b86a22012-11-14 11:36:51 +0900633 u = self.bare_git.var('GIT_COMMITTER_IDENT')
634 m = re.compile("^(.*) <([^>]*)> ").match(u)
635 if m:
636 self._userident_name = m.group(1)
637 self._userident_email = m.group(2)
638 else:
639 self._userident_name = ''
640 self._userident_email = ''
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700641
642 def GetRemote(self, name):
643 """Get the configuration for a single remote.
644 """
645 return self.config.GetRemote(name)
646
647 def GetBranch(self, name):
648 """Get the configuration for a single branch.
649 """
650 return self.config.GetBranch(name)
651
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700652 def GetBranches(self):
653 """Get all existing local branches.
654 """
655 current = self.CurrentBranch
David Pursehouse8a68ff92012-09-24 12:15:13 +0900656 all_refs = self._allrefs
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700657 heads = {}
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700658
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530659 for name, ref_id in all_refs.items():
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700660 if name.startswith(R_HEADS):
661 name = name[len(R_HEADS):]
662 b = self.GetBranch(name)
663 b.current = name == current
664 b.published = None
David Pursehouse8a68ff92012-09-24 12:15:13 +0900665 b.revision = ref_id
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700666 heads[name] = b
667
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530668 for name, ref_id in all_refs.items():
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700669 if name.startswith(R_PUB):
670 name = name[len(R_PUB):]
671 b = heads.get(name)
672 if b:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900673 b.published = ref_id
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700674
675 return heads
676
Colin Cross5acde752012-03-28 20:15:45 -0700677 def MatchesGroups(self, manifest_groups):
678 """Returns true if the manifest groups specified at init should cause
679 this project to be synced.
680 Prefixing a manifest group with "-" inverts the meaning of a group.
Conley Owensbb1b5f52012-08-13 13:11:18 -0700681 All projects are implicitly labelled with "all".
Conley Owens971de8e2012-04-16 10:36:08 -0700682
683 labels are resolved in order. In the example case of
Conley Owensbb1b5f52012-08-13 13:11:18 -0700684 project_groups: "all,group1,group2"
Conley Owens971de8e2012-04-16 10:36:08 -0700685 manifest_groups: "-group1,group2"
686 the project will be matched.
David Holmer0a1c6a12012-11-14 19:19:00 -0500687
688 The special manifest group "default" will match any project that
689 does not have the special project group "notdefault"
Colin Cross5acde752012-03-28 20:15:45 -0700690 """
David Holmer0a1c6a12012-11-14 19:19:00 -0500691 expanded_manifest_groups = manifest_groups or ['default']
Conley Owensbb1b5f52012-08-13 13:11:18 -0700692 expanded_project_groups = ['all'] + (self.groups or [])
David Holmer0a1c6a12012-11-14 19:19:00 -0500693 if not 'notdefault' in expanded_project_groups:
694 expanded_project_groups += ['default']
Conley Owensbb1b5f52012-08-13 13:11:18 -0700695
Conley Owens971de8e2012-04-16 10:36:08 -0700696 matched = False
Conley Owensbb1b5f52012-08-13 13:11:18 -0700697 for group in expanded_manifest_groups:
698 if group.startswith('-') and group[1:] in expanded_project_groups:
Conley Owens971de8e2012-04-16 10:36:08 -0700699 matched = False
Conley Owensbb1b5f52012-08-13 13:11:18 -0700700 elif group in expanded_project_groups:
Conley Owens971de8e2012-04-16 10:36:08 -0700701 matched = True
Colin Cross5acde752012-03-28 20:15:45 -0700702
Conley Owens971de8e2012-04-16 10:36:08 -0700703 return matched
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700704
705## Status Display ##
706
Anthony Newnamcc50bac2010-04-08 10:28:59 -0500707 def HasChanges(self):
708 """Returns true if there are uncommitted changes.
709 """
710 self.work_git.update_index('-q',
711 '--unmerged',
712 '--ignore-missing',
713 '--refresh')
714 if self.IsRebaseInProgress():
715 return True
716
717 if self.work_git.DiffZ('diff-index', '--cached', HEAD):
718 return True
719
720 if self.work_git.DiffZ('diff-files'):
721 return True
722
723 if self.work_git.LsOthers():
724 return True
725
726 return False
727
Terence Haddock4655e812011-03-31 12:33:34 +0200728 def PrintWorkTreeStatus(self, output_redir=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700729 """Prints the status of the repository to stdout.
Terence Haddock4655e812011-03-31 12:33:34 +0200730
731 Args:
732 output: If specified, redirect the output to this object.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700733 """
734 if not os.path.isdir(self.worktree):
Terence Haddock4655e812011-03-31 12:33:34 +0200735 if output_redir == None:
736 output_redir = sys.stdout
Sarah Owenscecd1d82012-11-01 22:59:27 -0700737 print(file=output_redir)
738 print('project %s/' % self.relpath, file=output_redir)
739 print(' missing (run "repo sync")', file=output_redir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700740 return
741
742 self.work_git.update_index('-q',
743 '--unmerged',
744 '--ignore-missing',
745 '--refresh')
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700746 rb = self.IsRebaseInProgress()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700747 di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
748 df = self.work_git.DiffZ('diff-files')
749 do = self.work_git.LsOthers()
Ali Utku Selen76abcc12012-01-25 10:51:12 +0100750 if not rb and not di and not df and not do and not self.CurrentBranch:
Shawn O. Pearce161f4452009-04-10 17:41:44 -0700751 return 'CLEAN'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700752
753 out = StatusColoring(self.config)
Terence Haddock4655e812011-03-31 12:33:34 +0200754 if not output_redir == None:
755 out.redirect(output_redir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700756 out.project('project %-40s', self.relpath + '/')
757
758 branch = self.CurrentBranch
759 if branch is None:
760 out.nobranch('(*** NO BRANCH ***)')
761 else:
762 out.branch('branch %s', branch)
763 out.nl()
764
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700765 if rb:
766 out.important('prior sync failed; rebase still in progress')
767 out.nl()
768
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700769 paths = list()
770 paths.extend(di.keys())
771 paths.extend(df.keys())
772 paths.extend(do)
773
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530774 for p in sorted(set(paths)):
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900775 try:
776 i = di[p]
777 except KeyError:
778 i = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700779
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900780 try:
781 f = df[p]
782 except KeyError:
783 f = None
Julius Gustavsson0cb1b3f2010-06-17 17:55:02 +0200784
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900785 if i:
786 i_status = i.status.upper()
787 else:
788 i_status = '-'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700789
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900790 if f:
791 f_status = f.status.lower()
792 else:
793 f_status = '-'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700794
795 if i and i.src_path:
Shawn O. Pearcefe086752009-03-03 13:49:48 -0800796 line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700797 i.src_path, p, i.level)
798 else:
799 line = ' %s%s\t%s' % (i_status, f_status, p)
800
801 if i and not f:
802 out.added('%s', line)
803 elif (i and f) or (not i and f):
804 out.changed('%s', line)
805 elif not i and not f:
806 out.untracked('%s', line)
807 else:
808 out.write('%s', line)
809 out.nl()
Terence Haddock4655e812011-03-31 12:33:34 +0200810
Shawn O. Pearce161f4452009-04-10 17:41:44 -0700811 return 'DIRTY'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700812
pelyad67872d2012-03-28 14:49:58 +0300813 def PrintWorkTreeDiff(self, absolute_paths=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700814 """Prints the status of the repository to stdout.
815 """
816 out = DiffColoring(self.config)
817 cmd = ['diff']
818 if out.is_on:
819 cmd.append('--color')
820 cmd.append(HEAD)
pelyad67872d2012-03-28 14:49:58 +0300821 if absolute_paths:
822 cmd.append('--src-prefix=a/%s/' % self.relpath)
823 cmd.append('--dst-prefix=b/%s/' % self.relpath)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700824 cmd.append('--')
825 p = GitCommand(self,
826 cmd,
827 capture_stdout = True,
828 capture_stderr = True)
829 has_diff = False
830 for line in p.process.stdout:
831 if not has_diff:
832 out.nl()
833 out.project('project %s/' % self.relpath)
834 out.nl()
835 has_diff = True
Sarah Owenscecd1d82012-11-01 22:59:27 -0700836 print(line[:-1])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700837 p.Wait()
838
839
840## Publish / Upload ##
841
David Pursehouse8a68ff92012-09-24 12:15:13 +0900842 def WasPublished(self, branch, all_refs=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700843 """Was the branch published (uploaded) for code review?
844 If so, returns the SHA-1 hash of the last published
845 state for the branch.
846 """
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700847 key = R_PUB + branch
David Pursehouse8a68ff92012-09-24 12:15:13 +0900848 if all_refs is None:
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700849 try:
850 return self.bare_git.rev_parse(key)
851 except GitError:
852 return None
853 else:
854 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900855 return all_refs[key]
Shawn O. Pearcefbcde472009-04-17 20:58:02 -0700856 except KeyError:
857 return None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700858
David Pursehouse8a68ff92012-09-24 12:15:13 +0900859 def CleanPublishedCache(self, all_refs=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700860 """Prunes any stale published refs.
861 """
David Pursehouse8a68ff92012-09-24 12:15:13 +0900862 if all_refs is None:
863 all_refs = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700864 heads = set()
865 canrm = {}
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530866 for name, ref_id in all_refs.items():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700867 if name.startswith(R_HEADS):
868 heads.add(name)
869 elif name.startswith(R_PUB):
David Pursehouse8a68ff92012-09-24 12:15:13 +0900870 canrm[name] = ref_id
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700871
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530872 for name, ref_id in canrm.items():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700873 n = name[len(R_PUB):]
874 if R_HEADS + n not in heads:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900875 self.bare_git.DeleteRef(name, ref_id)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700876
Mandeep Singh Bainesd6c93a22011-05-26 10:34:11 -0700877 def GetUploadableBranches(self, selected_branch=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700878 """List any branches which can be uploaded for review.
879 """
880 heads = {}
881 pubed = {}
882
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530883 for name, ref_id in self._allrefs.items():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700884 if name.startswith(R_HEADS):
David Pursehouse8a68ff92012-09-24 12:15:13 +0900885 heads[name[len(R_HEADS):]] = ref_id
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700886 elif name.startswith(R_PUB):
David Pursehouse8a68ff92012-09-24 12:15:13 +0900887 pubed[name[len(R_PUB):]] = ref_id
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700888
889 ready = []
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530890 for branch, ref_id in heads.items():
David Pursehouse8a68ff92012-09-24 12:15:13 +0900891 if branch in pubed and pubed[branch] == ref_id:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700892 continue
Mandeep Singh Bainesd6c93a22011-05-26 10:34:11 -0700893 if selected_branch and branch != selected_branch:
894 continue
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700895
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800896 rb = self.GetUploadableBranch(branch)
897 if rb:
898 ready.append(rb)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700899 return ready
900
Shawn O. Pearce35f25962008-11-11 17:03:13 -0800901 def GetUploadableBranch(self, branch_name):
902 """Get a single uploadable branch, or None.
903 """
904 branch = self.GetBranch(branch_name)
905 base = branch.LocalMerge
906 if branch.LocalMerge:
907 rb = ReviewableBranch(self, branch, base)
908 if rb.commits:
909 return rb
910 return None
911
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700912 def UploadForReview(self, branch=None,
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700913 people=([],[]),
Brian Harring435370c2012-07-28 15:37:04 -0700914 auto_topic=False,
Bryan Jacobsf609f912013-05-06 13:36:24 -0400915 draft=False,
916 dest_branch=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700917 """Uploads the named branch for code review.
918 """
919 if branch is None:
920 branch = self.CurrentBranch
921 if branch is None:
922 raise GitError('not currently on a branch')
923
924 branch = self.GetBranch(branch)
925 if not branch.LocalMerge:
926 raise GitError('branch %s does not track a remote' % branch.name)
927 if not branch.remote.review:
928 raise GitError('remote %s has no review url' % branch.remote.name)
929
Bryan Jacobsf609f912013-05-06 13:36:24 -0400930 if dest_branch is None:
931 dest_branch = self.dest_branch
932 if dest_branch is None:
933 dest_branch = branch.merge
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700934 if not dest_branch.startswith(R_HEADS):
935 dest_branch = R_HEADS + dest_branch
936
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800937 if not branch.remote.projectname:
938 branch.remote.projectname = self.name
939 branch.remote.Save()
940
Shawn O. Pearcec9571422012-01-11 14:58:54 -0800941 url = branch.remote.ReviewUrl(self.UserEmail)
942 if url is None:
943 raise UploadError('review not configured')
944 cmd = ['push']
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800945
Shawn O. Pearcec9571422012-01-11 14:58:54 -0800946 if url.startswith('ssh://'):
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800947 rp = ['gerrit receive-pack']
948 for e in people[0]:
949 rp.append('--reviewer=%s' % sq(e))
950 for e in people[1]:
951 rp.append('--cc=%s' % sq(e))
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800952 cmd.append('--receive-pack=%s' % " ".join(rp))
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700953
Shawn O. Pearcec9571422012-01-11 14:58:54 -0800954 cmd.append(url)
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800955
Shawn O. Pearcec9571422012-01-11 14:58:54 -0800956 if dest_branch.startswith(R_HEADS):
957 dest_branch = dest_branch[len(R_HEADS):]
Brian Harring435370c2012-07-28 15:37:04 -0700958
959 upload_type = 'for'
960 if draft:
961 upload_type = 'drafts'
962
963 ref_spec = '%s:refs/%s/%s' % (R_HEADS + branch.name, upload_type,
964 dest_branch)
Shawn O. Pearcec9571422012-01-11 14:58:54 -0800965 if auto_topic:
966 ref_spec = ref_spec + '/' + branch.name
Shawn Pearce45d21682013-02-28 00:35:51 -0800967 if not url.startswith('ssh://'):
968 rp = ['r=%s' % p for p in people[0]] + \
969 ['cc=%s' % p for p in people[1]]
970 if rp:
971 ref_spec = ref_spec + '%' + ','.join(rp)
Shawn O. Pearcec9571422012-01-11 14:58:54 -0800972 cmd.append(ref_spec)
973
974 if GitCommand(self, cmd, bare = True).Wait() != 0:
975 raise UploadError('Upload failed')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700976
977 msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
978 self.bare_git.UpdateRef(R_PUB + branch.name,
979 R_HEADS + branch.name,
980 message = msg)
981
982
983## Sync ##
984
Shawn O. Pearcee02ac0a2012-03-14 15:36:59 -0700985 def Sync_NetworkHalf(self,
986 quiet=False,
987 is_new=None,
988 current_branch_only=False,
Mitchel Humpherys597868b2012-10-29 10:18:34 -0700989 clone_bundle=True,
990 no_tags=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700991 """Perform only the network IO portion of the sync process.
992 Local working directory/branch state is not affected.
993 """
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700994 if is_new is None:
995 is_new = not self.Exists
Shawn O. Pearce88443382010-10-08 10:02:09 +0200996 if is_new:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700997 self._InitGitDir()
Jimmie Westera0444582012-10-24 13:44:42 +0200998 else:
999 self._UpdateHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001000 self._InitRemote()
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001001
1002 if is_new:
1003 alt = os.path.join(self.gitdir, 'objects/info/alternates')
1004 try:
1005 fd = open(alt, 'rb')
1006 try:
1007 alt_dir = fd.readline().rstrip()
1008 finally:
1009 fd.close()
1010 except IOError:
1011 alt_dir = None
1012 else:
1013 alt_dir = None
1014
Shawn O. Pearcee02ac0a2012-03-14 15:36:59 -07001015 if clone_bundle \
1016 and alt_dir is None \
1017 and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001018 is_new = False
1019
Shawn O. Pearce6ba6ba02012-05-24 09:46:50 -07001020 if not current_branch_only:
1021 if self.sync_c:
1022 current_branch_only = True
1023 elif not self.manifest._loaded:
1024 # Manifest cannot check defaults until it syncs.
1025 current_branch_only = False
1026 elif self.manifest.default.sync_c:
1027 current_branch_only = True
1028
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001029 if not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
Mitchel Humpherys597868b2012-10-29 10:18:34 -07001030 current_branch_only=current_branch_only,
1031 no_tags=no_tags):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001032 return False
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001033
1034 if self.worktree:
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001035 self._InitMRef()
1036 else:
1037 self._InitMirrorHead()
1038 try:
1039 os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
1040 except OSError:
1041 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001042 return True
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001043
1044 def PostRepoUpgrade(self):
1045 self._InitHooks()
1046
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001047 def _CopyFiles(self):
David Pursehouse8a68ff92012-09-24 12:15:13 +09001048 for copyfile in self.copyfiles:
1049 copyfile._Copy()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001050
David Pursehouse8a68ff92012-09-24 12:15:13 +09001051 def GetRevisionId(self, all_refs=None):
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001052 if self.revisionId:
1053 return self.revisionId
1054
1055 rem = self.GetRemote(self.remote.name)
1056 rev = rem.ToLocal(self.revisionExpr)
1057
David Pursehouse8a68ff92012-09-24 12:15:13 +09001058 if all_refs is not None and rev in all_refs:
1059 return all_refs[rev]
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001060
1061 try:
1062 return self.bare_git.rev_parse('--verify', '%s^0' % rev)
1063 except GitError:
1064 raise ManifestInvalidRevisionError(
1065 'revision %s in %s not found' % (self.revisionExpr,
1066 self.name))
1067
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001068 def Sync_LocalHalf(self, syncbuf):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001069 """Perform only the local IO portion of the sync process.
1070 Network access is not required.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001071 """
David Pursehouse8a68ff92012-09-24 12:15:13 +09001072 all_refs = self.bare_ref.all
1073 self.CleanPublishedCache(all_refs)
1074 revid = self.GetRevisionId(all_refs)
Skyler Kaufman835cd682011-03-08 12:14:41 -08001075
David Pursehouse1d947b32012-10-25 12:23:11 +09001076 def _doff():
1077 self._FastForward(revid)
1078 self._CopyFiles()
1079
Skyler Kaufman835cd682011-03-08 12:14:41 -08001080 self._InitWorkTree()
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001081 head = self.work_git.GetHead()
1082 if head.startswith(R_HEADS):
1083 branch = head[len(R_HEADS):]
1084 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001085 head = all_refs[head]
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001086 except KeyError:
1087 head = None
1088 else:
1089 branch = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001090
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001091 if branch is None or syncbuf.detach_head:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001092 # Currently on a detached HEAD. The user is assumed to
1093 # not have any local modifications worth worrying about.
1094 #
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -07001095 if self.IsRebaseInProgress():
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001096 syncbuf.fail(self, _PriorSyncFailedError())
1097 return
1098
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001099 if head == revid:
1100 # No changes; don't do anything further.
Florian Vallee7cf1b362012-06-07 17:11:42 +02001101 # Except if the head needs to be detached
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001102 #
Florian Vallee7cf1b362012-06-07 17:11:42 +02001103 if not syncbuf.detach_head:
1104 return
1105 else:
1106 lost = self._revlist(not_rev(revid), HEAD)
1107 if lost:
1108 syncbuf.info(self, "discarding %d commits", len(lost))
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001109
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001110 try:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001111 self._Checkout(revid, quiet=True)
Sarah Owensa5be53f2012-09-09 15:37:57 -07001112 except GitError as e:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001113 syncbuf.fail(self, e)
1114 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001115 self._CopyFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001116 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001117
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001118 if head == revid:
1119 # No changes; don't do anything further.
1120 #
1121 return
1122
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001123 branch = self.GetBranch(branch)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001124
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001125 if not branch.LocalMerge:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001126 # The current branch has no tracking configuration.
Anatol Pomazau2a32f6a2011-08-30 10:52:33 -07001127 # Jump off it to a detached HEAD.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001128 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001129 syncbuf.info(self,
1130 "leaving %s; does not track upstream",
1131 branch.name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001132 try:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001133 self._Checkout(revid, quiet=True)
Sarah Owensa5be53f2012-09-09 15:37:57 -07001134 except GitError as e:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001135 syncbuf.fail(self, e)
1136 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001137 self._CopyFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001138 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001139
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001140 upstream_gain = self._revlist(not_rev(HEAD), revid)
David Pursehouse8a68ff92012-09-24 12:15:13 +09001141 pub = self.WasPublished(branch.name, all_refs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001142 if pub:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001143 not_merged = self._revlist(not_rev(revid), pub)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001144 if not_merged:
1145 if upstream_gain:
1146 # The user has published this branch and some of those
1147 # commits are not yet merged upstream. We do not want
1148 # to rewrite the published commits so we punt.
1149 #
Daniel Sandler4c50dee2010-03-02 15:38:03 -05001150 syncbuf.fail(self,
1151 "branch %s is published (but not merged) and is now %d commits behind"
1152 % (branch.name, len(upstream_gain)))
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001153 return
Shawn O. Pearce05f66b62009-04-21 08:26:32 -07001154 elif pub == head:
1155 # All published commits are merged, and thus we are a
1156 # strict subset. We can fast-forward safely.
Shawn O. Pearcea54c5272008-10-30 11:03:00 -07001157 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001158 syncbuf.later1(self, _doff)
1159 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001160
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001161 # Examine the local commits not in the remote. Find the
1162 # last one attributed to this user, if any.
1163 #
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001164 local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001165 last_mine = None
1166 cnt_mine = 0
1167 for commit in local_changes:
Shawn O. Pearceaa4982e2009-12-30 18:38:27 -08001168 commit_id, committer_email = commit.split(' ', 1)
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001169 if committer_email == self.UserEmail:
1170 last_mine = commit_id
1171 cnt_mine += 1
1172
Shawn O. Pearceda88ff42009-06-03 11:09:12 -07001173 if not upstream_gain and cnt_mine == len(local_changes):
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001174 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001175
1176 if self.IsDirty(consider_untracked=False):
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001177 syncbuf.fail(self, _DirtyError())
1178 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001179
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001180 # If the upstream switched on us, warn the user.
1181 #
1182 if branch.merge != self.revisionExpr:
1183 if branch.merge and self.revisionExpr:
1184 syncbuf.info(self,
1185 'manifest switched %s...%s',
1186 branch.merge,
1187 self.revisionExpr)
1188 elif branch.merge:
1189 syncbuf.info(self,
1190 'manifest no longer tracks %s',
1191 branch.merge)
1192
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001193 if cnt_mine < len(local_changes):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001194 # Upstream rebased. Not everything in HEAD
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001195 # was created by this user.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001196 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001197 syncbuf.info(self,
1198 "discarding %d commits removed from upstream",
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001199 len(local_changes) - cnt_mine)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001200
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001201 branch.remote = self.GetRemote(self.remote.name)
Anatol Pomazaucd7c5de2012-03-20 13:45:00 -07001202 if not ID_RE.match(self.revisionExpr):
1203 # in case of manifest sync the revisionExpr might be a SHA1
1204 branch.merge = self.revisionExpr
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001205 branch.Save()
1206
Mike Pontillod3153822012-02-28 11:53:24 -08001207 if cnt_mine > 0 and self.rebase:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001208 def _dorebase():
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001209 self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001210 self._CopyFiles()
1211 syncbuf.later2(self, _dorebase)
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001212 elif local_changes:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001213 try:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001214 self._ResetHard(revid)
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001215 self._CopyFiles()
Sarah Owensa5be53f2012-09-09 15:37:57 -07001216 except GitError as e:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001217 syncbuf.fail(self, e)
1218 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001219 else:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001220 syncbuf.later1(self, _doff)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001221
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -08001222 def AddCopyFile(self, src, dest, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001223 # dest should already be an absolute path, but src is project relative
1224 # make src an absolute path
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -08001225 abssrc = os.path.join(self.worktree, src)
1226 self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001227
James W. Mills24c13082012-04-12 15:04:13 -05001228 def AddAnnotation(self, name, value, keep):
1229 self.annotations.append(_Annotation(name, value, keep))
1230
Shawn O. Pearce632768b2008-10-23 11:58:52 -07001231 def DownloadPatchSet(self, change_id, patch_id):
1232 """Download a single patch set of a single change to FETCH_HEAD.
1233 """
1234 remote = self.GetRemote(self.remote.name)
1235
1236 cmd = ['fetch', remote.name]
1237 cmd.append('refs/changes/%2.2d/%d/%d' \
1238 % (change_id % 100, change_id, patch_id))
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301239 cmd.extend(list(map(str, remote.fetch)))
Shawn O. Pearce632768b2008-10-23 11:58:52 -07001240 if GitCommand(self, cmd, bare=True).Wait() != 0:
1241 return None
1242 return DownloadedChange(self,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001243 self.GetRevisionId(),
Shawn O. Pearce632768b2008-10-23 11:58:52 -07001244 change_id,
1245 patch_id,
1246 self.bare_git.rev_parse('FETCH_HEAD'))
1247
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001248
1249## Branch Management ##
1250
1251 def StartBranch(self, name):
1252 """Create a new branch off the manifest's revision.
1253 """
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001254 head = self.work_git.GetHead()
1255 if head == (R_HEADS + name):
1256 return True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001257
David Pursehouse8a68ff92012-09-24 12:15:13 +09001258 all_refs = self.bare_ref.all
1259 if (R_HEADS + name) in all_refs:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001260 return GitCommand(self,
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001261 ['checkout', name, '--'],
Shawn O. Pearce0f0dfa32009-04-18 14:53:39 -07001262 capture_stdout = True,
1263 capture_stderr = True).Wait() == 0
Shawn O. Pearce0a389e92009-04-10 16:21:18 -07001264
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001265 branch = self.GetBranch(name)
1266 branch.remote = self.GetRemote(self.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001267 branch.merge = self.revisionExpr
David Pursehouse8a68ff92012-09-24 12:15:13 +09001268 revid = self.GetRevisionId(all_refs)
Shawn O. Pearce0a389e92009-04-10 16:21:18 -07001269
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001270 if head.startswith(R_HEADS):
1271 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001272 head = all_refs[head]
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001273 except KeyError:
1274 head = None
1275
1276 if revid and head and revid == head:
1277 ref = os.path.join(self.gitdir, R_HEADS + name)
1278 try:
1279 os.makedirs(os.path.dirname(ref))
1280 except OSError:
1281 pass
1282 _lwrite(ref, '%s\n' % revid)
1283 _lwrite(os.path.join(self.worktree, '.git', HEAD),
1284 'ref: %s%s\n' % (R_HEADS, name))
1285 branch.Save()
1286 return True
1287
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001288 if GitCommand(self,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001289 ['checkout', '-b', branch.name, revid],
Shawn O. Pearce0f0dfa32009-04-18 14:53:39 -07001290 capture_stdout = True,
1291 capture_stderr = True).Wait() == 0:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001292 branch.Save()
1293 return True
1294 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001295
Wink Saville02d79452009-04-10 13:01:24 -07001296 def CheckoutBranch(self, name):
1297 """Checkout a local topic branch.
Doug Anderson3ba5f952011-04-07 12:51:04 -07001298
1299 Args:
1300 name: The name of the branch to checkout.
1301
1302 Returns:
1303 True if the checkout succeeded; False if it didn't; None if the branch
1304 didn't exist.
Wink Saville02d79452009-04-10 13:01:24 -07001305 """
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001306 rev = R_HEADS + name
1307 head = self.work_git.GetHead()
1308 if head == rev:
1309 # Already on the branch
1310 #
1311 return True
Wink Saville02d79452009-04-10 13:01:24 -07001312
David Pursehouse8a68ff92012-09-24 12:15:13 +09001313 all_refs = self.bare_ref.all
Wink Saville02d79452009-04-10 13:01:24 -07001314 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001315 revid = all_refs[rev]
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001316 except KeyError:
1317 # Branch does not exist in this project
1318 #
Doug Anderson3ba5f952011-04-07 12:51:04 -07001319 return None
Wink Saville02d79452009-04-10 13:01:24 -07001320
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001321 if head.startswith(R_HEADS):
1322 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001323 head = all_refs[head]
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001324 except KeyError:
1325 head = None
1326
1327 if head == revid:
1328 # Same revision; just update HEAD to point to the new
1329 # target branch, but otherwise take no other action.
1330 #
1331 _lwrite(os.path.join(self.worktree, '.git', HEAD),
1332 'ref: %s%s\n' % (R_HEADS, name))
1333 return True
1334
1335 return GitCommand(self,
1336 ['checkout', name, '--'],
1337 capture_stdout = True,
1338 capture_stderr = True).Wait() == 0
Wink Saville02d79452009-04-10 13:01:24 -07001339
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001340 def AbandonBranch(self, name):
1341 """Destroy a local topic branch.
Doug Andersondafb1d62011-04-07 11:46:59 -07001342
1343 Args:
1344 name: The name of the branch to abandon.
1345
1346 Returns:
1347 True if the abandon succeeded; False if it didn't; None if the branch
1348 didn't exist.
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001349 """
Shawn O. Pearce552ac892009-04-18 15:15:24 -07001350 rev = R_HEADS + name
David Pursehouse8a68ff92012-09-24 12:15:13 +09001351 all_refs = self.bare_ref.all
1352 if rev not in all_refs:
Doug Andersondafb1d62011-04-07 11:46:59 -07001353 # Doesn't exist
1354 return None
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001355
Shawn O. Pearce552ac892009-04-18 15:15:24 -07001356 head = self.work_git.GetHead()
1357 if head == rev:
1358 # We can't destroy the branch while we are sitting
1359 # on it. Switch to a detached HEAD.
1360 #
David Pursehouse8a68ff92012-09-24 12:15:13 +09001361 head = all_refs[head]
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001362
David Pursehouse8a68ff92012-09-24 12:15:13 +09001363 revid = self.GetRevisionId(all_refs)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001364 if head == revid:
Shawn O. Pearce552ac892009-04-18 15:15:24 -07001365 _lwrite(os.path.join(self.worktree, '.git', HEAD),
1366 '%s\n' % revid)
1367 else:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001368 self._Checkout(revid, quiet=True)
Shawn O. Pearce552ac892009-04-18 15:15:24 -07001369
1370 return GitCommand(self,
1371 ['branch', '-D', name],
1372 capture_stdout = True,
1373 capture_stderr = True).Wait() == 0
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001374
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001375 def PruneHeads(self):
1376 """Prune any topic branches already merged into upstream.
1377 """
1378 cb = self.CurrentBranch
1379 kill = []
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001380 left = self._allrefs
1381 for name in left.keys():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001382 if name.startswith(R_HEADS):
1383 name = name[len(R_HEADS):]
1384 if cb is None or name != cb:
1385 kill.append(name)
1386
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001387 rev = self.GetRevisionId(left)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001388 if cb is not None \
1389 and not self._revlist(HEAD + '...' + rev) \
1390 and not self.IsDirty(consider_untracked = False):
1391 self.work_git.DetachHead(HEAD)
1392 kill.append(cb)
1393
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001394 if kill:
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07001395 old = self.bare_git.GetHead()
1396 if old is None:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001397 old = 'refs/heads/please_never_use_this_as_a_branch_name'
1398
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001399 try:
1400 self.bare_git.DetachHead(rev)
1401
1402 b = ['branch', '-d']
1403 b.extend(kill)
1404 b = GitCommand(self, b, bare=True,
1405 capture_stdout=True,
1406 capture_stderr=True)
1407 b.Wait()
1408 finally:
1409 self.bare_git.SetHead(old)
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001410 left = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001411
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001412 for branch in kill:
1413 if (R_HEADS + branch) not in left:
1414 self.CleanPublishedCache()
1415 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001416
1417 if cb and cb not in kill:
1418 kill.append(cb)
Shawn O. Pearce7c6c64d2009-03-02 12:38:13 -08001419 kill.sort()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001420
1421 kept = []
1422 for branch in kill:
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001423 if (R_HEADS + branch) in left:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001424 branch = self.GetBranch(branch)
1425 base = branch.LocalMerge
1426 if not base:
1427 base = rev
1428 kept.append(ReviewableBranch(self, branch, base))
1429 return kept
1430
1431
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001432## Submodule Management ##
1433
1434 def GetRegisteredSubprojects(self):
1435 result = []
1436 def rec(subprojects):
1437 if not subprojects:
1438 return
1439 result.extend(subprojects)
1440 for p in subprojects:
1441 rec(p.subprojects)
1442 rec(self.subprojects)
1443 return result
1444
1445 def _GetSubmodules(self):
1446 # Unfortunately we cannot call `git submodule status --recursive` here
1447 # because the working tree might not exist yet, and it cannot be used
1448 # without a working tree in its current implementation.
1449
1450 def get_submodules(gitdir, rev):
1451 # Parse .gitmodules for submodule sub_paths and sub_urls
1452 sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
1453 if not sub_paths:
1454 return []
1455 # Run `git ls-tree` to read SHAs of submodule object, which happen to be
1456 # revision of submodule repository
1457 sub_revs = git_ls_tree(gitdir, rev, sub_paths)
1458 submodules = []
1459 for sub_path, sub_url in zip(sub_paths, sub_urls):
1460 try:
1461 sub_rev = sub_revs[sub_path]
1462 except KeyError:
1463 # Ignore non-exist submodules
1464 continue
1465 submodules.append((sub_rev, sub_path, sub_url))
1466 return submodules
1467
1468 re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
1469 re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
1470 def parse_gitmodules(gitdir, rev):
1471 cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
1472 try:
1473 p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
1474 bare = True, gitdir = gitdir)
1475 except GitError:
1476 return [], []
1477 if p.Wait() != 0:
1478 return [], []
1479
1480 gitmodules_lines = []
1481 fd, temp_gitmodules_path = tempfile.mkstemp()
1482 try:
1483 os.write(fd, p.stdout)
1484 os.close(fd)
1485 cmd = ['config', '--file', temp_gitmodules_path, '--list']
1486 p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
1487 bare = True, gitdir = gitdir)
1488 if p.Wait() != 0:
1489 return [], []
1490 gitmodules_lines = p.stdout.split('\n')
1491 except GitError:
1492 return [], []
1493 finally:
1494 os.remove(temp_gitmodules_path)
1495
1496 names = set()
1497 paths = {}
1498 urls = {}
1499 for line in gitmodules_lines:
1500 if not line:
1501 continue
1502 m = re_path.match(line)
1503 if m:
1504 names.add(m.group(1))
1505 paths[m.group(1)] = m.group(2)
1506 continue
1507 m = re_url.match(line)
1508 if m:
1509 names.add(m.group(1))
1510 urls[m.group(1)] = m.group(2)
1511 continue
1512 names = sorted(names)
1513 return ([paths.get(name, '') for name in names],
1514 [urls.get(name, '') for name in names])
1515
1516 def git_ls_tree(gitdir, rev, paths):
1517 cmd = ['ls-tree', rev, '--']
1518 cmd.extend(paths)
1519 try:
1520 p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
1521 bare = True, gitdir = gitdir)
1522 except GitError:
1523 return []
1524 if p.Wait() != 0:
1525 return []
1526 objects = {}
1527 for line in p.stdout.split('\n'):
1528 if not line.strip():
1529 continue
1530 object_rev, object_path = line.split()[2:4]
1531 objects[object_path] = object_rev
1532 return objects
1533
1534 try:
1535 rev = self.GetRevisionId()
1536 except GitError:
1537 return []
1538 return get_submodules(self.gitdir, rev)
1539
1540 def GetDerivedSubprojects(self):
1541 result = []
1542 if not self.Exists:
1543 # If git repo does not exist yet, querying its submodules will
1544 # mess up its states; so return here.
1545 return result
1546 for rev, path, url in self._GetSubmodules():
1547 name = self.manifest.GetSubprojectName(self, path)
1548 project = self.manifest.projects.get(name)
1549 if project:
1550 result.extend(project.GetDerivedSubprojects())
1551 continue
1552 relpath, worktree, gitdir = self.manifest.GetSubprojectPaths(self, path)
1553 remote = RemoteSpec(self.remote.name,
1554 url = url,
1555 review = self.remote.review)
1556 subproject = Project(manifest = self.manifest,
1557 name = name,
1558 remote = remote,
1559 gitdir = gitdir,
1560 worktree = worktree,
1561 relpath = relpath,
1562 revisionExpr = self.revisionExpr,
1563 revisionId = rev,
1564 rebase = self.rebase,
1565 groups = self.groups,
1566 sync_c = self.sync_c,
1567 sync_s = self.sync_s,
1568 parent = self,
1569 is_derived = True)
1570 result.append(subproject)
1571 result.extend(subproject.GetDerivedSubprojects())
1572 return result
1573
1574
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001575## Direct Git Commands ##
1576
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001577 def _RemoteFetch(self, name=None,
1578 current_branch_only=False,
Shawn O. Pearce16614f82010-10-29 12:05:43 -07001579 initial=False,
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001580 quiet=False,
Mitchel Humpherys597868b2012-10-29 10:18:34 -07001581 alt_dir=None,
1582 no_tags=False):
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001583
1584 is_sha1 = False
1585 tag_name = None
1586
Brian Harring14a66742012-09-28 20:21:57 -07001587 def CheckForSha1():
David Pursehousec1b86a22012-11-14 11:36:51 +09001588 try:
1589 # if revision (sha or tag) is not present then following function
1590 # throws an error.
1591 self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
1592 return True
1593 except GitError:
1594 # There is no such persistent revision. We have to fetch it.
1595 return False
Brian Harring14a66742012-09-28 20:21:57 -07001596
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001597 if current_branch_only:
1598 if ID_RE.match(self.revisionExpr) is not None:
1599 is_sha1 = True
1600 elif self.revisionExpr.startswith(R_TAGS):
1601 # this is a tag and its sha1 value should never change
1602 tag_name = self.revisionExpr[len(R_TAGS):]
1603
1604 if is_sha1 or tag_name is not None:
Brian Harring14a66742012-09-28 20:21:57 -07001605 if CheckForSha1():
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001606 return True
Brian Harring14a66742012-09-28 20:21:57 -07001607 if is_sha1 and (not self.upstream or ID_RE.match(self.upstream)):
1608 current_branch_only = False
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001609
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001610 if not name:
1611 name = self.remote.name
Shawn O. Pearcefb231612009-04-10 18:53:46 -07001612
1613 ssh_proxy = False
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07001614 remote = self.GetRemote(name)
1615 if remote.PreConnectFetch():
Shawn O. Pearcefb231612009-04-10 18:53:46 -07001616 ssh_proxy = True
1617
Shawn O. Pearce88443382010-10-08 10:02:09 +02001618 if initial:
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001619 if alt_dir and 'objects' == os.path.basename(alt_dir):
1620 ref_dir = os.path.dirname(alt_dir)
Shawn O. Pearce88443382010-10-08 10:02:09 +02001621 packed_refs = os.path.join(self.gitdir, 'packed-refs')
1622 remote = self.GetRemote(name)
1623
David Pursehouse8a68ff92012-09-24 12:15:13 +09001624 all_refs = self.bare_ref.all
1625 ids = set(all_refs.values())
Shawn O. Pearce88443382010-10-08 10:02:09 +02001626 tmp = set()
1627
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301628 for r, ref_id in GitRefs(ref_dir).all.items():
David Pursehouse8a68ff92012-09-24 12:15:13 +09001629 if r not in all_refs:
Shawn O. Pearce88443382010-10-08 10:02:09 +02001630 if r.startswith(R_TAGS) or remote.WritesTo(r):
David Pursehouse8a68ff92012-09-24 12:15:13 +09001631 all_refs[r] = ref_id
1632 ids.add(ref_id)
Shawn O. Pearce88443382010-10-08 10:02:09 +02001633 continue
1634
David Pursehouse8a68ff92012-09-24 12:15:13 +09001635 if ref_id in ids:
Shawn O. Pearce88443382010-10-08 10:02:09 +02001636 continue
1637
David Pursehouse8a68ff92012-09-24 12:15:13 +09001638 r = 'refs/_alt/%s' % ref_id
1639 all_refs[r] = ref_id
1640 ids.add(ref_id)
Shawn O. Pearce88443382010-10-08 10:02:09 +02001641 tmp.add(r)
1642
Shawn O. Pearce88443382010-10-08 10:02:09 +02001643 tmp_packed = ''
1644 old_packed = ''
1645
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301646 for r in sorted(all_refs):
David Pursehouse8a68ff92012-09-24 12:15:13 +09001647 line = '%s %s\n' % (all_refs[r], r)
Shawn O. Pearce88443382010-10-08 10:02:09 +02001648 tmp_packed += line
1649 if r not in tmp:
1650 old_packed += line
1651
1652 _lwrite(packed_refs, tmp_packed)
Shawn O. Pearce88443382010-10-08 10:02:09 +02001653 else:
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001654 alt_dir = None
Shawn O. Pearce88443382010-10-08 10:02:09 +02001655
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001656 cmd = ['fetch']
Doug Anderson30d45292011-05-04 15:01:04 -07001657
1658 # The --depth option only affects the initial fetch; after that we'll do
1659 # full fetches of changes.
David Pursehouseede7f122012-11-27 22:25:30 +09001660 if self.clone_depth:
1661 depth = self.clone_depth
1662 else:
1663 depth = self.manifest.manifestProject.config.GetString('repo.depth')
Doug Anderson30d45292011-05-04 15:01:04 -07001664 if depth and initial:
1665 cmd.append('--depth=%s' % depth)
1666
Shawn O. Pearce16614f82010-10-29 12:05:43 -07001667 if quiet:
1668 cmd.append('--quiet')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001669 if not self.worktree:
1670 cmd.append('--update-head-ok')
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001671 cmd.append(name)
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001672
Brian Harring14a66742012-09-28 20:21:57 -07001673 if not current_branch_only:
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001674 # Fetch whole repo
Jimmie Wester2f992cb2012-12-07 12:49:51 +01001675 # If using depth then we should not get all the tags since they may
1676 # be outside of the depth.
1677 if no_tags or depth:
Mitchel Humpherys597868b2012-10-29 10:18:34 -07001678 cmd.append('--no-tags')
1679 else:
1680 cmd.append('--tags')
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301681 cmd.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001682 elif tag_name is not None:
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001683 cmd.append('tag')
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001684 cmd.append(tag_name)
1685 else:
1686 branch = self.revisionExpr
Brian Harring14a66742012-09-28 20:21:57 -07001687 if is_sha1:
1688 branch = self.upstream
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001689 if branch.startswith(R_HEADS):
1690 branch = branch[len(R_HEADS):]
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301691 cmd.append(str((u'+refs/heads/%s:' % branch) + remote.ToLocal('refs/heads/%s' % branch)))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07001692
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001693 ok = False
David Pursehouse8a68ff92012-09-24 12:15:13 +09001694 for _i in range(2):
Brian Harring14a66742012-09-28 20:21:57 -07001695 ret = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait()
1696 if ret == 0:
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001697 ok = True
1698 break
Brian Harring14a66742012-09-28 20:21:57 -07001699 elif current_branch_only and is_sha1 and ret == 128:
1700 # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
1701 # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
1702 # abort the optimization attempt and do a full sync.
1703 break
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001704 time.sleep(random.randint(30, 45))
Shawn O. Pearce88443382010-10-08 10:02:09 +02001705
1706 if initial:
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001707 if alt_dir:
Shawn O. Pearce88443382010-10-08 10:02:09 +02001708 if old_packed != '':
1709 _lwrite(packed_refs, old_packed)
1710 else:
1711 os.remove(packed_refs)
1712 self.bare_git.pack_refs('--all', '--prune')
Brian Harring14a66742012-09-28 20:21:57 -07001713
1714 if is_sha1 and current_branch_only and self.upstream:
1715 # We just synced the upstream given branch; verify we
1716 # got what we wanted, else trigger a second run of all
1717 # refs.
1718 if not CheckForSha1():
1719 return self._RemoteFetch(name=name, current_branch_only=False,
1720 initial=False, quiet=quiet, alt_dir=alt_dir)
1721
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001722 return ok
Shawn O. Pearce88443382010-10-08 10:02:09 +02001723
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001724 def _ApplyCloneBundle(self, initial=False, quiet=False):
David Pursehouseede7f122012-11-27 22:25:30 +09001725 if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001726 return False
1727
1728 remote = self.GetRemote(self.remote.name)
1729 bundle_url = remote.url + '/clone.bundle'
1730 bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
Dave Borowitz74c1f3d2013-06-03 15:05:07 -07001731 if GetSchemeFromUrl(bundle_url) not in (
1732 'http', 'https', 'persistent-http', 'persistent-https'):
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001733 return False
1734
1735 bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
1736 bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
1737
1738 exist_dst = os.path.exists(bundle_dst)
1739 exist_tmp = os.path.exists(bundle_tmp)
1740
1741 if not initial and not exist_dst and not exist_tmp:
1742 return False
1743
1744 if not exist_dst:
1745 exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
1746 if not exist_dst:
1747 return False
1748
1749 cmd = ['fetch']
1750 if quiet:
1751 cmd.append('--quiet')
1752 if not self.worktree:
1753 cmd.append('--update-head-ok')
1754 cmd.append(bundle_dst)
1755 for f in remote.fetch:
1756 cmd.append(str(f))
1757 cmd.append('refs/tags/*:refs/tags/*')
1758
1759 ok = GitCommand(self, cmd, bare=True).Wait() == 0
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07001760 if os.path.exists(bundle_dst):
1761 os.remove(bundle_dst)
1762 if os.path.exists(bundle_tmp):
1763 os.remove(bundle_tmp)
Shawn O. Pearce88443382010-10-08 10:02:09 +02001764 return ok
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001765
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001766 def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07001767 if os.path.exists(dstPath):
1768 os.remove(dstPath)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07001769
Matt Gumbel2dc810c2012-08-30 09:39:36 -07001770 cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07001771 if quiet:
1772 cmd += ['--silent']
1773 if os.path.exists(tmpPath):
1774 size = os.stat(tmpPath).st_size
1775 if size >= 1024:
1776 cmd += ['--continue-at', '%d' % (size,)]
1777 else:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07001778 os.remove(tmpPath)
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07001779 if 'http_proxy' in os.environ and 'darwin' == sys.platform:
1780 cmd += ['--proxy', os.environ['http_proxy']]
Dave Borowitz74c1f3d2013-06-03 15:05:07 -07001781 cookiefile = self._GetBundleCookieFile(srcUrl)
Torne (Richard Coles)ed68d0e2013-01-11 16:22:54 +00001782 if cookiefile:
1783 cmd += ['--cookie', cookiefile]
Dave Borowitz74c1f3d2013-06-03 15:05:07 -07001784 if srcUrl.startswith('persistent-'):
1785 srcUrl = srcUrl[len('persistent-'):]
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07001786 cmd += [srcUrl]
1787
1788 if IsTrace():
1789 Trace('%s', ' '.join(cmd))
1790 try:
1791 proc = subprocess.Popen(cmd)
1792 except OSError:
1793 return False
1794
Matt Gumbel2dc810c2012-08-30 09:39:36 -07001795 curlret = proc.wait()
1796
1797 if curlret == 22:
1798 # From curl man page:
1799 # 22: HTTP page not retrieved. The requested url was not found or
1800 # returned another error with the HTTP error code being 400 or above.
1801 # This return code only appears if -f, --fail is used.
1802 if not quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -07001803 print("Server does not provide clone.bundle; ignoring.",
1804 file=sys.stderr)
Matt Gumbel2dc810c2012-08-30 09:39:36 -07001805 return False
1806
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07001807 if os.path.exists(tmpPath):
Dave Borowitz91f3ba52013-06-03 12:15:23 -07001808 if curlret == 0 and self._IsValidBundle(tmpPath):
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07001809 os.rename(tmpPath, dstPath)
1810 return True
1811 else:
1812 os.remove(tmpPath)
1813 return False
1814 else:
1815 return False
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07001816
Dave Borowitz91f3ba52013-06-03 12:15:23 -07001817 def _IsValidBundle(self, path):
1818 try:
1819 with open(path) as f:
1820 if f.read(16) == '# v2 git bundle\n':
1821 return True
1822 else:
1823 print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
1824 return False
1825 except OSError:
1826 return False
1827
Dave Borowitz74c1f3d2013-06-03 15:05:07 -07001828 def _GetBundleCookieFile(self, url):
1829 if url.startswith('persistent-'):
1830 try:
1831 p = subprocess.Popen(
1832 ['git-remote-persistent-https', '-print_config', url],
1833 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1834 stderr=subprocess.PIPE)
1835 prefix = 'http.cookiefile='
1836 for line in p.stdout:
1837 line = line.strip()
1838 if line.startswith(prefix):
1839 return line[len(prefix):]
1840 if p.wait():
1841 line = iter(p.stderr).next()
1842 if ' -print_config' in line:
1843 pass # Persistent proxy doesn't support -print_config.
1844 else:
1845 print(line + p.stderr.read(), file=sys.stderr)
1846 except OSError as e:
1847 if e.errno == errno.ENOENT:
1848 pass # No persistent proxy.
1849 raise
1850 return GitConfig.ForUser().GetString('http.cookiefile')
1851
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001852 def _Checkout(self, rev, quiet=False):
1853 cmd = ['checkout']
1854 if quiet:
1855 cmd.append('-q')
1856 cmd.append(rev)
1857 cmd.append('--')
1858 if GitCommand(self, cmd).Wait() != 0:
1859 if self._allrefs:
1860 raise GitError('%s checkout %s ' % (self.name, rev))
1861
Pierre Tardye5a21222011-03-24 16:28:18 +01001862 def _CherryPick(self, rev, quiet=False):
1863 cmd = ['cherry-pick']
1864 cmd.append(rev)
1865 cmd.append('--')
1866 if GitCommand(self, cmd).Wait() != 0:
1867 if self._allrefs:
1868 raise GitError('%s cherry-pick %s ' % (self.name, rev))
1869
Erwan Mahea94f1622011-08-19 13:56:09 +02001870 def _Revert(self, rev, quiet=False):
1871 cmd = ['revert']
1872 cmd.append('--no-edit')
1873 cmd.append(rev)
1874 cmd.append('--')
1875 if GitCommand(self, cmd).Wait() != 0:
1876 if self._allrefs:
1877 raise GitError('%s revert %s ' % (self.name, rev))
1878
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001879 def _ResetHard(self, rev, quiet=True):
1880 cmd = ['reset', '--hard']
1881 if quiet:
1882 cmd.append('-q')
1883 cmd.append(rev)
1884 if GitCommand(self, cmd).Wait() != 0:
1885 raise GitError('%s reset --hard %s ' % (self.name, rev))
1886
1887 def _Rebase(self, upstream, onto = None):
Shawn O. Pearce19a83d82009-04-16 08:14:26 -07001888 cmd = ['rebase']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001889 if onto is not None:
1890 cmd.extend(['--onto', onto])
1891 cmd.append(upstream)
Shawn O. Pearce19a83d82009-04-16 08:14:26 -07001892 if GitCommand(self, cmd).Wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001893 raise GitError('%s rebase %s ' % (self.name, upstream))
1894
Pierre Tardy3d125942012-05-04 12:18:12 +02001895 def _FastForward(self, head, ffonly=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001896 cmd = ['merge', head]
Pierre Tardy3d125942012-05-04 12:18:12 +02001897 if ffonly:
1898 cmd.append("--ff-only")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001899 if GitCommand(self, cmd).Wait() != 0:
1900 raise GitError('%s merge %s ' % (self.name, head))
1901
Victor Boivie2b30e3a2012-10-05 12:37:58 +02001902 def _InitGitDir(self, mirror_git=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001903 if not os.path.exists(self.gitdir):
1904 os.makedirs(self.gitdir)
1905 self.bare_git.init()
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -08001906
Shawn O. Pearce88443382010-10-08 10:02:09 +02001907 mp = self.manifest.manifestProject
Victor Boivie2b30e3a2012-10-05 12:37:58 +02001908 ref_dir = mp.config.GetString('repo.reference') or ''
Shawn O. Pearce88443382010-10-08 10:02:09 +02001909
Victor Boivie2b30e3a2012-10-05 12:37:58 +02001910 if ref_dir or mirror_git:
1911 if not mirror_git:
1912 mirror_git = os.path.join(ref_dir, self.name + '.git')
Shawn O. Pearce88443382010-10-08 10:02:09 +02001913 repo_git = os.path.join(ref_dir, '.repo', 'projects',
1914 self.relpath + '.git')
1915
1916 if os.path.exists(mirror_git):
1917 ref_dir = mirror_git
1918
1919 elif os.path.exists(repo_git):
1920 ref_dir = repo_git
1921
1922 else:
1923 ref_dir = None
1924
1925 if ref_dir:
1926 _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
1927 os.path.join(ref_dir, 'objects') + '\n')
1928
Jimmie Westera0444582012-10-24 13:44:42 +02001929 self._UpdateHooks()
1930
1931 m = self.manifest.manifestProject.config
1932 for key in ['user.name', 'user.email']:
1933 if m.Has(key, include_defaults = False):
1934 self.config.SetString(key, m.GetString(key))
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -08001935 if self.manifest.IsMirror:
1936 self.config.SetString('core.bare', 'true')
1937 else:
1938 self.config.SetString('core.bare', None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001939
Jimmie Westera0444582012-10-24 13:44:42 +02001940 def _UpdateHooks(self):
1941 if os.path.exists(self.gitdir):
1942 # Always recreate hooks since they can have been changed
1943 # since the latest update.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001944 hooks = self._gitdir_path('hooks')
Shawn O. Pearcede646812008-10-29 14:38:12 -07001945 try:
1946 to_rm = os.listdir(hooks)
1947 except OSError:
1948 to_rm = []
1949 for old_hook in to_rm:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001950 os.remove(os.path.join(hooks, old_hook))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001951 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001952
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001953 def _InitHooks(self):
1954 hooks = self._gitdir_path('hooks')
1955 if not os.path.exists(hooks):
1956 os.makedirs(hooks)
Doug Anderson8ced8642011-01-10 14:16:30 -08001957 for stock_hook in _ProjectHooks():
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07001958 name = os.path.basename(stock_hook)
1959
Victor Boivie65e0f352011-04-18 11:23:29 +02001960 if name in ('commit-msg',) and not self.remote.review \
1961 and not self is self.manifest.manifestProject:
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07001962 # Don't install a Gerrit Code Review hook if this
1963 # project does not appear to use it for reviews.
1964 #
Victor Boivie65e0f352011-04-18 11:23:29 +02001965 # Since the manifest project is one of those, but also
1966 # managed through gerrit, it's excluded
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07001967 continue
1968
1969 dst = os.path.join(hooks, name)
1970 if os.path.islink(dst):
1971 continue
1972 if os.path.exists(dst):
1973 if filecmp.cmp(stock_hook, dst, shallow=False):
1974 os.remove(dst)
1975 else:
1976 _error("%s: Not replacing %s hook", self.relpath, name)
1977 continue
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001978 try:
Mickaël Salaünb9477bc2012-08-05 13:39:26 +02001979 os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
Sarah Owensa5be53f2012-09-09 15:37:57 -07001980 except OSError as e:
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07001981 if e.errno == errno.EPERM:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001982 raise GitError('filesystem must support symlinks')
1983 else:
1984 raise
1985
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001986 def _InitRemote(self):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -07001987 if self.remote.url:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001988 remote = self.GetRemote(self.remote.name)
Shawn O. Pearced1f70d92009-05-19 14:58:02 -07001989 remote.url = self.remote.url
1990 remote.review = self.remote.review
1991 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001992
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001993 if self.worktree:
1994 remote.ResetFetch(mirror=False)
1995 else:
1996 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001997 remote.Save()
1998
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001999 def _InitMRef(self):
2000 if self.manifest.branch:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002001 self._InitAnyMRef(R_M + self.manifest.branch)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002002
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08002003 def _InitMirrorHead(self):
Shawn O. Pearcefe200ee2009-06-01 15:28:21 -07002004 self._InitAnyMRef(HEAD)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002005
2006 def _InitAnyMRef(self, ref):
2007 cur = self.bare_ref.symref(ref)
2008
2009 if self.revisionId:
2010 if cur != '' or self.bare_ref.get(ref) != self.revisionId:
2011 msg = 'manifest set to %s' % self.revisionId
2012 dst = self.revisionId + '^0'
2013 self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
2014 else:
2015 remote = self.GetRemote(self.remote.name)
2016 dst = remote.ToLocal(self.revisionExpr)
2017 if cur != dst:
2018 msg = 'manifest set to %s' % self.revisionExpr
2019 self.bare_git.symbolic_ref('-m', msg, ref, dst)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08002020
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002021 def _InitWorkTree(self):
2022 dotgit = os.path.join(self.worktree, '.git')
2023 if not os.path.exists(dotgit):
2024 os.makedirs(dotgit)
2025
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002026 for name in ['config',
2027 'description',
2028 'hooks',
2029 'info',
2030 'logs',
2031 'objects',
2032 'packed-refs',
2033 'refs',
2034 'rr-cache',
2035 'svn']:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08002036 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08002037 src = os.path.join(self.gitdir, name)
2038 dst = os.path.join(dotgit, name)
Nico Sallembiend63060f2010-01-20 10:27:50 -08002039 if os.path.islink(dst) or not os.path.exists(dst):
Mickaël Salaünb9477bc2012-08-05 13:39:26 +02002040 os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
Nico Sallembiend63060f2010-01-20 10:27:50 -08002041 else:
2042 raise GitError('cannot overwrite a local work tree')
Sarah Owensa5be53f2012-09-09 15:37:57 -07002043 except OSError as e:
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -08002044 if e.errno == errno.EPERM:
2045 raise GitError('filesystem must support symlinks')
2046 else:
2047 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002048
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002049 _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002050
2051 cmd = ['read-tree', '--reset', '-u']
2052 cmd.append('-v')
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002053 cmd.append(HEAD)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002054 if GitCommand(self, cmd).Wait() != 0:
2055 raise GitError("cannot initialize work tree")
Victor Boivie0960b5b2010-11-26 13:42:13 +01002056
2057 rr_cache = os.path.join(self.gitdir, 'rr-cache')
2058 if not os.path.exists(rr_cache):
2059 os.makedirs(rr_cache)
2060
Shawn O. Pearce93609662009-04-21 10:50:33 -07002061 self._CopyFiles()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002062
2063 def _gitdir_path(self, path):
2064 return os.path.join(self.gitdir, path)
2065
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07002066 def _revlist(self, *args, **kw):
2067 a = []
2068 a.extend(args)
2069 a.append('--')
2070 return self.work_git.rev_list(*a, **kw)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002071
2072 @property
2073 def _allrefs(self):
Shawn O. Pearced237b692009-04-17 18:49:50 -07002074 return self.bare_ref.all
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002075
2076 class _GitGetByExec(object):
2077 def __init__(self, project, bare):
2078 self._project = project
2079 self._bare = bare
2080
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002081 def LsOthers(self):
2082 p = GitCommand(self._project,
2083 ['ls-files',
2084 '-z',
2085 '--others',
2086 '--exclude-standard'],
2087 bare = False,
2088 capture_stdout = True,
2089 capture_stderr = True)
2090 if p.Wait() == 0:
2091 out = p.stdout
2092 if out:
David Pursehouse1d947b32012-10-25 12:23:11 +09002093 return out[:-1].split('\0') # pylint: disable=W1401
2094 # Backslash is not anomalous
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002095 return []
2096
2097 def DiffZ(self, name, *args):
2098 cmd = [name]
2099 cmd.append('-z')
2100 cmd.extend(args)
2101 p = GitCommand(self._project,
2102 cmd,
2103 bare = False,
2104 capture_stdout = True,
2105 capture_stderr = True)
2106 try:
2107 out = p.process.stdout.read()
2108 r = {}
2109 if out:
David Pursehouse1d947b32012-10-25 12:23:11 +09002110 out = iter(out[:-1].split('\0')) # pylint: disable=W1401
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002111 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07002112 try:
2113 info = out.next()
2114 path = out.next()
2115 except StopIteration:
2116 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002117
2118 class _Info(object):
2119 def __init__(self, path, omode, nmode, oid, nid, state):
2120 self.path = path
2121 self.src_path = None
2122 self.old_mode = omode
2123 self.new_mode = nmode
2124 self.old_id = oid
2125 self.new_id = nid
2126
2127 if len(state) == 1:
2128 self.status = state
2129 self.level = None
2130 else:
2131 self.status = state[:1]
2132 self.level = state[1:]
2133 while self.level.startswith('0'):
2134 self.level = self.level[1:]
2135
2136 info = info[1:].split(' ')
David Pursehouse8f62fb72012-11-14 12:09:38 +09002137 info = _Info(path, *info)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002138 if info.status in ('R', 'C'):
2139 info.src_path = info.path
2140 info.path = out.next()
2141 r[info.path] = info
2142 return r
2143 finally:
2144 p.Wait()
2145
2146 def GetHead(self):
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07002147 if self._bare:
2148 path = os.path.join(self._project.gitdir, HEAD)
2149 else:
2150 path = os.path.join(self._project.worktree, '.git', HEAD)
Conley Owens75ee0572012-11-15 17:33:11 -08002151 try:
2152 fd = open(path, 'rb')
2153 except IOError:
2154 raise NoManifestException(path)
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -07002155 try:
2156 line = fd.read()
2157 finally:
2158 fd.close()
Chirayu Desai217ea7d2013-03-01 19:14:38 +05302159 try:
2160 line = line.decode()
2161 except AttributeError:
2162 pass
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07002163 if line.startswith('ref: '):
2164 return line[5:-1]
2165 return line[:-1]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002166
2167 def SetHead(self, ref, message=None):
2168 cmdv = []
2169 if message is not None:
2170 cmdv.extend(['-m', message])
2171 cmdv.append(HEAD)
2172 cmdv.append(ref)
2173 self.symbolic_ref(*cmdv)
2174
2175 def DetachHead(self, new, message=None):
2176 cmdv = ['--no-deref']
2177 if message is not None:
2178 cmdv.extend(['-m', message])
2179 cmdv.append(HEAD)
2180 cmdv.append(new)
2181 self.update_ref(*cmdv)
2182
2183 def UpdateRef(self, name, new, old=None,
2184 message=None,
2185 detach=False):
2186 cmdv = []
2187 if message is not None:
2188 cmdv.extend(['-m', message])
2189 if detach:
2190 cmdv.append('--no-deref')
2191 cmdv.append(name)
2192 cmdv.append(new)
2193 if old is not None:
2194 cmdv.append(old)
2195 self.update_ref(*cmdv)
2196
2197 def DeleteRef(self, name, old=None):
2198 if not old:
2199 old = self.rev_parse(name)
2200 self.update_ref('-d', name, old)
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07002201 self._project.bare_ref.deleted(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002202
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07002203 def rev_list(self, *args, **kw):
2204 if 'format' in kw:
2205 cmdv = ['log', '--pretty=format:%s' % kw['format']]
2206 else:
2207 cmdv = ['rev-list']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002208 cmdv.extend(args)
2209 p = GitCommand(self._project,
2210 cmdv,
2211 bare = self._bare,
2212 capture_stdout = True,
2213 capture_stderr = True)
2214 r = []
2215 for line in p.process.stdout:
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07002216 if line[-1] == '\n':
2217 line = line[:-1]
2218 r.append(line)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002219 if p.Wait() != 0:
2220 raise GitError('%s rev-list %s: %s' % (
2221 self._project.name,
2222 str(args),
2223 p.stderr))
2224 return r
2225
2226 def __getattr__(self, name):
Doug Anderson37282b42011-03-04 11:54:18 -08002227 """Allow arbitrary git commands using pythonic syntax.
2228
2229 This allows you to do things like:
2230 git_obj.rev_parse('HEAD')
2231
2232 Since we don't have a 'rev_parse' method defined, the __getattr__ will
2233 run. We'll replace the '_' with a '-' and try to run a git command.
Dave Borowitz091f8932012-10-23 17:01:04 -07002234 Any other positional arguments will be passed to the git command, and the
2235 following keyword arguments are supported:
2236 config: An optional dict of git config options to be passed with '-c'.
Doug Anderson37282b42011-03-04 11:54:18 -08002237
2238 Args:
2239 name: The name of the git command to call. Any '_' characters will
2240 be replaced with '-'.
2241
2242 Returns:
2243 A callable object that will try to call git with the named command.
2244 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002245 name = name.replace('_', '-')
Dave Borowitz091f8932012-10-23 17:01:04 -07002246 def runner(*args, **kwargs):
2247 cmdv = []
2248 config = kwargs.pop('config', None)
2249 for k in kwargs:
2250 raise TypeError('%s() got an unexpected keyword argument %r'
2251 % (name, k))
2252 if config is not None:
Dave Borowitzb42b4742012-10-31 12:27:27 -07002253 if not git_require((1, 7, 2)):
2254 raise ValueError('cannot set config on command line for %s()'
2255 % name)
Chirayu Desai217ea7d2013-03-01 19:14:38 +05302256 for k, v in config.items():
Dave Borowitz091f8932012-10-23 17:01:04 -07002257 cmdv.append('-c')
2258 cmdv.append('%s=%s' % (k, v))
2259 cmdv.append(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002260 cmdv.extend(args)
2261 p = GitCommand(self._project,
2262 cmdv,
2263 bare = self._bare,
2264 capture_stdout = True,
2265 capture_stderr = True)
2266 if p.Wait() != 0:
2267 raise GitError('%s %s: %s' % (
2268 self._project.name,
2269 name,
2270 p.stderr))
2271 r = p.stdout
Chirayu Desai217ea7d2013-03-01 19:14:38 +05302272 try:
2273 r = r.decode()
2274 except AttributeError:
2275 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002276 if r.endswith('\n') and r.index('\n') == len(r) - 1:
2277 return r[:-1]
2278 return r
2279 return runner
2280
2281
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002282class _PriorSyncFailedError(Exception):
2283 def __str__(self):
2284 return 'prior sync failed; rebase still in progress'
2285
2286class _DirtyError(Exception):
2287 def __str__(self):
2288 return 'contains uncommitted changes'
2289
2290class _InfoMessage(object):
2291 def __init__(self, project, text):
2292 self.project = project
2293 self.text = text
2294
2295 def Print(self, syncbuf):
2296 syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
2297 syncbuf.out.nl()
2298
2299class _Failure(object):
2300 def __init__(self, project, why):
2301 self.project = project
2302 self.why = why
2303
2304 def Print(self, syncbuf):
2305 syncbuf.out.fail('error: %s/: %s',
2306 self.project.relpath,
2307 str(self.why))
2308 syncbuf.out.nl()
2309
2310class _Later(object):
2311 def __init__(self, project, action):
2312 self.project = project
2313 self.action = action
2314
2315 def Run(self, syncbuf):
2316 out = syncbuf.out
2317 out.project('project %s/', self.project.relpath)
2318 out.nl()
2319 try:
2320 self.action()
2321 out.nl()
2322 return True
David Pursehouse8a68ff92012-09-24 12:15:13 +09002323 except GitError:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002324 out.nl()
2325 return False
2326
2327class _SyncColoring(Coloring):
2328 def __init__(self, config):
2329 Coloring.__init__(self, config, 'reposync')
2330 self.project = self.printer('header', attr = 'bold')
2331 self.info = self.printer('info')
2332 self.fail = self.printer('fail', fg='red')
2333
2334class SyncBuffer(object):
2335 def __init__(self, config, detach_head=False):
2336 self._messages = []
2337 self._failures = []
2338 self._later_queue1 = []
2339 self._later_queue2 = []
2340
2341 self.out = _SyncColoring(config)
2342 self.out.redirect(sys.stderr)
2343
2344 self.detach_head = detach_head
2345 self.clean = True
2346
2347 def info(self, project, fmt, *args):
2348 self._messages.append(_InfoMessage(project, fmt % args))
2349
2350 def fail(self, project, err=None):
2351 self._failures.append(_Failure(project, err))
2352 self.clean = False
2353
2354 def later1(self, project, what):
2355 self._later_queue1.append(_Later(project, what))
2356
2357 def later2(self, project, what):
2358 self._later_queue2.append(_Later(project, what))
2359
2360 def Finish(self):
2361 self._PrintMessages()
2362 self._RunLater()
2363 self._PrintMessages()
2364 return self.clean
2365
2366 def _RunLater(self):
2367 for q in ['_later_queue1', '_later_queue2']:
2368 if not self._RunQueue(q):
2369 return
2370
2371 def _RunQueue(self, queue):
2372 for m in getattr(self, queue):
2373 if not m.Run(self):
2374 self.clean = False
2375 return False
2376 setattr(self, queue, [])
2377 return True
2378
2379 def _PrintMessages(self):
2380 for m in self._messages:
2381 m.Print(self)
2382 for m in self._failures:
2383 m.Print(self)
2384
2385 self._messages = []
2386 self._failures = []
2387
2388
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002389class MetaProject(Project):
2390 """A special project housed under .repo.
2391 """
2392 def __init__(self, manifest, name, gitdir, worktree):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002393 Project.__init__(self,
2394 manifest = manifest,
2395 name = name,
2396 gitdir = gitdir,
2397 worktree = worktree,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -07002398 remote = RemoteSpec('origin'),
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002399 relpath = '.repo/%s' % name,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002400 revisionExpr = 'refs/heads/master',
Colin Cross5acde752012-03-28 20:15:45 -07002401 revisionId = None,
2402 groups = None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002403
2404 def PreSync(self):
2405 if self.Exists:
2406 cb = self.CurrentBranch
2407 if cb:
2408 base = self.GetBranch(cb).merge
2409 if base:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002410 self.revisionExpr = base
2411 self.revisionId = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002412
Florian Vallee5d016502012-06-07 17:19:26 +02002413 def MetaBranchSwitch(self, target):
2414 """ Prepare MetaProject for manifest branch switch
2415 """
2416
2417 # detach and delete manifest branch, allowing a new
2418 # branch to take over
2419 syncbuf = SyncBuffer(self.config, detach_head = True)
2420 self.Sync_LocalHalf(syncbuf)
2421 syncbuf.Finish()
2422
2423 return GitCommand(self,
Torne (Richard Coles)e8f75fa2012-07-20 15:32:19 +01002424 ['update-ref', '-d', 'refs/heads/default'],
Florian Vallee5d016502012-06-07 17:19:26 +02002425 capture_stdout = True,
2426 capture_stderr = True).Wait() == 0
2427
2428
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002429 @property
Shawn O. Pearcef6906872009-04-18 10:49:00 -07002430 def LastFetch(self):
2431 try:
2432 fh = os.path.join(self.gitdir, 'FETCH_HEAD')
2433 return os.path.getmtime(fh)
2434 except OSError:
2435 return 0
2436
2437 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002438 def HasChanges(self):
2439 """Has the remote received new commits not yet checked out?
2440 """
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002441 if not self.remote or not self.revisionExpr:
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07002442 return False
2443
David Pursehouse8a68ff92012-09-24 12:15:13 +09002444 all_refs = self.bare_ref.all
2445 revid = self.GetRevisionId(all_refs)
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07002446 head = self.work_git.GetHead()
2447 if head.startswith(R_HEADS):
2448 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09002449 head = all_refs[head]
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07002450 except KeyError:
2451 head = None
2452
2453 if revid == head:
2454 return False
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002455 elif self._revlist(not_rev(HEAD), revid):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002456 return True
2457 return False