blob: acaa9c4c28fa0faa363bc2fee0c054b7a486062f [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
David Pursehousec4c2b062016-08-17 13:16:31 +090026VERSION = (1, 23)
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')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800178group.add_option('--mirror',
179 dest='mirror', action='store_true',
David Pursehouse3794a782012-11-15 06:17:30 +0900180 help='create a replica of the remote repositories '
181 'rather than a client working directory')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200182group.add_option('--reference',
183 dest='reference',
184 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700185group.add_option('--depth', type='int', default=None,
186 dest='depth',
187 help='create a shallow clone with given depth; see git clone')
Julien Campergue335f5ef2013-10-16 11:02:35 +0200188group.add_option('--archive',
189 dest='archive', action='store_true',
190 help='checkout an archive instead of a git repository for '
191 'each project. See git archive.')
Colin Cross5acde752012-03-28 20:15:45 -0700192group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700193 dest='groups', default='default',
David Holmer0a1c6a12012-11-14 19:19:00 -0500194 help='restrict manifest projects to ones with specified '
195 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
Colin Cross5acde752012-03-28 20:15:45 -0700196 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700197group.add_option('-p', '--platform',
198 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700199 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700200 'platform group [auto|all|none|linux|darwin|...]',
201 metavar='PLATFORM')
Hu xiuyun9711a982015-12-11 11:16:41 +0800202group.add_option('--no-clone-bundle',
203 dest='no_clone_bundle', action='store_true',
204 help='disable use of /clone.bundle on HTTP/HTTPS')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700205
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700206
207# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700208group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700209group.add_option('--repo-url',
210 dest='repo_url',
211 help='repo repository location', metavar='URL')
212group.add_option('--repo-branch',
213 dest='repo_branch',
214 help='repo branch or revision', metavar='REVISION')
215group.add_option('--no-repo-verify',
216 dest='no_repo_verify', action='store_true',
217 help='do not verify repo source code')
218
Victor Boivie841be342011-04-05 11:31:10 +0200219# Other
220group = init_optparse.add_option_group('Other options')
221group.add_option('--config-name',
222 dest='config_name', action="store_true", default=False,
223 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700224
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700225
226def _GitcInitOptions(init_optparse_arg):
227 init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
228 g = init_optparse_arg.add_option_group('GITC options')
Simran Basi1efc2b42015-08-05 15:04:22 -0700229 g.add_option('-f', '--manifest-file',
230 dest='manifest_file',
231 help='Optional manifest file to use for this GITC client.')
232 g.add_option('-c', '--gitc-client',
233 dest='gitc_client',
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700234 help='The name of the gitc_client instance to create or modify.')
Simran Basi1efc2b42015-08-05 15:04:22 -0700235
Simran Basi8ce50412015-08-28 14:25:44 -0700236_gitc_manifest_dir = None
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700237
238
Simran Basi8ce50412015-08-28 14:25:44 -0700239def get_gitc_manifest_dir():
240 global _gitc_manifest_dir
241 if _gitc_manifest_dir is None:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700242 _gitc_manifest_dir = ''
Simran Basi8ce50412015-08-28 14:25:44 -0700243 try:
244 with open(GITC_CONFIG_FILE, 'r') as gitc_config:
245 for line in gitc_config:
246 match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
247 if match:
248 _gitc_manifest_dir = match.group('gitc_manifest_dir')
249 except IOError:
Dan Willemsen2487cb72015-08-31 15:45:06 -0700250 pass
Simran Basi8ce50412015-08-28 14:25:44 -0700251 return _gitc_manifest_dir
252
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700253
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700254def gitc_parse_clientdir(gitc_fs_path):
255 """Parse a path in the GITC FS and return its client name.
256
257 @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
258
259 @returns: The GITC client name
260 """
261 if gitc_fs_path == GITC_FS_ROOT_DIR:
262 return None
263 if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
264 manifest_dir = get_gitc_manifest_dir()
265 if manifest_dir == '':
266 return None
267 if manifest_dir[-1] != '/':
268 manifest_dir += '/'
269 if gitc_fs_path == manifest_dir:
270 return None
271 if not gitc_fs_path.startswith(manifest_dir):
272 return None
273 return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
274 return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
275
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700276
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700277class CloneFailure(Exception):
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700278
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700279 """Indicate the remote clone of repo itself failed.
280 """
281
282
Simran Basi1efc2b42015-08-05 15:04:22 -0700283def _Init(args, gitc_init=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700284 """Installs repo by cloning it over the network.
285 """
Simran Basi1efc2b42015-08-05 15:04:22 -0700286 if gitc_init:
287 _GitcInitOptions(init_optparse)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700288 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800289 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700290 init_optparse.print_usage()
291 sys.exit(1)
292
293 url = opt.repo_url
294 if not url:
295 url = REPO_URL
296 extra_args.append('--repo-url=%s' % url)
297
298 branch = opt.repo_branch
299 if not branch:
300 branch = REPO_REV
301 extra_args.append('--repo-branch=%s' % branch)
302
303 if branch.startswith('refs/heads/'):
304 branch = branch[len('refs/heads/'):]
305 if branch.startswith('refs/'):
Conley Owens5e0ee142013-09-26 15:50:49 -0700306 _print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700307 raise CloneFailure()
308
David Jamesbf79c662013-12-26 14:20:13 -0800309 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700310 if gitc_init:
Simran Basi8ce50412015-08-28 14:25:44 -0700311 gitc_manifest_dir = get_gitc_manifest_dir()
312 if not gitc_manifest_dir:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700313 _print('fatal: GITC filesystem is not available. Exiting...',
Simran Basi8ce50412015-08-28 14:25:44 -0700314 file=sys.stderr)
315 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700316 gitc_client = opt.gitc_client
317 if not gitc_client:
318 gitc_client = gitc_parse_clientdir(os.getcwd())
319 if not gitc_client:
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700320 _print('fatal: GITC client (-c) is required.', file=sys.stderr)
321 sys.exit(1)
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700322 client_dir = os.path.join(gitc_manifest_dir, gitc_client)
Simran Basi1efc2b42015-08-05 15:04:22 -0700323 if not os.path.exists(client_dir):
324 os.makedirs(client_dir)
325 os.chdir(client_dir)
326 if os.path.exists(repodir):
327 # This GITC Client has already initialized repo so continue.
328 return
329
David Jamesbf79c662013-12-26 14:20:13 -0800330 os.mkdir(repodir)
331 except OSError as e:
332 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700333 _print('fatal: cannot make %s directory: %s'
334 % (repodir, e.strerror), file=sys.stderr)
David Pursehouse3794a782012-11-15 06:17:30 +0900335 # Don't raise CloneFailure; that would delete the
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700336 # name. Instead exit immediately.
337 #
338 sys.exit(1)
339
340 _CheckGitVersion()
341 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700342 if NeedSetupGnuPG():
343 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700344 else:
345 can_verify = True
346
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700347 dst = os.path.abspath(os.path.join(repodir, S_repo))
Hu xiuyun9711a982015-12-11 11:16:41 +0800348 _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700349
350 if can_verify and not opt.no_repo_verify:
351 rev = _Verify(dst, branch, opt.quiet)
352 else:
353 rev = 'refs/remotes/origin/%s^0' % branch
354
355 _Checkout(dst, branch, rev, opt.quiet)
356 except CloneFailure:
357 if opt.quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700358 _print('fatal: repo init failed; run without --quiet to see why',
359 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700360 raise
361
362
Conley Owensff0a3c82014-01-30 14:46:03 -0800363def ParseGitVersion(ver_str):
364 if not ver_str.startswith('git version '):
365 return None
366
367 num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
368 to_tuple = []
369 for num_str in num_ver_str.split('.')[:3]:
370 if num_str.isdigit():
371 to_tuple.append(int(num_str))
372 else:
373 to_tuple.append(0)
374 return tuple(to_tuple)
375
376
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700377def _CheckGitVersion():
378 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700379 try:
380 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700381 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700382 _print(file=sys.stderr)
383 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
384 _print('fatal: %s' % e, file=sys.stderr)
385 _print(file=sys.stderr)
386 _print('Please make sure %s is installed and in your path.' % GIT,
387 file=sys.stderr)
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700388 raise CloneFailure()
389
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700390 ver_str = proc.stdout.read().strip()
391 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700392 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700393
Conley Owensff0a3c82014-01-30 14:46:03 -0800394 ver_act = ParseGitVersion(ver_str)
395 if ver_act is None:
Conley Owens5e0ee142013-09-26 15:50:49 -0700396 _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700397 raise CloneFailure()
398
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700399 if ver_act < MIN_GIT_VERSION:
David Pursehouse685f0802012-11-14 08:34:39 +0900400 need = '.'.join(map(str, MIN_GIT_VERSION))
Conley Owens5e0ee142013-09-26 15:50:49 -0700401 _print('fatal: git %s or later required' % need, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700402 raise CloneFailure()
403
404
Conley Owensc9129d92012-10-01 16:12:28 -0700405def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700406 if not os.path.isdir(home_dot_repo):
407 return True
408
409 kv = os.path.join(home_dot_repo, 'keyring-version')
410 if not os.path.exists(kv):
411 return True
412
413 kv = open(kv).read()
414 if not kv:
415 return True
416
David Pursehouse685f0802012-11-14 08:34:39 +0900417 kv = tuple(map(int, kv.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700418 if kv < KEYRING_VERSION:
419 return True
420 return False
421
422
Conley Owensc9129d92012-10-01 16:12:28 -0700423def SetupGnuPG(quiet):
David Jamesbf79c662013-12-26 14:20:13 -0800424 try:
425 os.mkdir(home_dot_repo)
426 except OSError as e:
427 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700428 _print('fatal: cannot make %s directory: %s'
429 % (home_dot_repo, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700430 sys.exit(1)
431
David Jamesbf79c662013-12-26 14:20:13 -0800432 try:
433 os.mkdir(gpg_dir, stat.S_IRWXU)
434 except OSError as e:
435 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700436 _print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
437 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700438 sys.exit(1)
439
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800440 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300441 try:
442 env['GNUPGHOME'] = gpg_dir
443 except UnicodeEncodeError:
444 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700445
446 cmd = ['gpg', '--import']
447 try:
448 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700449 env=env,
450 stdin=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700451 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700452 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700453 _print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
454 _print('warning: Installing it is strongly encouraged.', file=sys.stderr)
455 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700456 return False
457
458 proc.stdin.write(MAINTAINER_KEYS)
459 proc.stdin.close()
460
461 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700462 _print('fatal: registering repo maintainer keys failed', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700463 sys.exit(1)
Conley Owens5e0ee142013-09-26 15:50:49 -0700464 _print()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700465
466 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
David Pursehouse685f0802012-11-14 08:34:39 +0900467 fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700468 fd.close()
469 return True
470
471
472def _SetConfig(local, name, value):
473 """Set a git configuration option to the specified value.
474 """
475 cmd = [GIT, 'config', name, value]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700476 if subprocess.Popen(cmd, cwd=local).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700477 raise CloneFailure()
478
479
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700480def _InitHttp():
481 handlers = []
482
Sarah Owens1f7627f2012-10-31 09:21:55 -0700483 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700484 try:
485 import netrc
486 n = netrc.netrc()
487 for host in n.hosts:
488 p = n.hosts[host]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700489 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800490 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700491 except: # pylint: disable=bare-except
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700492 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700493 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
494 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700495
496 if 'http_proxy' in os.environ:
497 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700498 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700499 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700500 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
501 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
502 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700503
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700504
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700505def _Fetch(url, local, src, quiet):
506 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700507 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700508
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700509 cmd = [GIT, 'fetch']
510 if quiet:
511 cmd.append('--quiet')
512 err = subprocess.PIPE
513 else:
514 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700515 cmd.append(src)
516 cmd.append('+refs/heads/*:refs/remotes/origin/*')
517 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700518
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700519 proc = subprocess.Popen(cmd, cwd=local, stderr=err)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700520 if err:
521 proc.stderr.read()
522 proc.stderr.close()
523 if proc.wait() != 0:
524 raise CloneFailure()
525
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700526
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700527def _DownloadBundle(url, local, quiet):
528 if not url.endswith('/'):
529 url += '/'
530 url += 'clone.bundle'
531
532 proc = subprocess.Popen(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700533 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
534 cwd=local,
535 stdout=subprocess.PIPE)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700536 for line in proc.stdout:
537 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
538 if m:
539 new_url = m.group(1)
540 old_url = m.group(2)
541 if url.startswith(old_url):
542 url = new_url + url[len(old_url):]
543 break
544 proc.stdout.close()
545 proc.wait()
546
547 if not url.startswith('http:') and not url.startswith('https:'):
548 return False
549
550 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
551 try:
552 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700553 r = urllib.request.urlopen(url)
554 except urllib.error.HTTPError as e:
John Törnblomd3ddcdb2015-08-12 20:12:51 +0200555 if e.code in [401, 403, 404, 501]:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700556 return False
Conley Owens5e0ee142013-09-26 15:50:49 -0700557 _print('fatal: Cannot get %s' % url, file=sys.stderr)
558 _print('fatal: HTTP error %s' % e.code, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700559 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700560 except urllib.error.URLError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700561 _print('fatal: Cannot get %s' % url, file=sys.stderr)
562 _print('fatal: error %s' % e.reason, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700563 raise CloneFailure()
564 try:
565 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700566 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700567 while True:
568 buf = r.read(8192)
569 if buf == '':
570 return True
571 dest.write(buf)
572 finally:
573 r.close()
574 finally:
575 dest.close()
576
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700577
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700578def _ImportBundle(local):
579 path = os.path.join(local, '.git', 'clone.bundle')
580 try:
581 _Fetch(local, local, path, True)
582 finally:
583 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700584
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700585
Hu xiuyun9711a982015-12-11 11:16:41 +0800586def _Clone(url, local, quiet, clone_bundle):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700587 """Clones a git repository to a new subdirectory of repodir
588 """
589 try:
590 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700591 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700592 _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
593 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700594 raise CloneFailure()
595
596 cmd = [GIT, 'init', '--quiet']
597 try:
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700598 proc = subprocess.Popen(cmd, cwd=local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700599 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700600 _print(file=sys.stderr)
601 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
602 _print('fatal: %s' % e, file=sys.stderr)
603 _print(file=sys.stderr)
604 _print('Please make sure %s is installed and in your path.' % GIT,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700605 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700606 raise CloneFailure()
607 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700608 _print('fatal: could not create %s' % local, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700609 raise CloneFailure()
610
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700611 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700612 _SetConfig(local, 'remote.origin.url', url)
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700613 _SetConfig(local,
614 'remote.origin.fetch',
615 '+refs/heads/*:refs/remotes/origin/*')
Hu xiuyun9711a982015-12-11 11:16:41 +0800616 if clone_bundle and _DownloadBundle(url, local, quiet):
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700617 _ImportBundle(local)
Dan Willemsenfee390e2015-09-02 12:36:30 -0700618 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700619
620
621def _Verify(cwd, branch, quiet):
622 """Verify the branch has been signed by a tag.
623 """
624 cmd = [GIT, 'describe', 'origin/%s' % branch]
625 proc = subprocess.Popen(cmd,
626 stdout=subprocess.PIPE,
627 stderr=subprocess.PIPE,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700628 cwd=cwd)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700629 cur = proc.stdout.read().strip()
630 proc.stdout.close()
631
632 proc.stderr.read()
633 proc.stderr.close()
634
635 if proc.wait() != 0 or not cur:
Conley Owens5e0ee142013-09-26 15:50:49 -0700636 _print(file=sys.stderr)
637 _print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700638 raise CloneFailure()
639
640 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
641 if m:
642 cur = m.group(1)
643 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700644 _print(file=sys.stderr)
645 _print("info: Ignoring branch '%s'; using tagged release '%s'"
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700646 % (branch, cur), file=sys.stderr)
Conley Owens5e0ee142013-09-26 15:50:49 -0700647 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700648
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800649 env = os.environ.copy()
Dāvis Mosāns631d0ec2016-07-16 21:11:11 +0300650 try:
651 env['GNUPGHOME'] = gpg_dir
652 except UnicodeEncodeError:
653 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700654
655 cmd = [GIT, 'tag', '-v', cur]
656 proc = subprocess.Popen(cmd,
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700657 stdout=subprocess.PIPE,
658 stderr=subprocess.PIPE,
659 cwd=cwd,
660 env=env)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700661 out = proc.stdout.read()
662 proc.stdout.close()
663
664 err = proc.stderr.read()
665 proc.stderr.close()
666
667 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700668 _print(file=sys.stderr)
669 _print(out, file=sys.stderr)
670 _print(err, file=sys.stderr)
671 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700672 raise CloneFailure()
673 return '%s^0' % cur
674
675
676def _Checkout(cwd, branch, rev, quiet):
677 """Checkout an upstream branch into the repository and track it.
678 """
679 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700680 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700681 raise CloneFailure()
682
683 _SetConfig(cwd, 'branch.default.remote', 'origin')
684 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
685
686 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700687 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700688 raise CloneFailure()
689
690 cmd = [GIT, 'read-tree', '--reset', '-u']
691 if not quiet:
692 cmd.append('-v')
693 cmd.append('HEAD')
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700694 if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700695 raise CloneFailure()
696
697
698def _FindRepo():
699 """Look for a repo installation, starting at the current directory.
700 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200701 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700702 repo = None
703
Anthony Newnamdf14a702011-01-09 17:31:57 -0800704 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200705 while curdir != '/' \
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700706 and curdir != olddir \
707 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200708 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700709 if not os.path.isfile(repo):
710 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200711 olddir = curdir
712 curdir = os.path.dirname(curdir)
713 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700714
715
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700716class _Options(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700717 help = False
718
719
720def _ParseArguments(args):
721 cmd = None
722 opt = _Options()
723 arg = []
724
Sarah Owensa6053d52012-11-01 13:36:50 -0700725 for i in range(len(args)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700726 a = args[i]
727 if a == '-h' or a == '--help':
728 opt.help = True
729
730 elif not a.startswith('-'):
731 cmd = a
732 arg = args[i + 1:]
733 break
734 return cmd, opt, arg
735
736
737def _Usage():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700738 gitc_usage = ""
739 if get_gitc_manifest_dir():
740 gitc_usage = " gitc-init Initialize a GITC Client.\n"
741
Conley Owens5e0ee142013-09-26 15:50:49 -0700742 _print(
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700743 """usage: repo COMMAND [ARGS]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700744
745repo is not yet installed. Use "repo init" to install it here.
746
747The most commonly used repo commands are:
748
749 init Install repo in the current working directory
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700750""" + gitc_usage +
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700751 """ help Display detailed help on a command
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700752
753For access to the full online help, install repo ("repo init").
Sarah Owenscecd1d82012-11-01 22:59:27 -0700754""", file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700755 sys.exit(1)
756
757
758def _Help(args):
759 if args:
760 if args[0] == 'init':
761 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100762 sys.exit(0)
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700763 elif args[0] == 'gitc-init':
764 _GitcInitOptions(init_optparse)
765 init_optparse.print_help()
766 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700767 else:
Conley Owens5e0ee142013-09-26 15:50:49 -0700768 _print("error: '%s' is not a bootstrap command.\n"
769 ' For access to online help, install repo ("repo init").'
770 % args[0], file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700771 else:
772 _Usage()
773 sys.exit(1)
774
775
776def _NotInstalled():
Conley Owens5e0ee142013-09-26 15:50:49 -0700777 _print('error: repo is not installed. Use "repo init" to install it here.',
778 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700779 sys.exit(1)
780
781
782def _NoCommands(cmd):
Conley Owens5e0ee142013-09-26 15:50:49 -0700783 _print("""error: command '%s' requires repo to be installed first.
784 Use "repo init" to install it here.""" % cmd, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700785 sys.exit(1)
786
787
788def _RunSelf(wrapper_path):
789 my_dir = os.path.dirname(wrapper_path)
790 my_main = os.path.join(my_dir, 'main.py')
791 my_git = os.path.join(my_dir, '.git')
792
793 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700794 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700795 'project.py',
796 'subcmds']:
797 if not os.path.exists(os.path.join(my_dir, name)):
798 return None, None
799 return my_main, my_git
800 return None, None
801
802
803def _SetDefaultsTo(gitdir):
804 global REPO_URL
805 global REPO_REV
806
807 REPO_URL = gitdir
808 proc = subprocess.Popen([GIT,
809 '--git-dir=%s' % gitdir,
810 'symbolic-ref',
811 'HEAD'],
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700812 stdout=subprocess.PIPE,
813 stderr=subprocess.PIPE)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700814 REPO_REV = proc.stdout.read().strip()
815 proc.stdout.close()
816
817 proc.stderr.read()
818 proc.stderr.close()
819
820 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700821 _print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700822 sys.exit(1)
823
824
825def main(orig_args):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700826 cmd, opt, args = _ParseArguments(orig_args)
827
Dan Willemsen745b4ad2015-10-06 15:23:19 -0700828 repo_main, rel_repo_dir = None, None
829 # Don't use the local repo copy, make sure to switch to the gitc client first.
830 if cmd != 'gitc-init':
831 repo_main, rel_repo_dir = _FindRepo()
832
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700833 wrapper_path = os.path.abspath(__file__)
834 my_main, my_git = _RunSelf(wrapper_path)
835
Simran Basi8ce50412015-08-28 14:25:44 -0700836 cwd = os.getcwd()
Dan Willemsen2487cb72015-08-31 15:45:06 -0700837 if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
Simran Basi8ce50412015-08-28 14:25:44 -0700838 _print('error: repo cannot be used in the GITC local manifest directory.'
839 '\nIf you want to work on this GITC client please rerun this '
Mark E. Hamilton4088eb42016-02-10 10:44:30 -0700840 'command from the corresponding client under /gitc/',
841 file=sys.stderr)
Simran Basi8ce50412015-08-28 14:25:44 -0700842 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200843 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700844 if opt.help:
845 _Usage()
846 if cmd == 'help':
847 _Help(args)
848 if not cmd:
849 _NotInstalled()
Simran Basi1efc2b42015-08-05 15:04:22 -0700850 if cmd == 'init' or cmd == 'gitc-init':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700851 if my_git:
852 _SetDefaultsTo(my_git)
853 try:
Simran Basi1efc2b42015-08-05 15:04:22 -0700854 _Init(args, gitc_init=(cmd == 'gitc-init'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700855 except CloneFailure:
Mani Chandelf75870b2014-09-03 13:54:48 +0530856 shutil.rmtree(os.path.join(repodir, S_repo), ignore_errors=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700857 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200858 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700859 else:
860 _NoCommands(cmd)
861
862 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200863 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700864
David Pursehouse685f0802012-11-14 08:34:39 +0900865 ver_str = '.'.join(map(str, VERSION))
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300866 me = [sys.executable, repo_main,
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200867 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700868 '--wrapper-version=%s' % ver_str,
869 '--wrapper-path=%s' % wrapper_path,
870 '--']
871 me.extend(orig_args)
872 me.extend(extra_args)
873 try:
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300874 os.execv(sys.executable, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700875 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700876 _print("fatal: unable to start %s" % repo_main, file=sys.stderr)
877 _print("fatal: %s" % e, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700878 sys.exit(148)
879
880
881if __name__ == '__main__':
Anthony King6efdde92014-05-05 20:37:05 +0100882 if ver[0] == 3:
883 _print('warning: Python 3 support is currently experimental. YMMV.\n'
884 'Please use Python 2.6 - 2.7 instead.',
885 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700886 main(sys.argv[1:])