blob: c1d861945a8054187a5f79f41c067549595949be [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
39mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
40WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
41VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
42xI1WfzLqdJjsm1Nq98L0cLcD/iNsILCuw44PRds3J75YP0pze7YF/6WFMB6QSFGu
43aUX1FsTTztKNXGms8i5b2l1B8JaLRWq/jOnZzyl1zrUJhkc0JgyZW5oNLGyWGhKD
44Fxp5YpHuIuMImopWEMFIRQNrvlg+YVK8t3FpdI1RY0LYqha8pPzANhEYgSfoVzOb
45fbfbA/4ioOrxy8ifSoga7ITyZMA+XbW8bx33WXutO9N7SPKS/AK2JpasSEVLZcON
46ae5hvAEGVXKxVPDjJBmIc2cOe7kOKSi3OxLzBqrjS2rnjiP4o0ekhZIe4+ocwVOg
47e0PLlH5avCqihGRhpoqDRsmpzSHzJIxtoeb+GgGEX8KkUsVAhbQpUmVwbyBNYWlu
48dGFpbmVyIDxyZXBvQGFuZHJvaWQua2VybmVsLm9yZz6IYAQTEQIAIAUCSPe6AQIb
49AwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEBZTDV6SD1xl1GEAn0x/OKQpy7qI
506G73NJviU0IUMtftAKCFMUhGb/0bZvQ8Rm3QCUpWHyEIu7kEDQRI97ogEBAA2wI6
515fs9y/rMwD6dkD/vK9v4C9mOn1IL5JCPYMJBVSci+9ED4ChzYvfq7wOcj9qIvaE0
52GwCt2ar7Q56me5J+byhSb32Rqsw/r3Vo5cZMH80N4cjesGuSXOGyEWTe4HYoxnHv
53gF4EKI2LK7xfTUcxMtlyn52sUpkfKsCpUhFvdmbAiJE+jCkQZr1Z8u2KphV79Ou+
54P1N5IXY/XWOlq48Qf4MWCYlJFrB07xjUjLKMPDNDnm58L5byDrP/eHysKexpbakL
55xCmYyfT6DV1SWLblpd2hie0sL3YejdtuBMYMS2rI7Yxb8kGuqkz+9l1qhwJtei94
565MaretDy/d/JH/pRYkRf7L+ke7dpzrP+aJmcz9P1e6gq4NJsWejaALVASBiioqNf
57QmtqSVzF1wkR5avZkFHuYvj6V/t1RrOZTXxkSk18KFMJRBZrdHFCWbc5qrVxUB6e
58N5pja0NFIUCigLBV1c6I2DwiuboMNh18VtJJh+nwWeez/RueN4ig59gRTtkcc0PR
5935tX2DR8+xCCFVW/NcJ4PSePYzCuuLvp1vEDHnj41R52Fz51hgddT4rBsp0nL+5I
60socSOIIezw8T9vVzMY4ArCKFAVu2IVyBcahTfBS8q5EM63mONU6UVJEozfGljiMw
61xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
62ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
63Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
64FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
65+WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
66w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
67Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
68p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
690V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
705xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
71HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
72zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
73TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
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
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700123import re
Mitchel Humpheryseb5acc92014-03-12 10:48:15 -0700124import shutil
Sarah Owens60798a32012-10-25 17:53:09 -0700125import stat
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126import subprocess
127import sys
David Pursehouse59bbb582013-05-17 10:49:33 +0900128
129if sys.version_info[0] == 3:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700130 import urllib.request
131 import urllib.error
132else:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700133 import imp
David Pursehouse59bbb582013-05-17 10:49:33 +0900134 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -0700135 urllib = imp.new_module('urllib')
136 urllib.request = urllib2
137 urllib.error = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700138
Conley Owens5e0ee142013-09-26 15:50:49 -0700139
140def _print(*objects, **kwargs):
141 sep = kwargs.get('sep', ' ')
142 end = kwargs.get('end', '\n')
143 out = kwargs.get('file', sys.stdout)
144 out.write(sep.join(objects) + end)
145
146
Chirayu Desai51813df2013-04-16 19:36:09 +0530147# Python version check
148ver = sys.version_info
Chirayu Desai51813df2013-04-16 19:36:09 +0530149if (ver[0], ver[1]) < MIN_PYTHON_VERSION:
Conley Owens5e0ee142013-09-26 15:50:49 -0700150 _print('error: Python version %s unsupported.\n'
151 'Please use Python 2.6 - 2.7 instead.'
152 % sys.version.split(' ')[0], file=sys.stderr)
Chirayu Desai51813df2013-04-16 19:36:09 +0530153 sys.exit(1)
154
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700155home_dot_repo = os.path.expanduser('~/.repoconfig')
156gpg_dir = os.path.join(home_dot_repo, 'gnupg')
157
158extra_args = []
159init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
160
161# Logging
162group = init_optparse.add_option_group('Logging options')
163group.add_option('-q', '--quiet',
164 dest="quiet", action="store_true", default=False,
165 help="be quiet")
166
167# Manifest
168group = init_optparse.add_option_group('Manifest options')
169group.add_option('-u', '--manifest-url',
170 dest='manifest_url',
171 help='manifest repository location', metavar='URL')
172group.add_option('-b', '--manifest-branch',
173 dest='manifest_branch',
174 help='manifest branch or revision', metavar='REVISION')
175group.add_option('-m', '--manifest-name',
176 dest='manifest_name',
177 help='initial manifest file', metavar='NAME.xml')
Naseer Ahmedf4dda9a2016-12-01 18:49:54 -0500178group.add_option('-c', '--current-branch',
179 dest='current_branch_only', action='store_true',
180 help='fetch only current manifest branch from server')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800181group.add_option('--mirror',
182 dest='mirror', action='store_true',
David Pursehouse3794a782012-11-15 06:17:30 +0900183 help='create a replica of the remote repositories '
184 'rather than a client working directory')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200185group.add_option('--reference',
186 dest='reference',
187 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700188group.add_option('--depth', type='int', default=None,
189 dest='depth',
190 help='create a shallow clone with given depth; see git clone')
Julien Campergue335f5ef2013-10-16 11:02:35 +0200191group.add_option('--archive',
192 dest='archive', action='store_true',
193 help='checkout an archive instead of a git repository for '
194 'each project. See git archive.')
Martin Kellye4e94d22017-03-21 16:05:12 -0700195group.add_option('--submodules',
196 dest='submodules', action='store_true',
197 help='sync any submodules associated with the manifest repo')
Colin Cross5acde752012-03-28 20:15:45 -0700198group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700199 dest='groups', default='default',
David Holmer0a1c6a12012-11-14 19:19:00 -0500200 help='restrict manifest projects to ones with specified '
201 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
Colin Cross5acde752012-03-28 20:15:45 -0700202 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700203group.add_option('-p', '--platform',
204 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700205 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700206 'platform group [auto|all|none|linux|darwin|...]',
207 metavar='PLATFORM')
Hu xiuyun9711a982015-12-11 11:16:41 +0800208group.add_option('--no-clone-bundle',
209 dest='no_clone_bundle', action='store_true',
210 help='disable use of /clone.bundle on HTTP/HTTPS')
Naseer Ahmedf4dda9a2016-12-01 18:49:54 -0500211group.add_option('--no-tags',
212 dest='no_tags', action='store_true',
213 help="don't fetch tags in the manifest")
Doug Anderson49cd59b2011-06-13 21:42:06 -0700214
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700215
216# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700217group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218group.add_option('--repo-url',
219 dest='repo_url',
220 help='repo repository location', metavar='URL')
221group.add_option('--repo-branch',
222 dest='repo_branch',
223 help='repo branch or revision', metavar='REVISION')
224group.add_option('--no-repo-verify',
225 dest='no_repo_verify', action='store_true',
226 help='do not verify repo source code')
227
Victor Boivie841be342011-04-05 11:31:10 +0200228# Other
229group = init_optparse.add_option_group('Other options')
230group.add_option('--config-name',
231 dest='config_name', action="store_true", default=False,
232 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700233
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700234
235def _GitcInitOptions(init_optparse_arg):
236 init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
237 g = init_optparse_arg.add_option_group('GITC options')
Simran Basi1efc2b42015-08-05 15:04:22 -0700238 g.add_option('-f', '--manifest-file',
239 dest='manifest_file',
240 help='Optional manifest file to use for this GITC client.')
241 g.add_option('-c', '--gitc-client',
242 dest='gitc_client',
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700243 help='The name of the gitc_client instance to create or modify.')
Simran Basi1efc2b42015-08-05 15:04:22 -0700244
Simran Basi8ce50412015-08-28 14:25:44 -0700245_gitc_manifest_dir = None
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700246
247
Simran Basi8ce50412015-08-28 14:25:44 -0700248def get_gitc_manifest_dir():
249 global _gitc_manifest_dir
250 if _gitc_manifest_dir is None:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700251 _gitc_manifest_dir = ''
Simran Basi8ce50412015-08-28 14:25:44 -0700252 try:
253 with open(GITC_CONFIG_FILE, 'r') as gitc_config:
254 for line in gitc_config:
255 match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
256 if match:
257 _gitc_manifest_dir = match.group('gitc_manifest_dir')
258 except IOError:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700259 pass
Simran Basi8ce50412015-08-28 14:25:44 -0700260 return _gitc_manifest_dir
261
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700262
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700263def gitc_parse_clientdir(gitc_fs_path):
264 """Parse a path in the GITC FS and return its client name.
265
266 @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
267
268 @returns: The GITC client name
269 """
270 if gitc_fs_path == GITC_FS_ROOT_DIR:
271 return None
272 if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
273 manifest_dir = get_gitc_manifest_dir()
274 if manifest_dir == '':
275 return None
276 if manifest_dir[-1] != '/':
277 manifest_dir += '/'
278 if gitc_fs_path == manifest_dir:
279 return None
280 if not gitc_fs_path.startswith(manifest_dir):
281 return None
282 return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
283 return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
284
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700285
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700286class CloneFailure(Exception):
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700287
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700288 """Indicate the remote clone of repo itself failed.
289 """
290
291
Simran Basi1efc2b42015-08-05 15:04:22 -0700292def _Init(args, gitc_init=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700293 """Installs repo by cloning it over the network.
294 """
Simran Basi1efc2b42015-08-05 15:04:22 -0700295 if gitc_init:
296 _GitcInitOptions(init_optparse)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700297 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800298 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700299 init_optparse.print_usage()
300 sys.exit(1)
301
302 url = opt.repo_url
303 if not url:
304 url = REPO_URL
305 extra_args.append('--repo-url=%s' % url)
306
307 branch = opt.repo_branch
308 if not branch:
309 branch = REPO_REV
310 extra_args.append('--repo-branch=%s' % branch)
311
312 if branch.startswith('refs/heads/'):
313 branch = branch[len('refs/heads/'):]
314 if branch.startswith('refs/'):
Conley Owens5e0ee142013-09-26 15:50:49 -0700315 _print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700316 raise CloneFailure()
317
David Jamesbf79c662013-12-26 14:20:13 -0800318 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700319 if gitc_init:
Simran Basi8ce50412015-08-28 14:25:44 -0700320 gitc_manifest_dir = get_gitc_manifest_dir()
321 if not gitc_manifest_dir:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700322 _print('fatal: GITC filesystem is not available. Exiting...',
Simran Basi8ce50412015-08-28 14:25:44 -0700323 file=sys.stderr)
324 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700325 gitc_client = opt.gitc_client
326 if not gitc_client:
327 gitc_client = gitc_parse_clientdir(os.getcwd())
328 if not gitc_client:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700329 _print('fatal: GITC client (-c) is required.', file=sys.stderr)
330 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700331 client_dir = os.path.join(gitc_manifest_dir, gitc_client)
Simran Basi1efc2b42015-08-05 15:04:22 -0700332 if not os.path.exists(client_dir):
333 os.makedirs(client_dir)
334 os.chdir(client_dir)
335 if os.path.exists(repodir):
336 # This GITC Client has already initialized repo so continue.
337 return
338
David Jamesbf79c662013-12-26 14:20:13 -0800339 os.mkdir(repodir)
340 except OSError as e:
341 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700342 _print('fatal: cannot make %s directory: %s'
343 % (repodir, e.strerror), file=sys.stderr)
David Pursehouse3794a782012-11-15 06:17:30 +0900344 # Don't raise CloneFailure; that would delete the
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700345 # name. Instead exit immediately.
346 #
347 sys.exit(1)
348
349 _CheckGitVersion()
350 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700351 if NeedSetupGnuPG():
352 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700353 else:
354 can_verify = True
355
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700356 dst = os.path.abspath(os.path.join(repodir, S_repo))
Hu xiuyun9711a982015-12-11 11:16:41 +0800357 _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700358
Sebastian Schuberth27226e72016-10-28 14:27:43 +0200359 if not os.path.isfile('%s/repo' % dst):
360 _print("warning: '%s' does not look like a git-repo repository, is "
361 "REPO_URL set correctly?" % url, file=sys.stderr)
362
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700363 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)
369 except CloneFailure:
370 if opt.quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700371 _print('fatal: repo init failed; run without --quiet to see why',
372 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700373 raise
374
375
Conley Owensff0a3c82014-01-30 14:46:03 -0800376def ParseGitVersion(ver_str):
377 if not ver_str.startswith('git version '):
378 return None
379
380 num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
381 to_tuple = []
382 for num_str in num_ver_str.split('.')[:3]:
383 if num_str.isdigit():
384 to_tuple.append(int(num_str))
385 else:
386 to_tuple.append(0)
387 return tuple(to_tuple)
388
389
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700390def _CheckGitVersion():
391 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700392 try:
393 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700394 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700395 _print(file=sys.stderr)
396 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
397 _print('fatal: %s' % e, file=sys.stderr)
398 _print(file=sys.stderr)
399 _print('Please make sure %s is installed and in your path.' % GIT,
400 file=sys.stderr)
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700401 raise CloneFailure()
402
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700403 ver_str = proc.stdout.read().strip()
404 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700405 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700406
Conley Owensff0a3c82014-01-30 14:46:03 -0800407 ver_act = ParseGitVersion(ver_str)
408 if ver_act is None:
Conley Owens5e0ee142013-09-26 15:50:49 -0700409 _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700410 raise CloneFailure()
411
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700412 if ver_act < MIN_GIT_VERSION:
David Pursehouse685f0802012-11-14 08:34:39 +0900413 need = '.'.join(map(str, MIN_GIT_VERSION))
Conley Owens5e0ee142013-09-26 15:50:49 -0700414 _print('fatal: git %s or later required' % need, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700415 raise CloneFailure()
416
417
Conley Owensc9129d92012-10-01 16:12:28 -0700418def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700419 if not os.path.isdir(home_dot_repo):
420 return True
421
422 kv = os.path.join(home_dot_repo, 'keyring-version')
423 if not os.path.exists(kv):
424 return True
425
426 kv = open(kv).read()
427 if not kv:
428 return True
429
David Pursehouse685f0802012-11-14 08:34:39 +0900430 kv = tuple(map(int, kv.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700431 if kv < KEYRING_VERSION:
432 return True
433 return False
434
435
Conley Owensc9129d92012-10-01 16:12:28 -0700436def SetupGnuPG(quiet):
David Jamesbf79c662013-12-26 14:20:13 -0800437 try:
438 os.mkdir(home_dot_repo)
439 except OSError as e:
440 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700441 _print('fatal: cannot make %s directory: %s'
442 % (home_dot_repo, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700443 sys.exit(1)
444
David Jamesbf79c662013-12-26 14:20:13 -0800445 try:
446 os.mkdir(gpg_dir, stat.S_IRWXU)
447 except OSError as e:
448 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700449 _print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
450 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700451 sys.exit(1)
452
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800453 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300454 try:
455 env['GNUPGHOME'] = gpg_dir
456 except UnicodeEncodeError:
457 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700458
459 cmd = ['gpg', '--import']
460 try:
461 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700462 env=env,
463 stdin=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700464 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700465 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700466 _print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
467 _print('warning: Installing it is strongly encouraged.', file=sys.stderr)
468 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700469 return False
470
471 proc.stdin.write(MAINTAINER_KEYS)
472 proc.stdin.close()
473
474 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700475 _print('fatal: registering repo maintainer keys failed', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700476 sys.exit(1)
Conley Owens5e0ee142013-09-26 15:50:49 -0700477 _print()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700478
479 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
David Pursehouse685f0802012-11-14 08:34:39 +0900480 fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700481 fd.close()
482 return True
483
484
485def _SetConfig(local, name, value):
486 """Set a git configuration option to the specified value.
487 """
488 cmd = [GIT, 'config', name, value]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700489 if subprocess.Popen(cmd, cwd=local).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700490 raise CloneFailure()
491
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700492
493def _InitHttp():
494 handlers = []
495
Sarah Owens1f7627f2012-10-31 09:21:55 -0700496 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700497 try:
498 import netrc
499 n = netrc.netrc()
500 for host in n.hosts:
501 p = n.hosts[host]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700502 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800503 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700504 except: # pylint: disable=bare-except
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700505 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700506 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
507 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700508
509 if 'http_proxy' in os.environ:
510 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700511 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700512 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700513 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
514 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
515 urllib.request.install_opener(urllib.request.build_opener(*handlers))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700516
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700517
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700518def _Fetch(url, local, src, quiet):
519 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700520 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700521
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700522 cmd = [GIT, 'fetch']
523 if quiet:
524 cmd.append('--quiet')
525 err = subprocess.PIPE
526 else:
527 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700528 cmd.append(src)
529 cmd.append('+refs/heads/*:refs/remotes/origin/*')
530 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700531
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700532 proc = subprocess.Popen(cmd, cwd=local, stderr=err)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700533 if err:
534 proc.stderr.read()
535 proc.stderr.close()
536 if proc.wait() != 0:
537 raise CloneFailure()
538
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700539
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700540def _DownloadBundle(url, local, quiet):
541 if not url.endswith('/'):
542 url += '/'
543 url += 'clone.bundle'
544
545 proc = subprocess.Popen(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700546 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
547 cwd=local,
548 stdout=subprocess.PIPE)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700549 for line in proc.stdout:
550 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
551 if m:
552 new_url = m.group(1)
553 old_url = m.group(2)
554 if url.startswith(old_url):
555 url = new_url + url[len(old_url):]
556 break
557 proc.stdout.close()
558 proc.wait()
559
560 if not url.startswith('http:') and not url.startswith('https:'):
561 return False
562
563 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
564 try:
565 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700566 r = urllib.request.urlopen(url)
567 except urllib.error.HTTPError as e:
John Törnblomd3ddcdb2015-08-12 20:12:51 +0200568 if e.code in [401, 403, 404, 501]:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700569 return False
Conley Owens5e0ee142013-09-26 15:50:49 -0700570 _print('fatal: Cannot get %s' % url, file=sys.stderr)
571 _print('fatal: HTTP error %s' % e.code, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700572 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700573 except urllib.error.URLError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700574 _print('fatal: Cannot get %s' % url, file=sys.stderr)
575 _print('fatal: error %s' % e.reason, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700576 raise CloneFailure()
577 try:
578 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700579 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700580 while True:
581 buf = r.read(8192)
582 if buf == '':
583 return True
584 dest.write(buf)
585 finally:
586 r.close()
587 finally:
588 dest.close()
589
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700590
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700591def _ImportBundle(local):
592 path = os.path.join(local, '.git', 'clone.bundle')
593 try:
594 _Fetch(local, local, path, True)
595 finally:
596 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700597
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700598
Hu xiuyun9711a982015-12-11 11:16:41 +0800599def _Clone(url, local, quiet, clone_bundle):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700600 """Clones a git repository to a new subdirectory of repodir
601 """
602 try:
603 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700604 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700605 _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
606 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700607 raise CloneFailure()
608
609 cmd = [GIT, 'init', '--quiet']
610 try:
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700611 proc = subprocess.Popen(cmd, cwd=local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700612 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700613 _print(file=sys.stderr)
614 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
615 _print('fatal: %s' % e, file=sys.stderr)
616 _print(file=sys.stderr)
617 _print('Please make sure %s is installed and in your path.' % GIT,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700618 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700619 raise CloneFailure()
620 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700621 _print('fatal: could not create %s' % local, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700622 raise CloneFailure()
623
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700624 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700625 _SetConfig(local, 'remote.origin.url', url)
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700626 _SetConfig(local,
627 'remote.origin.fetch',
628 '+refs/heads/*:refs/remotes/origin/*')
Hu xiuyun9711a982015-12-11 11:16:41 +0800629 if clone_bundle and _DownloadBundle(url, local, quiet):
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700630 _ImportBundle(local)
Dan Willemsenfee390e2015-09-02 12:36:30 -0700631 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700632
633
634def _Verify(cwd, branch, quiet):
635 """Verify the branch has been signed by a tag.
636 """
637 cmd = [GIT, 'describe', 'origin/%s' % branch]
638 proc = subprocess.Popen(cmd,
639 stdout=subprocess.PIPE,
640 stderr=subprocess.PIPE,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700641 cwd=cwd)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700642 cur = proc.stdout.read().strip()
643 proc.stdout.close()
644
645 proc.stderr.read()
646 proc.stderr.close()
647
648 if proc.wait() != 0 or not cur:
Conley Owens5e0ee142013-09-26 15:50:49 -0700649 _print(file=sys.stderr)
650 _print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700651 raise CloneFailure()
652
653 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
654 if m:
655 cur = m.group(1)
656 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700657 _print(file=sys.stderr)
658 _print("info: Ignoring branch '%s'; using tagged release '%s'"
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700659 % (branch, cur), file=sys.stderr)
Conley Owens5e0ee142013-09-26 15:50:49 -0700660 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700661
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800662 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300663 try:
664 env['GNUPGHOME'] = gpg_dir
665 except UnicodeEncodeError:
666 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700667
668 cmd = [GIT, 'tag', '-v', cur]
669 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700670 stdout=subprocess.PIPE,
671 stderr=subprocess.PIPE,
672 cwd=cwd,
673 env=env)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700674 out = proc.stdout.read()
675 proc.stdout.close()
676
677 err = proc.stderr.read()
678 proc.stderr.close()
679
680 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700681 _print(file=sys.stderr)
682 _print(out, file=sys.stderr)
683 _print(err, file=sys.stderr)
684 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700685 raise CloneFailure()
686 return '%s^0' % cur
687
688
689def _Checkout(cwd, branch, rev, quiet):
690 """Checkout an upstream branch into the repository and track it.
691 """
692 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700693 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700694 raise CloneFailure()
695
696 _SetConfig(cwd, 'branch.default.remote', 'origin')
697 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
698
699 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700700 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700701 raise CloneFailure()
702
703 cmd = [GIT, 'read-tree', '--reset', '-u']
704 if not quiet:
705 cmd.append('-v')
706 cmd.append('HEAD')
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700707 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700708 raise CloneFailure()
709
710
711def _FindRepo():
712 """Look for a repo installation, starting at the current directory.
713 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200714 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700715 repo = None
716
Anthony Newnamdf14a702011-01-09 17:31:57 -0800717 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200718 while curdir != '/' \
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700719 and curdir != olddir \
720 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200721 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700722 if not os.path.isfile(repo):
723 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200724 olddir = curdir
725 curdir = os.path.dirname(curdir)
726 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700727
728
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700729class _Options(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700730 help = False
731
732
733def _ParseArguments(args):
734 cmd = None
735 opt = _Options()
736 arg = []
737
Sarah Owensa6053d52012-11-01 13:36:50 -0700738 for i in range(len(args)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700739 a = args[i]
740 if a == '-h' or a == '--help':
741 opt.help = True
742
743 elif not a.startswith('-'):
744 cmd = a
745 arg = args[i + 1:]
746 break
747 return cmd, opt, arg
748
749
750def _Usage():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700751 gitc_usage = ""
752 if get_gitc_manifest_dir():
753 gitc_usage = " gitc-init Initialize a GITC Client.\n"
754
Conley Owens5e0ee142013-09-26 15:50:49 -0700755 _print(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700756 """usage: repo COMMAND [ARGS]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700757
758repo is not yet installed. Use "repo init" to install it here.
759
760The most commonly used repo commands are:
761
762 init Install repo in the current working directory
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700763""" + gitc_usage +
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700764 """ help Display detailed help on a command
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700765
766For access to the full online help, install repo ("repo init").
Sarah Owenscecd1d82012-11-01 22:59:27 -0700767""", file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700768 sys.exit(1)
769
770
771def _Help(args):
772 if args:
773 if args[0] == 'init':
774 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100775 sys.exit(0)
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700776 elif args[0] == 'gitc-init':
777 _GitcInitOptions(init_optparse)
778 init_optparse.print_help()
779 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700780 else:
Conley Owens5e0ee142013-09-26 15:50:49 -0700781 _print("error: '%s' is not a bootstrap command.\n"
782 ' For access to online help, install repo ("repo init").'
783 % args[0], file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700784 else:
785 _Usage()
786 sys.exit(1)
787
788
789def _NotInstalled():
Conley Owens5e0ee142013-09-26 15:50:49 -0700790 _print('error: repo is not installed. Use "repo init" to install it here.',
791 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700792 sys.exit(1)
793
794
795def _NoCommands(cmd):
Conley Owens5e0ee142013-09-26 15:50:49 -0700796 _print("""error: command '%s' requires repo to be installed first.
797 Use "repo init" to install it here.""" % cmd, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700798 sys.exit(1)
799
800
801def _RunSelf(wrapper_path):
802 my_dir = os.path.dirname(wrapper_path)
803 my_main = os.path.join(my_dir, 'main.py')
804 my_git = os.path.join(my_dir, '.git')
805
806 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700807 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700808 'project.py',
809 'subcmds']:
810 if not os.path.exists(os.path.join(my_dir, name)):
811 return None, None
812 return my_main, my_git
813 return None, None
814
815
816def _SetDefaultsTo(gitdir):
817 global REPO_URL
818 global REPO_REV
819
820 REPO_URL = gitdir
821 proc = subprocess.Popen([GIT,
822 '--git-dir=%s' % gitdir,
823 'symbolic-ref',
824 'HEAD'],
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700825 stdout=subprocess.PIPE,
826 stderr=subprocess.PIPE)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700827 REPO_REV = proc.stdout.read().strip()
828 proc.stdout.close()
829
830 proc.stderr.read()
831 proc.stderr.close()
832
833 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700834 _print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700835 sys.exit(1)
836
837
838def main(orig_args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700839 cmd, opt, args = _ParseArguments(orig_args)
840
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700841 repo_main, rel_repo_dir = None, None
842 # Don't use the local repo copy, make sure to switch to the gitc client first.
843 if cmd != 'gitc-init':
844 repo_main, rel_repo_dir = _FindRepo()
845
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700846 wrapper_path = os.path.abspath(__file__)
847 my_main, my_git = _RunSelf(wrapper_path)
848
Simran Basi8ce50412015-08-28 14:25:44 -0700849 cwd = os.getcwd()
Dan Willemsen2487cb72015-08-31 15:45:06 -0700850 if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
Simran Basi8ce50412015-08-28 14:25:44 -0700851 _print('error: repo cannot be used in the GITC local manifest directory.'
852 '\nIf you want to work on this GITC client please rerun this '
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700853 'command from the corresponding client under /gitc/',
854 file=sys.stderr)
Simran Basi8ce50412015-08-28 14:25:44 -0700855 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200856 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700857 if opt.help:
858 _Usage()
859 if cmd == 'help':
860 _Help(args)
861 if not cmd:
862 _NotInstalled()
Simran Basi1efc2b42015-08-05 15:04:22 -0700863 if cmd == 'init' or cmd == 'gitc-init':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700864 if my_git:
865 _SetDefaultsTo(my_git)
866 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700867 _Init(args, gitc_init=(cmd == 'gitc-init'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700868 except CloneFailure:
Sebastian Schuberth27226e72016-10-28 14:27:43 +0200869 path = os.path.join(repodir, S_repo)
870 _print("fatal: cloning the git-repo repository failed, will remove "
871 "'%s' " % path, file=sys.stderr)
872 shutil.rmtree(path, ignore_errors=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700873 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200874 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700875 else:
876 _NoCommands(cmd)
877
878 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200879 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700880
David Pursehouse685f0802012-11-14 08:34:39 +0900881 ver_str = '.'.join(map(str, VERSION))
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300882 me = [sys.executable, repo_main,
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200883 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700884 '--wrapper-version=%s' % ver_str,
885 '--wrapper-path=%s' % wrapper_path,
886 '--']
887 me.extend(orig_args)
888 me.extend(extra_args)
889 try:
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300890 os.execv(sys.executable, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700891 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700892 _print("fatal: unable to start %s" % repo_main, file=sys.stderr)
893 _print("fatal: %s" % e, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700894 sys.exit(148)
895
896
897if __name__ == '__main__':
Anthony King6efdde92014-05-05 20:37:05 +0100898 if ver[0] == 3:
899 _print('warning: Python 3 support is currently experimental. YMMV.\n'
900 'Please use Python 2.6 - 2.7 instead.',
901 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700902 main(sys.argv[1:])