blob: 114bb6626521c1af16c327b9728c7d351b64899f [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
Mike Frysingerc92ce5c2019-06-13 01:14:23 -04004from __future__ import print_function
5
Mark E. Hamilton4088eb42016-02-10 10:44:30 -07006# repo default configuration
7#
Mark E. Hamilton55536282016-02-03 15:49:43 -07008import os
9REPO_URL = os.environ.get('REPO_URL', None)
10if not REPO_URL:
11 REPO_URL = 'https://gerrit.googlesource.com/git-repo'
David Pursehouse8f62fb72012-11-14 12:09:38 +090012REPO_REV = 'stable'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070013
14# Copyright (C) 2008 Google Inc.
15#
16# Licensed under the Apache License, Version 2.0 (the "License");
17# you may not use this file except in compliance with the License.
18# You may obtain a copy of the License at
19#
20# http://www.apache.org/licenses/LICENSE-2.0
21#
22# Unless required by applicable law or agreed to in writing, software
23# distributed under the License is distributed on an "AS IS" BASIS,
24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25# See the License for the specific language governing permissions and
26# limitations under the License.
27
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028# increment this whenever we make important changes to this script
Ereth McKnight-MacNeil12ee5442018-12-19 21:28:35 -080029VERSION = (1, 25)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030
31# increment this if the MAINTAINER_KEYS block is modified
Conley Owensbc030842013-07-01 11:05:32 -070032KEYRING_VERSION = (1, 2)
Mike Frysingere4433652016-09-13 18:06:07 -040033
34# Each individual key entry is created by using:
35# gpg --armor --export keyid
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070036MAINTAINER_KEYS = """
37
38 Repo Maintainer <repo@android.kernel.org>
39-----BEGIN PGP PUBLIC KEY BLOCK-----
40Version: GnuPG v1.4.2.2 (GNU/Linux)
41
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
77=CMiZ
78-----END PGP PUBLIC KEY BLOCK-----
Conley Owens55e4d462012-10-01 16:12:28 -070079
80 Conley Owens <cco3@android.com>
81-----BEGIN PGP PUBLIC KEY BLOCK-----
82Version: GnuPG v1.4.11 (GNU/Linux)
83
Conley Owensbc030842013-07-01 11:05:32 -070084mQENBFHRvc8BCADFg45Xx/y6QDC+T7Y/gGc7vx0ww7qfOwIKlAZ9xG3qKunMxo+S
85hPCnzEl3cq+6I1Ww/ndop/HB3N3toPXRCoN8Vs4/Hc7by+SnaLFnacrm+tV5/OgT
86V37Lzt8lhay1Kl+YfpFwHYYpIEBLFV9knyfRXS/428W2qhdzYfvB15/AasRmwmor
87py4NIzSs8UD/SPr1ihqNCdZM76+MQyN5HMYXW/ALZXUFG0pwluHFA7hrfPG74i8C
88zMiP7qvMWIl/r/jtzHioH1dRKgbod+LZsrDJ8mBaqsZaDmNJMhss9g76XvfMyLra
899DI9/iFuBpGzeqBv0hwOGQspLRrEoyTeR6n1ABEBAAG0H0NvbmxleSBPd2VucyA8
90Y2NvM0BhbmRyb2lkLmNvbT6JATgEEwECACIFAlHRvc8CGwMGCwkIBwMCBhUIAgkK
91CwQWAgMBAh4BAheAAAoJEGe35EhpKzgsP6AIAJKJmNtn4l7hkYHKHFSo3egb6RjQ
92zEIP3MFTcu8HFX1kF1ZFbrp7xqurLaE53kEkKuAAvjJDAgI8mcZHP1JyplubqjQA
93xvv84gK+OGP3Xk+QK1ZjUQSbjOpjEiSZpRhWcHci3dgOUH4blJfByHw25hlgHowd
94a/2PrNKZVcJ92YienaxxGjcXEUcd0uYEG2+rwllQigFcnMFDhr9B71MfalRHjFKE
95fmdoypqLrri61YBc59P88Rw2/WUpTQjgNubSqa3A2+CKdaRyaRw+2fdF4TdR0h8W
96zbg+lbaPtJHsV+3mJC7fq26MiJDRJa5ZztpMn8su20gbLgi2ShBOaHAYDDi5AQ0E
97UdG9zwEIAMoOBq+QLNozAhxOOl5GL3StTStGRgPRXINfmViTsihrqGCWBBUfXlUE
98OytC0mYcrDUQev/8ToVoyqw+iGSwDkcSXkrEUCKFtHV/GECWtk1keyHgR10YKI1R
99mquSXoubWGqPeG1PAI74XWaRx8UrL8uCXUtmD8Q5J7mDjKR5NpxaXrwlA0bKsf2E
100Gp9tu1kKauuToZhWHMRMqYSOGikQJwWSFYKT1KdNcOXLQF6+bfoJ6sjVYdwfmNQL
101Ixn8QVhoTDedcqClSWB17VDEFDFa7MmqXZz2qtM3X1R/MUMHqPtegQzBGNhRdnI2
102V45+1Nnx/uuCxDbeI4RbHzujnxDiq70AEQEAAYkBHwQYAQIACQUCUdG9zwIbDAAK
103CRBnt+RIaSs4LNVeB/0Y2pZ8I7gAAcEM0Xw8drr4omg2fUoK1J33ozlA/RxeA/lJ
104I3KnyCDTpXuIeBKPGkdL8uMATC9Z8DnBBajRlftNDVZS3Hz4G09G9QpMojvJkFJV
105By+01Flw/X+eeN8NpqSuLV4W+AjEO8at/VvgKr1AFvBRdZ7GkpI1o6DgPe7ZqX+1
106dzQZt3e13W0rVBb/bUgx9iSLoeWP3aq/k+/GRGOR+S6F6BBSl0SQ2EF2+dIywb1x
107JuinEP+AwLAUZ1Bsx9ISC0Agpk2VeHXPL3FGhroEmoMvBzO0kTFGyoeT7PR/BfKv
108+H/g3HsL2LOB9uoIm8/5p2TTU5ttYCXMHhQZ81AY
109=AUp4
Conley Owens55e4d462012-10-01 16:12:28 -0700110-----END PGP PUBLIC KEY BLOCK-----
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700111"""
112
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700113GIT = 'git' # our git command
114MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
115repodir = '.repo' # name of repo's private directory
116S_repo = 'repo' # special repo repository
117S_manifests = 'manifests' # special manifest repository
118REPO_MAIN = S_repo + '/main.py' # main script
Eli Ribbled4b13c22018-12-18 21:21:12 -0800119MIN_PYTHON_VERSION = (2, 7) # minimum supported python version
Simran Basi8ce50412015-08-28 14:25:44 -0700120GITC_CONFIG_FILE = '/gitc/.config'
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700121GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700122
123
Mike Frysinger6db1b9e2019-07-10 15:32:36 -0400124import collections
David Jamesbf79c662013-12-26 14:20:13 -0800125import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126import optparse
Renaud Paquay35d22212016-11-01 11:24:52 -0700127import platform
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700128import re
Mitchel Humpheryseb5acc92014-03-12 10:48:15 -0700129import shutil
Sarah Owens60798a32012-10-25 17:53:09 -0700130import stat
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700131import subprocess
132import sys
David Pursehouse59bbb582013-05-17 10:49:33 +0900133
134if sys.version_info[0] == 3:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700135 import urllib.request
136 import urllib.error
137else:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700138 import imp
David Pursehouse59bbb582013-05-17 10:49:33 +0900139 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -0700140 urllib = imp.new_module('urllib')
141 urllib.request = urllib2
142 urllib.error = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700143
Conley Owens5e0ee142013-09-26 15:50:49 -0700144
Chirayu Desai51813df2013-04-16 19:36:09 +0530145# Python version check
146ver = sys.version_info
Chirayu Desai51813df2013-04-16 19:36:09 +0530147if (ver[0], ver[1]) < MIN_PYTHON_VERSION:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400148 print('error: Python version {} unsupported.\n'
149 'Please use Python {}.{} instead.'.format(
150 sys.version.split(' ')[0],
151 MIN_PYTHON_VERSION[0],
152 MIN_PYTHON_VERSION[1],
153 ), file=sys.stderr)
Chirayu Desai51813df2013-04-16 19:36:09 +0530154 sys.exit(1)
155
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700156home_dot_repo = os.path.expanduser('~/.repoconfig')
157gpg_dir = os.path.join(home_dot_repo, 'gnupg')
158
159extra_args = []
160init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
161
162# Logging
163group = init_optparse.add_option_group('Logging options')
164group.add_option('-q', '--quiet',
165 dest="quiet", action="store_true", default=False,
166 help="be quiet")
167
168# Manifest
169group = init_optparse.add_option_group('Manifest options')
170group.add_option('-u', '--manifest-url',
171 dest='manifest_url',
172 help='manifest repository location', metavar='URL')
173group.add_option('-b', '--manifest-branch',
174 dest='manifest_branch',
175 help='manifest branch or revision', metavar='REVISION')
176group.add_option('-m', '--manifest-name',
177 dest='manifest_name',
178 help='initial manifest file', metavar='NAME.xml')
Ereth McKnight-MacNeil12ee5442018-12-19 21:28:35 -0800179group.add_option('--current-branch',
Naseer Ahmedf4dda9a2016-12-01 18:49:54 -0500180 dest='current_branch_only', action='store_true',
181 help='fetch only current manifest branch from server')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800182group.add_option('--mirror',
183 dest='mirror', action='store_true',
David Pursehouse3794a782012-11-15 06:17:30 +0900184 help='create a replica of the remote repositories '
185 'rather than a client working directory')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200186group.add_option('--reference',
187 dest='reference',
188 help='location of mirror directory', metavar='DIR')
Nikolai Merinov09f0abb2018-10-19 15:07:05 +0500189group.add_option('--dissociate',
190 dest='dissociate', action='store_true',
191 help='dissociate from reference mirrors after clone')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700192group.add_option('--depth', type='int', default=None,
193 dest='depth',
194 help='create a shallow clone with given depth; see git clone')
Julien Campergue335f5ef2013-10-16 11:02:35 +0200195group.add_option('--archive',
196 dest='archive', action='store_true',
197 help='checkout an archive instead of a git repository for '
198 'each project. See git archive.')
Martin Kellye4e94d22017-03-21 16:05:12 -0700199group.add_option('--submodules',
200 dest='submodules', action='store_true',
201 help='sync any submodules associated with the manifest repo')
Colin Cross5acde752012-03-28 20:15:45 -0700202group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700203 dest='groups', default='default',
David Holmer0a1c6a12012-11-14 19:19:00 -0500204 help='restrict manifest projects to ones with specified '
205 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
Colin Cross5acde752012-03-28 20:15:45 -0700206 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700207group.add_option('-p', '--platform',
208 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700209 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700210 'platform group [auto|all|none|linux|darwin|...]',
211 metavar='PLATFORM')
Hu xiuyun9711a982015-12-11 11:16:41 +0800212group.add_option('--no-clone-bundle',
213 dest='no_clone_bundle', action='store_true',
214 help='disable use of /clone.bundle on HTTP/HTTPS')
Naseer Ahmedf4dda9a2016-12-01 18:49:54 -0500215group.add_option('--no-tags',
216 dest='no_tags', action='store_true',
217 help="don't fetch tags in the manifest")
Doug Anderson49cd59b2011-06-13 21:42:06 -0700218
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700219
220# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700221group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700222group.add_option('--repo-url',
223 dest='repo_url',
224 help='repo repository location', metavar='URL')
225group.add_option('--repo-branch',
226 dest='repo_branch',
227 help='repo branch or revision', metavar='REVISION')
228group.add_option('--no-repo-verify',
229 dest='no_repo_verify', action='store_true',
230 help='do not verify repo source code')
231
Victor Boivie841be342011-04-05 11:31:10 +0200232# Other
233group = init_optparse.add_option_group('Other options')
234group.add_option('--config-name',
235 dest='config_name', action="store_true", default=False,
236 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700237
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700238
239def _GitcInitOptions(init_optparse_arg):
240 init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
241 g = init_optparse_arg.add_option_group('GITC options')
Simran Basi1efc2b42015-08-05 15:04:22 -0700242 g.add_option('-f', '--manifest-file',
243 dest='manifest_file',
244 help='Optional manifest file to use for this GITC client.')
245 g.add_option('-c', '--gitc-client',
246 dest='gitc_client',
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700247 help='The name of the gitc_client instance to create or modify.')
Simran Basi1efc2b42015-08-05 15:04:22 -0700248
Simran Basi8ce50412015-08-28 14:25:44 -0700249_gitc_manifest_dir = None
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700250
251
Simran Basi8ce50412015-08-28 14:25:44 -0700252def get_gitc_manifest_dir():
253 global _gitc_manifest_dir
254 if _gitc_manifest_dir is None:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700255 _gitc_manifest_dir = ''
Simran Basi8ce50412015-08-28 14:25:44 -0700256 try:
257 with open(GITC_CONFIG_FILE, 'r') as gitc_config:
258 for line in gitc_config:
259 match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
260 if match:
261 _gitc_manifest_dir = match.group('gitc_manifest_dir')
262 except IOError:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700263 pass
Simran Basi8ce50412015-08-28 14:25:44 -0700264 return _gitc_manifest_dir
265
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700266
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700267def gitc_parse_clientdir(gitc_fs_path):
268 """Parse a path in the GITC FS and return its client name.
269
270 @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
271
272 @returns: The GITC client name
273 """
274 if gitc_fs_path == GITC_FS_ROOT_DIR:
275 return None
276 if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
277 manifest_dir = get_gitc_manifest_dir()
278 if manifest_dir == '':
279 return None
280 if manifest_dir[-1] != '/':
281 manifest_dir += '/'
282 if gitc_fs_path == manifest_dir:
283 return None
284 if not gitc_fs_path.startswith(manifest_dir):
285 return None
286 return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
287 return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
288
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700289
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700290class CloneFailure(Exception):
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700291
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700292 """Indicate the remote clone of repo itself failed.
293 """
294
295
Simran Basi1efc2b42015-08-05 15:04:22 -0700296def _Init(args, gitc_init=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700297 """Installs repo by cloning it over the network.
298 """
Simran Basi1efc2b42015-08-05 15:04:22 -0700299 if gitc_init:
300 _GitcInitOptions(init_optparse)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700301 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800302 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700303 init_optparse.print_usage()
304 sys.exit(1)
305
306 url = opt.repo_url
307 if not url:
308 url = REPO_URL
309 extra_args.append('--repo-url=%s' % url)
310
311 branch = opt.repo_branch
312 if not branch:
313 branch = REPO_REV
314 extra_args.append('--repo-branch=%s' % branch)
315
316 if branch.startswith('refs/heads/'):
317 branch = branch[len('refs/heads/'):]
318 if branch.startswith('refs/'):
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400319 print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700320 raise CloneFailure()
321
David Jamesbf79c662013-12-26 14:20:13 -0800322 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700323 if gitc_init:
Simran Basi8ce50412015-08-28 14:25:44 -0700324 gitc_manifest_dir = get_gitc_manifest_dir()
325 if not gitc_manifest_dir:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400326 print('fatal: GITC filesystem is not available. Exiting...',
327 file=sys.stderr)
Simran Basi8ce50412015-08-28 14:25:44 -0700328 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700329 gitc_client = opt.gitc_client
330 if not gitc_client:
331 gitc_client = gitc_parse_clientdir(os.getcwd())
332 if not gitc_client:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400333 print('fatal: GITC client (-c) is required.', file=sys.stderr)
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700334 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700335 client_dir = os.path.join(gitc_manifest_dir, gitc_client)
Simran Basi1efc2b42015-08-05 15:04:22 -0700336 if not os.path.exists(client_dir):
337 os.makedirs(client_dir)
338 os.chdir(client_dir)
339 if os.path.exists(repodir):
340 # This GITC Client has already initialized repo so continue.
341 return
342
David Jamesbf79c662013-12-26 14:20:13 -0800343 os.mkdir(repodir)
344 except OSError as e:
345 if e.errno != errno.EEXIST:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400346 print('fatal: cannot make %s directory: %s'
347 % (repodir, e.strerror), file=sys.stderr)
David Pursehouse3794a782012-11-15 06:17:30 +0900348 # Don't raise CloneFailure; that would delete the
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700349 # name. Instead exit immediately.
350 #
351 sys.exit(1)
352
353 _CheckGitVersion()
354 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700355 if NeedSetupGnuPG():
356 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700357 else:
358 can_verify = True
359
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700360 dst = os.path.abspath(os.path.join(repodir, S_repo))
Hu xiuyun9711a982015-12-11 11:16:41 +0800361 _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700362
363 if can_verify and not opt.no_repo_verify:
364 rev = _Verify(dst, branch, opt.quiet)
365 else:
366 rev = 'refs/remotes/origin/%s^0' % branch
367
368 _Checkout(dst, branch, rev, opt.quiet)
Sebastian Schuberth993dcac2018-07-13 10:25:52 +0200369
370 if not os.path.isfile(os.path.join(dst, 'repo')):
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400371 print("warning: '%s' does not look like a git-repo repository, is "
372 "REPO_URL set correctly?" % url, file=sys.stderr)
Sebastian Schuberth993dcac2018-07-13 10:25:52 +0200373
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700374 except CloneFailure:
375 if opt.quiet:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400376 print('fatal: repo init failed; run without --quiet to see why',
377 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700378 raise
379
380
Mike Frysinger6db1b9e2019-07-10 15:32:36 -0400381# The git version info broken down into components for easy analysis.
382# Similar to Python's sys.version_info.
383GitVersion = collections.namedtuple(
384 'GitVersion', ('major', 'minor', 'micro', 'full'))
385
Conley Owensff0a3c82014-01-30 14:46:03 -0800386def ParseGitVersion(ver_str):
387 if not ver_str.startswith('git version '):
388 return None
389
Mike Frysinger6db1b9e2019-07-10 15:32:36 -0400390 full_version = ver_str[len('git version '):].strip()
391 num_ver_str = full_version.split('-')[0]
Conley Owensff0a3c82014-01-30 14:46:03 -0800392 to_tuple = []
393 for num_str in num_ver_str.split('.')[:3]:
394 if num_str.isdigit():
395 to_tuple.append(int(num_str))
396 else:
397 to_tuple.append(0)
Mike Frysinger6db1b9e2019-07-10 15:32:36 -0400398 to_tuple.append(full_version)
399 return GitVersion(*to_tuple)
Conley Owensff0a3c82014-01-30 14:46:03 -0800400
401
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700402def _CheckGitVersion():
403 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700404 try:
405 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700406 except OSError as e:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400407 print(file=sys.stderr)
408 print("fatal: '%s' is not available" % GIT, file=sys.stderr)
409 print('fatal: %s' % e, file=sys.stderr)
410 print(file=sys.stderr)
411 print('Please make sure %s is installed and in your path.' % GIT,
412 file=sys.stderr)
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700413 raise CloneFailure()
414
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700415 ver_str = proc.stdout.read().strip()
416 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700417 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700418
Conley Owensff0a3c82014-01-30 14:46:03 -0800419 ver_act = ParseGitVersion(ver_str)
420 if ver_act is None:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400421 print('error: "%s" unsupported' % ver_str, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700422 raise CloneFailure()
423
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700424 if ver_act < MIN_GIT_VERSION:
David Pursehouse685f0802012-11-14 08:34:39 +0900425 need = '.'.join(map(str, MIN_GIT_VERSION))
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400426 print('fatal: git %s or later required' % need, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700427 raise CloneFailure()
428
429
Conley Owensc9129d92012-10-01 16:12:28 -0700430def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700431 if not os.path.isdir(home_dot_repo):
432 return True
433
434 kv = os.path.join(home_dot_repo, 'keyring-version')
435 if not os.path.exists(kv):
436 return True
437
438 kv = open(kv).read()
439 if not kv:
440 return True
441
David Pursehouse685f0802012-11-14 08:34:39 +0900442 kv = tuple(map(int, kv.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700443 if kv < KEYRING_VERSION:
444 return True
445 return False
446
447
Conley Owensc9129d92012-10-01 16:12:28 -0700448def SetupGnuPG(quiet):
David Jamesbf79c662013-12-26 14:20:13 -0800449 try:
450 os.mkdir(home_dot_repo)
451 except OSError as e:
452 if e.errno != errno.EEXIST:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400453 print('fatal: cannot make %s directory: %s'
454 % (home_dot_repo, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700455 sys.exit(1)
456
David Jamesbf79c662013-12-26 14:20:13 -0800457 try:
458 os.mkdir(gpg_dir, stat.S_IRWXU)
459 except OSError as e:
460 if e.errno != errno.EEXIST:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400461 print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
462 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700463 sys.exit(1)
464
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800465 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300466 try:
467 env['GNUPGHOME'] = gpg_dir
468 except UnicodeEncodeError:
469 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700470
471 cmd = ['gpg', '--import']
472 try:
473 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700474 env=env,
475 stdin=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700476 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700477 if not quiet:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400478 print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
479 print('warning: Installing it is strongly encouraged.', file=sys.stderr)
480 print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700481 return False
482
483 proc.stdin.write(MAINTAINER_KEYS)
484 proc.stdin.close()
485
486 if proc.wait() != 0:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400487 print('fatal: registering repo maintainer keys failed', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700488 sys.exit(1)
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400489 print()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700490
491 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
David Pursehouse685f0802012-11-14 08:34:39 +0900492 fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700493 fd.close()
494 return True
495
496
497def _SetConfig(local, name, value):
498 """Set a git configuration option to the specified value.
499 """
500 cmd = [GIT, 'config', name, value]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700501 if subprocess.Popen(cmd, cwd=local).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700502 raise CloneFailure()
503
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700504
505def _InitHttp():
506 handlers = []
507
Sarah Owens1f7627f2012-10-31 09:21:55 -0700508 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700509 try:
510 import netrc
511 n = netrc.netrc()
512 for host in n.hosts:
513 p = n.hosts[host]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700514 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800515 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
David Pursehouse65b0ba52018-06-24 16:21:51 +0900516 except:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700517 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700518 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
519 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700520
521 if 'http_proxy' in os.environ:
522 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700523 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700524 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700525 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
526 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
527 urllib.request.install_opener(urllib.request.build_opener(*handlers))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700528
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700529
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700530def _Fetch(url, local, src, quiet):
531 if not quiet:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400532 print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700533
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700534 cmd = [GIT, 'fetch']
535 if quiet:
536 cmd.append('--quiet')
537 err = subprocess.PIPE
538 else:
539 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700540 cmd.append(src)
541 cmd.append('+refs/heads/*:refs/remotes/origin/*')
Xin Li6e538442018-12-10 11:33:16 -0800542 cmd.append('+refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700543
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700544 proc = subprocess.Popen(cmd, cwd=local, stderr=err)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700545 if err:
546 proc.stderr.read()
547 proc.stderr.close()
548 if proc.wait() != 0:
549 raise CloneFailure()
550
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700551
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700552def _DownloadBundle(url, local, quiet):
553 if not url.endswith('/'):
554 url += '/'
555 url += 'clone.bundle'
556
557 proc = subprocess.Popen(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700558 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
559 cwd=local,
560 stdout=subprocess.PIPE)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700561 for line in proc.stdout:
562 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
563 if m:
564 new_url = m.group(1)
565 old_url = m.group(2)
566 if url.startswith(old_url):
567 url = new_url + url[len(old_url):]
568 break
569 proc.stdout.close()
570 proc.wait()
571
572 if not url.startswith('http:') and not url.startswith('https:'):
573 return False
574
575 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
576 try:
577 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700578 r = urllib.request.urlopen(url)
579 except urllib.error.HTTPError as e:
John Törnblomd3ddcdb2015-08-12 20:12:51 +0200580 if e.code in [401, 403, 404, 501]:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700581 return False
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400582 print('fatal: Cannot get %s' % url, file=sys.stderr)
583 print('fatal: HTTP error %s' % e.code, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700584 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700585 except urllib.error.URLError as e:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400586 print('fatal: Cannot get %s' % url, file=sys.stderr)
587 print('fatal: error %s' % e.reason, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700588 raise CloneFailure()
589 try:
590 if not quiet:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400591 print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700592 while True:
593 buf = r.read(8192)
Mike Frysinger1b9adab2019-07-04 17:54:54 -0400594 if not buf:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700595 return True
596 dest.write(buf)
597 finally:
598 r.close()
599 finally:
600 dest.close()
601
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700602
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700603def _ImportBundle(local):
604 path = os.path.join(local, '.git', 'clone.bundle')
605 try:
606 _Fetch(local, local, path, True)
607 finally:
608 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700609
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700610
Hu xiuyun9711a982015-12-11 11:16:41 +0800611def _Clone(url, local, quiet, clone_bundle):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700612 """Clones a git repository to a new subdirectory of repodir
613 """
614 try:
615 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700616 except OSError as e:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400617 print('fatal: cannot make %s directory: %s' % (local, e.strerror),
618 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700619 raise CloneFailure()
620
621 cmd = [GIT, 'init', '--quiet']
622 try:
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700623 proc = subprocess.Popen(cmd, cwd=local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700624 except OSError as e:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400625 print(file=sys.stderr)
626 print("fatal: '%s' is not available" % GIT, file=sys.stderr)
627 print('fatal: %s' % e, file=sys.stderr)
628 print(file=sys.stderr)
629 print('Please make sure %s is installed and in your path.' % GIT,
630 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700631 raise CloneFailure()
632 if proc.wait() != 0:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400633 print('fatal: could not create %s' % local, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700634 raise CloneFailure()
635
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700636 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700637 _SetConfig(local, 'remote.origin.url', url)
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700638 _SetConfig(local,
639 'remote.origin.fetch',
640 '+refs/heads/*:refs/remotes/origin/*')
Hu xiuyun9711a982015-12-11 11:16:41 +0800641 if clone_bundle and _DownloadBundle(url, local, quiet):
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700642 _ImportBundle(local)
Dan Willemsenfee390e2015-09-02 12:36:30 -0700643 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700644
645
646def _Verify(cwd, branch, quiet):
647 """Verify the branch has been signed by a tag.
648 """
649 cmd = [GIT, 'describe', 'origin/%s' % branch]
650 proc = subprocess.Popen(cmd,
651 stdout=subprocess.PIPE,
652 stderr=subprocess.PIPE,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700653 cwd=cwd)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700654 cur = proc.stdout.read().strip()
655 proc.stdout.close()
656
657 proc.stderr.read()
658 proc.stderr.close()
659
660 if proc.wait() != 0 or not cur:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400661 print(file=sys.stderr)
662 print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700663 raise CloneFailure()
664
665 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
666 if m:
667 cur = m.group(1)
668 if not quiet:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400669 print(file=sys.stderr)
670 print("info: Ignoring branch '%s'; using tagged release '%s'"
671 % (branch, cur), file=sys.stderr)
672 print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700673
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800674 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300675 try:
676 env['GNUPGHOME'] = gpg_dir
677 except UnicodeEncodeError:
678 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700679
680 cmd = [GIT, 'tag', '-v', cur]
681 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700682 stdout=subprocess.PIPE,
683 stderr=subprocess.PIPE,
684 cwd=cwd,
685 env=env)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700686 out = proc.stdout.read()
687 proc.stdout.close()
688
689 err = proc.stderr.read()
690 proc.stderr.close()
691
692 if proc.wait() != 0:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400693 print(file=sys.stderr)
694 print(out, file=sys.stderr)
695 print(err, file=sys.stderr)
696 print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700697 raise CloneFailure()
698 return '%s^0' % cur
699
700
701def _Checkout(cwd, branch, rev, quiet):
702 """Checkout an upstream branch into the repository and track it.
703 """
704 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700705 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700706 raise CloneFailure()
707
708 _SetConfig(cwd, 'branch.default.remote', 'origin')
709 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
710
711 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700712 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700713 raise CloneFailure()
714
715 cmd = [GIT, 'read-tree', '--reset', '-u']
716 if not quiet:
717 cmd.append('-v')
718 cmd.append('HEAD')
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700719 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700720 raise CloneFailure()
721
722
723def _FindRepo():
724 """Look for a repo installation, starting at the current directory.
725 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200726 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700727 repo = None
728
Anthony Newnamdf14a702011-01-09 17:31:57 -0800729 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200730 while curdir != '/' \
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700731 and curdir != olddir \
732 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200733 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700734 if not os.path.isfile(repo):
735 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200736 olddir = curdir
737 curdir = os.path.dirname(curdir)
738 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700739
740
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700741class _Options(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700742 help = False
743
744
745def _ParseArguments(args):
746 cmd = None
747 opt = _Options()
748 arg = []
749
Sarah Owensa6053d52012-11-01 13:36:50 -0700750 for i in range(len(args)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700751 a = args[i]
752 if a == '-h' or a == '--help':
753 opt.help = True
754
755 elif not a.startswith('-'):
756 cmd = a
757 arg = args[i + 1:]
758 break
759 return cmd, opt, arg
760
761
762def _Usage():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700763 gitc_usage = ""
764 if get_gitc_manifest_dir():
765 gitc_usage = " gitc-init Initialize a GITC Client.\n"
766
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400767 print(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700768 """usage: repo COMMAND [ARGS]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700769
770repo is not yet installed. Use "repo init" to install it here.
771
772The most commonly used repo commands are:
773
774 init Install repo in the current working directory
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700775""" + gitc_usage +
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700776 """ help Display detailed help on a command
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700777
778For access to the full online help, install repo ("repo init").
Mike Frysinger35159ab2019-06-13 00:07:13 -0400779""")
780 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700781
782
783def _Help(args):
784 if args:
785 if args[0] == 'init':
786 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100787 sys.exit(0)
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700788 elif args[0] == 'gitc-init':
789 _GitcInitOptions(init_optparse)
790 init_optparse.print_help()
791 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700792 else:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400793 print("error: '%s' is not a bootstrap command.\n"
794 ' For access to online help, install repo ("repo init").'
795 % args[0], file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700796 else:
797 _Usage()
798 sys.exit(1)
799
800
801def _NotInstalled():
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400802 print('error: repo is not installed. Use "repo init" to install it here.',
803 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700804 sys.exit(1)
805
806
807def _NoCommands(cmd):
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400808 print("""error: command '%s' requires repo to be installed first.
809 Use "repo init" to install it here.""" % cmd, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700810 sys.exit(1)
811
812
813def _RunSelf(wrapper_path):
814 my_dir = os.path.dirname(wrapper_path)
815 my_main = os.path.join(my_dir, 'main.py')
816 my_git = os.path.join(my_dir, '.git')
817
818 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700819 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700820 'project.py',
821 'subcmds']:
822 if not os.path.exists(os.path.join(my_dir, name)):
823 return None, None
824 return my_main, my_git
825 return None, None
826
827
828def _SetDefaultsTo(gitdir):
829 global REPO_URL
830 global REPO_REV
831
832 REPO_URL = gitdir
833 proc = subprocess.Popen([GIT,
834 '--git-dir=%s' % gitdir,
835 'symbolic-ref',
836 'HEAD'],
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700837 stdout=subprocess.PIPE,
838 stderr=subprocess.PIPE)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700839 REPO_REV = proc.stdout.read().strip()
840 proc.stdout.close()
841
842 proc.stderr.read()
843 proc.stderr.close()
844
845 if proc.wait() != 0:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400846 print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700847 sys.exit(1)
848
849
850def main(orig_args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700851 cmd, opt, args = _ParseArguments(orig_args)
852
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700853 repo_main, rel_repo_dir = None, None
854 # Don't use the local repo copy, make sure to switch to the gitc client first.
855 if cmd != 'gitc-init':
856 repo_main, rel_repo_dir = _FindRepo()
857
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700858 wrapper_path = os.path.abspath(__file__)
859 my_main, my_git = _RunSelf(wrapper_path)
860
Simran Basi8ce50412015-08-28 14:25:44 -0700861 cwd = os.getcwd()
Dan Willemsen2487cb72015-08-31 15:45:06 -0700862 if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400863 print('error: repo cannot be used in the GITC local manifest directory.'
864 '\nIf you want to work on this GITC client please rerun this '
865 'command from the corresponding client under /gitc/',
866 file=sys.stderr)
Simran Basi8ce50412015-08-28 14:25:44 -0700867 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200868 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700869 if opt.help:
870 _Usage()
871 if cmd == 'help':
872 _Help(args)
873 if not cmd:
874 _NotInstalled()
Simran Basi1efc2b42015-08-05 15:04:22 -0700875 if cmd == 'init' or cmd == 'gitc-init':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700876 if my_git:
877 _SetDefaultsTo(my_git)
878 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700879 _Init(args, gitc_init=(cmd == 'gitc-init'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700880 except CloneFailure:
Sebastian Schuberth27226e72016-10-28 14:27:43 +0200881 path = os.path.join(repodir, S_repo)
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400882 print("fatal: cloning the git-repo repository failed, will remove "
883 "'%s' " % path, file=sys.stderr)
Sebastian Schuberth27226e72016-10-28 14:27:43 +0200884 shutil.rmtree(path, ignore_errors=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700885 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200886 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700887 else:
888 _NoCommands(cmd)
889
890 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200891 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700892
David Pursehouse685f0802012-11-14 08:34:39 +0900893 ver_str = '.'.join(map(str, VERSION))
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300894 me = [sys.executable, repo_main,
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200895 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700896 '--wrapper-version=%s' % ver_str,
897 '--wrapper-path=%s' % wrapper_path,
898 '--']
899 me.extend(orig_args)
900 me.extend(extra_args)
901 try:
Renaud Paquay35d22212016-11-01 11:24:52 -0700902 if platform.system() == "Windows":
903 sys.exit(subprocess.call(me))
904 else:
905 os.execv(sys.executable, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700906 except OSError as e:
Mike Frysingerc92ce5c2019-06-13 01:14:23 -0400907 print("fatal: unable to start %s" % repo_main, file=sys.stderr)
908 print("fatal: %s" % e, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700909 sys.exit(148)
910
911
912if __name__ == '__main__':
913 main(sys.argv[1:])