blob: b53165c396a6f2f3eae8870535e16127c6caaee4 [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
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -080016import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070017import filecmp
Wink Saville4c426ef2015-06-03 08:05:17 -070018import glob
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070019import 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
Julien Campergue335f5ef2013-10-16 11:02:35 +020026import tarfile
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +080027import tempfile
Shawn O. Pearcec325dc32011-10-03 08:30:24 -070028import time
Dave Borowitz137d0132015-01-02 11:12:54 -080029import traceback
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -070030
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070031from color import Coloring
Dave Borowitzb42b4742012-10-31 12:27:27 -070032from git_command import GitCommand, git_require
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -070033from git_config import GitConfig, IsId, GetSchemeFromUrl, GetUrlCookieFile, \
Ningning Xiac2fbc782016-08-22 14:24:39 -070034 ID_RE, RefSpec
Kevin Degiabaa7f32014-11-12 11:27:45 -070035from error import GitError, HookError, UploadError, DownloadError
Ningning Xiac2fbc782016-08-22 14:24:39 -070036from error import CacheApplyError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080037from error import ManifestInvalidRevisionError
Conley Owens75ee0572012-11-15 17:33:11 -080038from error import NoManifestException
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -070039from trace import IsTrace, Trace
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070040
Shawn O. Pearced237b692009-04-17 18:49:50 -070041from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042
David Pursehouse59bbb582013-05-17 10:49:33 +090043from pyversion import is_python3
Mike Frysinger40252c22016-08-15 21:23:44 -040044if is_python3():
45 import urllib.parse
46else:
47 import imp
48 import urlparse
49 urllib = imp.new_module('urllib')
50 urllib.parse = urlparse
David Pursehouse59bbb582013-05-17 10:49:33 +090051 # pylint:disable=W0622
Chirayu Desai217ea7d2013-03-01 19:14:38 +053052 input = raw_input
David Pursehouse59bbb582013-05-17 10:49:33 +090053 # pylint:enable=W0622
Chirayu Desai217ea7d2013-03-01 19:14:38 +053054
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -070055
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -070056def _lwrite(path, content):
57 lock = '%s.lock' % path
58
Chirayu Desai303a82f2014-08-19 22:57:17 +053059 fd = open(lock, 'w')
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -070060 try:
61 fd.write(content)
62 finally:
63 fd.close()
64
65 try:
66 os.rename(lock, path)
67 except OSError:
68 os.remove(lock)
69 raise
70
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -070071
Shawn O. Pearce48244782009-04-16 08:25:57 -070072def _error(fmt, *args):
73 msg = fmt % args
Sarah Owenscecd1d82012-11-01 22:59:27 -070074 print('error: %s' % msg, file=sys.stderr)
Shawn O. Pearce48244782009-04-16 08:25:57 -070075
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -070076
David Pursehousef33929d2015-08-24 14:39:14 +090077def _warn(fmt, *args):
78 msg = fmt % args
79 print('warn: %s' % msg, file=sys.stderr)
80
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -070081
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070082def not_rev(r):
83 return '^' + r
84
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -070085
Shawn O. Pearceb54a3922009-01-05 16:18:58 -080086def sq(r):
87 return "'" + r.replace("'", "'\''") + "'"
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -080088
Jonathan Nieder93719792015-03-17 11:29:58 -070089_project_hook_list = None
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -070090
91
Jonathan Nieder93719792015-03-17 11:29:58 -070092def _ProjectHooks():
93 """List the hooks present in the 'hooks' directory.
94
95 These hooks are project hooks and are copied to the '.git/hooks' directory
96 of all subprojects.
97
98 This function caches the list of hooks (based on the contents of the
99 'repo/hooks' directory) on the first call.
100
101 Returns:
102 A list of absolute paths to all of the files in the hooks directory.
103 """
104 global _project_hook_list
105 if _project_hook_list is None:
106 d = os.path.realpath(os.path.abspath(os.path.dirname(__file__)))
107 d = os.path.join(d, 'hooks')
108 _project_hook_list = [os.path.join(d, x) for x in os.listdir(d)]
109 return _project_hook_list
110
111
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700112class DownloadedChange(object):
113 _commit_cache = None
114
115 def __init__(self, project, base, change_id, ps_id, commit):
116 self.project = project
117 self.base = base
118 self.change_id = change_id
119 self.ps_id = ps_id
120 self.commit = commit
121
122 @property
123 def commits(self):
124 if self._commit_cache is None:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700125 self._commit_cache = self.project.bare_git.rev_list('--abbrev=8',
126 '--abbrev-commit',
127 '--pretty=oneline',
128 '--reverse',
129 '--date-order',
130 not_rev(self.base),
131 self.commit,
132 '--')
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700133 return self._commit_cache
134
135
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700136class ReviewableBranch(object):
137 _commit_cache = None
138
139 def __init__(self, project, branch, base):
140 self.project = project
141 self.branch = branch
142 self.base = base
143
144 @property
145 def name(self):
146 return self.branch.name
147
148 @property
149 def commits(self):
150 if self._commit_cache is None:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700151 self._commit_cache = self.project.bare_git.rev_list('--abbrev=8',
152 '--abbrev-commit',
153 '--pretty=oneline',
154 '--reverse',
155 '--date-order',
156 not_rev(self.base),
157 R_HEADS + self.name,
158 '--')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700159 return self._commit_cache
160
161 @property
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800162 def unabbrev_commits(self):
163 r = dict()
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700164 for commit in self.project.bare_git.rev_list(not_rev(self.base),
165 R_HEADS + self.name,
166 '--'):
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800167 r[commit[0:8]] = commit
168 return r
169
170 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700171 def date(self):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700172 return self.project.bare_git.log('--pretty=format:%cd',
173 '-n', '1',
174 R_HEADS + self.name,
175 '--')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700176
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700177 def UploadForReview(self, people,
178 auto_topic=False,
179 draft=False,
Changcheng Xiao7da6f862017-08-02 16:55:03 +0200180 private=False,
181 wip=False,
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700182 dest_branch=None):
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800183 self.project.UploadForReview(self.name,
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -0700184 people,
Brian Harring435370c2012-07-28 15:37:04 -0700185 auto_topic=auto_topic,
Bryan Jacobsf609f912013-05-06 13:36:24 -0400186 draft=draft,
Changcheng Xiao7da6f862017-08-02 16:55:03 +0200187 private=private,
188 wip=wip,
Bryan Jacobsf609f912013-05-06 13:36:24 -0400189 dest_branch=dest_branch)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700190
Ficus Kirkpatrickbc7ef672009-05-04 12:45:11 -0700191 def GetPublishedRefs(self):
192 refs = {}
193 output = self.project.bare_git.ls_remote(
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700194 self.branch.remote.SshReviewUrl(self.project.UserEmail),
195 'refs/changes/*')
Ficus Kirkpatrickbc7ef672009-05-04 12:45:11 -0700196 for line in output.split('\n'):
197 try:
198 (sha, ref) = line.split()
199 refs[sha] = ref
200 except ValueError:
201 pass
202
203 return refs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700204
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700205
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700206class StatusColoring(Coloring):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700207
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700208 def __init__(self, config):
209 Coloring.__init__(self, config, 'status')
Anthony King7bdac712014-07-16 12:56:40 +0100210 self.project = self.printer('header', attr='bold')
211 self.branch = self.printer('header', attr='bold')
212 self.nobranch = self.printer('nobranch', fg='red')
213 self.important = self.printer('important', fg='red')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700214
Anthony King7bdac712014-07-16 12:56:40 +0100215 self.added = self.printer('added', fg='green')
216 self.changed = self.printer('changed', fg='red')
217 self.untracked = self.printer('untracked', fg='red')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218
219
220class DiffColoring(Coloring):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700221
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700222 def __init__(self, config):
223 Coloring.__init__(self, config, 'diff')
Anthony King7bdac712014-07-16 12:56:40 +0100224 self.project = self.printer('header', attr='bold')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700225
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700226
Anthony King7bdac712014-07-16 12:56:40 +0100227class _Annotation(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700228
James W. Mills24c13082012-04-12 15:04:13 -0500229 def __init__(self, name, value, keep):
230 self.name = name
231 self.value = value
232 self.keep = keep
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700233
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700234
Anthony King7bdac712014-07-16 12:56:40 +0100235class _CopyFile(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700236
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800237 def __init__(self, src, dest, abssrc, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700238 self.src = src
239 self.dest = dest
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800240 self.abs_src = abssrc
241 self.abs_dest = absdest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700242
243 def _Copy(self):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800244 src = self.abs_src
245 dest = self.abs_dest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700246 # copy file if it does not exist or is out of date
247 if not os.path.exists(dest) or not filecmp.cmp(src, dest):
248 try:
249 # remove existing file first, since it might be read-only
250 if os.path.exists(dest):
251 os.remove(dest)
Matthew Buckett2daf6672009-07-11 09:43:47 -0400252 else:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200253 dest_dir = os.path.dirname(dest)
254 if not os.path.isdir(dest_dir):
255 os.makedirs(dest_dir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700256 shutil.copy(src, dest)
257 # make the file read-only
258 mode = os.stat(dest)[stat.ST_MODE]
259 mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
260 os.chmod(dest, mode)
261 except IOError:
Shawn O. Pearce48244782009-04-16 08:25:57 -0700262 _error('Cannot copy file %s to %s', src, dest)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700263
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700264
Anthony King7bdac712014-07-16 12:56:40 +0100265class _LinkFile(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700266
Wink Saville4c426ef2015-06-03 08:05:17 -0700267 def __init__(self, git_worktree, src, dest, relsrc, absdest):
268 self.git_worktree = git_worktree
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500269 self.src = src
270 self.dest = dest
Colin Cross0184dcc2015-05-05 00:24:54 -0700271 self.src_rel_to_dest = relsrc
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500272 self.abs_dest = absdest
273
Wink Saville4c426ef2015-06-03 08:05:17 -0700274 def __linkIt(self, relSrc, absDest):
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500275 # link file if it does not exist or is out of date
Wink Saville4c426ef2015-06-03 08:05:17 -0700276 if not os.path.islink(absDest) or (os.readlink(absDest) != relSrc):
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500277 try:
278 # remove existing file first, since it might be read-only
Dan Willemsene1e0bd12015-11-18 16:49:38 -0800279 if os.path.lexists(absDest):
Wink Saville4c426ef2015-06-03 08:05:17 -0700280 os.remove(absDest)
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500281 else:
Wink Saville4c426ef2015-06-03 08:05:17 -0700282 dest_dir = os.path.dirname(absDest)
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500283 if not os.path.isdir(dest_dir):
284 os.makedirs(dest_dir)
Wink Saville4c426ef2015-06-03 08:05:17 -0700285 os.symlink(relSrc, absDest)
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500286 except IOError:
Wink Saville4c426ef2015-06-03 08:05:17 -0700287 _error('Cannot link file %s to %s', relSrc, absDest)
288
289 def _Link(self):
290 """Link the self.rel_src_to_dest and self.abs_dest. Handles wild cards
291 on the src linking all of the files in the source in to the destination
292 directory.
293 """
294 # We use the absSrc to handle the situation where the current directory
295 # is not the root of the repo
296 absSrc = os.path.join(self.git_worktree, self.src)
297 if os.path.exists(absSrc):
298 # Entity exists so just a simple one to one link operation
299 self.__linkIt(self.src_rel_to_dest, self.abs_dest)
300 else:
301 # Entity doesn't exist assume there is a wild card
302 absDestDir = self.abs_dest
303 if os.path.exists(absDestDir) and not os.path.isdir(absDestDir):
304 _error('Link error: src with wildcard, %s must be a directory',
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700305 absDestDir)
Wink Saville4c426ef2015-06-03 08:05:17 -0700306 else:
307 absSrcFiles = glob.glob(absSrc)
308 for absSrcFile in absSrcFiles:
309 # Create a releative path from source dir to destination dir
310 absSrcDir = os.path.dirname(absSrcFile)
311 relSrcDir = os.path.relpath(absSrcDir, absDestDir)
312
313 # Get the source file name
314 srcFile = os.path.basename(absSrcFile)
315
316 # Now form the final full paths to srcFile. They will be
317 # absolute for the desintaiton and relative for the srouce.
318 absDest = os.path.join(absDestDir, srcFile)
319 relSrc = os.path.join(relSrcDir, srcFile)
320 self.__linkIt(relSrc, absDest)
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500321
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700322
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700323class RemoteSpec(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700324
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700325 def __init__(self,
326 name,
Anthony King7bdac712014-07-16 12:56:40 +0100327 url=None,
Steve Raed6480452016-08-10 15:00:00 -0700328 pushUrl=None,
Anthony King7bdac712014-07-16 12:56:40 +0100329 review=None,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700330 revision=None,
331 orig_name=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700332 self.name = name
333 self.url = url
Steve Raed6480452016-08-10 15:00:00 -0700334 self.pushUrl = pushUrl
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700335 self.review = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100336 self.revision = revision
Dan Willemsen96c2d652016-04-06 16:03:54 -0700337 self.orig_name = orig_name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700338
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700339
Doug Anderson37282b42011-03-04 11:54:18 -0800340class RepoHook(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700341
Doug Anderson37282b42011-03-04 11:54:18 -0800342 """A RepoHook contains information about a script to run as a hook.
343
344 Hooks are used to run a python script before running an upload (for instance,
345 to run presubmit checks). Eventually, we may have hooks for other actions.
346
347 This shouldn't be confused with files in the 'repo/hooks' directory. Those
348 files are copied into each '.git/hooks' folder for each project. Repo-level
349 hooks are associated instead with repo actions.
350
351 Hooks are always python. When a hook is run, we will load the hook into the
352 interpreter and execute its main() function.
353 """
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700354
Doug Anderson37282b42011-03-04 11:54:18 -0800355 def __init__(self,
356 hook_type,
357 hooks_project,
358 topdir,
Mike Frysinger40252c22016-08-15 21:23:44 -0400359 manifest_url,
Doug Anderson37282b42011-03-04 11:54:18 -0800360 abort_if_user_denies=False):
361 """RepoHook constructor.
362
363 Params:
364 hook_type: A string representing the type of hook. This is also used
365 to figure out the name of the file containing the hook. For
366 example: 'pre-upload'.
367 hooks_project: The project containing the repo hooks. If you have a
368 manifest, this is manifest.repo_hooks_project. OK if this is None,
369 which will make the hook a no-op.
370 topdir: Repo's top directory (the one containing the .repo directory).
371 Scripts will run with CWD as this directory. If you have a manifest,
372 this is manifest.topdir
Mike Frysinger40252c22016-08-15 21:23:44 -0400373 manifest_url: The URL to the manifest git repo.
Doug Anderson37282b42011-03-04 11:54:18 -0800374 abort_if_user_denies: If True, we'll throw a HookError() if the user
375 doesn't allow us to run the hook.
376 """
377 self._hook_type = hook_type
378 self._hooks_project = hooks_project
Mike Frysinger40252c22016-08-15 21:23:44 -0400379 self._manifest_url = manifest_url
Doug Anderson37282b42011-03-04 11:54:18 -0800380 self._topdir = topdir
381 self._abort_if_user_denies = abort_if_user_denies
382
383 # Store the full path to the script for convenience.
384 if self._hooks_project:
385 self._script_fullpath = os.path.join(self._hooks_project.worktree,
386 self._hook_type + '.py')
387 else:
388 self._script_fullpath = None
389
390 def _GetHash(self):
391 """Return a hash of the contents of the hooks directory.
392
393 We'll just use git to do this. This hash has the property that if anything
394 changes in the directory we will return a different has.
395
396 SECURITY CONSIDERATION:
397 This hash only represents the contents of files in the hook directory, not
398 any other files imported or called by hooks. Changes to imported files
399 can change the script behavior without affecting the hash.
400
401 Returns:
402 A string representing the hash. This will always be ASCII so that it can
403 be printed to the user easily.
404 """
405 assert self._hooks_project, "Must have hooks to calculate their hash."
406
407 # We will use the work_git object rather than just calling GetRevisionId().
408 # That gives us a hash of the latest checked in version of the files that
409 # the user will actually be executing. Specifically, GetRevisionId()
410 # doesn't appear to change even if a user checks out a different version
411 # of the hooks repo (via git checkout) nor if a user commits their own revs.
412 #
413 # NOTE: Local (non-committed) changes will not be factored into this hash.
414 # I think this is OK, since we're really only worried about warning the user
415 # about upstream changes.
416 return self._hooks_project.work_git.rev_parse('HEAD')
417
418 def _GetMustVerb(self):
419 """Return 'must' if the hook is required; 'should' if not."""
420 if self._abort_if_user_denies:
421 return 'must'
422 else:
423 return 'should'
424
425 def _CheckForHookApproval(self):
426 """Check to see whether this hook has been approved.
427
Mike Frysinger40252c22016-08-15 21:23:44 -0400428 We'll accept approval of manifest URLs if they're using secure transports.
429 This way the user can say they trust the manifest hoster. For insecure
430 hosts, we fall back to checking the hash of the hooks repo.
Doug Anderson37282b42011-03-04 11:54:18 -0800431
432 Note that we ask permission for each individual hook even though we use
433 the hash of all hooks when detecting changes. We'd like the user to be
434 able to approve / deny each hook individually. We only use the hash of all
435 hooks because there is no other easy way to detect changes to local imports.
436
437 Returns:
438 True if this hook is approved to run; False otherwise.
439
440 Raises:
441 HookError: Raised if the user doesn't approve and abort_if_user_denies
442 was passed to the consturctor.
443 """
Mike Frysinger40252c22016-08-15 21:23:44 -0400444 if self._ManifestUrlHasSecureScheme():
445 return self._CheckForHookApprovalManifest()
446 else:
447 return self._CheckForHookApprovalHash()
448
449 def _CheckForHookApprovalHelper(self, subkey, new_val, main_prompt,
450 changed_prompt):
451 """Check for approval for a particular attribute and hook.
452
453 Args:
454 subkey: The git config key under [repo.hooks.<hook_type>] to store the
455 last approved string.
456 new_val: The new value to compare against the last approved one.
457 main_prompt: Message to display to the user to ask for approval.
458 changed_prompt: Message explaining why we're re-asking for approval.
459
460 Returns:
461 True if this hook is approved to run; False otherwise.
462
463 Raises:
464 HookError: Raised if the user doesn't approve and abort_if_user_denies
465 was passed to the consturctor.
466 """
Doug Anderson37282b42011-03-04 11:54:18 -0800467 hooks_config = self._hooks_project.config
Mike Frysinger40252c22016-08-15 21:23:44 -0400468 git_approval_key = 'repo.hooks.%s.%s' % (self._hook_type, subkey)
Doug Anderson37282b42011-03-04 11:54:18 -0800469
Mike Frysinger40252c22016-08-15 21:23:44 -0400470 # Get the last value that the user approved for this hook; may be None.
471 old_val = hooks_config.GetString(git_approval_key)
Doug Anderson37282b42011-03-04 11:54:18 -0800472
Mike Frysinger40252c22016-08-15 21:23:44 -0400473 if old_val is not None:
Doug Anderson37282b42011-03-04 11:54:18 -0800474 # User previously approved hook and asked not to be prompted again.
Mike Frysinger40252c22016-08-15 21:23:44 -0400475 if new_val == old_val:
Doug Anderson37282b42011-03-04 11:54:18 -0800476 # Approval matched. We're done.
477 return True
478 else:
479 # Give the user a reason why we're prompting, since they last told
480 # us to "never ask again".
Mike Frysinger40252c22016-08-15 21:23:44 -0400481 prompt = 'WARNING: %s\n\n' % (changed_prompt,)
Doug Anderson37282b42011-03-04 11:54:18 -0800482 else:
483 prompt = ''
484
485 # Prompt the user if we're not on a tty; on a tty we'll assume "no".
486 if sys.stdout.isatty():
Mike Frysinger40252c22016-08-15 21:23:44 -0400487 prompt += main_prompt + ' (yes/always/NO)? '
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530488 response = input(prompt).lower()
David Pursehouse98ffba12012-11-14 11:18:00 +0900489 print()
Doug Anderson37282b42011-03-04 11:54:18 -0800490
491 # User is doing a one-time approval.
492 if response in ('y', 'yes'):
493 return True
Mike Frysinger40252c22016-08-15 21:23:44 -0400494 elif response == 'always':
495 hooks_config.SetString(git_approval_key, new_val)
Doug Anderson37282b42011-03-04 11:54:18 -0800496 return True
497
498 # For anything else, we'll assume no approval.
499 if self._abort_if_user_denies:
500 raise HookError('You must allow the %s hook or use --no-verify.' %
501 self._hook_type)
502
503 return False
504
Mike Frysinger40252c22016-08-15 21:23:44 -0400505 def _ManifestUrlHasSecureScheme(self):
506 """Check if the URI for the manifest is a secure transport."""
507 secure_schemes = ('file', 'https', 'ssh', 'persistent-https', 'sso', 'rpc')
508 parse_results = urllib.parse.urlparse(self._manifest_url)
509 return parse_results.scheme in secure_schemes
510
511 def _CheckForHookApprovalManifest(self):
512 """Check whether the user has approved this manifest host.
513
514 Returns:
515 True if this hook is approved to run; False otherwise.
516 """
517 return self._CheckForHookApprovalHelper(
518 'approvedmanifest',
519 self._manifest_url,
520 'Run hook scripts from %s' % (self._manifest_url,),
521 'Manifest URL has changed since %s was allowed.' % (self._hook_type,))
522
523 def _CheckForHookApprovalHash(self):
524 """Check whether the user has approved the hooks repo.
525
526 Returns:
527 True if this hook is approved to run; False otherwise.
528 """
529 prompt = ('Repo %s run the script:\n'
530 ' %s\n'
531 '\n'
Jonathan Nieder71e4cea2016-08-16 12:05:09 -0700532 'Do you want to allow this script to run')
Mike Frysinger40252c22016-08-15 21:23:44 -0400533 return self._CheckForHookApprovalHelper(
534 'approvedhash',
535 self._GetHash(),
Jonathan Nieder71e4cea2016-08-16 12:05:09 -0700536 prompt % (self._GetMustVerb(), self._script_fullpath),
Mike Frysinger40252c22016-08-15 21:23:44 -0400537 'Scripts have changed since %s was allowed.' % (self._hook_type,))
538
Doug Anderson37282b42011-03-04 11:54:18 -0800539 def _ExecuteHook(self, **kwargs):
540 """Actually execute the given hook.
541
542 This will run the hook's 'main' function in our python interpreter.
543
544 Args:
545 kwargs: Keyword arguments to pass to the hook. These are often specific
546 to the hook type. For instance, pre-upload hooks will contain
547 a project_list.
548 """
549 # Keep sys.path and CWD stashed away so that we can always restore them
550 # upon function exit.
551 orig_path = os.getcwd()
552 orig_syspath = sys.path
553
554 try:
555 # Always run hooks with CWD as topdir.
556 os.chdir(self._topdir)
557
558 # Put the hook dir as the first item of sys.path so hooks can do
559 # relative imports. We want to replace the repo dir as [0] so
560 # hooks can't import repo files.
561 sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
562
563 # Exec, storing global context in the context dict. We catch exceptions
564 # and convert to a HookError w/ just the failing traceback.
Mike Frysinger4aa4b212016-03-04 15:03:00 -0500565 context = {'__file__': self._script_fullpath}
Doug Anderson37282b42011-03-04 11:54:18 -0800566 try:
Anthony King70f68902014-05-05 21:15:34 +0100567 exec(compile(open(self._script_fullpath).read(),
568 self._script_fullpath, 'exec'), context)
Doug Anderson37282b42011-03-04 11:54:18 -0800569 except Exception:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700570 raise HookError('%s\nFailed to import %s hook; see traceback above.' %
571 (traceback.format_exc(), self._hook_type))
Doug Anderson37282b42011-03-04 11:54:18 -0800572
573 # Running the script should have defined a main() function.
574 if 'main' not in context:
575 raise HookError('Missing main() in: "%s"' % self._script_fullpath)
576
Doug Anderson37282b42011-03-04 11:54:18 -0800577 # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
578 # We don't actually want hooks to define their main with this argument--
579 # it's there to remind them that their hook should always take **kwargs.
580 # For instance, a pre-upload hook should be defined like:
581 # def main(project_list, **kwargs):
582 #
583 # This allows us to later expand the API without breaking old hooks.
584 kwargs = kwargs.copy()
585 kwargs['hook_should_take_kwargs'] = True
586
587 # Call the main function in the hook. If the hook should cause the
588 # build to fail, it will raise an Exception. We'll catch that convert
589 # to a HookError w/ just the failing traceback.
590 try:
591 context['main'](**kwargs)
592 except Exception:
593 raise HookError('%s\nFailed to run main() for %s hook; see traceback '
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700594 'above.' % (traceback.format_exc(),
595 self._hook_type))
Doug Anderson37282b42011-03-04 11:54:18 -0800596 finally:
597 # Restore sys.path and CWD.
598 sys.path = orig_syspath
599 os.chdir(orig_path)
600
601 def Run(self, user_allows_all_hooks, **kwargs):
602 """Run the hook.
603
604 If the hook doesn't exist (because there is no hooks project or because
605 this particular hook is not enabled), this is a no-op.
606
607 Args:
608 user_allows_all_hooks: If True, we will never prompt about running the
609 hook--we'll just assume it's OK to run it.
610 kwargs: Keyword arguments to pass to the hook. These are often specific
611 to the hook type. For instance, pre-upload hooks will contain
612 a project_list.
613
614 Raises:
615 HookError: If there was a problem finding the hook or the user declined
616 to run a required hook (from _CheckForHookApproval).
617 """
618 # No-op if there is no hooks project or if hook is disabled.
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700619 if ((not self._hooks_project) or (self._hook_type not in
620 self._hooks_project.enabled_repo_hooks)):
Doug Anderson37282b42011-03-04 11:54:18 -0800621 return
622
623 # Bail with a nice error if we can't find the hook.
624 if not os.path.isfile(self._script_fullpath):
625 raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
626
627 # Make sure the user is OK with running the hook.
628 if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
629 return
630
631 # Run the hook with the same version of python we're using.
632 self._ExecuteHook(**kwargs)
633
634
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700635class Project(object):
Kevin Degi384b3c52014-10-16 16:02:58 -0600636 # These objects can be shared between several working trees.
637 shareable_files = ['description', 'info']
638 shareable_dirs = ['hooks', 'objects', 'rr-cache', 'svn']
639 # These objects can only be used by a single working tree.
640 working_tree_files = ['config', 'packed-refs', 'shallow']
641 working_tree_dirs = ['logs', 'refs']
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700642
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700643 def __init__(self,
644 manifest,
645 name,
646 remote,
647 gitdir,
David James8d201162013-10-11 17:03:19 -0700648 objdir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700649 worktree,
650 relpath,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700651 revisionExpr,
Mike Pontillod3153822012-02-28 11:53:24 -0800652 revisionId,
Anthony King7bdac712014-07-16 12:56:40 +0100653 rebase=True,
654 groups=None,
655 sync_c=False,
656 sync_s=False,
657 clone_depth=None,
658 upstream=None,
659 parent=None,
660 is_derived=False,
David Pursehouseb1553542014-09-04 21:28:09 +0900661 dest_branch=None,
Simran Basib9a1b732015-08-20 12:19:28 -0700662 optimized_fetch=False,
663 old_revision=None):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800664 """Init a Project object.
665
666 Args:
667 manifest: The XmlManifest object.
668 name: The `name` attribute of manifest.xml's project element.
669 remote: RemoteSpec object specifying its remote's properties.
670 gitdir: Absolute path of git directory.
David James8d201162013-10-11 17:03:19 -0700671 objdir: Absolute path of directory to store git objects.
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800672 worktree: Absolute path of git working tree.
673 relpath: Relative path of git working tree to repo's top directory.
674 revisionExpr: The `revision` attribute of manifest.xml's project element.
675 revisionId: git commit id for checking out.
676 rebase: The `rebase` attribute of manifest.xml's project element.
677 groups: The `groups` attribute of manifest.xml's project element.
678 sync_c: The `sync-c` attribute of manifest.xml's project element.
679 sync_s: The `sync-s` attribute of manifest.xml's project element.
680 upstream: The `upstream` attribute of manifest.xml's project element.
681 parent: The parent Project object.
682 is_derived: False if the project was explicitly defined in the manifest;
683 True if the project is a discovered submodule.
Bryan Jacobsf609f912013-05-06 13:36:24 -0400684 dest_branch: The branch to which to push changes for review by default.
David Pursehouseb1553542014-09-04 21:28:09 +0900685 optimized_fetch: If True, when a project is set to a sha1 revision, only
686 fetch from the remote if the sha1 is not present locally.
Simran Basib9a1b732015-08-20 12:19:28 -0700687 old_revision: saved git commit id for open GITC projects.
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800688 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700689 self.manifest = manifest
690 self.name = name
691 self.remote = remote
Anthony Newnamdf14a702011-01-09 17:31:57 -0800692 self.gitdir = gitdir.replace('\\', '/')
David James8d201162013-10-11 17:03:19 -0700693 self.objdir = objdir.replace('\\', '/')
Shawn O. Pearce0ce6ca92011-01-10 13:26:01 -0800694 if worktree:
Mark E. Hamiltonf9fe3e12016-02-23 18:10:42 -0700695 self.worktree = os.path.normpath(worktree.replace('\\', '/'))
Shawn O. Pearce0ce6ca92011-01-10 13:26:01 -0800696 else:
697 self.worktree = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700698 self.relpath = relpath
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700699 self.revisionExpr = revisionExpr
700
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700701 if revisionId is None \
702 and revisionExpr \
703 and IsId(revisionExpr):
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700704 self.revisionId = revisionExpr
705 else:
706 self.revisionId = revisionId
707
Mike Pontillod3153822012-02-28 11:53:24 -0800708 self.rebase = rebase
Colin Cross5acde752012-03-28 20:15:45 -0700709 self.groups = groups
Anatol Pomazau79770d22012-04-20 14:41:59 -0700710 self.sync_c = sync_c
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800711 self.sync_s = sync_s
David Pursehouseede7f122012-11-27 22:25:30 +0900712 self.clone_depth = clone_depth
Brian Harring14a66742012-09-28 20:21:57 -0700713 self.upstream = upstream
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800714 self.parent = parent
715 self.is_derived = is_derived
David Pursehouseb1553542014-09-04 21:28:09 +0900716 self.optimized_fetch = optimized_fetch
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800717 self.subprojects = []
Mike Pontillod3153822012-02-28 11:53:24 -0800718
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700719 self.snapshots = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700720 self.copyfiles = []
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500721 self.linkfiles = []
James W. Mills24c13082012-04-12 15:04:13 -0500722 self.annotations = []
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700723 self.config = GitConfig.ForRepository(gitdir=self.gitdir,
724 defaults=self.manifest.globalConfig)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700725
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800726 if self.worktree:
David James8d201162013-10-11 17:03:19 -0700727 self.work_git = self._GitGetByExec(self, bare=False, gitdir=gitdir)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800728 else:
729 self.work_git = None
David James8d201162013-10-11 17:03:19 -0700730 self.bare_git = self._GitGetByExec(self, bare=True, gitdir=gitdir)
Shawn O. Pearced237b692009-04-17 18:49:50 -0700731 self.bare_ref = GitRefs(gitdir)
David James8d201162013-10-11 17:03:19 -0700732 self.bare_objdir = self._GitGetByExec(self, bare=True, gitdir=objdir)
Bryan Jacobsf609f912013-05-06 13:36:24 -0400733 self.dest_branch = dest_branch
Simran Basib9a1b732015-08-20 12:19:28 -0700734 self.old_revision = old_revision
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700735
Doug Anderson37282b42011-03-04 11:54:18 -0800736 # This will be filled in if a project is later identified to be the
737 # project containing repo hooks.
738 self.enabled_repo_hooks = []
739
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700740 @property
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800741 def Derived(self):
742 return self.is_derived
743
744 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700745 def Exists(self):
Kevin Degi384b3c52014-10-16 16:02:58 -0600746 return os.path.isdir(self.gitdir) and os.path.isdir(self.objdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700747
748 @property
749 def CurrentBranch(self):
750 """Obtain the name of the currently checked out branch.
751 The branch name omits the 'refs/heads/' prefix.
752 None is returned if the project is on a detached HEAD.
753 """
Shawn O. Pearce5b23f242009-04-17 18:43:33 -0700754 b = self.work_git.GetHead()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700755 if b.startswith(R_HEADS):
756 return b[len(R_HEADS):]
757 return None
758
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700759 def IsRebaseInProgress(self):
760 w = self.worktree
761 g = os.path.join(w, '.git')
762 return os.path.exists(os.path.join(g, 'rebase-apply')) \
763 or os.path.exists(os.path.join(g, 'rebase-merge')) \
764 or os.path.exists(os.path.join(w, '.dotest'))
Julius Gustavsson0cb1b3f2010-06-17 17:55:02 +0200765
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700766 def IsDirty(self, consider_untracked=True):
767 """Is the working directory modified in some way?
768 """
769 self.work_git.update_index('-q',
770 '--unmerged',
771 '--ignore-missing',
772 '--refresh')
David Pursehouse8f62fb72012-11-14 12:09:38 +0900773 if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700774 return True
775 if self.work_git.DiffZ('diff-files'):
776 return True
777 if consider_untracked and self.work_git.LsOthers():
778 return True
779 return False
780
781 _userident_name = None
782 _userident_email = None
783
784 @property
785 def UserName(self):
786 """Obtain the user's personal name.
787 """
788 if self._userident_name is None:
789 self._LoadUserIdentity()
790 return self._userident_name
791
792 @property
793 def UserEmail(self):
794 """Obtain the user's email address. This is very likely
795 to be their Gerrit login.
796 """
797 if self._userident_email is None:
798 self._LoadUserIdentity()
799 return self._userident_email
800
801 def _LoadUserIdentity(self):
David Pursehousec1b86a22012-11-14 11:36:51 +0900802 u = self.bare_git.var('GIT_COMMITTER_IDENT')
803 m = re.compile("^(.*) <([^>]*)> ").match(u)
804 if m:
805 self._userident_name = m.group(1)
806 self._userident_email = m.group(2)
807 else:
808 self._userident_name = ''
809 self._userident_email = ''
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700810
811 def GetRemote(self, name):
812 """Get the configuration for a single remote.
813 """
814 return self.config.GetRemote(name)
815
816 def GetBranch(self, name):
817 """Get the configuration for a single branch.
818 """
819 return self.config.GetBranch(name)
820
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700821 def GetBranches(self):
822 """Get all existing local branches.
823 """
824 current = self.CurrentBranch
David Pursehouse8a68ff92012-09-24 12:15:13 +0900825 all_refs = self._allrefs
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700826 heads = {}
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700827
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530828 for name, ref_id in all_refs.items():
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700829 if name.startswith(R_HEADS):
830 name = name[len(R_HEADS):]
831 b = self.GetBranch(name)
832 b.current = name == current
833 b.published = None
David Pursehouse8a68ff92012-09-24 12:15:13 +0900834 b.revision = ref_id
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700835 heads[name] = b
836
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530837 for name, ref_id in all_refs.items():
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700838 if name.startswith(R_PUB):
839 name = name[len(R_PUB):]
840 b = heads.get(name)
841 if b:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900842 b.published = ref_id
Shawn O. Pearce27b07322009-04-10 16:02:48 -0700843
844 return heads
845
Colin Cross5acde752012-03-28 20:15:45 -0700846 def MatchesGroups(self, manifest_groups):
847 """Returns true if the manifest groups specified at init should cause
848 this project to be synced.
849 Prefixing a manifest group with "-" inverts the meaning of a group.
Conley Owensbb1b5f52012-08-13 13:11:18 -0700850 All projects are implicitly labelled with "all".
Conley Owens971de8e2012-04-16 10:36:08 -0700851
852 labels are resolved in order. In the example case of
Conley Owensbb1b5f52012-08-13 13:11:18 -0700853 project_groups: "all,group1,group2"
Conley Owens971de8e2012-04-16 10:36:08 -0700854 manifest_groups: "-group1,group2"
855 the project will be matched.
David Holmer0a1c6a12012-11-14 19:19:00 -0500856
857 The special manifest group "default" will match any project that
858 does not have the special project group "notdefault"
Colin Cross5acde752012-03-28 20:15:45 -0700859 """
David Holmer0a1c6a12012-11-14 19:19:00 -0500860 expanded_manifest_groups = manifest_groups or ['default']
Conley Owensbb1b5f52012-08-13 13:11:18 -0700861 expanded_project_groups = ['all'] + (self.groups or [])
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700862 if 'notdefault' not in expanded_project_groups:
David Holmer0a1c6a12012-11-14 19:19:00 -0500863 expanded_project_groups += ['default']
Conley Owensbb1b5f52012-08-13 13:11:18 -0700864
Conley Owens971de8e2012-04-16 10:36:08 -0700865 matched = False
Conley Owensbb1b5f52012-08-13 13:11:18 -0700866 for group in expanded_manifest_groups:
867 if group.startswith('-') and group[1:] in expanded_project_groups:
Conley Owens971de8e2012-04-16 10:36:08 -0700868 matched = False
Conley Owensbb1b5f52012-08-13 13:11:18 -0700869 elif group in expanded_project_groups:
Conley Owens971de8e2012-04-16 10:36:08 -0700870 matched = True
Colin Cross5acde752012-03-28 20:15:45 -0700871
Conley Owens971de8e2012-04-16 10:36:08 -0700872 return matched
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700873
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700874# Status Display ##
Vadim Bendebury14e134d2014-10-05 15:40:30 -0700875 def UncommitedFiles(self, get_all=True):
876 """Returns a list of strings, uncommitted files in the git tree.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700877
Vadim Bendebury14e134d2014-10-05 15:40:30 -0700878 Args:
879 get_all: a boolean, if True - get information about all different
880 uncommitted files. If False - return as soon as any kind of
881 uncommitted files is detected.
Anthony Newnamcc50bac2010-04-08 10:28:59 -0500882 """
Vadim Bendebury14e134d2014-10-05 15:40:30 -0700883 details = []
Anthony Newnamcc50bac2010-04-08 10:28:59 -0500884 self.work_git.update_index('-q',
885 '--unmerged',
886 '--ignore-missing',
887 '--refresh')
888 if self.IsRebaseInProgress():
Vadim Bendebury14e134d2014-10-05 15:40:30 -0700889 details.append("rebase in progress")
890 if not get_all:
891 return details
Anthony Newnamcc50bac2010-04-08 10:28:59 -0500892
Vadim Bendebury14e134d2014-10-05 15:40:30 -0700893 changes = self.work_git.DiffZ('diff-index', '--cached', HEAD).keys()
894 if changes:
895 details.extend(changes)
896 if not get_all:
897 return details
Anthony Newnamcc50bac2010-04-08 10:28:59 -0500898
Vadim Bendebury14e134d2014-10-05 15:40:30 -0700899 changes = self.work_git.DiffZ('diff-files').keys()
900 if changes:
901 details.extend(changes)
902 if not get_all:
903 return details
Anthony Newnamcc50bac2010-04-08 10:28:59 -0500904
Vadim Bendebury14e134d2014-10-05 15:40:30 -0700905 changes = self.work_git.LsOthers()
906 if changes:
907 details.extend(changes)
Anthony Newnamcc50bac2010-04-08 10:28:59 -0500908
Vadim Bendebury14e134d2014-10-05 15:40:30 -0700909 return details
910
911 def HasChanges(self):
912 """Returns true if there are uncommitted changes.
913 """
914 if self.UncommitedFiles(get_all=False):
915 return True
916 else:
917 return False
Anthony Newnamcc50bac2010-04-08 10:28:59 -0500918
Terence Haddock4655e812011-03-31 12:33:34 +0200919 def PrintWorkTreeStatus(self, output_redir=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700920 """Prints the status of the repository to stdout.
Terence Haddock4655e812011-03-31 12:33:34 +0200921
922 Args:
923 output: If specified, redirect the output to this object.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700924 """
925 if not os.path.isdir(self.worktree):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700926 if output_redir is None:
Terence Haddock4655e812011-03-31 12:33:34 +0200927 output_redir = sys.stdout
Sarah Owenscecd1d82012-11-01 22:59:27 -0700928 print(file=output_redir)
929 print('project %s/' % self.relpath, file=output_redir)
930 print(' missing (run "repo sync")', file=output_redir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700931 return
932
933 self.work_git.update_index('-q',
934 '--unmerged',
935 '--ignore-missing',
936 '--refresh')
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700937 rb = self.IsRebaseInProgress()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700938 di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
939 df = self.work_git.DiffZ('diff-files')
940 do = self.work_git.LsOthers()
Ali Utku Selen76abcc12012-01-25 10:51:12 +0100941 if not rb and not di and not df and not do and not self.CurrentBranch:
Shawn O. Pearce161f4452009-04-10 17:41:44 -0700942 return 'CLEAN'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700943
944 out = StatusColoring(self.config)
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700945 if output_redir is not None:
Terence Haddock4655e812011-03-31 12:33:34 +0200946 out.redirect(output_redir)
Jakub Vrana0402cd82014-09-09 15:39:15 -0700947 out.project('project %-40s', self.relpath + '/ ')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700948
949 branch = self.CurrentBranch
950 if branch is None:
951 out.nobranch('(*** NO BRANCH ***)')
952 else:
953 out.branch('branch %s', branch)
954 out.nl()
955
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -0700956 if rb:
957 out.important('prior sync failed; rebase still in progress')
958 out.nl()
959
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700960 paths = list()
961 paths.extend(di.keys())
962 paths.extend(df.keys())
963 paths.extend(do)
964
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530965 for p in sorted(set(paths)):
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900966 try:
967 i = di[p]
968 except KeyError:
969 i = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700970
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900971 try:
972 f = df[p]
973 except KeyError:
974 f = None
Julius Gustavsson0cb1b3f2010-06-17 17:55:02 +0200975
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900976 if i:
977 i_status = i.status.upper()
978 else:
979 i_status = '-'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700980
David Pursehouse5c6eeac2012-10-11 16:44:48 +0900981 if f:
982 f_status = f.status.lower()
983 else:
984 f_status = '-'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700985
986 if i and i.src_path:
Shawn O. Pearcefe086752009-03-03 13:49:48 -0800987 line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700988 i.src_path, p, i.level)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700989 else:
990 line = ' %s%s\t%s' % (i_status, f_status, p)
991
992 if i and not f:
993 out.added('%s', line)
994 elif (i and f) or (not i and f):
995 out.changed('%s', line)
996 elif not i and not f:
997 out.untracked('%s', line)
998 else:
999 out.write('%s', line)
1000 out.nl()
Terence Haddock4655e812011-03-31 12:33:34 +02001001
Shawn O. Pearce161f4452009-04-10 17:41:44 -07001002 return 'DIRTY'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001003
pelyad67872d2012-03-28 14:49:58 +03001004 def PrintWorkTreeDiff(self, absolute_paths=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001005 """Prints the status of the repository to stdout.
1006 """
1007 out = DiffColoring(self.config)
1008 cmd = ['diff']
1009 if out.is_on:
1010 cmd.append('--color')
1011 cmd.append(HEAD)
pelyad67872d2012-03-28 14:49:58 +03001012 if absolute_paths:
1013 cmd.append('--src-prefix=a/%s/' % self.relpath)
1014 cmd.append('--dst-prefix=b/%s/' % self.relpath)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001015 cmd.append('--')
1016 p = GitCommand(self,
1017 cmd,
Anthony King7bdac712014-07-16 12:56:40 +01001018 capture_stdout=True,
1019 capture_stderr=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001020 has_diff = False
1021 for line in p.process.stdout:
1022 if not has_diff:
1023 out.nl()
1024 out.project('project %s/' % self.relpath)
1025 out.nl()
1026 has_diff = True
Sarah Owenscecd1d82012-11-01 22:59:27 -07001027 print(line[:-1])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001028 p.Wait()
1029
1030
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001031# Publish / Upload ##
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001032
David Pursehouse8a68ff92012-09-24 12:15:13 +09001033 def WasPublished(self, branch, all_refs=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001034 """Was the branch published (uploaded) for code review?
1035 If so, returns the SHA-1 hash of the last published
1036 state for the branch.
1037 """
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001038 key = R_PUB + branch
David Pursehouse8a68ff92012-09-24 12:15:13 +09001039 if all_refs is None:
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001040 try:
1041 return self.bare_git.rev_parse(key)
1042 except GitError:
1043 return None
1044 else:
1045 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001046 return all_refs[key]
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001047 except KeyError:
1048 return None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001049
David Pursehouse8a68ff92012-09-24 12:15:13 +09001050 def CleanPublishedCache(self, all_refs=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001051 """Prunes any stale published refs.
1052 """
David Pursehouse8a68ff92012-09-24 12:15:13 +09001053 if all_refs is None:
1054 all_refs = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001055 heads = set()
1056 canrm = {}
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301057 for name, ref_id in all_refs.items():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001058 if name.startswith(R_HEADS):
1059 heads.add(name)
1060 elif name.startswith(R_PUB):
David Pursehouse8a68ff92012-09-24 12:15:13 +09001061 canrm[name] = ref_id
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001062
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301063 for name, ref_id in canrm.items():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001064 n = name[len(R_PUB):]
1065 if R_HEADS + n not in heads:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001066 self.bare_git.DeleteRef(name, ref_id)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001067
Mandeep Singh Bainesd6c93a22011-05-26 10:34:11 -07001068 def GetUploadableBranches(self, selected_branch=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001069 """List any branches which can be uploaded for review.
1070 """
1071 heads = {}
1072 pubed = {}
1073
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301074 for name, ref_id in self._allrefs.items():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001075 if name.startswith(R_HEADS):
David Pursehouse8a68ff92012-09-24 12:15:13 +09001076 heads[name[len(R_HEADS):]] = ref_id
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001077 elif name.startswith(R_PUB):
David Pursehouse8a68ff92012-09-24 12:15:13 +09001078 pubed[name[len(R_PUB):]] = ref_id
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001079
1080 ready = []
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301081 for branch, ref_id in heads.items():
David Pursehouse8a68ff92012-09-24 12:15:13 +09001082 if branch in pubed and pubed[branch] == ref_id:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001083 continue
Mandeep Singh Bainesd6c93a22011-05-26 10:34:11 -07001084 if selected_branch and branch != selected_branch:
1085 continue
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001086
Shawn O. Pearce35f25962008-11-11 17:03:13 -08001087 rb = self.GetUploadableBranch(branch)
1088 if rb:
1089 ready.append(rb)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001090 return ready
1091
Shawn O. Pearce35f25962008-11-11 17:03:13 -08001092 def GetUploadableBranch(self, branch_name):
1093 """Get a single uploadable branch, or None.
1094 """
1095 branch = self.GetBranch(branch_name)
1096 base = branch.LocalMerge
1097 if branch.LocalMerge:
1098 rb = ReviewableBranch(self, branch, base)
1099 if rb.commits:
1100 return rb
1101 return None
1102
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -07001103 def UploadForReview(self, branch=None,
Anthony King7bdac712014-07-16 12:56:40 +01001104 people=([], []),
Brian Harring435370c2012-07-28 15:37:04 -07001105 auto_topic=False,
Bryan Jacobsf609f912013-05-06 13:36:24 -04001106 draft=False,
Changcheng Xiao7da6f862017-08-02 16:55:03 +02001107 private=False,
1108 wip=False,
Bryan Jacobsf609f912013-05-06 13:36:24 -04001109 dest_branch=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001110 """Uploads the named branch for code review.
1111 """
1112 if branch is None:
1113 branch = self.CurrentBranch
1114 if branch is None:
1115 raise GitError('not currently on a branch')
1116
1117 branch = self.GetBranch(branch)
1118 if not branch.LocalMerge:
1119 raise GitError('branch %s does not track a remote' % branch.name)
1120 if not branch.remote.review:
1121 raise GitError('remote %s has no review url' % branch.remote.name)
1122
Bryan Jacobsf609f912013-05-06 13:36:24 -04001123 if dest_branch is None:
1124 dest_branch = self.dest_branch
1125 if dest_branch is None:
1126 dest_branch = branch.merge
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001127 if not dest_branch.startswith(R_HEADS):
1128 dest_branch = R_HEADS + dest_branch
1129
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -08001130 if not branch.remote.projectname:
1131 branch.remote.projectname = self.name
1132 branch.remote.Save()
1133
Shawn O. Pearcec9571422012-01-11 14:58:54 -08001134 url = branch.remote.ReviewUrl(self.UserEmail)
1135 if url is None:
1136 raise UploadError('review not configured')
1137 cmd = ['push']
Shawn O. Pearceb54a3922009-01-05 16:18:58 -08001138
Shawn O. Pearcec9571422012-01-11 14:58:54 -08001139 if url.startswith('ssh://'):
Jonathan Nieder4ad4c462018-11-05 13:21:52 -08001140 cmd.append('--receive-pack=gerrit receive-pack')
Shawn O. Pearcea5ece0e2010-07-15 16:52:42 -07001141
Shawn O. Pearcec9571422012-01-11 14:58:54 -08001142 cmd.append(url)
Shawn O. Pearceb54a3922009-01-05 16:18:58 -08001143
Shawn O. Pearcec9571422012-01-11 14:58:54 -08001144 if dest_branch.startswith(R_HEADS):
1145 dest_branch = dest_branch[len(R_HEADS):]
Brian Harring435370c2012-07-28 15:37:04 -07001146
1147 upload_type = 'for'
1148 if draft:
1149 upload_type = 'drafts'
1150
1151 ref_spec = '%s:refs/%s/%s' % (R_HEADS + branch.name, upload_type,
1152 dest_branch)
Shawn O. Pearcec9571422012-01-11 14:58:54 -08001153 if auto_topic:
1154 ref_spec = ref_spec + '/' + branch.name
Changcheng Xiao7da6f862017-08-02 16:55:03 +02001155
Jonathan Nieder4ad4c462018-11-05 13:21:52 -08001156 opts = ['r=%s' % p for p in people[0]]
1157 opts += ['cc=%s' % p for p in people[1]]
1158 if private:
1159 opts += ['private']
1160 if wip:
1161 opts += ['wip']
1162 if opts:
1163 ref_spec = ref_spec + '%' + ','.join(opts)
Shawn O. Pearcec9571422012-01-11 14:58:54 -08001164 cmd.append(ref_spec)
1165
Anthony King7bdac712014-07-16 12:56:40 +01001166 if GitCommand(self, cmd, bare=True).Wait() != 0:
Shawn O. Pearcec9571422012-01-11 14:58:54 -08001167 raise UploadError('Upload failed')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001168
1169 msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
1170 self.bare_git.UpdateRef(R_PUB + branch.name,
1171 R_HEADS + branch.name,
Anthony King7bdac712014-07-16 12:56:40 +01001172 message=msg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001173
1174
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001175# Sync ##
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001176
Julien Campergue335f5ef2013-10-16 11:02:35 +02001177 def _ExtractArchive(self, tarpath, path=None):
1178 """Extract the given tar on its current location
1179
1180 Args:
1181 - tarpath: The path to the actual tar file
1182
1183 """
1184 try:
1185 with tarfile.open(tarpath, 'r') as tar:
1186 tar.extractall(path=path)
1187 return True
1188 except (IOError, tarfile.TarError) as e:
David Pursehousef33929d2015-08-24 14:39:14 +09001189 _error("Cannot extract archive %s: %s", tarpath, str(e))
Julien Campergue335f5ef2013-10-16 11:02:35 +02001190 return False
1191
Ningning Xiac2fbc782016-08-22 14:24:39 -07001192 def CachePopulate(self, cache_dir, url):
1193 """Populate cache in the cache_dir.
1194
1195 Args:
1196 cache_dir: Directory to cache git files from Google Storage.
1197 url: Git url of current repository.
1198
1199 Raises:
1200 CacheApplyError if it fails to populate the git cache.
1201 """
1202 cmd = ['cache', 'populate', '--ignore_locks', '-v',
1203 '--cache-dir', cache_dir, url]
1204
1205 if GitCommand(self, cmd, cwd=cache_dir).Wait() != 0:
1206 raise CacheApplyError('Failed to populate cache. cache_dir: %s '
1207 'url: %s' % (cache_dir, url))
1208
1209 def CacheExists(self, cache_dir, url):
1210 """Check the existence of the cache files.
1211
1212 Args:
1213 cache_dir: Directory to cache git files.
1214 url: Git url of current repository.
1215
1216 Raises:
1217 CacheApplyError if the cache files do not exist.
1218 """
1219 cmd = ['cache', 'exists', '--quiet', '--cache-dir', cache_dir, url]
1220
1221 exist = GitCommand(self, cmd, cwd=self.gitdir, capture_stdout=True)
1222 if exist.Wait() != 0:
1223 raise CacheApplyError('Failed to execute git cache exists cmd. '
1224 'cache_dir: %s url: %s' % (cache_dir, url))
1225
1226 if not exist.stdout or not exist.stdout.strip():
1227 raise CacheApplyError('Failed to find cache. cache_dir: %s '
1228 'url: %s' % (cache_dir, url))
1229 return exist.stdout.strip()
1230
1231 def CacheApply(self, cache_dir):
1232 """Apply git cache files populated from Google Storage buckets.
1233
1234 Args:
1235 cache_dir: Directory to cache git files.
1236
1237 Raises:
1238 CacheApplyError if it fails to apply git caches.
1239 """
1240 remote = self.GetRemote(self.remote.name)
1241
1242 self.CachePopulate(cache_dir, remote.url)
1243
1244 mirror_dir = self.CacheExists(cache_dir, remote.url)
1245
1246 refspec = RefSpec(True, 'refs/heads/*',
1247 'refs/remotes/%s/*' % remote.name)
1248
1249 fetch_cache_cmd = ['fetch', mirror_dir, str(refspec)]
1250 if GitCommand(self, fetch_cache_cmd, self.gitdir).Wait() != 0:
1251 raise CacheApplyError('Failed to fetch refs %s from %s' %
1252 (mirror_dir, str(refspec)))
1253
Shawn O. Pearcee02ac0a2012-03-14 15:36:59 -07001254 def Sync_NetworkHalf(self,
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001255 quiet=False,
1256 is_new=None,
1257 current_branch_only=False,
1258 force_sync=False,
1259 clone_bundle=True,
1260 no_tags=False,
1261 archive=False,
1262 optimized_fetch=False,
Ningning Xiac2fbc782016-08-22 14:24:39 -07001263 prune=False,
1264 cache_dir=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001265 """Perform only the network IO portion of the sync process.
1266 Local working directory/branch state is not affected.
1267 """
Julien Campergue335f5ef2013-10-16 11:02:35 +02001268 if archive and not isinstance(self, MetaProject):
1269 if self.remote.url.startswith(('http://', 'https://')):
David Pursehousef33929d2015-08-24 14:39:14 +09001270 _error("%s: Cannot fetch archives from http/https remotes.", self.name)
Julien Campergue335f5ef2013-10-16 11:02:35 +02001271 return False
1272
1273 name = self.relpath.replace('\\', '/')
1274 name = name.replace('/', '_')
1275 tarpath = '%s.tar' % name
1276 topdir = self.manifest.topdir
1277
1278 try:
1279 self._FetchArchive(tarpath, cwd=topdir)
1280 except GitError as e:
David Pursehousef33929d2015-08-24 14:39:14 +09001281 _error('%s', e)
Julien Campergue335f5ef2013-10-16 11:02:35 +02001282 return False
1283
1284 # From now on, we only need absolute tarpath
1285 tarpath = os.path.join(topdir, tarpath)
1286
1287 if not self._ExtractArchive(tarpath, path=topdir):
1288 return False
1289 try:
1290 os.remove(tarpath)
1291 except OSError as e:
David Pursehousef33929d2015-08-24 14:39:14 +09001292 _warn("Cannot remove archive %s: %s", tarpath, str(e))
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001293 self._CopyAndLinkFiles()
Julien Campergue335f5ef2013-10-16 11:02:35 +02001294 return True
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07001295 if is_new is None:
1296 is_new = not self.Exists
Shawn O. Pearce88443382010-10-08 10:02:09 +02001297 if is_new:
Kevin Degiabaa7f32014-11-12 11:27:45 -07001298 self._InitGitDir(force_sync=force_sync)
Jimmie Westera0444582012-10-24 13:44:42 +02001299 else:
1300 self._UpdateHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001301 self._InitRemote()
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001302
1303 if is_new:
1304 alt = os.path.join(self.gitdir, 'objects/info/alternates')
1305 try:
1306 fd = open(alt, 'rb')
1307 try:
1308 alt_dir = fd.readline().rstrip()
1309 finally:
1310 fd.close()
1311 except IOError:
1312 alt_dir = None
1313 else:
1314 alt_dir = None
1315
Ningning Xiac2fbc782016-08-22 14:24:39 -07001316 applied_cache = False
1317 # If cache_dir is provided, and it's a new repository without
1318 # alternative_dir, bootstrap this project repo with the git
1319 # cache files.
1320 if cache_dir is not None and is_new and alt_dir is None:
1321 try:
1322 self.CacheApply(cache_dir)
1323 applied_cache = True
1324 is_new = False
1325 except CacheApplyError as e:
1326 _error('Could not apply git cache: %s', e)
1327 _error('Please check if you have the right GS credentials.')
1328 _error('Please check if the cache files exist in GS.')
1329
Shawn O. Pearcee02ac0a2012-03-14 15:36:59 -07001330 if clone_bundle \
Ningning Xiac2fbc782016-08-22 14:24:39 -07001331 and not applied_cache \
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001332 and alt_dir is None \
1333 and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001334 is_new = False
1335
Shawn O. Pearce6ba6ba02012-05-24 09:46:50 -07001336 if not current_branch_only:
1337 if self.sync_c:
1338 current_branch_only = True
1339 elif not self.manifest._loaded:
1340 # Manifest cannot check defaults until it syncs.
1341 current_branch_only = False
1342 elif self.manifest.default.sync_c:
1343 current_branch_only = True
1344
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001345 need_to_fetch = not (optimized_fetch and
1346 (ID_RE.match(self.revisionExpr) and
1347 self._CheckForSha1()))
1348 if (need_to_fetch and
1349 not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
1350 current_branch_only=current_branch_only,
1351 no_tags=no_tags, prune=prune)):
Anthony King7bdac712014-07-16 12:56:40 +01001352 return False
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001353
1354 if self.worktree:
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001355 self._InitMRef()
1356 else:
1357 self._InitMirrorHead()
1358 try:
1359 os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
1360 except OSError:
1361 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001362 return True
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08001363
1364 def PostRepoUpgrade(self):
1365 self._InitHooks()
1366
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001367 def _CopyAndLinkFiles(self):
Simran Basib9a1b732015-08-20 12:19:28 -07001368 if self.manifest.isGitcClient:
1369 return
David Pursehouse8a68ff92012-09-24 12:15:13 +09001370 for copyfile in self.copyfiles:
1371 copyfile._Copy()
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001372 for linkfile in self.linkfiles:
1373 linkfile._Link()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001374
Julien Camperguedd654222014-01-09 16:21:37 +01001375 def GetCommitRevisionId(self):
1376 """Get revisionId of a commit.
1377
1378 Use this method instead of GetRevisionId to get the id of the commit rather
1379 than the id of the current git object (for example, a tag)
1380
1381 """
1382 if not self.revisionExpr.startswith(R_TAGS):
1383 return self.GetRevisionId(self._allrefs)
1384
1385 try:
1386 return self.bare_git.rev_list(self.revisionExpr, '-1')[0]
1387 except GitError:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001388 raise ManifestInvalidRevisionError('revision %s in %s not found' %
1389 (self.revisionExpr, self.name))
Julien Camperguedd654222014-01-09 16:21:37 +01001390
David Pursehouse8a68ff92012-09-24 12:15:13 +09001391 def GetRevisionId(self, all_refs=None):
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001392 if self.revisionId:
1393 return self.revisionId
1394
1395 rem = self.GetRemote(self.remote.name)
1396 rev = rem.ToLocal(self.revisionExpr)
1397
David Pursehouse8a68ff92012-09-24 12:15:13 +09001398 if all_refs is not None and rev in all_refs:
1399 return all_refs[rev]
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001400
1401 try:
1402 return self.bare_git.rev_parse('--verify', '%s^0' % rev)
1403 except GitError:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001404 raise ManifestInvalidRevisionError('revision %s in %s not found' %
1405 (self.revisionExpr, self.name))
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001406
Kevin Degiabaa7f32014-11-12 11:27:45 -07001407 def Sync_LocalHalf(self, syncbuf, force_sync=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001408 """Perform only the local IO portion of the sync process.
1409 Network access is not required.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001410 """
Kevin Degiabaa7f32014-11-12 11:27:45 -07001411 self._InitWorkTree(force_sync=force_sync)
David Pursehouse8a68ff92012-09-24 12:15:13 +09001412 all_refs = self.bare_ref.all
1413 self.CleanPublishedCache(all_refs)
1414 revid = self.GetRevisionId(all_refs)
Skyler Kaufman835cd682011-03-08 12:14:41 -08001415
David Pursehouse1d947b32012-10-25 12:23:11 +09001416 def _doff():
1417 self._FastForward(revid)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001418 self._CopyAndLinkFiles()
David Pursehouse1d947b32012-10-25 12:23:11 +09001419
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001420 head = self.work_git.GetHead()
1421 if head.startswith(R_HEADS):
1422 branch = head[len(R_HEADS):]
1423 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001424 head = all_refs[head]
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001425 except KeyError:
1426 head = None
1427 else:
1428 branch = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001429
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001430 if branch is None or syncbuf.detach_head:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001431 # Currently on a detached HEAD. The user is assumed to
1432 # not have any local modifications worth worrying about.
1433 #
Shawn O. Pearce3d2cdd02009-04-18 15:26:10 -07001434 if self.IsRebaseInProgress():
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001435 syncbuf.fail(self, _PriorSyncFailedError())
1436 return
1437
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001438 if head == revid:
1439 # No changes; don't do anything further.
Florian Vallee7cf1b362012-06-07 17:11:42 +02001440 # Except if the head needs to be detached
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001441 #
Florian Vallee7cf1b362012-06-07 17:11:42 +02001442 if not syncbuf.detach_head:
Dan Willemsen029eaf32015-09-03 12:52:28 -07001443 # The copy/linkfile config may have changed.
1444 self._CopyAndLinkFiles()
Florian Vallee7cf1b362012-06-07 17:11:42 +02001445 return
1446 else:
1447 lost = self._revlist(not_rev(revid), HEAD)
1448 if lost:
1449 syncbuf.info(self, "discarding %d commits", len(lost))
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001450
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001451 try:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001452 self._Checkout(revid, quiet=True)
Sarah Owensa5be53f2012-09-09 15:37:57 -07001453 except GitError as e:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001454 syncbuf.fail(self, e)
1455 return
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001456 self._CopyAndLinkFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001457 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001458
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001459 if head == revid:
1460 # No changes; don't do anything further.
1461 #
Dan Willemsen029eaf32015-09-03 12:52:28 -07001462 # The copy/linkfile config may have changed.
1463 self._CopyAndLinkFiles()
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07001464 return
1465
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001466 branch = self.GetBranch(branch)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001467
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001468 if not branch.LocalMerge:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001469 # The current branch has no tracking configuration.
Anatol Pomazau2a32f6a2011-08-30 10:52:33 -07001470 # Jump off it to a detached HEAD.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001471 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001472 syncbuf.info(self,
1473 "leaving %s; does not track upstream",
1474 branch.name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001475 try:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001476 self._Checkout(revid, quiet=True)
Sarah Owensa5be53f2012-09-09 15:37:57 -07001477 except GitError as e:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001478 syncbuf.fail(self, e)
1479 return
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001480 self._CopyAndLinkFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001481 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001482
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001483 upstream_gain = self._revlist(not_rev(HEAD), revid)
David Pursehouse8a68ff92012-09-24 12:15:13 +09001484 pub = self.WasPublished(branch.name, all_refs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001485 if pub:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001486 not_merged = self._revlist(not_rev(revid), pub)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001487 if not_merged:
1488 if upstream_gain:
1489 # The user has published this branch and some of those
1490 # commits are not yet merged upstream. We do not want
1491 # to rewrite the published commits so we punt.
1492 #
Daniel Sandler4c50dee2010-03-02 15:38:03 -05001493 syncbuf.fail(self,
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001494 "branch %s is published (but not merged) and is now "
1495 "%d commits behind" % (branch.name, len(upstream_gain)))
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001496 return
Shawn O. Pearce05f66b62009-04-21 08:26:32 -07001497 elif pub == head:
1498 # All published commits are merged, and thus we are a
1499 # strict subset. We can fast-forward safely.
Shawn O. Pearcea54c5272008-10-30 11:03:00 -07001500 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001501 syncbuf.later1(self, _doff)
1502 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001503
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001504 # Examine the local commits not in the remote. Find the
1505 # last one attributed to this user, if any.
1506 #
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001507 local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001508 last_mine = None
1509 cnt_mine = 0
1510 for commit in local_changes:
Chirayu Desai0eb35cb2013-11-19 18:46:29 +05301511 commit_id, committer_email = commit.decode('utf-8').split(' ', 1)
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001512 if committer_email == self.UserEmail:
1513 last_mine = commit_id
1514 cnt_mine += 1
1515
Shawn O. Pearceda88ff42009-06-03 11:09:12 -07001516 if not upstream_gain and cnt_mine == len(local_changes):
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001517 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001518
1519 if self.IsDirty(consider_untracked=False):
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001520 syncbuf.fail(self, _DirtyError())
1521 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001522
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001523 # If the upstream switched on us, warn the user.
1524 #
1525 if branch.merge != self.revisionExpr:
1526 if branch.merge and self.revisionExpr:
1527 syncbuf.info(self,
1528 'manifest switched %s...%s',
1529 branch.merge,
1530 self.revisionExpr)
1531 elif branch.merge:
1532 syncbuf.info(self,
1533 'manifest no longer tracks %s',
1534 branch.merge)
1535
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001536 if cnt_mine < len(local_changes):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001537 # Upstream rebased. Not everything in HEAD
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001538 # was created by this user.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001539 #
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001540 syncbuf.info(self,
1541 "discarding %d commits removed from upstream",
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001542 len(local_changes) - cnt_mine)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001543
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001544 branch.remote = self.GetRemote(self.remote.name)
Anatol Pomazaucd7c5de2012-03-20 13:45:00 -07001545 if not ID_RE.match(self.revisionExpr):
1546 # in case of manifest sync the revisionExpr might be a SHA1
1547 branch.merge = self.revisionExpr
Conley Owens04f2f0e2014-10-01 17:22:46 -07001548 if not branch.merge.startswith('refs/'):
1549 branch.merge = R_HEADS + branch.merge
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001550 branch.Save()
1551
Mike Pontillod3153822012-02-28 11:53:24 -08001552 if cnt_mine > 0 and self.rebase:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001553 def _dorebase():
Anthony King7bdac712014-07-16 12:56:40 +01001554 self._Rebase(upstream='%s^1' % last_mine, onto=revid)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001555 self._CopyAndLinkFiles()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001556 syncbuf.later2(self, _dorebase)
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07001557 elif local_changes:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001558 try:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001559 self._ResetHard(revid)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001560 self._CopyAndLinkFiles()
Sarah Owensa5be53f2012-09-09 15:37:57 -07001561 except GitError as e:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001562 syncbuf.fail(self, e)
1563 return
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001564 else:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07001565 syncbuf.later1(self, _doff)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001566
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -08001567 def AddCopyFile(self, src, dest, absdest):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001568 # dest should already be an absolute path, but src is project relative
1569 # make src an absolute path
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -08001570 abssrc = os.path.join(self.worktree, src)
1571 self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001572
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001573 def AddLinkFile(self, src, dest, absdest):
1574 # dest should already be an absolute path, but src is project relative
Colin Cross0184dcc2015-05-05 00:24:54 -07001575 # make src relative path to dest
1576 absdestdir = os.path.dirname(absdest)
1577 relsrc = os.path.relpath(os.path.join(self.worktree, src), absdestdir)
Wink Saville4c426ef2015-06-03 08:05:17 -07001578 self.linkfiles.append(_LinkFile(self.worktree, src, dest, relsrc, absdest))
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001579
James W. Mills24c13082012-04-12 15:04:13 -05001580 def AddAnnotation(self, name, value, keep):
1581 self.annotations.append(_Annotation(name, value, keep))
1582
Shawn O. Pearce632768b2008-10-23 11:58:52 -07001583 def DownloadPatchSet(self, change_id, patch_id):
1584 """Download a single patch set of a single change to FETCH_HEAD.
1585 """
1586 remote = self.GetRemote(self.remote.name)
1587
1588 cmd = ['fetch', remote.name]
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001589 cmd.append('refs/changes/%2.2d/%d/%d'
Shawn O. Pearce632768b2008-10-23 11:58:52 -07001590 % (change_id % 100, change_id, patch_id))
Shawn O. Pearce632768b2008-10-23 11:58:52 -07001591 if GitCommand(self, cmd, bare=True).Wait() != 0:
1592 return None
1593 return DownloadedChange(self,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001594 self.GetRevisionId(),
Shawn O. Pearce632768b2008-10-23 11:58:52 -07001595 change_id,
1596 patch_id,
1597 self.bare_git.rev_parse('FETCH_HEAD'))
1598
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001599
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001600# Branch Management ##
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001601
Simran Basib9a1b732015-08-20 12:19:28 -07001602 def StartBranch(self, name, branch_merge=''):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001603 """Create a new branch off the manifest's revision.
1604 """
Simran Basib9a1b732015-08-20 12:19:28 -07001605 if not branch_merge:
1606 branch_merge = self.revisionExpr
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001607 head = self.work_git.GetHead()
1608 if head == (R_HEADS + name):
1609 return True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001610
David Pursehouse8a68ff92012-09-24 12:15:13 +09001611 all_refs = self.bare_ref.all
Anthony King7bdac712014-07-16 12:56:40 +01001612 if R_HEADS + name in all_refs:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001613 return GitCommand(self,
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001614 ['checkout', name, '--'],
Anthony King7bdac712014-07-16 12:56:40 +01001615 capture_stdout=True,
1616 capture_stderr=True).Wait() == 0
Shawn O. Pearce0a389e92009-04-10 16:21:18 -07001617
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001618 branch = self.GetBranch(name)
1619 branch.remote = self.GetRemote(self.remote.name)
Simran Basib9a1b732015-08-20 12:19:28 -07001620 branch.merge = branch_merge
1621 if not branch.merge.startswith('refs/') and not ID_RE.match(branch_merge):
1622 branch.merge = R_HEADS + branch_merge
David Pursehouse8a68ff92012-09-24 12:15:13 +09001623 revid = self.GetRevisionId(all_refs)
Shawn O. Pearce0a389e92009-04-10 16:21:18 -07001624
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001625 if head.startswith(R_HEADS):
1626 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001627 head = all_refs[head]
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001628 except KeyError:
1629 head = None
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001630 if revid and head and revid == head:
1631 ref = os.path.join(self.gitdir, R_HEADS + name)
1632 try:
1633 os.makedirs(os.path.dirname(ref))
1634 except OSError:
1635 pass
1636 _lwrite(ref, '%s\n' % revid)
1637 _lwrite(os.path.join(self.worktree, '.git', HEAD),
1638 'ref: %s%s\n' % (R_HEADS, name))
1639 branch.Save()
1640 return True
1641
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001642 if GitCommand(self,
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001643 ['checkout', '-b', branch.name, revid],
Anthony King7bdac712014-07-16 12:56:40 +01001644 capture_stdout=True,
1645 capture_stderr=True).Wait() == 0:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -07001646 branch.Save()
1647 return True
1648 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001649
Wink Saville02d79452009-04-10 13:01:24 -07001650 def CheckoutBranch(self, name):
1651 """Checkout a local topic branch.
Doug Anderson3ba5f952011-04-07 12:51:04 -07001652
1653 Args:
1654 name: The name of the branch to checkout.
1655
1656 Returns:
1657 True if the checkout succeeded; False if it didn't; None if the branch
1658 didn't exist.
Wink Saville02d79452009-04-10 13:01:24 -07001659 """
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001660 rev = R_HEADS + name
1661 head = self.work_git.GetHead()
1662 if head == rev:
1663 # Already on the branch
1664 #
1665 return True
Wink Saville02d79452009-04-10 13:01:24 -07001666
David Pursehouse8a68ff92012-09-24 12:15:13 +09001667 all_refs = self.bare_ref.all
Wink Saville02d79452009-04-10 13:01:24 -07001668 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001669 revid = all_refs[rev]
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001670 except KeyError:
1671 # Branch does not exist in this project
1672 #
Doug Anderson3ba5f952011-04-07 12:51:04 -07001673 return None
Wink Saville02d79452009-04-10 13:01:24 -07001674
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001675 if head.startswith(R_HEADS):
1676 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09001677 head = all_refs[head]
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001678 except KeyError:
1679 head = None
1680
1681 if head == revid:
1682 # Same revision; just update HEAD to point to the new
1683 # target branch, but otherwise take no other action.
1684 #
1685 _lwrite(os.path.join(self.worktree, '.git', HEAD),
1686 'ref: %s%s\n' % (R_HEADS, name))
1687 return True
1688
1689 return GitCommand(self,
1690 ['checkout', name, '--'],
Anthony King7bdac712014-07-16 12:56:40 +01001691 capture_stdout=True,
1692 capture_stderr=True).Wait() == 0
Wink Saville02d79452009-04-10 13:01:24 -07001693
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001694 def AbandonBranch(self, name):
1695 """Destroy a local topic branch.
Doug Andersondafb1d62011-04-07 11:46:59 -07001696
1697 Args:
1698 name: The name of the branch to abandon.
1699
1700 Returns:
1701 True if the abandon succeeded; False if it didn't; None if the branch
1702 didn't exist.
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001703 """
Shawn O. Pearce552ac892009-04-18 15:15:24 -07001704 rev = R_HEADS + name
David Pursehouse8a68ff92012-09-24 12:15:13 +09001705 all_refs = self.bare_ref.all
1706 if rev not in all_refs:
Doug Andersondafb1d62011-04-07 11:46:59 -07001707 # Doesn't exist
1708 return None
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001709
Shawn O. Pearce552ac892009-04-18 15:15:24 -07001710 head = self.work_git.GetHead()
1711 if head == rev:
1712 # We can't destroy the branch while we are sitting
1713 # on it. Switch to a detached HEAD.
1714 #
David Pursehouse8a68ff92012-09-24 12:15:13 +09001715 head = all_refs[head]
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001716
David Pursehouse8a68ff92012-09-24 12:15:13 +09001717 revid = self.GetRevisionId(all_refs)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001718 if head == revid:
Shawn O. Pearce552ac892009-04-18 15:15:24 -07001719 _lwrite(os.path.join(self.worktree, '.git', HEAD),
1720 '%s\n' % revid)
1721 else:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001722 self._Checkout(revid, quiet=True)
Shawn O. Pearce552ac892009-04-18 15:15:24 -07001723
1724 return GitCommand(self,
1725 ['branch', '-D', name],
Anthony King7bdac712014-07-16 12:56:40 +01001726 capture_stdout=True,
1727 capture_stderr=True).Wait() == 0
Shawn O. Pearce9fa44db2008-11-03 11:24:59 -08001728
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001729 def PruneHeads(self):
1730 """Prune any topic branches already merged into upstream.
1731 """
1732 cb = self.CurrentBranch
1733 kill = []
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001734 left = self._allrefs
1735 for name in left.keys():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001736 if name.startswith(R_HEADS):
1737 name = name[len(R_HEADS):]
1738 if cb is None or name != cb:
1739 kill.append(name)
1740
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001741 rev = self.GetRevisionId(left)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001742 if cb is not None \
1743 and not self._revlist(HEAD + '...' + rev) \
Anthony King7bdac712014-07-16 12:56:40 +01001744 and not self.IsDirty(consider_untracked=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001745 self.work_git.DetachHead(HEAD)
1746 kill.append(cb)
1747
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001748 if kill:
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07001749 old = self.bare_git.GetHead()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001750
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001751 try:
1752 self.bare_git.DetachHead(rev)
1753
1754 b = ['branch', '-d']
1755 b.extend(kill)
1756 b = GitCommand(self, b, bare=True,
1757 capture_stdout=True,
1758 capture_stderr=True)
1759 b.Wait()
1760 finally:
Dan Willemsen1a799d12015-12-15 13:40:05 -08001761 if ID_RE.match(old):
1762 self.bare_git.DetachHead(old)
1763 else:
1764 self.bare_git.SetHead(old)
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001765 left = self._allrefs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001766
Shawn O. Pearce3778f9d2009-03-02 12:30:50 -08001767 for branch in kill:
1768 if (R_HEADS + branch) not in left:
1769 self.CleanPublishedCache()
1770 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001771
1772 if cb and cb not in kill:
1773 kill.append(cb)
Shawn O. Pearce7c6c64d2009-03-02 12:38:13 -08001774 kill.sort()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001775
1776 kept = []
1777 for branch in kill:
Anthony King7bdac712014-07-16 12:56:40 +01001778 if R_HEADS + branch in left:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001779 branch = self.GetBranch(branch)
1780 base = branch.LocalMerge
1781 if not base:
1782 base = rev
1783 kept.append(ReviewableBranch(self, branch, base))
1784 return kept
1785
1786
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001787# Submodule Management ##
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001788
1789 def GetRegisteredSubprojects(self):
1790 result = []
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001791
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001792 def rec(subprojects):
1793 if not subprojects:
1794 return
1795 result.extend(subprojects)
1796 for p in subprojects:
1797 rec(p.subprojects)
1798 rec(self.subprojects)
1799 return result
1800
1801 def _GetSubmodules(self):
1802 # Unfortunately we cannot call `git submodule status --recursive` here
1803 # because the working tree might not exist yet, and it cannot be used
1804 # without a working tree in its current implementation.
1805
1806 def get_submodules(gitdir, rev):
1807 # Parse .gitmodules for submodule sub_paths and sub_urls
1808 sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
1809 if not sub_paths:
1810 return []
1811 # Run `git ls-tree` to read SHAs of submodule object, which happen to be
1812 # revision of submodule repository
1813 sub_revs = git_ls_tree(gitdir, rev, sub_paths)
1814 submodules = []
1815 for sub_path, sub_url in zip(sub_paths, sub_urls):
1816 try:
1817 sub_rev = sub_revs[sub_path]
1818 except KeyError:
1819 # Ignore non-exist submodules
1820 continue
1821 submodules.append((sub_rev, sub_path, sub_url))
1822 return submodules
1823
1824 re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
1825 re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001826
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001827 def parse_gitmodules(gitdir, rev):
1828 cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
1829 try:
Anthony King7bdac712014-07-16 12:56:40 +01001830 p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
1831 bare=True, gitdir=gitdir)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001832 except GitError:
1833 return [], []
1834 if p.Wait() != 0:
1835 return [], []
1836
1837 gitmodules_lines = []
1838 fd, temp_gitmodules_path = tempfile.mkstemp()
1839 try:
1840 os.write(fd, p.stdout)
1841 os.close(fd)
1842 cmd = ['config', '--file', temp_gitmodules_path, '--list']
Anthony King7bdac712014-07-16 12:56:40 +01001843 p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
1844 bare=True, gitdir=gitdir)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001845 if p.Wait() != 0:
1846 return [], []
1847 gitmodules_lines = p.stdout.split('\n')
1848 except GitError:
1849 return [], []
1850 finally:
1851 os.remove(temp_gitmodules_path)
1852
1853 names = set()
1854 paths = {}
1855 urls = {}
1856 for line in gitmodules_lines:
1857 if not line:
1858 continue
1859 m = re_path.match(line)
1860 if m:
1861 names.add(m.group(1))
1862 paths[m.group(1)] = m.group(2)
1863 continue
1864 m = re_url.match(line)
1865 if m:
1866 names.add(m.group(1))
1867 urls[m.group(1)] = m.group(2)
1868 continue
1869 names = sorted(names)
1870 return ([paths.get(name, '') for name in names],
1871 [urls.get(name, '') for name in names])
1872
1873 def git_ls_tree(gitdir, rev, paths):
1874 cmd = ['ls-tree', rev, '--']
1875 cmd.extend(paths)
1876 try:
Anthony King7bdac712014-07-16 12:56:40 +01001877 p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
1878 bare=True, gitdir=gitdir)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001879 except GitError:
1880 return []
1881 if p.Wait() != 0:
1882 return []
1883 objects = {}
1884 for line in p.stdout.split('\n'):
1885 if not line.strip():
1886 continue
1887 object_rev, object_path = line.split()[2:4]
1888 objects[object_path] = object_rev
1889 return objects
1890
1891 try:
1892 rev = self.GetRevisionId()
1893 except GitError:
1894 return []
1895 return get_submodules(self.gitdir, rev)
1896
1897 def GetDerivedSubprojects(self):
1898 result = []
1899 if not self.Exists:
1900 # If git repo does not exist yet, querying its submodules will
1901 # mess up its states; so return here.
1902 return result
1903 for rev, path, url in self._GetSubmodules():
1904 name = self.manifest.GetSubprojectName(self, path)
David James8d201162013-10-11 17:03:19 -07001905 relpath, worktree, gitdir, objdir = \
1906 self.manifest.GetSubprojectPaths(self, name, path)
1907 project = self.manifest.paths.get(relpath)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001908 if project:
1909 result.extend(project.GetDerivedSubprojects())
1910 continue
David James8d201162013-10-11 17:03:19 -07001911
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001912 remote = RemoteSpec(self.remote.name,
Anthony King7bdac712014-07-16 12:56:40 +01001913 url=url,
Steve Raed6480452016-08-10 15:00:00 -07001914 pushUrl=self.remote.pushUrl,
Anthony King7bdac712014-07-16 12:56:40 +01001915 review=self.remote.review,
1916 revision=self.remote.revision)
1917 subproject = Project(manifest=self.manifest,
1918 name=name,
1919 remote=remote,
1920 gitdir=gitdir,
1921 objdir=objdir,
1922 worktree=worktree,
1923 relpath=relpath,
Aymen Bouaziz2598ed02016-06-24 14:34:08 +02001924 revisionExpr=rev,
Anthony King7bdac712014-07-16 12:56:40 +01001925 revisionId=rev,
1926 rebase=self.rebase,
1927 groups=self.groups,
1928 sync_c=self.sync_c,
1929 sync_s=self.sync_s,
1930 parent=self,
1931 is_derived=True)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001932 result.append(subproject)
1933 result.extend(subproject.GetDerivedSubprojects())
1934 return result
1935
1936
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001937# Direct Git Commands ##
Chris AtLee2fb64662014-01-16 21:32:33 -05001938 def _CheckForSha1(self):
1939 try:
1940 # if revision (sha or tag) is not present then following function
1941 # throws an error.
1942 self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
1943 return True
1944 except GitError:
1945 # There is no such persistent revision. We have to fetch it.
1946 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001947
Julien Campergue335f5ef2013-10-16 11:02:35 +02001948 def _FetchArchive(self, tarpath, cwd=None):
1949 cmd = ['archive', '-v', '-o', tarpath]
1950 cmd.append('--remote=%s' % self.remote.url)
1951 cmd.append('--prefix=%s/' % self.relpath)
1952 cmd.append(self.revisionExpr)
1953
1954 command = GitCommand(self, cmd, cwd=cwd,
1955 capture_stdout=True,
1956 capture_stderr=True)
1957
1958 if command.Wait() != 0:
1959 raise GitError('git archive %s: %s' % (self.name, command.stderr))
1960
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001961 def _RemoteFetch(self, name=None,
1962 current_branch_only=False,
Shawn O. Pearce16614f82010-10-29 12:05:43 -07001963 initial=False,
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07001964 quiet=False,
Mitchel Humpherys597868b2012-10-29 10:18:34 -07001965 alt_dir=None,
David Pursehouse74cfd272015-10-14 10:50:15 +09001966 no_tags=False,
1967 prune=False):
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001968
1969 is_sha1 = False
1970 tag_name = None
David Pursehouse9bc422f2014-04-15 10:28:56 +09001971 depth = None
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001972
David Pursehouse9bc422f2014-04-15 10:28:56 +09001973 # The depth should not be used when fetching to a mirror because
1974 # it will result in a shallow repository that cannot be cloned or
1975 # fetched from.
1976 if not self.manifest.IsMirror:
1977 if self.clone_depth:
1978 depth = self.clone_depth
1979 else:
1980 depth = self.manifest.manifestProject.config.GetString('repo.depth')
Conley Owense4978cf2015-02-03 18:06:16 -08001981 # The repo project should never be synced with partial depth
1982 if self.relpath == '.repo/repo':
1983 depth = None
David Pursehouse9bc422f2014-04-15 10:28:56 +09001984
Shawn Pearce69e04d82014-01-29 12:48:54 -08001985 if depth:
1986 current_branch_only = True
1987
Nasser Grainawi909d58b2014-09-19 12:13:04 -06001988 if ID_RE.match(self.revisionExpr) is not None:
1989 is_sha1 = True
1990
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001991 if current_branch_only:
Nasser Grainawi909d58b2014-09-19 12:13:04 -06001992 if self.revisionExpr.startswith(R_TAGS):
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001993 # this is a tag and its sha1 value should never change
1994 tag_name = self.revisionExpr[len(R_TAGS):]
1995
1996 if is_sha1 or tag_name is not None:
Chris AtLee2fb64662014-01-16 21:32:33 -05001997 if self._CheckForSha1():
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07001998 return True
Bertrand SIMONNET3000cda2014-11-25 16:19:29 -08001999 if is_sha1 and not depth:
2000 # When syncing a specific commit and --depth is not set:
2001 # * if upstream is explicitly specified and is not a sha1, fetch only
2002 # upstream as users expect only upstream to be fetch.
2003 # Note: The commit might not be in upstream in which case the sync
2004 # will fail.
2005 # * otherwise, fetch all branches to make sure we end up with the
2006 # specific commit.
Aymen Bouaziz037040f2016-06-28 12:27:23 +02002007 if self.upstream:
2008 current_branch_only = not ID_RE.match(self.upstream)
2009 else:
2010 current_branch_only = False
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07002011
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002012 if not name:
2013 name = self.remote.name
Shawn O. Pearcefb231612009-04-10 18:53:46 -07002014
2015 ssh_proxy = False
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07002016 remote = self.GetRemote(name)
2017 if remote.PreConnectFetch():
Shawn O. Pearcefb231612009-04-10 18:53:46 -07002018 ssh_proxy = True
2019
Shawn O. Pearce88443382010-10-08 10:02:09 +02002020 if initial:
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002021 if alt_dir and 'objects' == os.path.basename(alt_dir):
2022 ref_dir = os.path.dirname(alt_dir)
Shawn O. Pearce88443382010-10-08 10:02:09 +02002023 packed_refs = os.path.join(self.gitdir, 'packed-refs')
2024 remote = self.GetRemote(name)
2025
David Pursehouse8a68ff92012-09-24 12:15:13 +09002026 all_refs = self.bare_ref.all
2027 ids = set(all_refs.values())
Shawn O. Pearce88443382010-10-08 10:02:09 +02002028 tmp = set()
2029
Chirayu Desai217ea7d2013-03-01 19:14:38 +05302030 for r, ref_id in GitRefs(ref_dir).all.items():
David Pursehouse8a68ff92012-09-24 12:15:13 +09002031 if r not in all_refs:
Shawn O. Pearce88443382010-10-08 10:02:09 +02002032 if r.startswith(R_TAGS) or remote.WritesTo(r):
David Pursehouse8a68ff92012-09-24 12:15:13 +09002033 all_refs[r] = ref_id
2034 ids.add(ref_id)
Shawn O. Pearce88443382010-10-08 10:02:09 +02002035 continue
2036
David Pursehouse8a68ff92012-09-24 12:15:13 +09002037 if ref_id in ids:
Shawn O. Pearce88443382010-10-08 10:02:09 +02002038 continue
2039
David Pursehouse8a68ff92012-09-24 12:15:13 +09002040 r = 'refs/_alt/%s' % ref_id
2041 all_refs[r] = ref_id
2042 ids.add(ref_id)
Shawn O. Pearce88443382010-10-08 10:02:09 +02002043 tmp.add(r)
2044
Shawn O. Pearce88443382010-10-08 10:02:09 +02002045 tmp_packed = ''
2046 old_packed = ''
2047
Chirayu Desai217ea7d2013-03-01 19:14:38 +05302048 for r in sorted(all_refs):
David Pursehouse8a68ff92012-09-24 12:15:13 +09002049 line = '%s %s\n' % (all_refs[r], r)
Shawn O. Pearce88443382010-10-08 10:02:09 +02002050 tmp_packed += line
2051 if r not in tmp:
2052 old_packed += line
2053
2054 _lwrite(packed_refs, tmp_packed)
Shawn O. Pearce88443382010-10-08 10:02:09 +02002055 else:
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002056 alt_dir = None
Shawn O. Pearce88443382010-10-08 10:02:09 +02002057
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08002058 cmd = ['fetch']
Doug Anderson30d45292011-05-04 15:01:04 -07002059
Conley Owensf97e8382015-01-21 11:12:46 -08002060 if depth:
Doug Anderson30d45292011-05-04 15:01:04 -07002061 cmd.append('--depth=%s' % depth)
Dan Willemseneeab6862015-08-03 13:11:53 -07002062 else:
2063 # If this repo has shallow objects, then we don't know which refs have
2064 # shallow objects or not. Tell git to unshallow all fetched refs. Don't
2065 # do this with projects that don't have shallow objects, since it is less
2066 # efficient.
2067 if os.path.exists(os.path.join(self.gitdir, 'shallow')):
2068 cmd.append('--depth=2147483647')
Doug Anderson30d45292011-05-04 15:01:04 -07002069
Shawn O. Pearce16614f82010-10-29 12:05:43 -07002070 if quiet:
2071 cmd.append('--quiet')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08002072 if not self.worktree:
2073 cmd.append('--update-head-ok')
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002074 cmd.append(name)
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07002075
Mitchel Humpherys26c45a72014-03-10 14:21:59 -07002076 # If using depth then we should not get all the tags since they may
2077 # be outside of the depth.
2078 if no_tags or depth:
2079 cmd.append('--no-tags')
2080 else:
2081 cmd.append('--tags')
2082
David Pursehouse74cfd272015-10-14 10:50:15 +09002083 if prune:
2084 cmd.append('--prune')
2085
Conley Owens80b87fe2014-05-09 17:13:44 -07002086 spec = []
Brian Harring14a66742012-09-28 20:21:57 -07002087 if not current_branch_only:
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07002088 # Fetch whole repo
Conley Owens80b87fe2014-05-09 17:13:44 -07002089 spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
Anatol Pomazau53d6f4d2011-08-25 17:21:47 -07002090 elif tag_name is not None:
Conley Owens80b87fe2014-05-09 17:13:44 -07002091 spec.append('tag')
2092 spec.append(tag_name)
Nasser Grainawi04e52d62014-09-30 13:34:52 -06002093
David Pursehouse403b64e2015-04-27 10:41:33 +09002094 if not self.manifest.IsMirror:
2095 branch = self.revisionExpr
Kevin Degi679bac42015-06-22 15:31:26 -06002096 if is_sha1 and depth and git_require((1, 8, 3)):
David Pursehouse403b64e2015-04-27 10:41:33 +09002097 # Shallow checkout of a specific commit, fetch from that commit and not
2098 # the heads only as the commit might be deeper in the history.
2099 spec.append(branch)
2100 else:
2101 if is_sha1:
2102 branch = self.upstream
2103 if branch is not None and branch.strip():
2104 if not branch.startswith('refs/'):
2105 branch = R_HEADS + branch
2106 spec.append(str((u'+%s:' % branch) + remote.ToLocal(branch)))
Conley Owens80b87fe2014-05-09 17:13:44 -07002107 cmd.extend(spec)
2108
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002109 ok = False
David Pursehouse8a68ff92012-09-24 12:15:13 +09002110 for _i in range(2):
John L. Villalovos9c76f672015-03-16 20:49:10 -07002111 gitcmd = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy)
John L. Villalovos126e2982015-01-29 21:58:12 -08002112 ret = gitcmd.Wait()
Brian Harring14a66742012-09-28 20:21:57 -07002113 if ret == 0:
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002114 ok = True
2115 break
John L. Villalovos126e2982015-01-29 21:58:12 -08002116 # If needed, run the 'git remote prune' the first time through the loop
2117 elif (not _i and
2118 "error:" in gitcmd.stderr and
2119 "git remote prune" in gitcmd.stderr):
2120 prunecmd = GitCommand(self, ['remote', 'prune', name], bare=True,
John L. Villalovos9c76f672015-03-16 20:49:10 -07002121 ssh_proxy=ssh_proxy)
John L. Villalovose30f46b2015-02-25 14:27:02 -08002122 ret = prunecmd.Wait()
John L. Villalovose30f46b2015-02-25 14:27:02 -08002123 if ret:
John L. Villalovos126e2982015-01-29 21:58:12 -08002124 break
2125 continue
Brian Harring14a66742012-09-28 20:21:57 -07002126 elif current_branch_only and is_sha1 and ret == 128:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002127 # Exit code 128 means "couldn't find the ref you asked for"; if we're
2128 # in sha1 mode, we just tried sync'ing from the upstream field; it
2129 # doesn't exist, thus abort the optimization attempt and do a full sync.
Brian Harring14a66742012-09-28 20:21:57 -07002130 break
Colin Crossc4b301f2015-05-13 00:10:02 -07002131 elif ret < 0:
2132 # Git died with a signal, exit immediately
2133 break
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002134 time.sleep(random.randint(30, 45))
Shawn O. Pearce88443382010-10-08 10:02:09 +02002135
2136 if initial:
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002137 if alt_dir:
Shawn O. Pearce88443382010-10-08 10:02:09 +02002138 if old_packed != '':
2139 _lwrite(packed_refs, old_packed)
2140 else:
2141 os.remove(packed_refs)
2142 self.bare_git.pack_refs('--all', '--prune')
Brian Harring14a66742012-09-28 20:21:57 -07002143
2144 if is_sha1 and current_branch_only and self.upstream:
2145 # We just synced the upstream given branch; verify we
2146 # got what we wanted, else trigger a second run of all
2147 # refs.
Chris AtLee2fb64662014-01-16 21:32:33 -05002148 if not self._CheckForSha1():
Kevin Degi679bac42015-06-22 15:31:26 -06002149 if not depth:
2150 # Avoid infinite recursion when depth is True (since depth implies
2151 # current_branch_only)
2152 return self._RemoteFetch(name=name, current_branch_only=False,
2153 initial=False, quiet=quiet, alt_dir=alt_dir)
2154 if self.clone_depth:
2155 self.clone_depth = None
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002156 return self._RemoteFetch(name=name,
2157 current_branch_only=current_branch_only,
Kevin Degi679bac42015-06-22 15:31:26 -06002158 initial=False, quiet=quiet, alt_dir=alt_dir)
Brian Harring14a66742012-09-28 20:21:57 -07002159
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002160 return ok
Shawn O. Pearce88443382010-10-08 10:02:09 +02002161
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002162 def _ApplyCloneBundle(self, initial=False, quiet=False):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002163 if initial and \
2164 (self.manifest.manifestProject.config.GetString('repo.depth') or
2165 self.clone_depth):
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002166 return False
2167
2168 remote = self.GetRemote(self.remote.name)
2169 bundle_url = remote.url + '/clone.bundle'
2170 bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002171 if GetSchemeFromUrl(bundle_url) not in ('http', 'https',
2172 'persistent-http',
2173 'persistent-https'):
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002174 return False
2175
2176 bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
2177 bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
2178
2179 exist_dst = os.path.exists(bundle_dst)
2180 exist_tmp = os.path.exists(bundle_tmp)
2181
2182 if not initial and not exist_dst and not exist_tmp:
2183 return False
2184
2185 if not exist_dst:
2186 exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
2187 if not exist_dst:
2188 return False
2189
2190 cmd = ['fetch']
2191 if quiet:
2192 cmd.append('--quiet')
2193 if not self.worktree:
2194 cmd.append('--update-head-ok')
2195 cmd.append(bundle_dst)
2196 for f in remote.fetch:
2197 cmd.append(str(f))
2198 cmd.append('refs/tags/*:refs/tags/*')
2199
2200 ok = GitCommand(self, cmd, bare=True).Wait() == 0
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07002201 if os.path.exists(bundle_dst):
2202 os.remove(bundle_dst)
2203 if os.path.exists(bundle_tmp):
2204 os.remove(bundle_tmp)
Shawn O. Pearce88443382010-10-08 10:02:09 +02002205 return ok
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002206
Shawn O. Pearcec325dc32011-10-03 08:30:24 -07002207 def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07002208 if os.path.exists(dstPath):
2209 os.remove(dstPath)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07002210
Matt Gumbel2dc810c2012-08-30 09:39:36 -07002211 cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07002212 if quiet:
2213 cmd += ['--silent']
2214 if os.path.exists(tmpPath):
2215 size = os.stat(tmpPath).st_size
2216 if size >= 1024:
2217 cmd += ['--continue-at', '%d' % (size,)]
2218 else:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07002219 os.remove(tmpPath)
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07002220 if 'http_proxy' in os.environ and 'darwin' == sys.platform:
2221 cmd += ['--proxy', os.environ['http_proxy']]
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002222 with GetUrlCookieFile(srcUrl, quiet) as (cookiefile, _proxy):
Dave Borowitz137d0132015-01-02 11:12:54 -08002223 if cookiefile:
Dave Borowitz4abf8e62015-01-02 11:39:04 -08002224 cmd += ['--cookie', cookiefile, '--cookie-jar', cookiefile]
Dave Borowitz137d0132015-01-02 11:12:54 -08002225 if srcUrl.startswith('persistent-'):
2226 srcUrl = srcUrl[len('persistent-'):]
2227 cmd += [srcUrl]
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07002228
Dave Borowitz137d0132015-01-02 11:12:54 -08002229 if IsTrace():
2230 Trace('%s', ' '.join(cmd))
2231 try:
2232 proc = subprocess.Popen(cmd)
2233 except OSError:
2234 return False
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07002235
Dave Borowitz137d0132015-01-02 11:12:54 -08002236 curlret = proc.wait()
Matt Gumbel2dc810c2012-08-30 09:39:36 -07002237
Dave Borowitz137d0132015-01-02 11:12:54 -08002238 if curlret == 22:
2239 # From curl man page:
2240 # 22: HTTP page not retrieved. The requested url was not found or
2241 # returned another error with the HTTP error code being 400 or above.
2242 # This return code only appears if -f, --fail is used.
2243 if not quiet:
2244 print("Server does not provide clone.bundle; ignoring.",
2245 file=sys.stderr)
2246 return False
Matt Gumbel2dc810c2012-08-30 09:39:36 -07002247
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07002248 if os.path.exists(tmpPath):
Kris Giesingc8d882a2014-12-23 13:02:32 -08002249 if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -07002250 os.rename(tmpPath, dstPath)
2251 return True
2252 else:
2253 os.remove(tmpPath)
2254 return False
2255 else:
2256 return False
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -07002257
Kris Giesingc8d882a2014-12-23 13:02:32 -08002258 def _IsValidBundle(self, path, quiet):
Dave Borowitz91f3ba52013-06-03 12:15:23 -07002259 try:
2260 with open(path) as f:
2261 if f.read(16) == '# v2 git bundle\n':
2262 return True
2263 else:
Kris Giesingc8d882a2014-12-23 13:02:32 -08002264 if not quiet:
2265 print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
Dave Borowitz91f3ba52013-06-03 12:15:23 -07002266 return False
2267 except OSError:
2268 return False
2269
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002270 def _Checkout(self, rev, quiet=False):
2271 cmd = ['checkout']
2272 if quiet:
2273 cmd.append('-q')
2274 cmd.append(rev)
2275 cmd.append('--')
2276 if GitCommand(self, cmd).Wait() != 0:
2277 if self._allrefs:
2278 raise GitError('%s checkout %s ' % (self.name, rev))
2279
Anthony King7bdac712014-07-16 12:56:40 +01002280 def _CherryPick(self, rev):
Pierre Tardye5a21222011-03-24 16:28:18 +01002281 cmd = ['cherry-pick']
2282 cmd.append(rev)
2283 cmd.append('--')
2284 if GitCommand(self, cmd).Wait() != 0:
2285 if self._allrefs:
2286 raise GitError('%s cherry-pick %s ' % (self.name, rev))
2287
Anthony King7bdac712014-07-16 12:56:40 +01002288 def _Revert(self, rev):
Erwan Mahea94f1622011-08-19 13:56:09 +02002289 cmd = ['revert']
2290 cmd.append('--no-edit')
2291 cmd.append(rev)
2292 cmd.append('--')
2293 if GitCommand(self, cmd).Wait() != 0:
2294 if self._allrefs:
2295 raise GitError('%s revert %s ' % (self.name, rev))
2296
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002297 def _ResetHard(self, rev, quiet=True):
2298 cmd = ['reset', '--hard']
2299 if quiet:
2300 cmd.append('-q')
2301 cmd.append(rev)
2302 if GitCommand(self, cmd).Wait() != 0:
2303 raise GitError('%s reset --hard %s ' % (self.name, rev))
2304
Anthony King7bdac712014-07-16 12:56:40 +01002305 def _Rebase(self, upstream, onto=None):
Shawn O. Pearce19a83d82009-04-16 08:14:26 -07002306 cmd = ['rebase']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002307 if onto is not None:
2308 cmd.extend(['--onto', onto])
2309 cmd.append(upstream)
Shawn O. Pearce19a83d82009-04-16 08:14:26 -07002310 if GitCommand(self, cmd).Wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002311 raise GitError('%s rebase %s ' % (self.name, upstream))
2312
Pierre Tardy3d125942012-05-04 12:18:12 +02002313 def _FastForward(self, head, ffonly=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002314 cmd = ['merge', head]
Pierre Tardy3d125942012-05-04 12:18:12 +02002315 if ffonly:
2316 cmd.append("--ff-only")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002317 if GitCommand(self, cmd).Wait() != 0:
2318 raise GitError('%s merge %s ' % (self.name, head))
2319
Kevin Degiabaa7f32014-11-12 11:27:45 -07002320 def _InitGitDir(self, mirror_git=None, force_sync=False):
Kevin Degi384b3c52014-10-16 16:02:58 -06002321 init_git_dir = not os.path.exists(self.gitdir)
2322 init_obj_dir = not os.path.exists(self.objdir)
Kevin Degib1a07b82015-07-27 13:33:43 -06002323 try:
2324 # Initialize the bare repository, which contains all of the objects.
2325 if init_obj_dir:
2326 os.makedirs(self.objdir)
2327 self.bare_objdir.init()
David James8d201162013-10-11 17:03:19 -07002328
Kevin Degib1a07b82015-07-27 13:33:43 -06002329 # If we have a separate directory to hold refs, initialize it as well.
2330 if self.objdir != self.gitdir:
2331 if init_git_dir:
2332 os.makedirs(self.gitdir)
2333
2334 if init_obj_dir or init_git_dir:
2335 self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
2336 copy_all=True)
Kevin Degiabaa7f32014-11-12 11:27:45 -07002337 try:
2338 self._CheckDirReference(self.objdir, self.gitdir, share_refs=False)
2339 except GitError as e:
Kevin Degiabaa7f32014-11-12 11:27:45 -07002340 if force_sync:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002341 print("Retrying clone after deleting %s" %
2342 self.gitdir, file=sys.stderr)
Kevin Degiabaa7f32014-11-12 11:27:45 -07002343 try:
2344 shutil.rmtree(os.path.realpath(self.gitdir))
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002345 if self.worktree and os.path.exists(os.path.realpath
2346 (self.worktree)):
Kevin Degiabaa7f32014-11-12 11:27:45 -07002347 shutil.rmtree(os.path.realpath(self.worktree))
2348 return self._InitGitDir(mirror_git=mirror_git, force_sync=False)
2349 except:
2350 raise e
2351 raise e
Kevin Degib1a07b82015-07-27 13:33:43 -06002352
Kevin Degi384b3c52014-10-16 16:02:58 -06002353 if init_git_dir:
Kevin Degib1a07b82015-07-27 13:33:43 -06002354 mp = self.manifest.manifestProject
2355 ref_dir = mp.config.GetString('repo.reference') or ''
Kevin Degi384b3c52014-10-16 16:02:58 -06002356
Kevin Degib1a07b82015-07-27 13:33:43 -06002357 if ref_dir or mirror_git:
2358 if not mirror_git:
2359 mirror_git = os.path.join(ref_dir, self.name + '.git')
2360 repo_git = os.path.join(ref_dir, '.repo', 'projects',
2361 self.relpath + '.git')
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -08002362
Kevin Degib1a07b82015-07-27 13:33:43 -06002363 if os.path.exists(mirror_git):
2364 ref_dir = mirror_git
Shawn O. Pearce88443382010-10-08 10:02:09 +02002365
Kevin Degib1a07b82015-07-27 13:33:43 -06002366 elif os.path.exists(repo_git):
2367 ref_dir = repo_git
Shawn O. Pearce88443382010-10-08 10:02:09 +02002368
Kevin Degib1a07b82015-07-27 13:33:43 -06002369 else:
2370 ref_dir = None
Shawn O. Pearce88443382010-10-08 10:02:09 +02002371
Kevin Degib1a07b82015-07-27 13:33:43 -06002372 if ref_dir:
2373 _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
2374 os.path.join(ref_dir, 'objects') + '\n')
Shawn O. Pearce88443382010-10-08 10:02:09 +02002375
Kevin Degib1a07b82015-07-27 13:33:43 -06002376 self._UpdateHooks()
2377
2378 m = self.manifest.manifestProject.config
2379 for key in ['user.name', 'user.email']:
2380 if m.Has(key, include_defaults=False):
2381 self.config.SetString(key, m.GetString(key))
David Pursehouse76a4a9d2016-08-16 12:11:12 +09002382 self.config.SetString('filter.lfs.smudge', 'git-lfs smudge --skip -- %f')
Kevin Degib1a07b82015-07-27 13:33:43 -06002383 if self.manifest.IsMirror:
2384 self.config.SetString('core.bare', 'true')
Shawn O. Pearce88443382010-10-08 10:02:09 +02002385 else:
Kevin Degib1a07b82015-07-27 13:33:43 -06002386 self.config.SetString('core.bare', None)
2387 except Exception:
2388 if init_obj_dir and os.path.exists(self.objdir):
2389 shutil.rmtree(self.objdir)
2390 if init_git_dir and os.path.exists(self.gitdir):
2391 shutil.rmtree(self.gitdir)
2392 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002393
Jimmie Westera0444582012-10-24 13:44:42 +02002394 def _UpdateHooks(self):
2395 if os.path.exists(self.gitdir):
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08002396 self._InitHooks()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002397
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08002398 def _InitHooks(self):
Jesse Hall672cc492013-11-27 11:17:13 -08002399 hooks = os.path.realpath(self._gitdir_path('hooks'))
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08002400 if not os.path.exists(hooks):
2401 os.makedirs(hooks)
Jonathan Nieder93719792015-03-17 11:29:58 -07002402 for stock_hook in _ProjectHooks():
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07002403 name = os.path.basename(stock_hook)
2404
Victor Boivie65e0f352011-04-18 11:23:29 +02002405 if name in ('commit-msg',) and not self.remote.review \
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002406 and self is not self.manifest.manifestProject:
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07002407 # Don't install a Gerrit Code Review hook if this
2408 # project does not appear to use it for reviews.
2409 #
Victor Boivie65e0f352011-04-18 11:23:29 +02002410 # Since the manifest project is one of those, but also
2411 # managed through gerrit, it's excluded
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07002412 continue
2413
2414 dst = os.path.join(hooks, name)
2415 if os.path.islink(dst):
2416 continue
2417 if os.path.exists(dst):
2418 if filecmp.cmp(stock_hook, dst, shallow=False):
2419 os.remove(dst)
2420 else:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002421 _warn("%s: Not replacing locally modified %s hook",
2422 self.relpath, name)
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07002423 continue
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08002424 try:
Mickaël Salaünb9477bc2012-08-05 13:39:26 +02002425 os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
Sarah Owensa5be53f2012-09-09 15:37:57 -07002426 except OSError as e:
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07002427 if e.errno == errno.EPERM:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08002428 raise GitError('filesystem must support symlinks')
2429 else:
2430 raise
2431
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002432 def _InitRemote(self):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -07002433 if self.remote.url:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002434 remote = self.GetRemote(self.remote.name)
Shawn O. Pearced1f70d92009-05-19 14:58:02 -07002435 remote.url = self.remote.url
Steve Raed6480452016-08-10 15:00:00 -07002436 remote.pushUrl = self.remote.pushUrl
Shawn O. Pearced1f70d92009-05-19 14:58:02 -07002437 remote.review = self.remote.review
2438 remote.projectname = self.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002439
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08002440 if self.worktree:
2441 remote.ResetFetch(mirror=False)
2442 else:
2443 remote.ResetFetch(mirror=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002444 remote.Save()
2445
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002446 def _InitMRef(self):
2447 if self.manifest.branch:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002448 self._InitAnyMRef(R_M + self.manifest.branch)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002449
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08002450 def _InitMirrorHead(self):
Shawn O. Pearcefe200ee2009-06-01 15:28:21 -07002451 self._InitAnyMRef(HEAD)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002452
2453 def _InitAnyMRef(self, ref):
2454 cur = self.bare_ref.symref(ref)
2455
2456 if self.revisionId:
2457 if cur != '' or self.bare_ref.get(ref) != self.revisionId:
2458 msg = 'manifest set to %s' % self.revisionId
2459 dst = self.revisionId + '^0'
Anthony King7bdac712014-07-16 12:56:40 +01002460 self.bare_git.UpdateRef(ref, dst, message=msg, detach=True)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002461 else:
2462 remote = self.GetRemote(self.remote.name)
2463 dst = remote.ToLocal(self.revisionExpr)
2464 if cur != dst:
2465 msg = 'manifest set to %s' % self.revisionExpr
2466 self.bare_git.symbolic_ref('-m', msg, ref, dst)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08002467
Kevin Degi384b3c52014-10-16 16:02:58 -06002468 def _CheckDirReference(self, srcdir, destdir, share_refs):
Dan Willemsenbdb866e2016-04-05 17:22:02 -07002469 symlink_files = self.shareable_files[:]
2470 symlink_dirs = self.shareable_dirs[:]
Kevin Degi384b3c52014-10-16 16:02:58 -06002471 if share_refs:
2472 symlink_files += self.working_tree_files
2473 symlink_dirs += self.working_tree_dirs
2474 to_symlink = symlink_files + symlink_dirs
2475 for name in set(to_symlink):
2476 dst = os.path.realpath(os.path.join(destdir, name))
2477 if os.path.lexists(dst):
2478 src = os.path.realpath(os.path.join(srcdir, name))
2479 # Fail if the links are pointing to the wrong place
2480 if src != dst:
Kevin Degiabaa7f32014-11-12 11:27:45 -07002481 raise GitError('--force-sync not enabled; cannot overwrite a local '
Simon Ruggierf9b76832015-07-31 17:18:34 -04002482 'work tree. If you\'re comfortable with the '
2483 'possibility of losing the work tree\'s git metadata,'
2484 ' use `repo sync --force-sync {0}` to '
2485 'proceed.'.format(self.relpath))
Kevin Degi384b3c52014-10-16 16:02:58 -06002486
David James8d201162013-10-11 17:03:19 -07002487 def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
2488 """Update |dotgit| to reference |gitdir|, using symlinks where possible.
2489
2490 Args:
2491 gitdir: The bare git repository. Must already be initialized.
2492 dotgit: The repository you would like to initialize.
2493 share_refs: If true, |dotgit| will store its refs under |gitdir|.
2494 Only one work tree can store refs under a given |gitdir|.
2495 copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
2496 This saves you the effort of initializing |dotgit| yourself.
2497 """
Dan Willemsenbdb866e2016-04-05 17:22:02 -07002498 symlink_files = self.shareable_files[:]
2499 symlink_dirs = self.shareable_dirs[:]
David James8d201162013-10-11 17:03:19 -07002500 if share_refs:
Kevin Degi384b3c52014-10-16 16:02:58 -06002501 symlink_files += self.working_tree_files
2502 symlink_dirs += self.working_tree_dirs
David James8d201162013-10-11 17:03:19 -07002503 to_symlink = symlink_files + symlink_dirs
2504
2505 to_copy = []
2506 if copy_all:
2507 to_copy = os.listdir(gitdir)
2508
Dan Willemsen2a3e1522015-07-30 20:43:33 -07002509 dotgit = os.path.realpath(dotgit)
David James8d201162013-10-11 17:03:19 -07002510 for name in set(to_copy).union(to_symlink):
2511 try:
2512 src = os.path.realpath(os.path.join(gitdir, name))
Dan Willemsen2a3e1522015-07-30 20:43:33 -07002513 dst = os.path.join(dotgit, name)
David James8d201162013-10-11 17:03:19 -07002514
Kevin Degi384b3c52014-10-16 16:02:58 -06002515 if os.path.lexists(dst):
2516 continue
David James8d201162013-10-11 17:03:19 -07002517
2518 # If the source dir doesn't exist, create an empty dir.
2519 if name in symlink_dirs and not os.path.lexists(src):
2520 os.makedirs(src)
2521
Conley Owens80b87fe2014-05-09 17:13:44 -07002522 # If the source file doesn't exist, ensure the destination
2523 # file doesn't either.
2524 if name in symlink_files and not os.path.lexists(src):
2525 try:
2526 os.remove(dst)
2527 except OSError:
2528 pass
2529
David James8d201162013-10-11 17:03:19 -07002530 if name in to_symlink:
2531 os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
2532 elif copy_all and not os.path.islink(dst):
2533 if os.path.isdir(src):
2534 shutil.copytree(src, dst)
2535 elif os.path.isfile(src):
2536 shutil.copy(src, dst)
2537 except OSError as e:
2538 if e.errno == errno.EPERM:
Kevin Degiabaa7f32014-11-12 11:27:45 -07002539 raise DownloadError('filesystem must support symlinks')
David James8d201162013-10-11 17:03:19 -07002540 else:
2541 raise
2542
Kevin Degiabaa7f32014-11-12 11:27:45 -07002543 def _InitWorkTree(self, force_sync=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002544 dotgit = os.path.join(self.worktree, '.git')
Kevin Degi384b3c52014-10-16 16:02:58 -06002545 init_dotgit = not os.path.exists(dotgit)
Kevin Degib1a07b82015-07-27 13:33:43 -06002546 try:
2547 if init_dotgit:
2548 os.makedirs(dotgit)
2549 self._ReferenceGitDir(self.gitdir, dotgit, share_refs=True,
2550 copy_all=False)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002551
Kevin Degiabaa7f32014-11-12 11:27:45 -07002552 try:
2553 self._CheckDirReference(self.gitdir, dotgit, share_refs=True)
2554 except GitError as e:
2555 if force_sync:
2556 try:
2557 shutil.rmtree(dotgit)
2558 return self._InitWorkTree(force_sync=False)
2559 except:
2560 raise e
2561 raise e
Kevin Degi384b3c52014-10-16 16:02:58 -06002562
Kevin Degib1a07b82015-07-27 13:33:43 -06002563 if init_dotgit:
2564 _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002565
Kevin Degib1a07b82015-07-27 13:33:43 -06002566 cmd = ['read-tree', '--reset', '-u']
2567 cmd.append('-v')
2568 cmd.append(HEAD)
2569 if GitCommand(self, cmd).Wait() != 0:
2570 raise GitError("cannot initialize work tree")
Victor Boivie0960b5b2010-11-26 13:42:13 +01002571
Kevin Degib1a07b82015-07-27 13:33:43 -06002572 self._CopyAndLinkFiles()
2573 except Exception:
2574 if init_dotgit:
2575 shutil.rmtree(dotgit)
2576 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002577
2578 def _gitdir_path(self, path):
David James8d201162013-10-11 17:03:19 -07002579 return os.path.realpath(os.path.join(self.gitdir, path))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002580
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07002581 def _revlist(self, *args, **kw):
2582 a = []
2583 a.extend(args)
2584 a.append('--')
2585 return self.work_git.rev_list(*a, **kw)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002586
2587 @property
2588 def _allrefs(self):
Shawn O. Pearced237b692009-04-17 18:49:50 -07002589 return self.bare_ref.all
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002590
Sebastian Schuberth7ecccf62016-03-29 14:11:20 +02002591 def _getLogs(self, rev1, rev2, oneline=False, color=True, pretty_format=None):
Julien Camperguedd654222014-01-09 16:21:37 +01002592 """Get logs between two revisions of this project."""
2593 comp = '..'
2594 if rev1:
2595 revs = [rev1]
2596 if rev2:
2597 revs.extend([comp, rev2])
2598 cmd = ['log', ''.join(revs)]
2599 out = DiffColoring(self.config)
2600 if out.is_on and color:
2601 cmd.append('--color')
Sebastian Schuberth7ecccf62016-03-29 14:11:20 +02002602 if pretty_format is not None:
2603 cmd.append('--pretty=format:%s' % pretty_format)
Julien Camperguedd654222014-01-09 16:21:37 +01002604 if oneline:
2605 cmd.append('--oneline')
2606
2607 try:
2608 log = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
2609 if log.Wait() == 0:
2610 return log.stdout
2611 except GitError:
2612 # worktree may not exist if groups changed for example. In that case,
2613 # try in gitdir instead.
2614 if not os.path.exists(self.worktree):
2615 return self.bare_git.log(*cmd[1:])
2616 else:
2617 raise
2618 return None
2619
Sebastian Schuberth7ecccf62016-03-29 14:11:20 +02002620 def getAddedAndRemovedLogs(self, toProject, oneline=False, color=True,
2621 pretty_format=None):
Julien Camperguedd654222014-01-09 16:21:37 +01002622 """Get the list of logs from this revision to given revisionId"""
2623 logs = {}
2624 selfId = self.GetRevisionId(self._allrefs)
2625 toId = toProject.GetRevisionId(toProject._allrefs)
2626
Sebastian Schuberth7ecccf62016-03-29 14:11:20 +02002627 logs['added'] = self._getLogs(selfId, toId, oneline=oneline, color=color,
2628 pretty_format=pretty_format)
2629 logs['removed'] = self._getLogs(toId, selfId, oneline=oneline, color=color,
2630 pretty_format=pretty_format)
Julien Camperguedd654222014-01-09 16:21:37 +01002631 return logs
2632
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002633 class _GitGetByExec(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002634
David James8d201162013-10-11 17:03:19 -07002635 def __init__(self, project, bare, gitdir):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002636 self._project = project
2637 self._bare = bare
David James8d201162013-10-11 17:03:19 -07002638 self._gitdir = gitdir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002639
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002640 def LsOthers(self):
2641 p = GitCommand(self._project,
2642 ['ls-files',
2643 '-z',
2644 '--others',
2645 '--exclude-standard'],
Anthony King7bdac712014-07-16 12:56:40 +01002646 bare=False,
David James8d201162013-10-11 17:03:19 -07002647 gitdir=self._gitdir,
Anthony King7bdac712014-07-16 12:56:40 +01002648 capture_stdout=True,
2649 capture_stderr=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002650 if p.Wait() == 0:
2651 out = p.stdout
2652 if out:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002653 # Backslash is not anomalous
David Pursehouse1d947b32012-10-25 12:23:11 +09002654 return out[:-1].split('\0') # pylint: disable=W1401
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002655 return []
2656
2657 def DiffZ(self, name, *args):
2658 cmd = [name]
2659 cmd.append('-z')
2660 cmd.extend(args)
2661 p = GitCommand(self._project,
2662 cmd,
David James8d201162013-10-11 17:03:19 -07002663 gitdir=self._gitdir,
Anthony King7bdac712014-07-16 12:56:40 +01002664 bare=False,
2665 capture_stdout=True,
2666 capture_stderr=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002667 try:
2668 out = p.process.stdout.read()
2669 r = {}
2670 if out:
David Pursehouse1d947b32012-10-25 12:23:11 +09002671 out = iter(out[:-1].split('\0')) # pylint: disable=W1401
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002672 while out:
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07002673 try:
Anthony King2cd1f042014-05-05 21:24:05 +01002674 info = next(out)
2675 path = next(out)
Shawn O. Pearce02dbb6d2008-10-21 13:59:08 -07002676 except StopIteration:
2677 break
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002678
2679 class _Info(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002680
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002681 def __init__(self, path, omode, nmode, oid, nid, state):
2682 self.path = path
2683 self.src_path = None
2684 self.old_mode = omode
2685 self.new_mode = nmode
2686 self.old_id = oid
2687 self.new_id = nid
2688
2689 if len(state) == 1:
2690 self.status = state
2691 self.level = None
2692 else:
2693 self.status = state[:1]
2694 self.level = state[1:]
2695 while self.level.startswith('0'):
2696 self.level = self.level[1:]
2697
2698 info = info[1:].split(' ')
David Pursehouse8f62fb72012-11-14 12:09:38 +09002699 info = _Info(path, *info)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002700 if info.status in ('R', 'C'):
2701 info.src_path = info.path
Anthony King2cd1f042014-05-05 21:24:05 +01002702 info.path = next(out)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002703 r[info.path] = info
2704 return r
2705 finally:
2706 p.Wait()
2707
2708 def GetHead(self):
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07002709 if self._bare:
2710 path = os.path.join(self._project.gitdir, HEAD)
2711 else:
2712 path = os.path.join(self._project.worktree, '.git', HEAD)
Conley Owens75ee0572012-11-15 17:33:11 -08002713 try:
2714 fd = open(path, 'rb')
Dan Sandler53e902a2014-03-09 13:20:02 -04002715 except IOError as e:
2716 raise NoManifestException(path, str(e))
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -07002717 try:
2718 line = fd.read()
2719 finally:
2720 fd.close()
Chirayu Desai217ea7d2013-03-01 19:14:38 +05302721 try:
2722 line = line.decode()
2723 except AttributeError:
2724 pass
Shawn O. Pearce5b23f242009-04-17 18:43:33 -07002725 if line.startswith('ref: '):
2726 return line[5:-1]
2727 return line[:-1]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002728
2729 def SetHead(self, ref, message=None):
2730 cmdv = []
2731 if message is not None:
2732 cmdv.extend(['-m', message])
2733 cmdv.append(HEAD)
2734 cmdv.append(ref)
2735 self.symbolic_ref(*cmdv)
2736
2737 def DetachHead(self, new, message=None):
2738 cmdv = ['--no-deref']
2739 if message is not None:
2740 cmdv.extend(['-m', message])
2741 cmdv.append(HEAD)
2742 cmdv.append(new)
2743 self.update_ref(*cmdv)
2744
2745 def UpdateRef(self, name, new, old=None,
2746 message=None,
2747 detach=False):
2748 cmdv = []
2749 if message is not None:
2750 cmdv.extend(['-m', message])
2751 if detach:
2752 cmdv.append('--no-deref')
2753 cmdv.append(name)
2754 cmdv.append(new)
2755 if old is not None:
2756 cmdv.append(old)
2757 self.update_ref(*cmdv)
2758
2759 def DeleteRef(self, name, old=None):
2760 if not old:
2761 old = self.rev_parse(name)
2762 self.update_ref('-d', name, old)
Shawn O. Pearcefbcde472009-04-17 20:58:02 -07002763 self._project.bare_ref.deleted(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002764
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07002765 def rev_list(self, *args, **kw):
2766 if 'format' in kw:
2767 cmdv = ['log', '--pretty=format:%s' % kw['format']]
2768 else:
2769 cmdv = ['rev-list']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002770 cmdv.extend(args)
2771 p = GitCommand(self._project,
2772 cmdv,
Anthony King7bdac712014-07-16 12:56:40 +01002773 bare=self._bare,
David James8d201162013-10-11 17:03:19 -07002774 gitdir=self._gitdir,
Anthony King7bdac712014-07-16 12:56:40 +01002775 capture_stdout=True,
2776 capture_stderr=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002777 r = []
2778 for line in p.process.stdout:
Shawn O. Pearce8ad8a0e2009-05-29 18:28:25 -07002779 if line[-1] == '\n':
2780 line = line[:-1]
2781 r.append(line)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002782 if p.Wait() != 0:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002783 raise GitError('%s rev-list %s: %s' %
2784 (self._project.name, str(args), p.stderr))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002785 return r
2786
2787 def __getattr__(self, name):
Doug Anderson37282b42011-03-04 11:54:18 -08002788 """Allow arbitrary git commands using pythonic syntax.
2789
2790 This allows you to do things like:
2791 git_obj.rev_parse('HEAD')
2792
2793 Since we don't have a 'rev_parse' method defined, the __getattr__ will
2794 run. We'll replace the '_' with a '-' and try to run a git command.
Dave Borowitz091f8932012-10-23 17:01:04 -07002795 Any other positional arguments will be passed to the git command, and the
2796 following keyword arguments are supported:
2797 config: An optional dict of git config options to be passed with '-c'.
Doug Anderson37282b42011-03-04 11:54:18 -08002798
2799 Args:
2800 name: The name of the git command to call. Any '_' characters will
2801 be replaced with '-'.
2802
2803 Returns:
2804 A callable object that will try to call git with the named command.
2805 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002806 name = name.replace('_', '-')
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002807
Dave Borowitz091f8932012-10-23 17:01:04 -07002808 def runner(*args, **kwargs):
2809 cmdv = []
2810 config = kwargs.pop('config', None)
2811 for k in kwargs:
2812 raise TypeError('%s() got an unexpected keyword argument %r'
2813 % (name, k))
2814 if config is not None:
Dave Borowitzb42b4742012-10-31 12:27:27 -07002815 if not git_require((1, 7, 2)):
2816 raise ValueError('cannot set config on command line for %s()'
2817 % name)
Chirayu Desai217ea7d2013-03-01 19:14:38 +05302818 for k, v in config.items():
Dave Borowitz091f8932012-10-23 17:01:04 -07002819 cmdv.append('-c')
2820 cmdv.append('%s=%s' % (k, v))
2821 cmdv.append(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002822 cmdv.extend(args)
2823 p = GitCommand(self._project,
2824 cmdv,
Anthony King7bdac712014-07-16 12:56:40 +01002825 bare=self._bare,
David James8d201162013-10-11 17:03:19 -07002826 gitdir=self._gitdir,
Anthony King7bdac712014-07-16 12:56:40 +01002827 capture_stdout=True,
2828 capture_stderr=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002829 if p.Wait() != 0:
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002830 raise GitError('%s %s: %s' %
2831 (self._project.name, name, p.stderr))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002832 r = p.stdout
Chirayu Desai217ea7d2013-03-01 19:14:38 +05302833 try:
Conley Owensedd01512013-09-26 12:59:58 -07002834 r = r.decode('utf-8')
Chirayu Desai217ea7d2013-03-01 19:14:38 +05302835 except AttributeError:
2836 pass
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002837 if r.endswith('\n') and r.index('\n') == len(r) - 1:
2838 return r[:-1]
2839 return r
2840 return runner
2841
2842
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002843class _PriorSyncFailedError(Exception):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002844
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002845 def __str__(self):
2846 return 'prior sync failed; rebase still in progress'
2847
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002848
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002849class _DirtyError(Exception):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002850
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002851 def __str__(self):
2852 return 'contains uncommitted changes'
2853
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002854
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002855class _InfoMessage(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002856
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002857 def __init__(self, project, text):
2858 self.project = project
2859 self.text = text
2860
2861 def Print(self, syncbuf):
2862 syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
2863 syncbuf.out.nl()
2864
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002865
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002866class _Failure(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002867
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002868 def __init__(self, project, why):
2869 self.project = project
2870 self.why = why
2871
2872 def Print(self, syncbuf):
2873 syncbuf.out.fail('error: %s/: %s',
2874 self.project.relpath,
2875 str(self.why))
2876 syncbuf.out.nl()
2877
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002878
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002879class _Later(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002880
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002881 def __init__(self, project, action):
2882 self.project = project
2883 self.action = action
2884
2885 def Run(self, syncbuf):
2886 out = syncbuf.out
2887 out.project('project %s/', self.project.relpath)
2888 out.nl()
2889 try:
2890 self.action()
2891 out.nl()
2892 return True
David Pursehouse8a68ff92012-09-24 12:15:13 +09002893 except GitError:
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002894 out.nl()
2895 return False
2896
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002897
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002898class _SyncColoring(Coloring):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002899
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002900 def __init__(self, config):
2901 Coloring.__init__(self, config, 'reposync')
Anthony King7bdac712014-07-16 12:56:40 +01002902 self.project = self.printer('header', attr='bold')
2903 self.info = self.printer('info')
2904 self.fail = self.printer('fail', fg='red')
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002905
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002906
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002907class SyncBuffer(object):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002908
Shawn O. Pearce350cde42009-04-16 11:21:18 -07002909 def __init__(self, config, detach_head=False):
2910 self._messages = []
2911 self._failures = []
2912 self._later_queue1 = []
2913 self._later_queue2 = []
2914
2915 self.out = _SyncColoring(config)
2916 self.out.redirect(sys.stderr)
2917
2918 self.detach_head = detach_head
2919 self.clean = True
2920
2921 def info(self, project, fmt, *args):
2922 self._messages.append(_InfoMessage(project, fmt % args))
2923
2924 def fail(self, project, err=None):
2925 self._failures.append(_Failure(project, err))
2926 self.clean = False
2927
2928 def later1(self, project, what):
2929 self._later_queue1.append(_Later(project, what))
2930
2931 def later2(self, project, what):
2932 self._later_queue2.append(_Later(project, what))
2933
2934 def Finish(self):
2935 self._PrintMessages()
2936 self._RunLater()
2937 self._PrintMessages()
2938 return self.clean
2939
2940 def _RunLater(self):
2941 for q in ['_later_queue1', '_later_queue2']:
2942 if not self._RunQueue(q):
2943 return
2944
2945 def _RunQueue(self, queue):
2946 for m in getattr(self, queue):
2947 if not m.Run(self):
2948 self.clean = False
2949 return False
2950 setattr(self, queue, [])
2951 return True
2952
2953 def _PrintMessages(self):
2954 for m in self._messages:
2955 m.Print(self)
2956 for m in self._failures:
2957 m.Print(self)
2958
2959 self._messages = []
2960 self._failures = []
2961
2962
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002963class MetaProject(Project):
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002964
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002965 """A special project housed under .repo.
2966 """
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07002967
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002968 def __init__(self, manifest, name, gitdir, worktree):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002969 Project.__init__(self,
Anthony King7bdac712014-07-16 12:56:40 +01002970 manifest=manifest,
2971 name=name,
2972 gitdir=gitdir,
2973 objdir=gitdir,
2974 worktree=worktree,
2975 remote=RemoteSpec('origin'),
2976 relpath='.repo/%s' % name,
2977 revisionExpr='refs/heads/master',
2978 revisionId=None,
2979 groups=None)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002980
2981 def PreSync(self):
2982 if self.Exists:
2983 cb = self.CurrentBranch
2984 if cb:
2985 base = self.GetBranch(cb).merge
2986 if base:
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07002987 self.revisionExpr = base
2988 self.revisionId = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002989
Anthony King7bdac712014-07-16 12:56:40 +01002990 def MetaBranchSwitch(self):
Florian Vallee5d016502012-06-07 17:19:26 +02002991 """ Prepare MetaProject for manifest branch switch
2992 """
2993
2994 # detach and delete manifest branch, allowing a new
2995 # branch to take over
Anthony King7bdac712014-07-16 12:56:40 +01002996 syncbuf = SyncBuffer(self.config, detach_head=True)
Florian Vallee5d016502012-06-07 17:19:26 +02002997 self.Sync_LocalHalf(syncbuf)
2998 syncbuf.Finish()
2999
3000 return GitCommand(self,
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003001 ['update-ref', '-d', 'refs/heads/default'],
3002 capture_stdout=True,
3003 capture_stderr=True).Wait() == 0
Florian Vallee5d016502012-06-07 17:19:26 +02003004
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003005 @property
Shawn O. Pearcef6906872009-04-18 10:49:00 -07003006 def LastFetch(self):
3007 try:
3008 fh = os.path.join(self.gitdir, 'FETCH_HEAD')
3009 return os.path.getmtime(fh)
3010 except OSError:
3011 return 0
3012
3013 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003014 def HasChanges(self):
3015 """Has the remote received new commits not yet checked out?
3016 """
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07003017 if not self.remote or not self.revisionExpr:
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07003018 return False
3019
David Pursehouse8a68ff92012-09-24 12:15:13 +09003020 all_refs = self.bare_ref.all
3021 revid = self.GetRevisionId(all_refs)
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07003022 head = self.work_git.GetHead()
3023 if head.startswith(R_HEADS):
3024 try:
David Pursehouse8a68ff92012-09-24 12:15:13 +09003025 head = all_refs[head]
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07003026 except KeyError:
3027 head = None
3028
3029 if revid == head:
3030 return False
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07003031 elif self._revlist(not_rev(HEAD), revid):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003032 return True
3033 return False