blob: b8c414be629987f6a77bf669137f681661192c0d [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
3## repo default configuration
4##
David Pursehouse8f62fb72012-11-14 12:09:38 +09005REPO_URL = 'https://gerrit.googlesource.com/git-repo'
6REPO_REV = 'stable'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07007
8# Copyright (C) 2008 Google Inc.
9#
10# Licensed under the Apache License, Version 2.0 (the "License");
11# you may not use this file except in compliance with the License.
12# You may obtain a copy of the License at
13#
14# http://www.apache.org/licenses/LICENSE-2.0
15#
16# Unless required by applicable law or agreed to in writing, software
17# distributed under the License is distributed on an "AS IS" BASIS,
18# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19# See the License for the specific language governing permissions and
20# limitations under the License.
21
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070022# increment this whenever we make important changes to this script
Conley Owens5db69f32014-01-30 16:00:35 -080023VERSION = (1, 21)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070024
25# increment this if the MAINTAINER_KEYS block is modified
Conley Owensbc030842013-07-01 11:05:32 -070026KEYRING_VERSION = (1, 2)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070027MAINTAINER_KEYS = """
28
29 Repo Maintainer <repo@android.kernel.org>
30-----BEGIN PGP PUBLIC KEY BLOCK-----
31Version: GnuPG v1.4.2.2 (GNU/Linux)
32
33mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
34WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
35VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
36xI1WfzLqdJjsm1Nq98L0cLcD/iNsILCuw44PRds3J75YP0pze7YF/6WFMB6QSFGu
37aUX1FsTT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uuLvp1vEDHnj41R52Fz51hgddT4rBsp0nL+5I
54socSOIIezw8T9vVzMY4ArCKFAVu2IVyBcahTfBS8q5EM63mONU6UVJEozfGljiMw
55xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
56ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
57Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
58FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
59+WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
60w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
61Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
62p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
630V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
645xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
65HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
66zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
67TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
68=CMiZ
69-----END PGP PUBLIC KEY BLOCK-----
Conley Owens55e4d462012-10-01 16:12:28 -070070
71 Conley Owens <cco3@android.com>
72-----BEGIN PGP PUBLIC KEY BLOCK-----
73Version: GnuPG v1.4.11 (GNU/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sf2E
91Gp9tu1kKauuToZhWHMRMqYSOGikQJwWSFYKT1KdNcOXLQF6+bfoJ6sjVYdwfmNQL
92Ixn8QVhoTDedcqClSWB17VDEFDFa7MmqXZz2qtM3X1R/MUMHqPtegQzBGNhRdnI2
93V45+1Nnx/uuCxDbeI4RbHzujnxDiq70AEQEAAYkBHwQYAQIACQUCUdG9zwIbDAAK
94CRBnt+RIaSs4LNVeB/0Y2pZ8I7gAAcEM0Xw8drr4omg2fUoK1J33ozlA/RxeA/lJ
95I3KnyCDTpXuIeBKPGkdL8uMATC9Z8DnBBajRlftNDVZS3Hz4G09G9QpMojvJkFJV
96By+01Flw/X+eeN8NpqSuLV4W+AjEO8at/VvgKr1AFvBRdZ7GkpI1o6DgPe7ZqX+1
97dzQZt3e13W0rVBb/bUgx9iSLoeWP3aq/k+/GRGOR+S6F6BBSl0SQ2EF2+dIywb1x
98JuinEP+AwLAUZ1Bsx9ISC0Agpk2VeHXPL3FGhroEmoMvBzO0kTFGyoeT7PR/BfKv
99+H/g3HsL2LOB9uoIm8/5p2TTU5ttYCXMHhQZ81AY
100=AUp4
Conley Owens55e4d462012-10-01 16:12:28 -0700101-----END PGP PUBLIC KEY BLOCK-----
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700102"""
103
104GIT = 'git' # our git command
Conley Owensc5aa4d32012-10-26 11:34:11 -0700105MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700106repodir = '.repo' # name of repo's private directory
Conley Owensc9129d92012-10-01 16:12:28 -0700107S_repo = 'repo' # special repo repository
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700108S_manifests = 'manifests' # special manifest repository
109REPO_MAIN = S_repo + '/main.py' # main script
Chirayu Desai51813df2013-04-16 19:36:09 +0530110MIN_PYTHON_VERSION = (2, 6) # minimum supported python version
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700111
112
David Jamesbf79c662013-12-26 14:20:13 -0800113import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700114import optparse
115import os
116import re
Mitchel Humpheryseb5acc92014-03-12 10:48:15 -0700117import shutil
Sarah Owens60798a32012-10-25 17:53:09 -0700118import stat
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700119import subprocess
120import sys
David Pursehouse59bbb582013-05-17 10:49:33 +0900121
122if sys.version_info[0] == 3:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700123 import urllib.request
124 import urllib.error
125else:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700126 import imp
David Pursehouse59bbb582013-05-17 10:49:33 +0900127 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -0700128 urllib = imp.new_module('urllib')
129 urllib.request = urllib2
130 urllib.error = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700131
Conley Owens5e0ee142013-09-26 15:50:49 -0700132
133def _print(*objects, **kwargs):
134 sep = kwargs.get('sep', ' ')
135 end = kwargs.get('end', '\n')
136 out = kwargs.get('file', sys.stdout)
137 out.write(sep.join(objects) + end)
138
139
Chirayu Desai51813df2013-04-16 19:36:09 +0530140# Python version check
141ver = sys.version_info
142if ver[0] == 3:
Chirayu Desai5d6cb802013-11-21 13:42:39 +0530143 _print('warning: Python 3 support is currently experimental. YMMV.\n'
Conley Owens5e0ee142013-09-26 15:50:49 -0700144 'Please use Python 2.6 - 2.7 instead.',
145 file=sys.stderr)
Chirayu Desai51813df2013-04-16 19:36:09 +0530146if (ver[0], ver[1]) < MIN_PYTHON_VERSION:
Conley Owens5e0ee142013-09-26 15:50:49 -0700147 _print('error: Python version %s unsupported.\n'
148 'Please use Python 2.6 - 2.7 instead.'
149 % sys.version.split(' ')[0], file=sys.stderr)
Chirayu Desai51813df2013-04-16 19:36:09 +0530150 sys.exit(1)
151
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700152home_dot_repo = os.path.expanduser('~/.repoconfig')
153gpg_dir = os.path.join(home_dot_repo, 'gnupg')
154
155extra_args = []
156init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
157
158# Logging
159group = init_optparse.add_option_group('Logging options')
160group.add_option('-q', '--quiet',
161 dest="quiet", action="store_true", default=False,
162 help="be quiet")
163
164# Manifest
165group = init_optparse.add_option_group('Manifest options')
166group.add_option('-u', '--manifest-url',
167 dest='manifest_url',
168 help='manifest repository location', metavar='URL')
169group.add_option('-b', '--manifest-branch',
170 dest='manifest_branch',
171 help='manifest branch or revision', metavar='REVISION')
172group.add_option('-m', '--manifest-name',
173 dest='manifest_name',
174 help='initial manifest file', metavar='NAME.xml')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800175group.add_option('--mirror',
176 dest='mirror', action='store_true',
David Pursehouse3794a782012-11-15 06:17:30 +0900177 help='create a replica of the remote repositories '
178 'rather than a client working directory')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200179group.add_option('--reference',
180 dest='reference',
181 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700182group.add_option('--depth', type='int', default=None,
183 dest='depth',
184 help='create a shallow clone with given depth; see git clone')
Julien Campergue335f5ef2013-10-16 11:02:35 +0200185group.add_option('--archive',
186 dest='archive', action='store_true',
187 help='checkout an archive instead of a git repository for '
188 'each project. See git archive.')
Colin Cross5acde752012-03-28 20:15:45 -0700189group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700190 dest='groups', default='default',
David Holmer0a1c6a12012-11-14 19:19:00 -0500191 help='restrict manifest projects to ones with specified '
192 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
Colin Cross5acde752012-03-28 20:15:45 -0700193 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700194group.add_option('-p', '--platform',
195 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700196 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700197 'platform group [auto|all|none|linux|darwin|...]',
198 metavar='PLATFORM')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700199
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700200
201# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700202group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700203group.add_option('--repo-url',
204 dest='repo_url',
205 help='repo repository location', metavar='URL')
206group.add_option('--repo-branch',
207 dest='repo_branch',
208 help='repo branch or revision', metavar='REVISION')
209group.add_option('--no-repo-verify',
210 dest='no_repo_verify', action='store_true',
211 help='do not verify repo source code')
212
Victor Boivie841be342011-04-05 11:31:10 +0200213# Other
214group = init_optparse.add_option_group('Other options')
215group.add_option('--config-name',
216 dest='config_name', action="store_true", default=False,
217 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218
219class CloneFailure(Exception):
220 """Indicate the remote clone of repo itself failed.
221 """
222
223
224def _Init(args):
225 """Installs repo by cloning it over the network.
226 """
227 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800228 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700229 init_optparse.print_usage()
230 sys.exit(1)
231
232 url = opt.repo_url
233 if not url:
234 url = REPO_URL
235 extra_args.append('--repo-url=%s' % url)
236
237 branch = opt.repo_branch
238 if not branch:
239 branch = REPO_REV
240 extra_args.append('--repo-branch=%s' % branch)
241
242 if branch.startswith('refs/heads/'):
243 branch = branch[len('refs/heads/'):]
244 if branch.startswith('refs/'):
Conley Owens5e0ee142013-09-26 15:50:49 -0700245 _print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700246 raise CloneFailure()
247
David Jamesbf79c662013-12-26 14:20:13 -0800248 try:
249 os.mkdir(repodir)
250 except OSError as e:
251 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700252 _print('fatal: cannot make %s directory: %s'
253 % (repodir, e.strerror), file=sys.stderr)
David Pursehouse3794a782012-11-15 06:17:30 +0900254 # Don't raise CloneFailure; that would delete the
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700255 # name. Instead exit immediately.
256 #
257 sys.exit(1)
258
259 _CheckGitVersion()
260 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700261 if NeedSetupGnuPG():
262 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700263 else:
264 can_verify = True
265
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700266 dst = os.path.abspath(os.path.join(repodir, S_repo))
267 _Clone(url, dst, opt.quiet)
268
269 if can_verify and not opt.no_repo_verify:
270 rev = _Verify(dst, branch, opt.quiet)
271 else:
272 rev = 'refs/remotes/origin/%s^0' % branch
273
274 _Checkout(dst, branch, rev, opt.quiet)
275 except CloneFailure:
276 if opt.quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700277 _print('fatal: repo init failed; run without --quiet to see why',
278 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700279 raise
280
281
Conley Owensff0a3c82014-01-30 14:46:03 -0800282def ParseGitVersion(ver_str):
283 if not ver_str.startswith('git version '):
284 return None
285
286 num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
287 to_tuple = []
288 for num_str in num_ver_str.split('.')[:3]:
289 if num_str.isdigit():
290 to_tuple.append(int(num_str))
291 else:
292 to_tuple.append(0)
293 return tuple(to_tuple)
294
295
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700296def _CheckGitVersion():
297 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700298 try:
299 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700300 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700301 _print(file=sys.stderr)
302 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
303 _print('fatal: %s' % e, file=sys.stderr)
304 _print(file=sys.stderr)
305 _print('Please make sure %s is installed and in your path.' % GIT,
306 file=sys.stderr)
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700307 raise CloneFailure()
308
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700309 ver_str = proc.stdout.read().strip()
310 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700311 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700312
Conley Owensff0a3c82014-01-30 14:46:03 -0800313 ver_act = ParseGitVersion(ver_str)
314 if ver_act is None:
Conley Owens5e0ee142013-09-26 15:50:49 -0700315 _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700316 raise CloneFailure()
317
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700318 if ver_act < MIN_GIT_VERSION:
David Pursehouse685f0802012-11-14 08:34:39 +0900319 need = '.'.join(map(str, MIN_GIT_VERSION))
Conley Owens5e0ee142013-09-26 15:50:49 -0700320 _print('fatal: git %s or later required' % need, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700321 raise CloneFailure()
322
323
Conley Owensc9129d92012-10-01 16:12:28 -0700324def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700325 if not os.path.isdir(home_dot_repo):
326 return True
327
328 kv = os.path.join(home_dot_repo, 'keyring-version')
329 if not os.path.exists(kv):
330 return True
331
332 kv = open(kv).read()
333 if not kv:
334 return True
335
David Pursehouse685f0802012-11-14 08:34:39 +0900336 kv = tuple(map(int, kv.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700337 if kv < KEYRING_VERSION:
338 return True
339 return False
340
341
Conley Owensc9129d92012-10-01 16:12:28 -0700342def SetupGnuPG(quiet):
David Jamesbf79c662013-12-26 14:20:13 -0800343 try:
344 os.mkdir(home_dot_repo)
345 except OSError as e:
346 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700347 _print('fatal: cannot make %s directory: %s'
348 % (home_dot_repo, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700349 sys.exit(1)
350
David Jamesbf79c662013-12-26 14:20:13 -0800351 try:
352 os.mkdir(gpg_dir, stat.S_IRWXU)
353 except OSError as e:
354 if e.errno != errno.EEXIST:
Conley Owens5e0ee142013-09-26 15:50:49 -0700355 _print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
356 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700357 sys.exit(1)
358
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800359 env = os.environ.copy()
360 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700361
362 cmd = ['gpg', '--import']
363 try:
364 proc = subprocess.Popen(cmd,
365 env = env,
366 stdin = subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700367 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700368 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700369 _print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
370 _print('warning: Installing it is strongly encouraged.', file=sys.stderr)
371 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700372 return False
373
374 proc.stdin.write(MAINTAINER_KEYS)
375 proc.stdin.close()
376
377 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700378 _print('fatal: registering repo maintainer keys failed', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700379 sys.exit(1)
Conley Owens5e0ee142013-09-26 15:50:49 -0700380 _print()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700381
382 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
David Pursehouse685f0802012-11-14 08:34:39 +0900383 fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700384 fd.close()
385 return True
386
387
388def _SetConfig(local, name, value):
389 """Set a git configuration option to the specified value.
390 """
391 cmd = [GIT, 'config', name, value]
392 if subprocess.Popen(cmd, cwd = local).wait() != 0:
393 raise CloneFailure()
394
395
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700396def _InitHttp():
397 handlers = []
398
Sarah Owens1f7627f2012-10-31 09:21:55 -0700399 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700400 try:
401 import netrc
402 n = netrc.netrc()
403 for host in n.hosts:
404 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800405 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
406 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700407 except:
408 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700409 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
410 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700411
412 if 'http_proxy' in os.environ:
413 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700414 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700415 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700416 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
417 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
418 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700419
420def _Fetch(url, local, src, quiet):
421 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700422 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700423
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700424 cmd = [GIT, 'fetch']
425 if quiet:
426 cmd.append('--quiet')
427 err = subprocess.PIPE
428 else:
429 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700430 cmd.append(src)
431 cmd.append('+refs/heads/*:refs/remotes/origin/*')
432 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700433
434 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
435 if err:
436 proc.stderr.read()
437 proc.stderr.close()
438 if proc.wait() != 0:
439 raise CloneFailure()
440
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700441def _DownloadBundle(url, local, quiet):
442 if not url.endswith('/'):
443 url += '/'
444 url += 'clone.bundle'
445
446 proc = subprocess.Popen(
447 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
448 cwd = local,
449 stdout = subprocess.PIPE)
450 for line in proc.stdout:
451 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
452 if m:
453 new_url = m.group(1)
454 old_url = m.group(2)
455 if url.startswith(old_url):
456 url = new_url + url[len(old_url):]
457 break
458 proc.stdout.close()
459 proc.wait()
460
461 if not url.startswith('http:') and not url.startswith('https:'):
462 return False
463
464 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
465 try:
466 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700467 r = urllib.request.urlopen(url)
468 except urllib.error.HTTPError as e:
David Pursehouse87b9d9b2012-11-26 18:30:32 +0900469 if e.code in [403, 404]:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700470 return False
Conley Owens5e0ee142013-09-26 15:50:49 -0700471 _print('fatal: Cannot get %s' % url, file=sys.stderr)
472 _print('fatal: HTTP error %s' % e.code, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700473 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700474 except urllib.error.URLError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700475 _print('fatal: Cannot get %s' % url, file=sys.stderr)
476 _print('fatal: error %s' % e.reason, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700477 raise CloneFailure()
478 try:
479 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700480 _print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700481 while True:
482 buf = r.read(8192)
483 if buf == '':
484 return True
485 dest.write(buf)
486 finally:
487 r.close()
488 finally:
489 dest.close()
490
491def _ImportBundle(local):
492 path = os.path.join(local, '.git', 'clone.bundle')
493 try:
494 _Fetch(local, local, path, True)
495 finally:
496 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700497
498def _Clone(url, local, quiet):
499 """Clones a git repository to a new subdirectory of repodir
500 """
501 try:
502 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700503 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700504 _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
505 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700506 raise CloneFailure()
507
508 cmd = [GIT, 'init', '--quiet']
509 try:
510 proc = subprocess.Popen(cmd, cwd = local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700511 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700512 _print(file=sys.stderr)
513 _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
514 _print('fatal: %s' % e, file=sys.stderr)
515 _print(file=sys.stderr)
516 _print('Please make sure %s is installed and in your path.' % GIT,
Sarah Owenscecd1d82012-11-01 22:59:27 -0700517 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700518 raise CloneFailure()
519 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700520 _print('fatal: could not create %s' % local, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700521 raise CloneFailure()
522
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700523 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700524 _SetConfig(local, 'remote.origin.url', url)
525 _SetConfig(local, 'remote.origin.fetch',
526 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700527 if _DownloadBundle(url, local, quiet):
528 _ImportBundle(local)
529 else:
530 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700531
532
533def _Verify(cwd, branch, quiet):
534 """Verify the branch has been signed by a tag.
535 """
536 cmd = [GIT, 'describe', 'origin/%s' % branch]
537 proc = subprocess.Popen(cmd,
538 stdout=subprocess.PIPE,
539 stderr=subprocess.PIPE,
540 cwd = cwd)
541 cur = proc.stdout.read().strip()
542 proc.stdout.close()
543
544 proc.stderr.read()
545 proc.stderr.close()
546
547 if proc.wait() != 0 or not cur:
Conley Owens5e0ee142013-09-26 15:50:49 -0700548 _print(file=sys.stderr)
549 _print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700550 raise CloneFailure()
551
552 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
553 if m:
554 cur = m.group(1)
555 if not quiet:
Conley Owens5e0ee142013-09-26 15:50:49 -0700556 _print(file=sys.stderr)
557 _print("info: Ignoring branch '%s'; using tagged release '%s'"
Sarah Owenscecd1d82012-11-01 22:59:27 -0700558 % (branch, cur), file=sys.stderr)
Conley Owens5e0ee142013-09-26 15:50:49 -0700559 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700560
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800561 env = os.environ.copy()
562 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700563
564 cmd = [GIT, 'tag', '-v', cur]
565 proc = subprocess.Popen(cmd,
566 stdout = subprocess.PIPE,
567 stderr = subprocess.PIPE,
568 cwd = cwd,
569 env = env)
570 out = proc.stdout.read()
571 proc.stdout.close()
572
573 err = proc.stderr.read()
574 proc.stderr.close()
575
576 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700577 _print(file=sys.stderr)
578 _print(out, file=sys.stderr)
579 _print(err, file=sys.stderr)
580 _print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700581 raise CloneFailure()
582 return '%s^0' % cur
583
584
585def _Checkout(cwd, branch, rev, quiet):
586 """Checkout an upstream branch into the repository and track it.
587 """
588 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
589 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
590 raise CloneFailure()
591
592 _SetConfig(cwd, 'branch.default.remote', 'origin')
593 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
594
595 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
596 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
597 raise CloneFailure()
598
599 cmd = [GIT, 'read-tree', '--reset', '-u']
600 if not quiet:
601 cmd.append('-v')
602 cmd.append('HEAD')
603 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
604 raise CloneFailure()
605
606
607def _FindRepo():
608 """Look for a repo installation, starting at the current directory.
609 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200610 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700611 repo = None
612
Anthony Newnamdf14a702011-01-09 17:31:57 -0800613 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200614 while curdir != '/' \
615 and curdir != olddir \
Anthony Newnamdf14a702011-01-09 17:31:57 -0800616 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200617 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700618 if not os.path.isfile(repo):
619 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200620 olddir = curdir
621 curdir = os.path.dirname(curdir)
622 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700623
624
625class _Options:
626 help = False
627
628
629def _ParseArguments(args):
630 cmd = None
631 opt = _Options()
632 arg = []
633
Sarah Owensa6053d52012-11-01 13:36:50 -0700634 for i in range(len(args)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700635 a = args[i]
636 if a == '-h' or a == '--help':
637 opt.help = True
638
639 elif not a.startswith('-'):
640 cmd = a
641 arg = args[i + 1:]
642 break
643 return cmd, opt, arg
644
645
646def _Usage():
Conley Owens5e0ee142013-09-26 15:50:49 -0700647 _print(
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700648"""usage: repo COMMAND [ARGS]
649
650repo is not yet installed. Use "repo init" to install it here.
651
652The most commonly used repo commands are:
653
654 init Install repo in the current working directory
655 help Display detailed help on a command
656
657For access to the full online help, install repo ("repo init").
Sarah Owenscecd1d82012-11-01 22:59:27 -0700658""", file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700659 sys.exit(1)
660
661
662def _Help(args):
663 if args:
664 if args[0] == 'init':
665 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100666 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700667 else:
Conley Owens5e0ee142013-09-26 15:50:49 -0700668 _print("error: '%s' is not a bootstrap command.\n"
669 ' For access to online help, install repo ("repo init").'
670 % args[0], file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700671 else:
672 _Usage()
673 sys.exit(1)
674
675
676def _NotInstalled():
Conley Owens5e0ee142013-09-26 15:50:49 -0700677 _print('error: repo is not installed. Use "repo init" to install it here.',
678 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700679 sys.exit(1)
680
681
682def _NoCommands(cmd):
Conley Owens5e0ee142013-09-26 15:50:49 -0700683 _print("""error: command '%s' requires repo to be installed first.
684 Use "repo init" to install it here.""" % cmd, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700685 sys.exit(1)
686
687
688def _RunSelf(wrapper_path):
689 my_dir = os.path.dirname(wrapper_path)
690 my_main = os.path.join(my_dir, 'main.py')
691 my_git = os.path.join(my_dir, '.git')
692
693 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700694 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700695 'project.py',
696 'subcmds']:
697 if not os.path.exists(os.path.join(my_dir, name)):
698 return None, None
699 return my_main, my_git
700 return None, None
701
702
703def _SetDefaultsTo(gitdir):
704 global REPO_URL
705 global REPO_REV
706
707 REPO_URL = gitdir
708 proc = subprocess.Popen([GIT,
709 '--git-dir=%s' % gitdir,
710 'symbolic-ref',
711 'HEAD'],
712 stdout = subprocess.PIPE,
713 stderr = subprocess.PIPE)
714 REPO_REV = proc.stdout.read().strip()
715 proc.stdout.close()
716
717 proc.stderr.read()
718 proc.stderr.close()
719
720 if proc.wait() != 0:
Conley Owens5e0ee142013-09-26 15:50:49 -0700721 _print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700722 sys.exit(1)
723
724
725def main(orig_args):
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200726 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700727 cmd, opt, args = _ParseArguments(orig_args)
728
729 wrapper_path = os.path.abspath(__file__)
730 my_main, my_git = _RunSelf(wrapper_path)
731
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200732 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700733 if opt.help:
734 _Usage()
735 if cmd == 'help':
736 _Help(args)
737 if not cmd:
738 _NotInstalled()
739 if cmd == 'init':
740 if my_git:
741 _SetDefaultsTo(my_git)
742 try:
743 _Init(args)
744 except CloneFailure:
Mitchel Humpheryseb5acc92014-03-12 10:48:15 -0700745 shutil.rmtree(repodir, ignore_errors=True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700746 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200747 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700748 else:
749 _NoCommands(cmd)
750
751 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200752 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700753
David Pursehouse685f0802012-11-14 08:34:39 +0900754 ver_str = '.'.join(map(str, VERSION))
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300755 me = [sys.executable, repo_main,
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200756 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700757 '--wrapper-version=%s' % ver_str,
758 '--wrapper-path=%s' % wrapper_path,
759 '--']
760 me.extend(orig_args)
761 me.extend(extra_args)
762 try:
anatoly techtonik3a2a59e2013-09-21 19:29:10 +0300763 os.execv(sys.executable, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700764 except OSError as e:
Conley Owens5e0ee142013-09-26 15:50:49 -0700765 _print("fatal: unable to start %s" % repo_main, file=sys.stderr)
766 _print("fatal: %s" % e, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700767 sys.exit(148)
768
769
770if __name__ == '__main__':
771 main(sys.argv[1:])