blob: 6d3e8c2f1f4285cb0753fc7b1903f6e625fb2b8c [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
Naseer Ahmedf4dda9a2016-12-01 18:49:54 -050026VERSION = (1, 24)
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)
Mike Frysingere4433652016-09-13 18:06:07 -040030
31# Each individual key entry is created by using:
32# gpg --armor --export keyid
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070033MAINTAINER_KEYS = """
34
35 Repo Maintainer <repo@android.kernel.org>
36-----BEGIN PGP PUBLIC KEY BLOCK-----
37Version: GnuPG v1.4.2.2 (GNU/Linux)
38
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
74=CMiZ
75-----END PGP PUBLIC KEY BLOCK-----
Conley Owens55e4d462012-10-01 16:12:28 -070076
77 Conley Owens <cco3@android.com>
78-----BEGIN PGP PUBLIC KEY BLOCK-----
79Version: GnuPG v1.4.11 (GNU/Linux)
80
Conley Owensbc030842013-07-01 11:05:32 -070081mQENBFHRvc8BCADFg45Xx/y6QDC+T7Y/gGc7vx0ww7qfOwIKlAZ9xG3qKunMxo+S
82hPCnzEl3cq+6I1Ww/ndop/HB3N3toPXRCoN8Vs4/Hc7by+SnaLFnacrm+tV5/OgT
83V37Lzt8lhay1Kl+YfpFwHYYpIEBLFV9knyfRXS/428W2qhdzYfvB15/AasRmwmor
84py4NIzSs8UD/SPr1ihqNCdZM76+MQyN5HMYXW/ALZXUFG0pwluHFA7hrfPG74i8C
85zMiP7qvMWIl/r/jtzHioH1dRKgbod+LZsrDJ8mBaqsZaDmNJMhss9g76XvfMyLra
869DI9/iFuBpGzeqBv0hwOGQspLRrEoyTeR6n1ABEBAAG0H0NvbmxleSBPd2VucyA8
87Y2NvM0BhbmRyb2lkLmNvbT6JATgEEwECACIFAlHRvc8CGwMGCwkIBwMCBhUIAgkK
88CwQWAgMBAh4BAheAAAoJEGe35EhpKzgsP6AIAJKJmNtn4l7hkYHKHFSo3egb6RjQ
89zEIP3MFTcu8HFX1kF1ZFbrp7xqurLaE53kEkKuAAvjJDAgI8mcZHP1JyplubqjQA
90xvv84gK+OGP3Xk+QK1ZjUQSbjOpjEiSZpRhWcHci3dgOUH4blJfByHw25hlgHowd
91a/2PrNKZVcJ92YienaxxGjcXEUcd0uYEG2+rwllQigFcnMFDhr9B71MfalRHjFKE
92fmdoypqLrri61YBc59P88Rw2/WUpTQjgNubSqa3A2+CKdaRyaRw+2fdF4TdR0h8W
93zbg+lbaPtJHsV+3mJC7fq26MiJDRJa5ZztpMn8su20gbLgi2ShBOaHAYDDi5AQ0E
94UdG9zwEIAMoOBq+QLNozAhxOOl5GL3StTStGRgPRXINfmViTsihrqGCWBBUfXlUE
95OytC0mYcrDUQev/8ToVoyqw+iGSwDkcSXkrEUCKFtHV/GECWtk1keyHgR10YKI1R
96mquSXoubWGqPeG1PAI74XWaRx8UrL8uCXUtmD8Q5J7mDjKR5NpxaXrwlA0bKsf2E
97Gp9tu1kKauuToZhWHMRMqYSOGikQJwWSFYKT1KdNcOXLQF6+bfoJ6sjVYdwfmNQL
98Ixn8QVhoTDedcqClSWB17VDEFDFa7MmqXZz2qtM3X1R/MUMHqPtegQzBGNhRdnI2
99V45+1Nnx/uuCxDbeI4RbHzujnxDiq70AEQEAAYkBHwQYAQIACQUCUdG9zwIbDAAK
100CRBnt+RIaSs4LNVeB/0Y2pZ8I7gAAcEM0Xw8drr4omg2fUoK1J33ozlA/RxeA/lJ
101I3KnyCDTpXuIeBKPGkdL8uMATC9Z8DnBBajRlftNDVZS3Hz4G09G9QpMojvJkFJV
102By+01Flw/X+eeN8NpqSuLV4W+AjEO8at/VvgKr1AFvBRdZ7GkpI1o6DgPe7ZqX+1
103dzQZt3e13W0rVBb/bUgx9iSLoeWP3aq/k+/GRGOR+S6F6BBSl0SQ2EF2+dIywb1x
104JuinEP+AwLAUZ1Bsx9ISC0Agpk2VeHXPL3FGhroEmoMvBzO0kTFGyoeT7PR/BfKv
105+H/g3HsL2LOB9uoIm8/5p2TTU5ttYCXMHhQZ81AY
106=AUp4
Conley Owens55e4d462012-10-01 16:12:28 -0700107-----END PGP PUBLIC KEY BLOCK-----
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700108"""
109
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700110GIT = 'git' # our git command
111MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
112repodir = '.repo' # name of repo's private directory
113S_repo = 'repo' # special repo repository
114S_manifests = 'manifests' # special manifest repository
115REPO_MAIN = S_repo + '/main.py' # main script
116MIN_PYTHON_VERSION = (2, 6) # minimum supported python version
Simran Basi8ce50412015-08-28 14:25:44 -0700117GITC_CONFIG_FILE = '/gitc/.config'
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700118GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700119
120
David Jamesbf79c662013-12-26 14:20:13 -0800121import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700122import optparse
Renaud Paquay35d22212016-11-01 11:24:52 -0700123import platform
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124import re
Mitchel Humpheryseb5acc92014-03-12 10:48:15 -0700125import shutil
Sarah Owens60798a32012-10-25 17:53:09 -0700126import stat
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700127import subprocess
128import sys
David Pursehouse59bbb582013-05-17 10:49:33 +0900129
130if sys.version_info[0] == 3:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700131 import urllib.request
132 import urllib.error
133else:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700134 import imp
David Pursehouse59bbb582013-05-17 10:49:33 +0900135 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -0700136 urllib = imp.new_module('urllib')
137 urllib.request = urllib2
138 urllib.error = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700139
Conley Owens5e0ee142013-09-26 15:50:49 -0700140
141def _print(*objects, **kwargs):
142 sep = kwargs.get('sep', ' ')
143 end = kwargs.get('end', '\n')
144 out = kwargs.get('file', sys.stdout)
145 out.write(sep.join(objects) + end)
146
Sebastian Schubertha9399842018-07-13 11:47:10 +0200147 # On Windows stderr is buffered, so flush to maintain the order of error messages.
148 if out == sys.stderr and platform.system() == "Windows":
149 out.flush()
150
Conley Owens5e0ee142013-09-26 15:50:49 -0700151
Chirayu Desai51813df2013-04-16 19:36:09 +0530152# Python version check
153ver = sys.version_info
Chirayu Desai51813df2013-04-16 19:36:09 +0530154if (ver[0], ver[1]) < MIN_PYTHON_VERSION:
Conley Owens5e0ee142013-09-26 15:50:49 -0700155 _print('error: Python version %s unsupported.\n'
156 'Please use Python 2.6 - 2.7 instead.'
157 % sys.version.split(' ')[0], file=sys.stderr)
Chirayu Desai51813df2013-04-16 19:36:09 +0530158 sys.exit(1)
159
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700160home_dot_repo = os.path.expanduser('~/.repoconfig')
161gpg_dir = os.path.join(home_dot_repo, 'gnupg')
162
163extra_args = []
164init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
165
166# Logging
167group = init_optparse.add_option_group('Logging options')
168group.add_option('-q', '--quiet',
169 dest="quiet", action="store_true", default=False,
170 help="be quiet")
171
172# Manifest
173group = init_optparse.add_option_group('Manifest options')
174group.add_option('-u', '--manifest-url',
175 dest='manifest_url',
176 help='manifest repository location', metavar='URL')
177group.add_option('-b', '--manifest-branch',
178 dest='manifest_branch',
179 help='manifest branch or revision', metavar='REVISION')
180group.add_option('-m', '--manifest-name',
181 dest='manifest_name',
182 help='initial manifest file', metavar='NAME.xml')
Naseer Ahmedf4dda9a2016-12-01 18:49:54 -0500183group.add_option('-c', '--current-branch',
184 dest='current_branch_only', action='store_true',
185 help='fetch only current manifest branch from server')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800186group.add_option('--mirror',
187 dest='mirror', action='store_true',
David Pursehouse3794a782012-11-15 06:17:30 +0900188 help='create a replica of the remote repositories '
189 'rather than a client working directory')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200190group.add_option('--reference',
191 dest='reference',
192 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700193group.add_option('--depth', type='int', default=None,
194 dest='depth',
195 help='create a shallow clone with given depth; see git clone')
Julien Campergue335f5ef2013-10-16 11:02:35 +0200196group.add_option('--archive',
197 dest='archive', action='store_true',
198 help='checkout an archive instead of a git repository for '
199 'each project. See git archive.')
Martin Kellye4e94d22017-03-21 16:05:12 -0700200group.add_option('--submodules',
201 dest='submodules', action='store_true',
202 help='sync any submodules associated with the manifest repo')
Colin Cross5acde752012-03-28 20:15:45 -0700203group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700204 dest='groups', default='default',
David Holmer0a1c6a12012-11-14 19:19:00 -0500205 help='restrict manifest projects to ones with specified '
206 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
Colin Cross5acde752012-03-28 20:15:45 -0700207 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700208group.add_option('-p', '--platform',
209 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700210 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700211 'platform group [auto|all|none|linux|darwin|...]',
212 metavar='PLATFORM')
Hu xiuyun9711a982015-12-11 11:16:41 +0800213group.add_option('--no-clone-bundle',
214 dest='no_clone_bundle', action='store_true',
215 help='disable use of /clone.bundle on HTTP/HTTPS')
Naseer Ahmedf4dda9a2016-12-01 18:49:54 -0500216group.add_option('--no-tags',
217 dest='no_tags', action='store_true',
218 help="don't fetch tags in the manifest")
Doug Anderson49cd59b2011-06-13 21:42:06 -0700219
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700220
221# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700222group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700223group.add_option('--repo-url',
224 dest='repo_url',
225 help='repo repository location', metavar='URL')
226group.add_option('--repo-branch',
227 dest='repo_branch',
228 help='repo branch or revision', metavar='REVISION')
229group.add_option('--no-repo-verify',
230 dest='no_repo_verify', action='store_true',
231 help='do not verify repo source code')
232
Victor Boivie841be342011-04-05 11:31:10 +0200233# Other
234group = init_optparse.add_option_group('Other options')
235group.add_option('--config-name',
236 dest='config_name', action="store_true", default=False,
237 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700238
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700239
240def _GitcInitOptions(init_optparse_arg):
241 init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
242 g = init_optparse_arg.add_option_group('GITC options')
Simran Basi1efc2b42015-08-05 15:04:22 -0700243 g.add_option('-f', '--manifest-file',
244 dest='manifest_file',
245 help='Optional manifest file to use for this GITC client.')
246 g.add_option('-c', '--gitc-client',
247 dest='gitc_client',
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700248 help='The name of the gitc_client instance to create or modify.')
Simran Basi1efc2b42015-08-05 15:04:22 -0700249
Simran Basi8ce50412015-08-28 14:25:44 -0700250_gitc_manifest_dir = None
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700251
252
Simran Basi8ce50412015-08-28 14:25:44 -0700253def get_gitc_manifest_dir():
254 global _gitc_manifest_dir
255 if _gitc_manifest_dir is None:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700256 _gitc_manifest_dir = ''
Simran Basi8ce50412015-08-28 14:25:44 -0700257 try:
258 with open(GITC_CONFIG_FILE, 'r') as gitc_config:
259 for line in gitc_config:
260 match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
261 if match:
262 _gitc_manifest_dir = match.group('gitc_manifest_dir')
263 except IOError:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700264 pass
Simran Basi8ce50412015-08-28 14:25:44 -0700265 return _gitc_manifest_dir
266
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700267
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700268def gitc_parse_clientdir(gitc_fs_path):
269 """Parse a path in the GITC FS and return its client name.
270
271 @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
272
273 @returns: The GITC client name
274 """
275 if gitc_fs_path == GITC_FS_ROOT_DIR:
276 return None
277 if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
278 manifest_dir = get_gitc_manifest_dir()
279 if manifest_dir == '':
280 return None
281 if manifest_dir[-1] != '/':
282 manifest_dir += '/'
283 if gitc_fs_path == manifest_dir:
284 return None
285 if not gitc_fs_path.startswith(manifest_dir):
286 return None
287 return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
288 return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
289
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700290
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700291class CloneFailure(Exception):
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700292
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700293 """Indicate the remote clone of repo itself failed.
294 """
295
296
Simran Basi1efc2b42015-08-05 15:04:22 -0700297def _Init(args, gitc_init=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700298 """Installs repo by cloning it over the network.
299 """
Simran Basi1efc2b42015-08-05 15:04:22 -0700300 if gitc_init:
301 _GitcInitOptions(init_optparse)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700302 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800303 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700304 init_optparse.print_usage()
305 sys.exit(1)
306
307 url = opt.repo_url
308 if not url:
309 url = REPO_URL
310 extra_args.append('--repo-url=%s' % url)
311
312 branch = opt.repo_branch
313 if not branch:
314 branch = REPO_REV
315 extra_args.append('--repo-branch=%s' % branch)
316
317 if branch.startswith('refs/heads/'):
318 branch = branch[len('refs/heads/'):]
319 if branch.startswith('refs/'):
Conley Owens5e0ee142013-09-26 15:50:49 -0700320 _print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700321 raise CloneFailure()
322
David Jamesbf79c662013-12-26 14:20:13 -0800323 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700324 if gitc_init:
Simran Basi8ce50412015-08-28 14:25:44 -0700325 gitc_manifest_dir = get_gitc_manifest_dir()
326 if not gitc_manifest_dir:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700327 _print('fatal: GITC filesystem is not available. Exiting...',
Simran Basi8ce50412015-08-28 14:25:44 -0700328 file=sys.stderr)
329 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700330 gitc_client = opt.gitc_client
331 if not gitc_client:
332 gitc_client = gitc_parse_clientdir(os.getcwd())
333 if not gitc_client:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700334 _print('fatal: GITC client (-c) is required.', file=sys.stderr)
335 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700336 client_dir = os.path.join(gitc_manifest_dir, gitc_client)
Simran Basi1efc2b42015-08-05 15:04:22 -0700337 if not os.path.exists(client_dir):
338 os.makedirs(client_dir)
339 os.chdir(client_dir)
340 if os.path.exists(repodir):
341 # This GITC Client has already initialized repo so continue.
342 return
343
David Jamesbf79c662013-12-26 14:20:13 -0800344 os.mkdir(repodir)
345 except OSError as e:
346 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700347 _print('fatal: cannot make %s directory: %s'
348 % (repodir, e.strerror), file=sys.stderr)
David Pursehouse3794a782012-11-15 06:17:30 +0900349 # Don't raise CloneFailure; that would delete the
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700350 # name. Instead exit immediately.
351 #
352 sys.exit(1)
353
354 _CheckGitVersion()
355 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700356 if NeedSetupGnuPG():
357 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700358 else:
359 can_verify = True
360
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700361 dst = os.path.abspath(os.path.join(repodir, S_repo))
Hu xiuyun9711a982015-12-11 11:16:41 +0800362 _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700363
364 if can_verify and not opt.no_repo_verify:
365 rev = _Verify(dst, branch, opt.quiet)
366 else:
367 rev = 'refs/remotes/origin/%s^0' % branch
368
369 _Checkout(dst, branch, rev, opt.quiet)
Sebastian Schuberth993dcac2018-07-13 10:25:52 +0200370
371 if not os.path.isfile(os.path.join(dst, 'repo')):
372 _print("warning: '%s' does not look like a git-repo repository, is "
373 "REPO_URL set correctly?" % url, file=sys.stderr)
374
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700375 except CloneFailure:
376 if opt.quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700377 _print('fatal: repo init failed; run without --quiet to see why',
378 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700379 raise
380
381
Conley Owensff0a3c82014-01-30 14:46:03 -0800382def ParseGitVersion(ver_str):
383 if not ver_str.startswith('git version '):
384 return None
385
386 num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
387 to_tuple = []
388 for num_str in num_ver_str.split('.')[:3]:
389 if num_str.isdigit():
390 to_tuple.append(int(num_str))
391 else:
392 to_tuple.append(0)
393 return tuple(to_tuple)
394
395
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700396def _CheckGitVersion():
397 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700398 try:
399 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700400 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700401 _print(file=sys.stderr)
402 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
403 _print('fatal: %s' % e, file=sys.stderr)
404 _print(file=sys.stderr)
405 _print('Please make sure %s is installed and in your path.' % GIT,
406 file=sys.stderr)
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700407 raise CloneFailure()
408
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700409 ver_str = proc.stdout.read().strip()
410 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700411 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700412
Conley Owensff0a3c82014-01-30 14:46:03 -0800413 ver_act = ParseGitVersion(ver_str)
414 if ver_act is None:
Conley Owens5e0ee142013-09-26 15:50:49 -0700415 _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700416 raise CloneFailure()
417
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700418 if ver_act < MIN_GIT_VERSION:
David Pursehouse685f0802012-11-14 08:34:39 +0900419 need = '.'.join(map(str, MIN_GIT_VERSION))
Conley Owens5e0ee142013-09-26 15:50:49 -0700420 _print('fatal: git %s or later required' % need, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700421 raise CloneFailure()
422
423
Conley Owensc9129d92012-10-01 16:12:28 -0700424def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700425 if not os.path.isdir(home_dot_repo):
426 return True
427
428 kv = os.path.join(home_dot_repo, 'keyring-version')
429 if not os.path.exists(kv):
430 return True
431
432 kv = open(kv).read()
433 if not kv:
434 return True
435
David Pursehouse685f0802012-11-14 08:34:39 +0900436 kv = tuple(map(int, kv.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700437 if kv < KEYRING_VERSION:
438 return True
439 return False
440
441
Conley Owensc9129d92012-10-01 16:12:28 -0700442def SetupGnuPG(quiet):
David Jamesbf79c662013-12-26 14:20:13 -0800443 try:
444 os.mkdir(home_dot_repo)
445 except OSError as e:
446 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700447 _print('fatal: cannot make %s directory: %s'
448 % (home_dot_repo, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700449 sys.exit(1)
450
David Jamesbf79c662013-12-26 14:20:13 -0800451 try:
452 os.mkdir(gpg_dir, stat.S_IRWXU)
453 except OSError as e:
454 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700455 _print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
456 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700457 sys.exit(1)
458
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800459 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300460 try:
461 env['GNUPGHOME'] = gpg_dir
462 except UnicodeEncodeError:
463 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700464
465 cmd = ['gpg', '--import']
466 try:
467 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700468 env=env,
469 stdin=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700470 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700471 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700472 _print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
473 _print('warning: Installing it is strongly encouraged.', file=sys.stderr)
474 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700475 return False
476
477 proc.stdin.write(MAINTAINER_KEYS)
478 proc.stdin.close()
479
480 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700481 _print('fatal: registering repo maintainer keys failed', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700482 sys.exit(1)
Conley Owens5e0ee142013-09-26 15:50:49 -0700483 _print()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700484
485 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
David Pursehouse685f0802012-11-14 08:34:39 +0900486 fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700487 fd.close()
488 return True
489
490
491def _SetConfig(local, name, value):
492 """Set a git configuration option to the specified value.
493 """
494 cmd = [GIT, 'config', name, value]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700495 if subprocess.Popen(cmd, cwd=local).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700496 raise CloneFailure()
497
498
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700499def _InitHttp():
500 handlers = []
501
Sarah Owens1f7627f2012-10-31 09:21:55 -0700502 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700503 try:
504 import netrc
505 n = netrc.netrc()
506 for host in n.hosts:
507 p = n.hosts[host]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700508 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800509 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
David Pursehouse65b0ba52018-06-24 16:21:51 +0900510 except:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700511 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700512 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
513 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700514
515 if 'http_proxy' in os.environ:
516 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700517 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700518 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700519 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
520 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
521 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700522
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700523
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700524def _Fetch(url, local, src, quiet):
525 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700526 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700527
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700528 cmd = [GIT, 'fetch']
529 if quiet:
530 cmd.append('--quiet')
531 err = subprocess.PIPE
532 else:
533 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700534 cmd.append(src)
535 cmd.append('+refs/heads/*:refs/remotes/origin/*')
536 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700537
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700538 proc = subprocess.Popen(cmd, cwd=local, stderr=err)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700539 if err:
540 proc.stderr.read()
541 proc.stderr.close()
542 if proc.wait() != 0:
543 raise CloneFailure()
544
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700545
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700546def _DownloadBundle(url, local, quiet):
547 if not url.endswith('/'):
548 url += '/'
549 url += 'clone.bundle'
550
551 proc = subprocess.Popen(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700552 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
553 cwd=local,
554 stdout=subprocess.PIPE)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700555 for line in proc.stdout:
556 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
557 if m:
558 new_url = m.group(1)
559 old_url = m.group(2)
560 if url.startswith(old_url):
561 url = new_url + url[len(old_url):]
562 break
563 proc.stdout.close()
564 proc.wait()
565
566 if not url.startswith('http:') and not url.startswith('https:'):
567 return False
568
569 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
570 try:
571 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700572 r = urllib.request.urlopen(url)
573 except urllib.error.HTTPError as e:
John Törnblomd3ddcdb2015-08-12 20:12:51 +0200574 if e.code in [401, 403, 404, 501]:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700575 return False
Conley Owens5e0ee142013-09-26 15:50:49 -0700576 _print('fatal: Cannot get %s' % url, file=sys.stderr)
577 _print('fatal: HTTP error %s' % e.code, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700578 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700579 except urllib.error.URLError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700580 _print('fatal: Cannot get %s' % url, file=sys.stderr)
581 _print('fatal: error %s' % e.reason, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700582 raise CloneFailure()
583 try:
584 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700585 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700586 while True:
587 buf = r.read(8192)
588 if buf == '':
589 return True
590 dest.write(buf)
591 finally:
592 r.close()
593 finally:
594 dest.close()
595
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700596
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700597def _ImportBundle(local):
598 path = os.path.join(local, '.git', 'clone.bundle')
599 try:
600 _Fetch(local, local, path, True)
601 finally:
602 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700603
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700604
Hu xiuyun9711a982015-12-11 11:16:41 +0800605def _Clone(url, local, quiet, clone_bundle):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700606 """Clones a git repository to a new subdirectory of repodir
607 """
608 try:
609 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700610 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700611 _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
612 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700613 raise CloneFailure()
614
615 cmd = [GIT, 'init', '--quiet']
616 try:
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700617 proc = subprocess.Popen(cmd, cwd=local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700618 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700619 _print(file=sys.stderr)
620 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
621 _print('fatal: %s' % e, file=sys.stderr)
622 _print(file=sys.stderr)
623 _print('Please make sure %s is installed and in your path.' % GIT,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700624 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700625 raise CloneFailure()
626 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700627 _print('fatal: could not create %s' % local, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700628 raise CloneFailure()
629
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700630 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700631 _SetConfig(local, 'remote.origin.url', url)
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700632 _SetConfig(local,
633 'remote.origin.fetch',
634 '+refs/heads/*:refs/remotes/origin/*')
Hu xiuyun9711a982015-12-11 11:16:41 +0800635 if clone_bundle and _DownloadBundle(url, local, quiet):
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700636 _ImportBundle(local)
Dan Willemsenfee390e2015-09-02 12:36:30 -0700637 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700638
639
640def _Verify(cwd, branch, quiet):
641 """Verify the branch has been signed by a tag.
642 """
643 cmd = [GIT, 'describe', 'origin/%s' % branch]
644 proc = subprocess.Popen(cmd,
645 stdout=subprocess.PIPE,
646 stderr=subprocess.PIPE,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700647 cwd=cwd)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700648 cur = proc.stdout.read().strip()
649 proc.stdout.close()
650
651 proc.stderr.read()
652 proc.stderr.close()
653
654 if proc.wait() != 0 or not cur:
Conley Owens5e0ee142013-09-26 15:50:49 -0700655 _print(file=sys.stderr)
656 _print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700657 raise CloneFailure()
658
659 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
660 if m:
661 cur = m.group(1)
662 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700663 _print(file=sys.stderr)
664 _print("info: Ignoring branch '%s'; using tagged release '%s'"
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700665 % (branch, cur), file=sys.stderr)
Conley Owens5e0ee142013-09-26 15:50:49 -0700666 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700667
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800668 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300669 try:
670 env['GNUPGHOME'] = gpg_dir
671 except UnicodeEncodeError:
672 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700673
674 cmd = [GIT, 'tag', '-v', cur]
675 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700676 stdout=subprocess.PIPE,
677 stderr=subprocess.PIPE,
678 cwd=cwd,
679 env=env)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700680 out = proc.stdout.read()
681 proc.stdout.close()
682
683 err = proc.stderr.read()
684 proc.stderr.close()
685
686 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700687 _print(file=sys.stderr)
688 _print(out, file=sys.stderr)
689 _print(err, file=sys.stderr)
690 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700691 raise CloneFailure()
692 return '%s^0' % cur
693
694
695def _Checkout(cwd, branch, rev, quiet):
696 """Checkout an upstream branch into the repository and track it.
697 """
698 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700699 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700700 raise CloneFailure()
701
702 _SetConfig(cwd, 'branch.default.remote', 'origin')
703 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
704
705 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700706 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700707 raise CloneFailure()
708
709 cmd = [GIT, 'read-tree', '--reset', '-u']
710 if not quiet:
711 cmd.append('-v')
712 cmd.append('HEAD')
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700713 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700714 raise CloneFailure()
715
716
717def _FindRepo():
718 """Look for a repo installation, starting at the current directory.
719 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200720 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700721 repo = None
722
Anthony Newnamdf14a702011-01-09 17:31:57 -0800723 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200724 while curdir != '/' \
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700725 and curdir != olddir \
726 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200727 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700728 if not os.path.isfile(repo):
729 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200730 olddir = curdir
731 curdir = os.path.dirname(curdir)
732 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700733
734
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700735class _Options(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700736 help = False
737
738
739def _ParseArguments(args):
740 cmd = None
741 opt = _Options()
742 arg = []
743
Sarah Owensa6053d52012-11-01 13:36:50 -0700744 for i in range(len(args)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700745 a = args[i]
746 if a == '-h' or a == '--help':
747 opt.help = True
748
749 elif not a.startswith('-'):
750 cmd = a
751 arg = args[i + 1:]
752 break
753 return cmd, opt, arg
754
755
756def _Usage():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700757 gitc_usage = ""
758 if get_gitc_manifest_dir():
759 gitc_usage = " gitc-init Initialize a GITC Client.\n"
760
Conley Owens5e0ee142013-09-26 15:50:49 -0700761 _print(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700762 """usage: repo COMMAND [ARGS]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700763
764repo is not yet installed. Use "repo init" to install it here.
765
766The most commonly used repo commands are:
767
768 init Install repo in the current working directory
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700769""" + gitc_usage +
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700770 """ help Display detailed help on a command
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700771
772For access to the full online help, install repo ("repo init").
Sarah Owenscecd1d82012-11-01 22:59:27 -0700773""", file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700774 sys.exit(1)
775
776
777def _Help(args):
778 if args:
779 if args[0] == 'init':
780 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100781 sys.exit(0)
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700782 elif args[0] == 'gitc-init':
783 _GitcInitOptions(init_optparse)
784 init_optparse.print_help()
785 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700786 else:
Conley Owens5e0ee142013-09-26 15:50:49 -0700787 _print("error: '%s' is not a bootstrap command.\n"
788 ' For access to online help, install repo ("repo init").'
789 % args[0], file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700790 else:
791 _Usage()
792 sys.exit(1)
793
794
795def _NotInstalled():
Conley Owens5e0ee142013-09-26 15:50:49 -0700796 _print('error: repo is not installed. Use "repo init" to install it here.',
797 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700798 sys.exit(1)
799
800
801def _NoCommands(cmd):
Conley Owens5e0ee142013-09-26 15:50:49 -0700802 _print("""error: command '%s' requires repo to be installed first.
803 Use "repo init" to install it here.""" % cmd, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700804 sys.exit(1)
805
806
807def _RunSelf(wrapper_path):
808 my_dir = os.path.dirname(wrapper_path)
809 my_main = os.path.join(my_dir, 'main.py')
810 my_git = os.path.join(my_dir, '.git')
811
812 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700813 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700814 'project.py',
815 'subcmds']:
816 if not os.path.exists(os.path.join(my_dir, name)):
817 return None, None
818 return my_main, my_git
819 return None, None
820
821
822def _SetDefaultsTo(gitdir):
823 global REPO_URL
824 global REPO_REV
825
826 REPO_URL = gitdir
827 proc = subprocess.Popen([GIT,
828 '--git-dir=%s' % gitdir,
829 'symbolic-ref',
830 'HEAD'],
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700831 stdout=subprocess.PIPE,
832 stderr=subprocess.PIPE)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700833 REPO_REV = proc.stdout.read().strip()
834 proc.stdout.close()
835
836 proc.stderr.read()
837 proc.stderr.close()
838
839 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700840 _print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700841 sys.exit(1)
842
843
844def main(orig_args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700845 cmd, opt, args = _ParseArguments(orig_args)
846
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700847 repo_main, rel_repo_dir = None, None
848 # Don't use the local repo copy, make sure to switch to the gitc client first.
849 if cmd != 'gitc-init':
850 repo_main, rel_repo_dir = _FindRepo()
851
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700852 wrapper_path = os.path.abspath(__file__)
853 my_main, my_git = _RunSelf(wrapper_path)
854
Simran Basi8ce50412015-08-28 14:25:44 -0700855 cwd = os.getcwd()
Dan Willemsen2487cb72015-08-31 15:45:06 -0700856 if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
Simran Basi8ce50412015-08-28 14:25:44 -0700857 _print('error: repo cannot be used in the GITC local manifest directory.'
858 '\nIf you want to work on this GITC client please rerun this '
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700859 'command from the corresponding client under /gitc/',
860 file=sys.stderr)
Simran Basi8ce50412015-08-28 14:25:44 -0700861 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200862 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700863 if opt.help:
864 _Usage()
865 if cmd == 'help':
866 _Help(args)
867 if not cmd:
868 _NotInstalled()
Simran Basi1efc2b42015-08-05 15:04:22 -0700869 if cmd == 'init' or cmd == 'gitc-init':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700870 if my_git:
871 _SetDefaultsTo(my_git)
872 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700873 _Init(args, gitc_init=(cmd == 'gitc-init'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700874 except CloneFailure:
Sebastian Schuberth27226e72016-10-28 14:27:43 +0200875 path = os.path.join(repodir, S_repo)
876 _print("fatal: cloning the git-repo repository failed, will remove "
877 "'%s' " % path, file=sys.stderr)
878 shutil.rmtree(path, ignore_errors=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700879 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200880 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700881 else:
882 _NoCommands(cmd)
883
884 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200885 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700886
David Pursehouse685f0802012-11-14 08:34:39 +0900887 ver_str = '.'.join(map(str, VERSION))
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300888 me = [sys.executable, repo_main,
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200889 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700890 '--wrapper-version=%s' % ver_str,
891 '--wrapper-path=%s' % wrapper_path,
892 '--']
893 me.extend(orig_args)
894 me.extend(extra_args)
895 try:
Renaud Paquay35d22212016-11-01 11:24:52 -0700896 if platform.system() == "Windows":
897 sys.exit(subprocess.call(me))
898 else:
899 os.execv(sys.executable, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700900 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700901 _print("fatal: unable to start %s" % repo_main, file=sys.stderr)
902 _print("fatal: %s" % e, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700903 sys.exit(148)
904
905
906if __name__ == '__main__':
Anthony King6efdde92014-05-05 20:37:05 +0100907 if ver[0] == 3:
908 _print('warning: Python 3 support is currently experimental. YMMV.\n'
909 'Please use Python 2.6 - 2.7 instead.',
910 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700911 main(sys.argv[1:])