blob: 69c14a8953cfec4dc22271f7c8eb5c9c46a420b3 [file] [log] [blame]
David Pursehouse8898e2f2012-11-14 07:51:03 +09001#!/usr/bin/env python
Mike Frysingerf6013762019-06-13 02:30:51 -04002# -*- coding:utf-8 -*-
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003
Mark E. Hamilton4088eb42016-02-10 10:44:30 -07004# repo default configuration
5#
Mark E. Hamilton55536282016-02-03 15:49:43 -07006import os
7REPO_URL = os.environ.get('REPO_URL', None)
8if not REPO_URL:
9 REPO_URL = 'https://gerrit.googlesource.com/git-repo'
David Pursehouse8f62fb72012-11-14 12:09:38 +090010REPO_REV = 'stable'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070011
12# Copyright (C) 2008 Google Inc.
13#
14# Licensed under the Apache License, Version 2.0 (the "License");
15# you may not use this file except in compliance with the License.
16# You may obtain a copy of the License at
17#
18# http://www.apache.org/licenses/LICENSE-2.0
19#
20# Unless required by applicable law or agreed to in writing, software
21# distributed under the License is distributed on an "AS IS" BASIS,
22# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23# See the License for the specific language governing permissions and
24# limitations under the License.
25
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070026# increment this whenever we make important changes to this script
Ereth McKnight-MacNeil12ee5442018-12-19 21:28:35 -080027VERSION = (1, 25)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028
29# increment this if the MAINTAINER_KEYS block is modified
Conley Owensbc030842013-07-01 11:05:32 -070030KEYRING_VERSION = (1, 2)
Mike Frysingere4433652016-09-13 18:06:07 -040031
32# Each individual key entry is created by using:
33# gpg --armor --export keyid
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070034MAINTAINER_KEYS = """
35
36 Repo Maintainer <repo@android.kernel.org>
37-----BEGIN PGP PUBLIC KEY BLOCK-----
38Version: GnuPG v1.4.2.2 (GNU/Linux)
39
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
75=CMiZ
76-----END PGP PUBLIC KEY BLOCK-----
Conley Owens55e4d462012-10-01 16:12:28 -070077
78 Conley Owens <cco3@android.com>
79-----BEGIN PGP PUBLIC KEY BLOCK-----
80Version: GnuPG v1.4.11 (GNU/Linux)
81
Conley Owensbc030842013-07-01 11:05:32 -070082mQENBFHRvc8BCADFg45Xx/y6QDC+T7Y/gGc7vx0ww7qfOwIKlAZ9xG3qKunMxo+S
83hPCnzEl3cq+6I1Ww/ndop/HB3N3toPXRCoN8Vs4/Hc7by+SnaLFnacrm+tV5/OgT
84V37Lzt8lhay1Kl+YfpFwHYYpIEBLFV9knyfRXS/428W2qhdzYfvB15/AasRmwmor
85py4NIzSs8UD/SPr1ihqNCdZM76+MQyN5HMYXW/ALZXUFG0pwluHFA7hrfPG74i8C
86zMiP7qvMWIl/r/jtzHioH1dRKgbod+LZsrDJ8mBaqsZaDmNJMhss9g76XvfMyLra
879DI9/iFuBpGzeqBv0hwOGQspLRrEoyTeR6n1ABEBAAG0H0NvbmxleSBPd2VucyA8
88Y2NvM0BhbmRyb2lkLmNvbT6JATgEEwECACIFAlHRvc8CGwMGCwkIBwMCBhUIAgkK
89CwQWAgMBAh4BAheAAAoJEGe35EhpKzgsP6AIAJKJmNtn4l7hkYHKHFSo3egb6RjQ
90zEIP3MFTcu8HFX1kF1ZFbrp7xqurLaE53kEkKuAAvjJDAgI8mcZHP1JyplubqjQA
91xvv84gK+OGP3Xk+QK1ZjUQSbjOpjEiSZpRhWcHci3dgOUH4blJfByHw25hlgHowd
92a/2PrNKZVcJ92YienaxxGjcXEUcd0uYEG2+rwllQigFcnMFDhr9B71MfalRHjFKE
93fmdoypqLrri61YBc59P88Rw2/WUpTQjgNubSqa3A2+CKdaRyaRw+2fdF4TdR0h8W
94zbg+lbaPtJHsV+3mJC7fq26MiJDRJa5ZztpMn8su20gbLgi2ShBOaHAYDDi5AQ0E
95UdG9zwEIAMoOBq+QLNozAhxOOl5GL3StTStGRgPRXINfmViTsihrqGCWBBUfXlUE
96OytC0mYcrDUQev/8ToVoyqw+iGSwDkcSXkrEUCKFtHV/GECWtk1keyHgR10YKI1R
97mquSXoubWGqPeG1PAI74XWaRx8UrL8uCXUtmD8Q5J7mDjKR5NpxaXrwlA0bKsf2E
98Gp9tu1kKauuToZhWHMRMqYSOGikQJwWSFYKT1KdNcOXLQF6+bfoJ6sjVYdwfmNQL
99Ixn8QVhoTDedcqClSWB17VDEFDFa7MmqXZz2qtM3X1R/MUMHqPtegQzBGNhRdnI2
100V45+1Nnx/uuCxDbeI4RbHzujnxDiq70AEQEAAYkBHwQYAQIACQUCUdG9zwIbDAAK
101CRBnt+RIaSs4LNVeB/0Y2pZ8I7gAAcEM0Xw8drr4omg2fUoK1J33ozlA/RxeA/lJ
102I3KnyCDTpXuIeBKPGkdL8uMATC9Z8DnBBajRlftNDVZS3Hz4G09G9QpMojvJkFJV
103By+01Flw/X+eeN8NpqSuLV4W+AjEO8at/VvgKr1AFvBRdZ7GkpI1o6DgPe7ZqX+1
104dzQZt3e13W0rVBb/bUgx9iSLoeWP3aq/k+/GRGOR+S6F6BBSl0SQ2EF2+dIywb1x
105JuinEP+AwLAUZ1Bsx9ISC0Agpk2VeHXPL3FGhroEmoMvBzO0kTFGyoeT7PR/BfKv
106+H/g3HsL2LOB9uoIm8/5p2TTU5ttYCXMHhQZ81AY
107=AUp4
Conley Owens55e4d462012-10-01 16:12:28 -0700108-----END PGP PUBLIC KEY BLOCK-----
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700109"""
110
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700111GIT = 'git' # our git command
112MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
113repodir = '.repo' # name of repo's private directory
114S_repo = 'repo' # special repo repository
115S_manifests = 'manifests' # special manifest repository
116REPO_MAIN = S_repo + '/main.py' # main script
Eli Ribbled4b13c22018-12-18 21:21:12 -0800117MIN_PYTHON_VERSION = (2, 7) # minimum supported python version
Simran Basi8ce50412015-08-28 14:25:44 -0700118GITC_CONFIG_FILE = '/gitc/.config'
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700119GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700120
121
David Jamesbf79c662013-12-26 14:20:13 -0800122import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700123import optparse
Renaud Paquay35d22212016-11-01 11:24:52 -0700124import platform
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700125import re
Mitchel Humpheryseb5acc92014-03-12 10:48:15 -0700126import shutil
Sarah Owens60798a32012-10-25 17:53:09 -0700127import stat
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700128import subprocess
129import sys
David Pursehouse59bbb582013-05-17 10:49:33 +0900130
131if sys.version_info[0] == 3:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700132 import urllib.request
133 import urllib.error
134else:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700135 import imp
David Pursehouse59bbb582013-05-17 10:49:33 +0900136 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -0700137 urllib = imp.new_module('urllib')
138 urllib.request = urllib2
139 urllib.error = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700140
Conley Owens5e0ee142013-09-26 15:50:49 -0700141
142def _print(*objects, **kwargs):
143 sep = kwargs.get('sep', ' ')
144 end = kwargs.get('end', '\n')
145 out = kwargs.get('file', sys.stdout)
146 out.write(sep.join(objects) + end)
147
Sebastian Schubertha9399842018-07-13 11:47:10 +0200148 # On Windows stderr is buffered, so flush to maintain the order of error messages.
149 if out == sys.stderr and platform.system() == "Windows":
150 out.flush()
151
Conley Owens5e0ee142013-09-26 15:50:49 -0700152
Chirayu Desai51813df2013-04-16 19:36:09 +0530153# Python version check
154ver = sys.version_info
Chirayu Desai51813df2013-04-16 19:36:09 +0530155if (ver[0], ver[1]) < MIN_PYTHON_VERSION:
Eli Ribbled4b13c22018-12-18 21:21:12 -0800156 _print('error: Python version {} unsupported.\n'
157 'Please use Python {}.{} instead.'.format(
158 sys.version.split(' ')[0],
159 MIN_PYTHON_VERSION[0],
160 MIN_PYTHON_VERSION[1],
161 ), file=sys.stderr)
Chirayu Desai51813df2013-04-16 19:36:09 +0530162 sys.exit(1)
163
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700164home_dot_repo = os.path.expanduser('~/.repoconfig')
165gpg_dir = os.path.join(home_dot_repo, 'gnupg')
166
167extra_args = []
168init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
169
170# Logging
171group = init_optparse.add_option_group('Logging options')
172group.add_option('-q', '--quiet',
173 dest="quiet", action="store_true", default=False,
174 help="be quiet")
175
176# Manifest
177group = init_optparse.add_option_group('Manifest options')
178group.add_option('-u', '--manifest-url',
179 dest='manifest_url',
180 help='manifest repository location', metavar='URL')
181group.add_option('-b', '--manifest-branch',
182 dest='manifest_branch',
183 help='manifest branch or revision', metavar='REVISION')
184group.add_option('-m', '--manifest-name',
185 dest='manifest_name',
186 help='initial manifest file', metavar='NAME.xml')
Ereth McKnight-MacNeil12ee5442018-12-19 21:28:35 -0800187group.add_option('--current-branch',
Naseer Ahmedf4dda9a2016-12-01 18:49:54 -0500188 dest='current_branch_only', action='store_true',
189 help='fetch only current manifest branch from server')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800190group.add_option('--mirror',
191 dest='mirror', action='store_true',
David Pursehouse3794a782012-11-15 06:17:30 +0900192 help='create a replica of the remote repositories '
193 'rather than a client working directory')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200194group.add_option('--reference',
195 dest='reference',
196 help='location of mirror directory', metavar='DIR')
Nikolai Merinov09f0abb2018-10-19 15:07:05 +0500197group.add_option('--dissociate',
198 dest='dissociate', action='store_true',
199 help='dissociate from reference mirrors after clone')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700200group.add_option('--depth', type='int', default=None,
201 dest='depth',
202 help='create a shallow clone with given depth; see git clone')
Julien Campergue335f5ef2013-10-16 11:02:35 +0200203group.add_option('--archive',
204 dest='archive', action='store_true',
205 help='checkout an archive instead of a git repository for '
206 'each project. See git archive.')
Martin Kellye4e94d22017-03-21 16:05:12 -0700207group.add_option('--submodules',
208 dest='submodules', action='store_true',
209 help='sync any submodules associated with the manifest repo')
Colin Cross5acde752012-03-28 20:15:45 -0700210group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700211 dest='groups', default='default',
David Holmer0a1c6a12012-11-14 19:19:00 -0500212 help='restrict manifest projects to ones with specified '
213 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
Colin Cross5acde752012-03-28 20:15:45 -0700214 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700215group.add_option('-p', '--platform',
216 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700217 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700218 'platform group [auto|all|none|linux|darwin|...]',
219 metavar='PLATFORM')
Hu xiuyun9711a982015-12-11 11:16:41 +0800220group.add_option('--no-clone-bundle',
221 dest='no_clone_bundle', action='store_true',
222 help='disable use of /clone.bundle on HTTP/HTTPS')
Naseer Ahmedf4dda9a2016-12-01 18:49:54 -0500223group.add_option('--no-tags',
224 dest='no_tags', action='store_true',
225 help="don't fetch tags in the manifest")
Doug Anderson49cd59b2011-06-13 21:42:06 -0700226
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700227
228# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700229group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700230group.add_option('--repo-url',
231 dest='repo_url',
232 help='repo repository location', metavar='URL')
233group.add_option('--repo-branch',
234 dest='repo_branch',
235 help='repo branch or revision', metavar='REVISION')
236group.add_option('--no-repo-verify',
237 dest='no_repo_verify', action='store_true',
238 help='do not verify repo source code')
239
Victor Boivie841be342011-04-05 11:31:10 +0200240# Other
241group = init_optparse.add_option_group('Other options')
242group.add_option('--config-name',
243 dest='config_name', action="store_true", default=False,
244 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700245
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700246
247def _GitcInitOptions(init_optparse_arg):
248 init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
249 g = init_optparse_arg.add_option_group('GITC options')
Simran Basi1efc2b42015-08-05 15:04:22 -0700250 g.add_option('-f', '--manifest-file',
251 dest='manifest_file',
252 help='Optional manifest file to use for this GITC client.')
253 g.add_option('-c', '--gitc-client',
254 dest='gitc_client',
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700255 help='The name of the gitc_client instance to create or modify.')
Simran Basi1efc2b42015-08-05 15:04:22 -0700256
Simran Basi8ce50412015-08-28 14:25:44 -0700257_gitc_manifest_dir = None
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700258
259
Simran Basi8ce50412015-08-28 14:25:44 -0700260def get_gitc_manifest_dir():
261 global _gitc_manifest_dir
262 if _gitc_manifest_dir is None:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700263 _gitc_manifest_dir = ''
Simran Basi8ce50412015-08-28 14:25:44 -0700264 try:
265 with open(GITC_CONFIG_FILE, 'r') as gitc_config:
266 for line in gitc_config:
267 match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
268 if match:
269 _gitc_manifest_dir = match.group('gitc_manifest_dir')
270 except IOError:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700271 pass
Simran Basi8ce50412015-08-28 14:25:44 -0700272 return _gitc_manifest_dir
273
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700274
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700275def gitc_parse_clientdir(gitc_fs_path):
276 """Parse a path in the GITC FS and return its client name.
277
278 @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
279
280 @returns: The GITC client name
281 """
282 if gitc_fs_path == GITC_FS_ROOT_DIR:
283 return None
284 if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
285 manifest_dir = get_gitc_manifest_dir()
286 if manifest_dir == '':
287 return None
288 if manifest_dir[-1] != '/':
289 manifest_dir += '/'
290 if gitc_fs_path == manifest_dir:
291 return None
292 if not gitc_fs_path.startswith(manifest_dir):
293 return None
294 return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
295 return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
296
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700297
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700298class CloneFailure(Exception):
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700299
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700300 """Indicate the remote clone of repo itself failed.
301 """
302
303
Simran Basi1efc2b42015-08-05 15:04:22 -0700304def _Init(args, gitc_init=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700305 """Installs repo by cloning it over the network.
306 """
Simran Basi1efc2b42015-08-05 15:04:22 -0700307 if gitc_init:
308 _GitcInitOptions(init_optparse)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700309 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800310 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700311 init_optparse.print_usage()
312 sys.exit(1)
313
314 url = opt.repo_url
315 if not url:
316 url = REPO_URL
317 extra_args.append('--repo-url=%s' % url)
318
319 branch = opt.repo_branch
320 if not branch:
321 branch = REPO_REV
322 extra_args.append('--repo-branch=%s' % branch)
323
324 if branch.startswith('refs/heads/'):
325 branch = branch[len('refs/heads/'):]
326 if branch.startswith('refs/'):
Conley Owens5e0ee142013-09-26 15:50:49 -0700327 _print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700328 raise CloneFailure()
329
David Jamesbf79c662013-12-26 14:20:13 -0800330 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700331 if gitc_init:
Simran Basi8ce50412015-08-28 14:25:44 -0700332 gitc_manifest_dir = get_gitc_manifest_dir()
333 if not gitc_manifest_dir:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700334 _print('fatal: GITC filesystem is not available. Exiting...',
Simran Basi8ce50412015-08-28 14:25:44 -0700335 file=sys.stderr)
336 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700337 gitc_client = opt.gitc_client
338 if not gitc_client:
339 gitc_client = gitc_parse_clientdir(os.getcwd())
340 if not gitc_client:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700341 _print('fatal: GITC client (-c) is required.', file=sys.stderr)
342 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700343 client_dir = os.path.join(gitc_manifest_dir, gitc_client)
Simran Basi1efc2b42015-08-05 15:04:22 -0700344 if not os.path.exists(client_dir):
345 os.makedirs(client_dir)
346 os.chdir(client_dir)
347 if os.path.exists(repodir):
348 # This GITC Client has already initialized repo so continue.
349 return
350
David Jamesbf79c662013-12-26 14:20:13 -0800351 os.mkdir(repodir)
352 except OSError as e:
353 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700354 _print('fatal: cannot make %s directory: %s'
355 % (repodir, e.strerror), file=sys.stderr)
David Pursehouse3794a782012-11-15 06:17:30 +0900356 # Don't raise CloneFailure; that would delete the
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700357 # name. Instead exit immediately.
358 #
359 sys.exit(1)
360
361 _CheckGitVersion()
362 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700363 if NeedSetupGnuPG():
364 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700365 else:
366 can_verify = True
367
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700368 dst = os.path.abspath(os.path.join(repodir, S_repo))
Hu xiuyun9711a982015-12-11 11:16:41 +0800369 _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700370
371 if can_verify and not opt.no_repo_verify:
372 rev = _Verify(dst, branch, opt.quiet)
373 else:
374 rev = 'refs/remotes/origin/%s^0' % branch
375
376 _Checkout(dst, branch, rev, opt.quiet)
Sebastian Schuberth993dcac2018-07-13 10:25:52 +0200377
378 if not os.path.isfile(os.path.join(dst, 'repo')):
379 _print("warning: '%s' does not look like a git-repo repository, is "
380 "REPO_URL set correctly?" % url, file=sys.stderr)
381
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700382 except CloneFailure:
383 if opt.quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700384 _print('fatal: repo init failed; run without --quiet to see why',
385 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700386 raise
387
388
Conley Owensff0a3c82014-01-30 14:46:03 -0800389def ParseGitVersion(ver_str):
390 if not ver_str.startswith('git version '):
391 return None
392
393 num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
394 to_tuple = []
395 for num_str in num_ver_str.split('.')[:3]:
396 if num_str.isdigit():
397 to_tuple.append(int(num_str))
398 else:
399 to_tuple.append(0)
400 return tuple(to_tuple)
401
402
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700403def _CheckGitVersion():
404 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700405 try:
406 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700407 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700408 _print(file=sys.stderr)
409 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
410 _print('fatal: %s' % e, file=sys.stderr)
411 _print(file=sys.stderr)
412 _print('Please make sure %s is installed and in your path.' % GIT,
413 file=sys.stderr)
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700414 raise CloneFailure()
415
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700416 ver_str = proc.stdout.read().strip()
417 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700418 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700419
Conley Owensff0a3c82014-01-30 14:46:03 -0800420 ver_act = ParseGitVersion(ver_str)
421 if ver_act is None:
Conley Owens5e0ee142013-09-26 15:50:49 -0700422 _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700423 raise CloneFailure()
424
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700425 if ver_act < MIN_GIT_VERSION:
David Pursehouse685f0802012-11-14 08:34:39 +0900426 need = '.'.join(map(str, MIN_GIT_VERSION))
Conley Owens5e0ee142013-09-26 15:50:49 -0700427 _print('fatal: git %s or later required' % need, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700428 raise CloneFailure()
429
430
Conley Owensc9129d92012-10-01 16:12:28 -0700431def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700432 if not os.path.isdir(home_dot_repo):
433 return True
434
435 kv = os.path.join(home_dot_repo, 'keyring-version')
436 if not os.path.exists(kv):
437 return True
438
439 kv = open(kv).read()
440 if not kv:
441 return True
442
David Pursehouse685f0802012-11-14 08:34:39 +0900443 kv = tuple(map(int, kv.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700444 if kv < KEYRING_VERSION:
445 return True
446 return False
447
448
Conley Owensc9129d92012-10-01 16:12:28 -0700449def SetupGnuPG(quiet):
David Jamesbf79c662013-12-26 14:20:13 -0800450 try:
451 os.mkdir(home_dot_repo)
452 except OSError as e:
453 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700454 _print('fatal: cannot make %s directory: %s'
455 % (home_dot_repo, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700456 sys.exit(1)
457
David Jamesbf79c662013-12-26 14:20:13 -0800458 try:
459 os.mkdir(gpg_dir, stat.S_IRWXU)
460 except OSError as e:
461 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700462 _print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
463 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700464 sys.exit(1)
465
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800466 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300467 try:
468 env['GNUPGHOME'] = gpg_dir
469 except UnicodeEncodeError:
470 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700471
472 cmd = ['gpg', '--import']
473 try:
474 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700475 env=env,
476 stdin=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700477 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700478 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700479 _print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
480 _print('warning: Installing it is strongly encouraged.', file=sys.stderr)
481 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700482 return False
483
484 proc.stdin.write(MAINTAINER_KEYS)
485 proc.stdin.close()
486
487 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700488 _print('fatal: registering repo maintainer keys failed', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700489 sys.exit(1)
Conley Owens5e0ee142013-09-26 15:50:49 -0700490 _print()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700491
492 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
David Pursehouse685f0802012-11-14 08:34:39 +0900493 fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700494 fd.close()
495 return True
496
497
498def _SetConfig(local, name, value):
499 """Set a git configuration option to the specified value.
500 """
501 cmd = [GIT, 'config', name, value]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700502 if subprocess.Popen(cmd, cwd=local).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700503 raise CloneFailure()
504
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700505
506def _InitHttp():
507 handlers = []
508
Sarah Owens1f7627f2012-10-31 09:21:55 -0700509 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700510 try:
511 import netrc
512 n = netrc.netrc()
513 for host in n.hosts:
514 p = n.hosts[host]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700515 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800516 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
David Pursehouse65b0ba52018-06-24 16:21:51 +0900517 except:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700518 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700519 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
520 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700521
522 if 'http_proxy' in os.environ:
523 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700524 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700525 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700526 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
527 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
528 urllib.request.install_opener(urllib.request.build_opener(*handlers))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700529
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700530
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700531def _Fetch(url, local, src, quiet):
532 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700533 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700534
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700535 cmd = [GIT, 'fetch']
536 if quiet:
537 cmd.append('--quiet')
538 err = subprocess.PIPE
539 else:
540 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700541 cmd.append(src)
542 cmd.append('+refs/heads/*:refs/remotes/origin/*')
Xin Li6e538442018-12-10 11:33:16 -0800543 cmd.append('+refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700544
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700545 proc = subprocess.Popen(cmd, cwd=local, stderr=err)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700546 if err:
547 proc.stderr.read()
548 proc.stderr.close()
549 if proc.wait() != 0:
550 raise CloneFailure()
551
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700552
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700553def _DownloadBundle(url, local, quiet):
554 if not url.endswith('/'):
555 url += '/'
556 url += 'clone.bundle'
557
558 proc = subprocess.Popen(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700559 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
560 cwd=local,
561 stdout=subprocess.PIPE)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700562 for line in proc.stdout:
563 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
564 if m:
565 new_url = m.group(1)
566 old_url = m.group(2)
567 if url.startswith(old_url):
568 url = new_url + url[len(old_url):]
569 break
570 proc.stdout.close()
571 proc.wait()
572
573 if not url.startswith('http:') and not url.startswith('https:'):
574 return False
575
576 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
577 try:
578 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700579 r = urllib.request.urlopen(url)
580 except urllib.error.HTTPError as e:
John Törnblomd3ddcdb2015-08-12 20:12:51 +0200581 if e.code in [401, 403, 404, 501]:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700582 return False
Conley Owens5e0ee142013-09-26 15:50:49 -0700583 _print('fatal: Cannot get %s' % url, file=sys.stderr)
584 _print('fatal: HTTP error %s' % e.code, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700585 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700586 except urllib.error.URLError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700587 _print('fatal: Cannot get %s' % url, file=sys.stderr)
588 _print('fatal: error %s' % e.reason, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700589 raise CloneFailure()
590 try:
591 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700592 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700593 while True:
594 buf = r.read(8192)
595 if buf == '':
596 return True
597 dest.write(buf)
598 finally:
599 r.close()
600 finally:
601 dest.close()
602
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700603
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700604def _ImportBundle(local):
605 path = os.path.join(local, '.git', 'clone.bundle')
606 try:
607 _Fetch(local, local, path, True)
608 finally:
609 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700610
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700611
Hu xiuyun9711a982015-12-11 11:16:41 +0800612def _Clone(url, local, quiet, clone_bundle):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700613 """Clones a git repository to a new subdirectory of repodir
614 """
615 try:
616 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700617 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700618 _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
619 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700620 raise CloneFailure()
621
622 cmd = [GIT, 'init', '--quiet']
623 try:
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700624 proc = subprocess.Popen(cmd, cwd=local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700625 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700626 _print(file=sys.stderr)
627 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
628 _print('fatal: %s' % e, file=sys.stderr)
629 _print(file=sys.stderr)
630 _print('Please make sure %s is installed and in your path.' % GIT,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700631 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700632 raise CloneFailure()
633 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700634 _print('fatal: could not create %s' % local, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700635 raise CloneFailure()
636
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700637 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700638 _SetConfig(local, 'remote.origin.url', url)
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700639 _SetConfig(local,
640 'remote.origin.fetch',
641 '+refs/heads/*:refs/remotes/origin/*')
Hu xiuyun9711a982015-12-11 11:16:41 +0800642 if clone_bundle and _DownloadBundle(url, local, quiet):
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700643 _ImportBundle(local)
Dan Willemsenfee390e2015-09-02 12:36:30 -0700644 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700645
646
647def _Verify(cwd, branch, quiet):
648 """Verify the branch has been signed by a tag.
649 """
650 cmd = [GIT, 'describe', 'origin/%s' % branch]
651 proc = subprocess.Popen(cmd,
652 stdout=subprocess.PIPE,
653 stderr=subprocess.PIPE,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700654 cwd=cwd)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700655 cur = proc.stdout.read().strip()
656 proc.stdout.close()
657
658 proc.stderr.read()
659 proc.stderr.close()
660
661 if proc.wait() != 0 or not cur:
Conley Owens5e0ee142013-09-26 15:50:49 -0700662 _print(file=sys.stderr)
663 _print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700664 raise CloneFailure()
665
666 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
667 if m:
668 cur = m.group(1)
669 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700670 _print(file=sys.stderr)
671 _print("info: Ignoring branch '%s'; using tagged release '%s'"
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700672 % (branch, cur), file=sys.stderr)
Conley Owens5e0ee142013-09-26 15:50:49 -0700673 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700674
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800675 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300676 try:
677 env['GNUPGHOME'] = gpg_dir
678 except UnicodeEncodeError:
679 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700680
681 cmd = [GIT, 'tag', '-v', cur]
682 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700683 stdout=subprocess.PIPE,
684 stderr=subprocess.PIPE,
685 cwd=cwd,
686 env=env)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700687 out = proc.stdout.read()
688 proc.stdout.close()
689
690 err = proc.stderr.read()
691 proc.stderr.close()
692
693 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700694 _print(file=sys.stderr)
695 _print(out, file=sys.stderr)
696 _print(err, file=sys.stderr)
697 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700698 raise CloneFailure()
699 return '%s^0' % cur
700
701
702def _Checkout(cwd, branch, rev, quiet):
703 """Checkout an upstream branch into the repository and track it.
704 """
705 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
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 _SetConfig(cwd, 'branch.default.remote', 'origin')
710 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
711
712 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
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 cmd = [GIT, 'read-tree', '--reset', '-u']
717 if not quiet:
718 cmd.append('-v')
719 cmd.append('HEAD')
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700720 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700721 raise CloneFailure()
722
723
724def _FindRepo():
725 """Look for a repo installation, starting at the current directory.
726 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200727 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700728 repo = None
729
Anthony Newnamdf14a702011-01-09 17:31:57 -0800730 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200731 while curdir != '/' \
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700732 and curdir != olddir \
733 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200734 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700735 if not os.path.isfile(repo):
736 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200737 olddir = curdir
738 curdir = os.path.dirname(curdir)
739 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700740
741
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700742class _Options(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700743 help = False
744
745
746def _ParseArguments(args):
747 cmd = None
748 opt = _Options()
749 arg = []
750
Sarah Owensa6053d52012-11-01 13:36:50 -0700751 for i in range(len(args)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700752 a = args[i]
753 if a == '-h' or a == '--help':
754 opt.help = True
755
756 elif not a.startswith('-'):
757 cmd = a
758 arg = args[i + 1:]
759 break
760 return cmd, opt, arg
761
762
763def _Usage():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700764 gitc_usage = ""
765 if get_gitc_manifest_dir():
766 gitc_usage = " gitc-init Initialize a GITC Client.\n"
767
Conley Owens5e0ee142013-09-26 15:50:49 -0700768 _print(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700769 """usage: repo COMMAND [ARGS]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700770
771repo is not yet installed. Use "repo init" to install it here.
772
773The most commonly used repo commands are:
774
775 init Install repo in the current working directory
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700776""" + gitc_usage +
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700777 """ help Display detailed help on a command
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700778
779For access to the full online help, install repo ("repo init").
Mike Frysinger35159ab2019-06-13 00:07:13 -0400780""")
781 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700782
783
784def _Help(args):
785 if args:
786 if args[0] == 'init':
787 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100788 sys.exit(0)
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700789 elif args[0] == 'gitc-init':
790 _GitcInitOptions(init_optparse)
791 init_optparse.print_help()
792 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700793 else:
Conley Owens5e0ee142013-09-26 15:50:49 -0700794 _print("error: '%s' is not a bootstrap command.\n"
795 ' For access to online help, install repo ("repo init").'
796 % args[0], file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700797 else:
798 _Usage()
799 sys.exit(1)
800
801
802def _NotInstalled():
Conley Owens5e0ee142013-09-26 15:50:49 -0700803 _print('error: repo is not installed. Use "repo init" to install it here.',
804 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700805 sys.exit(1)
806
807
808def _NoCommands(cmd):
Conley Owens5e0ee142013-09-26 15:50:49 -0700809 _print("""error: command '%s' requires repo to be installed first.
810 Use "repo init" to install it here.""" % cmd, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700811 sys.exit(1)
812
813
814def _RunSelf(wrapper_path):
815 my_dir = os.path.dirname(wrapper_path)
816 my_main = os.path.join(my_dir, 'main.py')
817 my_git = os.path.join(my_dir, '.git')
818
819 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700820 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700821 'project.py',
822 'subcmds']:
823 if not os.path.exists(os.path.join(my_dir, name)):
824 return None, None
825 return my_main, my_git
826 return None, None
827
828
829def _SetDefaultsTo(gitdir):
830 global REPO_URL
831 global REPO_REV
832
833 REPO_URL = gitdir
834 proc = subprocess.Popen([GIT,
835 '--git-dir=%s' % gitdir,
836 'symbolic-ref',
837 'HEAD'],
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700838 stdout=subprocess.PIPE,
839 stderr=subprocess.PIPE)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700840 REPO_REV = proc.stdout.read().strip()
841 proc.stdout.close()
842
843 proc.stderr.read()
844 proc.stderr.close()
845
846 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700847 _print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700848 sys.exit(1)
849
850
851def main(orig_args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700852 cmd, opt, args = _ParseArguments(orig_args)
853
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700854 repo_main, rel_repo_dir = None, None
855 # Don't use the local repo copy, make sure to switch to the gitc client first.
856 if cmd != 'gitc-init':
857 repo_main, rel_repo_dir = _FindRepo()
858
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700859 wrapper_path = os.path.abspath(__file__)
860 my_main, my_git = _RunSelf(wrapper_path)
861
Simran Basi8ce50412015-08-28 14:25:44 -0700862 cwd = os.getcwd()
Dan Willemsen2487cb72015-08-31 15:45:06 -0700863 if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
Simran Basi8ce50412015-08-28 14:25:44 -0700864 _print('error: repo cannot be used in the GITC local manifest directory.'
865 '\nIf you want to work on this GITC client please rerun this '
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700866 'command from the corresponding client under /gitc/',
867 file=sys.stderr)
Simran Basi8ce50412015-08-28 14:25:44 -0700868 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200869 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700870 if opt.help:
871 _Usage()
872 if cmd == 'help':
873 _Help(args)
874 if not cmd:
875 _NotInstalled()
Simran Basi1efc2b42015-08-05 15:04:22 -0700876 if cmd == 'init' or cmd == 'gitc-init':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700877 if my_git:
878 _SetDefaultsTo(my_git)
879 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700880 _Init(args, gitc_init=(cmd == 'gitc-init'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700881 except CloneFailure:
Sebastian Schuberth27226e72016-10-28 14:27:43 +0200882 path = os.path.join(repodir, S_repo)
883 _print("fatal: cloning the git-repo repository failed, will remove "
884 "'%s' " % path, file=sys.stderr)
885 shutil.rmtree(path, ignore_errors=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700886 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200887 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700888 else:
889 _NoCommands(cmd)
890
891 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200892 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700893
David Pursehouse685f0802012-11-14 08:34:39 +0900894 ver_str = '.'.join(map(str, VERSION))
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300895 me = [sys.executable, repo_main,
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200896 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700897 '--wrapper-version=%s' % ver_str,
898 '--wrapper-path=%s' % wrapper_path,
899 '--']
900 me.extend(orig_args)
901 me.extend(extra_args)
902 try:
Renaud Paquay35d22212016-11-01 11:24:52 -0700903 if platform.system() == "Windows":
904 sys.exit(subprocess.call(me))
905 else:
906 os.execv(sys.executable, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700907 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700908 _print("fatal: unable to start %s" % repo_main, file=sys.stderr)
909 _print("fatal: %s" % e, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700910 sys.exit(148)
911
912
913if __name__ == '__main__':
Anthony King6efdde92014-05-05 20:37:05 +0100914 if ver[0] == 3:
915 _print('warning: Python 3 support is currently experimental. YMMV.\n'
Eli Ribbled4b13c22018-12-18 21:21:12 -0800916 'Please use Python 2.7 instead.',
Anthony King6efdde92014-05-05 20:37:05 +0100917 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700918 main(sys.argv[1:])