blob: ebd12c60106b535d0197e0d5441f18e9ac7374d5 [file] [log] [blame]
David Pursehouse8898e2f2012-11-14 07:51:03 +09001#!/usr/bin/env python
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002
Mark E. Hamilton4088eb42016-02-10 10:44:30 -07003# repo default configuration
4#
Mark E. Hamilton55536282016-02-03 15:49:43 -07005import os
6REPO_URL = os.environ.get('REPO_URL', None)
7if not REPO_URL:
8 REPO_URL = 'https://gerrit.googlesource.com/git-repo'
David Pursehouse8f62fb72012-11-14 12:09:38 +09009REPO_REV = 'stable'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070010
11# Copyright (C) 2008 Google Inc.
12#
13# Licensed under the Apache License, Version 2.0 (the "License");
14# you may not use this file except in compliance with the License.
15# You may obtain a copy of the License at
16#
17# http://www.apache.org/licenses/LICENSE-2.0
18#
19# Unless required by applicable law or agreed to in writing, software
20# distributed under the License is distributed on an "AS IS" BASIS,
21# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22# See the License for the specific language governing permissions and
23# limitations under the License.
24
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070025# increment this whenever we make important changes to this script
Dan Willemsenfee390e2015-09-02 12:36:30 -070026VERSION = (1, 22)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070027
28# increment this if the MAINTAINER_KEYS block is modified
Conley Owensbc030842013-07-01 11:05:32 -070029KEYRING_VERSION = (1, 2)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030MAINTAINER_KEYS = """
31
32 Repo Maintainer <repo@android.kernel.org>
33-----BEGIN PGP PUBLIC KEY BLOCK-----
34Version: GnuPG v1.4.2.2 (GNU/Linux)
35
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
71=CMiZ
72-----END PGP PUBLIC KEY BLOCK-----
Conley Owens55e4d462012-10-01 16:12:28 -070073
74 Conley Owens <cco3@android.com>
75-----BEGIN PGP PUBLIC KEY BLOCK-----
76Version: GnuPG v1.4.11 (GNU/Linux)
77
Conley Owensbc030842013-07-01 11:05:32 -070078mQENBFHRvc8BCADFg45Xx/y6QDC+T7Y/gGc7vx0ww7qfOwIKlAZ9xG3qKunMxo+S
79hPCnzEl3cq+6I1Ww/ndop/HB3N3toPXRCoN8Vs4/Hc7by+SnaLFnacrm+tV5/OgT
80V37Lzt8lhay1Kl+YfpFwHYYpIEBLFV9knyfRXS/428W2qhdzYfvB15/AasRmwmor
81py4NIzSs8UD/SPr1ihqNCdZM76+MQyN5HMYXW/ALZXUFG0pwluHFA7hrfPG74i8C
82zMiP7qvMWIl/r/jtzHioH1dRKgbod+LZsrDJ8mBaqsZaDmNJMhss9g76XvfMyLra
839DI9/iFuBpGzeqBv0hwOGQspLRrEoyTeR6n1ABEBAAG0H0NvbmxleSBPd2VucyA8
84Y2NvM0BhbmRyb2lkLmNvbT6JATgEEwECACIFAlHRvc8CGwMGCwkIBwMCBhUIAgkK
85CwQWAgMBAh4BAheAAAoJEGe35EhpKzgsP6AIAJKJmNtn4l7hkYHKHFSo3egb6RjQ
86zEIP3MFTcu8HFX1kF1ZFbrp7xqurLaE53kEkKuAAvjJDAgI8mcZHP1JyplubqjQA
87xvv84gK+OGP3Xk+QK1ZjUQSbjOpjEiSZpRhWcHci3dgOUH4blJfByHw25hlgHowd
88a/2PrNKZVcJ92YienaxxGjcXEUcd0uYEG2+rwllQigFcnMFDhr9B71MfalRHjFKE
89fmdoypqLrri61YBc59P88Rw2/WUpTQjgNubSqa3A2+CKdaRyaRw+2fdF4TdR0h8W
90zbg+lbaPtJHsV+3mJC7fq26MiJDRJa5ZztpMn8su20gbLgi2ShBOaHAYDDi5AQ0E
91UdG9zwEIAMoOBq+QLNozAhxOOl5GL3StTStGRgPRXINfmViTsihrqGCWBBUfXlUE
92OytC0mYcrDUQev/8ToVoyqw+iGSwDkcSXkrEUCKFtHV/GECWtk1keyHgR10YKI1R
93mquSXoubWGqPeG1PAI74XWaRx8UrL8uCXUtmD8Q5J7mDjKR5NpxaXrwlA0bKsf2E
94Gp9tu1kKauuToZhWHMRMqYSOGikQJwWSFYKT1KdNcOXLQF6+bfoJ6sjVYdwfmNQL
95Ixn8QVhoTDedcqClSWB17VDEFDFa7MmqXZz2qtM3X1R/MUMHqPtegQzBGNhRdnI2
96V45+1Nnx/uuCxDbeI4RbHzujnxDiq70AEQEAAYkBHwQYAQIACQUCUdG9zwIbDAAK
97CRBnt+RIaSs4LNVeB/0Y2pZ8I7gAAcEM0Xw8drr4omg2fUoK1J33ozlA/RxeA/lJ
98I3KnyCDTpXuIeBKPGkdL8uMATC9Z8DnBBajRlftNDVZS3Hz4G09G9QpMojvJkFJV
99By+01Flw/X+eeN8NpqSuLV4W+AjEO8at/VvgKr1AFvBRdZ7GkpI1o6DgPe7ZqX+1
100dzQZt3e13W0rVBb/bUgx9iSLoeWP3aq/k+/GRGOR+S6F6BBSl0SQ2EF2+dIywb1x
101JuinEP+AwLAUZ1Bsx9ISC0Agpk2VeHXPL3FGhroEmoMvBzO0kTFGyoeT7PR/BfKv
102+H/g3HsL2LOB9uoIm8/5p2TTU5ttYCXMHhQZ81AY
103=AUp4
Conley Owens55e4d462012-10-01 16:12:28 -0700104-----END PGP PUBLIC KEY BLOCK-----
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700105"""
106
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700107GIT = 'git' # our git command
108MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
109repodir = '.repo' # name of repo's private directory
110S_repo = 'repo' # special repo repository
111S_manifests = 'manifests' # special manifest repository
112REPO_MAIN = S_repo + '/main.py' # main script
113MIN_PYTHON_VERSION = (2, 6) # minimum supported python version
Simran Basi8ce50412015-08-28 14:25:44 -0700114GITC_CONFIG_FILE = '/gitc/.config'
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700115GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700116
117
David Jamesbf79c662013-12-26 14:20:13 -0800118import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700119import optparse
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700120import re
Mitchel Humpheryseb5acc92014-03-12 10:48:15 -0700121import shutil
Sarah Owens60798a32012-10-25 17:53:09 -0700122import stat
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700123import subprocess
124import sys
David Pursehouse59bbb582013-05-17 10:49:33 +0900125
126if sys.version_info[0] == 3:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700127 import urllib.request
128 import urllib.error
129else:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700130 import imp
David Pursehouse59bbb582013-05-17 10:49:33 +0900131 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -0700132 urllib = imp.new_module('urllib')
133 urllib.request = urllib2
134 urllib.error = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135
Conley Owens5e0ee142013-09-26 15:50:49 -0700136
137def _print(*objects, **kwargs):
138 sep = kwargs.get('sep', ' ')
139 end = kwargs.get('end', '\n')
140 out = kwargs.get('file', sys.stdout)
141 out.write(sep.join(objects) + end)
142
143
Chirayu Desai51813df2013-04-16 19:36:09 +0530144# Python version check
145ver = sys.version_info
Chirayu Desai51813df2013-04-16 19:36:09 +0530146if (ver[0], ver[1]) < MIN_PYTHON_VERSION:
Conley Owens5e0ee142013-09-26 15:50:49 -0700147 _print('error: Python version %s unsupported.\n'
148 'Please use Python 2.6 - 2.7 instead.'
149 % sys.version.split(' ')[0], file=sys.stderr)
Chirayu Desai51813df2013-04-16 19:36:09 +0530150 sys.exit(1)
151
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700152home_dot_repo = os.path.expanduser('~/.repoconfig')
153gpg_dir = os.path.join(home_dot_repo, 'gnupg')
154
155extra_args = []
156init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
157
158# Logging
159group = init_optparse.add_option_group('Logging options')
160group.add_option('-q', '--quiet',
161 dest="quiet", action="store_true", default=False,
162 help="be quiet")
163
164# Manifest
165group = init_optparse.add_option_group('Manifest options')
166group.add_option('-u', '--manifest-url',
167 dest='manifest_url',
168 help='manifest repository location', metavar='URL')
169group.add_option('-b', '--manifest-branch',
170 dest='manifest_branch',
171 help='manifest branch or revision', metavar='REVISION')
172group.add_option('-m', '--manifest-name',
173 dest='manifest_name',
174 help='initial manifest file', metavar='NAME.xml')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800175group.add_option('--mirror',
176 dest='mirror', action='store_true',
David Pursehouse3794a782012-11-15 06:17:30 +0900177 help='create a replica of the remote repositories '
178 'rather than a client working directory')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200179group.add_option('--reference',
180 dest='reference',
181 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700182group.add_option('--depth', type='int', default=None,
183 dest='depth',
184 help='create a shallow clone with given depth; see git clone')
Julien Campergue335f5ef2013-10-16 11:02:35 +0200185group.add_option('--archive',
186 dest='archive', action='store_true',
187 help='checkout an archive instead of a git repository for '
188 'each project. See git archive.')
Colin Cross5acde752012-03-28 20:15:45 -0700189group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700190 dest='groups', default='default',
David Holmer0a1c6a12012-11-14 19:19:00 -0500191 help='restrict manifest projects to ones with specified '
192 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
Colin Cross5acde752012-03-28 20:15:45 -0700193 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700194group.add_option('-p', '--platform',
195 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700196 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700197 'platform group [auto|all|none|linux|darwin|...]',
198 metavar='PLATFORM')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700199
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700200
201# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700202group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700203group.add_option('--repo-url',
204 dest='repo_url',
205 help='repo repository location', metavar='URL')
206group.add_option('--repo-branch',
207 dest='repo_branch',
208 help='repo branch or revision', metavar='REVISION')
209group.add_option('--no-repo-verify',
210 dest='no_repo_verify', action='store_true',
211 help='do not verify repo source code')
212
Victor Boivie841be342011-04-05 11:31:10 +0200213# Other
214group = init_optparse.add_option_group('Other options')
215group.add_option('--config-name',
216 dest='config_name', action="store_true", default=False,
217 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700219
220def _GitcInitOptions(init_optparse_arg):
221 init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
222 g = init_optparse_arg.add_option_group('GITC options')
Simran Basi1efc2b42015-08-05 15:04:22 -0700223 g.add_option('-f', '--manifest-file',
224 dest='manifest_file',
225 help='Optional manifest file to use for this GITC client.')
226 g.add_option('-c', '--gitc-client',
227 dest='gitc_client',
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700228 help='The name of the gitc_client instance to create or modify.')
Simran Basi1efc2b42015-08-05 15:04:22 -0700229
Simran Basi8ce50412015-08-28 14:25:44 -0700230_gitc_manifest_dir = None
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700231
232
Simran Basi8ce50412015-08-28 14:25:44 -0700233def get_gitc_manifest_dir():
234 global _gitc_manifest_dir
235 if _gitc_manifest_dir is None:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700236 _gitc_manifest_dir = ''
Simran Basi8ce50412015-08-28 14:25:44 -0700237 try:
238 with open(GITC_CONFIG_FILE, 'r') as gitc_config:
239 for line in gitc_config:
240 match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
241 if match:
242 _gitc_manifest_dir = match.group('gitc_manifest_dir')
243 except IOError:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700244 pass
Simran Basi8ce50412015-08-28 14:25:44 -0700245 return _gitc_manifest_dir
246
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700247
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700248def gitc_parse_clientdir(gitc_fs_path):
249 """Parse a path in the GITC FS and return its client name.
250
251 @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
252
253 @returns: The GITC client name
254 """
255 if gitc_fs_path == GITC_FS_ROOT_DIR:
256 return None
257 if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
258 manifest_dir = get_gitc_manifest_dir()
259 if manifest_dir == '':
260 return None
261 if manifest_dir[-1] != '/':
262 manifest_dir += '/'
263 if gitc_fs_path == manifest_dir:
264 return None
265 if not gitc_fs_path.startswith(manifest_dir):
266 return None
267 return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
268 return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
269
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700270
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700271class CloneFailure(Exception):
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700272
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700273 """Indicate the remote clone of repo itself failed.
274 """
275
276
Simran Basi1efc2b42015-08-05 15:04:22 -0700277def _Init(args, gitc_init=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700278 """Installs repo by cloning it over the network.
279 """
Simran Basi1efc2b42015-08-05 15:04:22 -0700280 if gitc_init:
281 _GitcInitOptions(init_optparse)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700282 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800283 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700284 init_optparse.print_usage()
285 sys.exit(1)
286
287 url = opt.repo_url
288 if not url:
289 url = REPO_URL
290 extra_args.append('--repo-url=%s' % url)
291
292 branch = opt.repo_branch
293 if not branch:
294 branch = REPO_REV
295 extra_args.append('--repo-branch=%s' % branch)
296
297 if branch.startswith('refs/heads/'):
298 branch = branch[len('refs/heads/'):]
299 if branch.startswith('refs/'):
Conley Owens5e0ee142013-09-26 15:50:49 -0700300 _print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700301 raise CloneFailure()
302
David Jamesbf79c662013-12-26 14:20:13 -0800303 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700304 if gitc_init:
Simran Basi8ce50412015-08-28 14:25:44 -0700305 gitc_manifest_dir = get_gitc_manifest_dir()
306 if not gitc_manifest_dir:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700307 _print('fatal: GITC filesystem is not available. Exiting...',
Simran Basi8ce50412015-08-28 14:25:44 -0700308 file=sys.stderr)
309 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700310 gitc_client = opt.gitc_client
311 if not gitc_client:
312 gitc_client = gitc_parse_clientdir(os.getcwd())
313 if not gitc_client:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700314 _print('fatal: GITC client (-c) is required.', file=sys.stderr)
315 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700316 client_dir = os.path.join(gitc_manifest_dir, gitc_client)
Simran Basi1efc2b42015-08-05 15:04:22 -0700317 if not os.path.exists(client_dir):
318 os.makedirs(client_dir)
319 os.chdir(client_dir)
320 if os.path.exists(repodir):
321 # This GITC Client has already initialized repo so continue.
322 return
323
David Jamesbf79c662013-12-26 14:20:13 -0800324 os.mkdir(repodir)
325 except OSError as e:
326 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700327 _print('fatal: cannot make %s directory: %s'
328 % (repodir, e.strerror), file=sys.stderr)
David Pursehouse3794a782012-11-15 06:17:30 +0900329 # Don't raise CloneFailure; that would delete the
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700330 # name. Instead exit immediately.
331 #
332 sys.exit(1)
333
334 _CheckGitVersion()
335 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700336 if NeedSetupGnuPG():
337 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700338 else:
339 can_verify = True
340
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700341 dst = os.path.abspath(os.path.join(repodir, S_repo))
342 _Clone(url, dst, opt.quiet)
343
344 if can_verify and not opt.no_repo_verify:
345 rev = _Verify(dst, branch, opt.quiet)
346 else:
347 rev = 'refs/remotes/origin/%s^0' % branch
348
349 _Checkout(dst, branch, rev, opt.quiet)
350 except CloneFailure:
351 if opt.quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700352 _print('fatal: repo init failed; run without --quiet to see why',
353 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700354 raise
355
356
Conley Owensff0a3c82014-01-30 14:46:03 -0800357def ParseGitVersion(ver_str):
358 if not ver_str.startswith('git version '):
359 return None
360
361 num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
362 to_tuple = []
363 for num_str in num_ver_str.split('.')[:3]:
364 if num_str.isdigit():
365 to_tuple.append(int(num_str))
366 else:
367 to_tuple.append(0)
368 return tuple(to_tuple)
369
370
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700371def _CheckGitVersion():
372 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700373 try:
374 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700375 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700376 _print(file=sys.stderr)
377 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
378 _print('fatal: %s' % e, file=sys.stderr)
379 _print(file=sys.stderr)
380 _print('Please make sure %s is installed and in your path.' % GIT,
381 file=sys.stderr)
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700382 raise CloneFailure()
383
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700384 ver_str = proc.stdout.read().strip()
385 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700386 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700387
Conley Owensff0a3c82014-01-30 14:46:03 -0800388 ver_act = ParseGitVersion(ver_str)
389 if ver_act is None:
Conley Owens5e0ee142013-09-26 15:50:49 -0700390 _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700391 raise CloneFailure()
392
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700393 if ver_act < MIN_GIT_VERSION:
David Pursehouse685f0802012-11-14 08:34:39 +0900394 need = '.'.join(map(str, MIN_GIT_VERSION))
Conley Owens5e0ee142013-09-26 15:50:49 -0700395 _print('fatal: git %s or later required' % need, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700396 raise CloneFailure()
397
398
Conley Owensc9129d92012-10-01 16:12:28 -0700399def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700400 if not os.path.isdir(home_dot_repo):
401 return True
402
403 kv = os.path.join(home_dot_repo, 'keyring-version')
404 if not os.path.exists(kv):
405 return True
406
407 kv = open(kv).read()
408 if not kv:
409 return True
410
David Pursehouse685f0802012-11-14 08:34:39 +0900411 kv = tuple(map(int, kv.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700412 if kv < KEYRING_VERSION:
413 return True
414 return False
415
416
Conley Owensc9129d92012-10-01 16:12:28 -0700417def SetupGnuPG(quiet):
David Jamesbf79c662013-12-26 14:20:13 -0800418 try:
419 os.mkdir(home_dot_repo)
420 except OSError as e:
421 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700422 _print('fatal: cannot make %s directory: %s'
423 % (home_dot_repo, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700424 sys.exit(1)
425
David Jamesbf79c662013-12-26 14:20:13 -0800426 try:
427 os.mkdir(gpg_dir, stat.S_IRWXU)
428 except OSError as e:
429 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700430 _print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
431 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700432 sys.exit(1)
433
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800434 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300435 try:
436 env['GNUPGHOME'] = gpg_dir
437 except UnicodeEncodeError:
438 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700439
440 cmd = ['gpg', '--import']
441 try:
442 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700443 env=env,
444 stdin=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700445 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700446 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700447 _print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
448 _print('warning: Installing it is strongly encouraged.', file=sys.stderr)
449 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700450 return False
451
452 proc.stdin.write(MAINTAINER_KEYS)
453 proc.stdin.close()
454
455 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700456 _print('fatal: registering repo maintainer keys failed', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700457 sys.exit(1)
Conley Owens5e0ee142013-09-26 15:50:49 -0700458 _print()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700459
460 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
David Pursehouse685f0802012-11-14 08:34:39 +0900461 fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700462 fd.close()
463 return True
464
465
466def _SetConfig(local, name, value):
467 """Set a git configuration option to the specified value.
468 """
469 cmd = [GIT, 'config', name, value]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700470 if subprocess.Popen(cmd, cwd=local).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700471 raise CloneFailure()
472
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700473
474def _InitHttp():
475 handlers = []
476
Sarah Owens1f7627f2012-10-31 09:21:55 -0700477 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700478 try:
479 import netrc
480 n = netrc.netrc()
481 for host in n.hosts:
482 p = n.hosts[host]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700483 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800484 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700485 except: # pylint: disable=bare-except
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700486 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700487 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
488 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700489
490 if 'http_proxy' in os.environ:
491 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700492 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700493 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700494 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
495 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
496 urllib.request.install_opener(urllib.request.build_opener(*handlers))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700497
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700498
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700499def _Fetch(url, local, src, quiet):
500 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700501 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700502
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700503 cmd = [GIT, 'fetch']
504 if quiet:
505 cmd.append('--quiet')
506 err = subprocess.PIPE
507 else:
508 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700509 cmd.append(src)
510 cmd.append('+refs/heads/*:refs/remotes/origin/*')
511 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700512
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700513 proc = subprocess.Popen(cmd, cwd=local, stderr=err)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700514 if err:
515 proc.stderr.read()
516 proc.stderr.close()
517 if proc.wait() != 0:
518 raise CloneFailure()
519
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700520
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700521def _DownloadBundle(url, local, quiet):
522 if not url.endswith('/'):
523 url += '/'
524 url += 'clone.bundle'
525
526 proc = subprocess.Popen(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700527 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
528 cwd=local,
529 stdout=subprocess.PIPE)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700530 for line in proc.stdout:
531 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
532 if m:
533 new_url = m.group(1)
534 old_url = m.group(2)
535 if url.startswith(old_url):
536 url = new_url + url[len(old_url):]
537 break
538 proc.stdout.close()
539 proc.wait()
540
541 if not url.startswith('http:') and not url.startswith('https:'):
542 return False
543
544 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
545 try:
546 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700547 r = urllib.request.urlopen(url)
548 except urllib.error.HTTPError as e:
John Törnblomd3ddcdb2015-08-12 20:12:51 +0200549 if e.code in [401, 403, 404, 501]:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700550 return False
Conley Owens5e0ee142013-09-26 15:50:49 -0700551 _print('fatal: Cannot get %s' % url, file=sys.stderr)
552 _print('fatal: HTTP error %s' % e.code, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700553 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700554 except urllib.error.URLError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700555 _print('fatal: Cannot get %s' % url, file=sys.stderr)
556 _print('fatal: error %s' % e.reason, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700557 raise CloneFailure()
558 try:
559 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700560 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700561 while True:
562 buf = r.read(8192)
563 if buf == '':
564 return True
565 dest.write(buf)
566 finally:
567 r.close()
568 finally:
569 dest.close()
570
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700571
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700572def _ImportBundle(local):
573 path = os.path.join(local, '.git', 'clone.bundle')
574 try:
575 _Fetch(local, local, path, True)
576 finally:
577 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700578
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700579
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700580def _Clone(url, local, quiet):
581 """Clones a git repository to a new subdirectory of repodir
582 """
583 try:
584 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700585 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700586 _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
587 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700588 raise CloneFailure()
589
590 cmd = [GIT, 'init', '--quiet']
591 try:
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700592 proc = subprocess.Popen(cmd, cwd=local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700593 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700594 _print(file=sys.stderr)
595 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
596 _print('fatal: %s' % e, file=sys.stderr)
597 _print(file=sys.stderr)
598 _print('Please make sure %s is installed and in your path.' % GIT,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700599 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700600 raise CloneFailure()
601 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700602 _print('fatal: could not create %s' % local, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700603 raise CloneFailure()
604
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700605 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700606 _SetConfig(local, 'remote.origin.url', url)
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700607 _SetConfig(local,
608 'remote.origin.fetch',
609 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700610 if _DownloadBundle(url, local, quiet):
611 _ImportBundle(local)
Dan Willemsenfee390e2015-09-02 12:36:30 -0700612 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700613
614
615def _Verify(cwd, branch, quiet):
616 """Verify the branch has been signed by a tag.
617 """
618 cmd = [GIT, 'describe', 'origin/%s' % branch]
619 proc = subprocess.Popen(cmd,
620 stdout=subprocess.PIPE,
621 stderr=subprocess.PIPE,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700622 cwd=cwd)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700623 cur = proc.stdout.read().strip()
624 proc.stdout.close()
625
626 proc.stderr.read()
627 proc.stderr.close()
628
629 if proc.wait() != 0 or not cur:
Conley Owens5e0ee142013-09-26 15:50:49 -0700630 _print(file=sys.stderr)
631 _print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700632 raise CloneFailure()
633
634 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
635 if m:
636 cur = m.group(1)
637 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700638 _print(file=sys.stderr)
639 _print("info: Ignoring branch '%s'; using tagged release '%s'"
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700640 % (branch, cur), file=sys.stderr)
Conley Owens5e0ee142013-09-26 15:50:49 -0700641 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700642
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800643 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300644 try:
645 env['GNUPGHOME'] = gpg_dir
646 except UnicodeEncodeError:
647 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700648
649 cmd = [GIT, 'tag', '-v', cur]
650 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700651 stdout=subprocess.PIPE,
652 stderr=subprocess.PIPE,
653 cwd=cwd,
654 env=env)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700655 out = proc.stdout.read()
656 proc.stdout.close()
657
658 err = proc.stderr.read()
659 proc.stderr.close()
660
661 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700662 _print(file=sys.stderr)
663 _print(out, file=sys.stderr)
664 _print(err, file=sys.stderr)
665 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700666 raise CloneFailure()
667 return '%s^0' % cur
668
669
670def _Checkout(cwd, branch, rev, quiet):
671 """Checkout an upstream branch into the repository and track it.
672 """
673 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700674 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700675 raise CloneFailure()
676
677 _SetConfig(cwd, 'branch.default.remote', 'origin')
678 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
679
680 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700681 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700682 raise CloneFailure()
683
684 cmd = [GIT, 'read-tree', '--reset', '-u']
685 if not quiet:
686 cmd.append('-v')
687 cmd.append('HEAD')
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700688 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700689 raise CloneFailure()
690
691
692def _FindRepo():
693 """Look for a repo installation, starting at the current directory.
694 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200695 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700696 repo = None
697
Anthony Newnamdf14a702011-01-09 17:31:57 -0800698 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200699 while curdir != '/' \
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700700 and curdir != olddir \
701 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200702 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700703 if not os.path.isfile(repo):
704 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200705 olddir = curdir
706 curdir = os.path.dirname(curdir)
707 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700708
709
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700710class _Options(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700711 help = False
712
713
714def _ParseArguments(args):
715 cmd = None
716 opt = _Options()
717 arg = []
718
Sarah Owensa6053d52012-11-01 13:36:50 -0700719 for i in range(len(args)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700720 a = args[i]
721 if a == '-h' or a == '--help':
722 opt.help = True
723
724 elif not a.startswith('-'):
725 cmd = a
726 arg = args[i + 1:]
727 break
728 return cmd, opt, arg
729
730
731def _Usage():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700732 gitc_usage = ""
733 if get_gitc_manifest_dir():
734 gitc_usage = " gitc-init Initialize a GITC Client.\n"
735
Conley Owens5e0ee142013-09-26 15:50:49 -0700736 _print(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700737 """usage: repo COMMAND [ARGS]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700738
739repo is not yet installed. Use "repo init" to install it here.
740
741The most commonly used repo commands are:
742
743 init Install repo in the current working directory
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700744""" + gitc_usage +
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700745 """ help Display detailed help on a command
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700746
747For access to the full online help, install repo ("repo init").
Sarah Owenscecd1d82012-11-01 22:59:27 -0700748""", file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700749 sys.exit(1)
750
751
752def _Help(args):
753 if args:
754 if args[0] == 'init':
755 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100756 sys.exit(0)
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700757 elif args[0] == 'gitc-init':
758 _GitcInitOptions(init_optparse)
759 init_optparse.print_help()
760 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700761 else:
Conley Owens5e0ee142013-09-26 15:50:49 -0700762 _print("error: '%s' is not a bootstrap command.\n"
763 ' For access to online help, install repo ("repo init").'
764 % args[0], file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700765 else:
766 _Usage()
767 sys.exit(1)
768
769
770def _NotInstalled():
Conley Owens5e0ee142013-09-26 15:50:49 -0700771 _print('error: repo is not installed. Use "repo init" to install it here.',
772 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700773 sys.exit(1)
774
775
776def _NoCommands(cmd):
Conley Owens5e0ee142013-09-26 15:50:49 -0700777 _print("""error: command '%s' requires repo to be installed first.
778 Use "repo init" to install it here.""" % cmd, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700779 sys.exit(1)
780
781
782def _RunSelf(wrapper_path):
783 my_dir = os.path.dirname(wrapper_path)
784 my_main = os.path.join(my_dir, 'main.py')
785 my_git = os.path.join(my_dir, '.git')
786
787 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700788 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700789 'project.py',
790 'subcmds']:
791 if not os.path.exists(os.path.join(my_dir, name)):
792 return None, None
793 return my_main, my_git
794 return None, None
795
796
797def _SetDefaultsTo(gitdir):
798 global REPO_URL
799 global REPO_REV
800
801 REPO_URL = gitdir
802 proc = subprocess.Popen([GIT,
803 '--git-dir=%s' % gitdir,
804 'symbolic-ref',
805 'HEAD'],
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700806 stdout=subprocess.PIPE,
807 stderr=subprocess.PIPE)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700808 REPO_REV = proc.stdout.read().strip()
809 proc.stdout.close()
810
811 proc.stderr.read()
812 proc.stderr.close()
813
814 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700815 _print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700816 sys.exit(1)
817
818
819def main(orig_args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700820 cmd, opt, args = _ParseArguments(orig_args)
821
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700822 repo_main, rel_repo_dir = None, None
823 # Don't use the local repo copy, make sure to switch to the gitc client first.
824 if cmd != 'gitc-init':
825 repo_main, rel_repo_dir = _FindRepo()
826
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700827 wrapper_path = os.path.abspath(__file__)
828 my_main, my_git = _RunSelf(wrapper_path)
829
Simran Basi8ce50412015-08-28 14:25:44 -0700830 cwd = os.getcwd()
Dan Willemsen2487cb72015-08-31 15:45:06 -0700831 if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
Simran Basi8ce50412015-08-28 14:25:44 -0700832 _print('error: repo cannot be used in the GITC local manifest directory.'
833 '\nIf you want to work on this GITC client please rerun this '
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700834 'command from the corresponding client under /gitc/',
835 file=sys.stderr)
Simran Basi8ce50412015-08-28 14:25:44 -0700836 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200837 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700838 if opt.help:
839 _Usage()
840 if cmd == 'help':
841 _Help(args)
842 if not cmd:
843 _NotInstalled()
Simran Basi1efc2b42015-08-05 15:04:22 -0700844 if cmd == 'init' or cmd == 'gitc-init':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700845 if my_git:
846 _SetDefaultsTo(my_git)
847 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700848 _Init(args, gitc_init=(cmd == 'gitc-init'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700849 except CloneFailure:
Mani Chandelf75870b2014-09-03 13:54:48 +0530850 shutil.rmtree(os.path.join(repodir, S_repo), ignore_errors=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700851 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200852 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700853 else:
854 _NoCommands(cmd)
855
856 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200857 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700858
David Pursehouse685f0802012-11-14 08:34:39 +0900859 ver_str = '.'.join(map(str, VERSION))
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300860 me = [sys.executable, repo_main,
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200861 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700862 '--wrapper-version=%s' % ver_str,
863 '--wrapper-path=%s' % wrapper_path,
864 '--']
865 me.extend(orig_args)
866 me.extend(extra_args)
867 try:
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300868 os.execv(sys.executable, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700869 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700870 _print("fatal: unable to start %s" % repo_main, file=sys.stderr)
871 _print("fatal: %s" % e, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700872 sys.exit(148)
873
874
875if __name__ == '__main__':
Anthony King6efdde92014-05-05 20:37:05 +0100876 if ver[0] == 3:
877 _print('warning: Python 3 support is currently experimental. YMMV.\n'
878 'Please use Python 2.6 - 2.7 instead.',
879 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700880 main(sys.argv[1:])