blob: c3484745f0c366d520571d5f6d57d8ad5a06f5e5 [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##
Sarah Owenscecd1d82012-11-01 22:59:27 -07005from __future__ import print_function
David Pursehouse8f62fb72012-11-14 12:09:38 +09006REPO_URL = 'https://gerrit.googlesource.com/git-repo'
7REPO_REV = 'stable'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07008
9# Copyright (C) 2008 Google Inc.
10#
11# Licensed under the Apache License, Version 2.0 (the "License");
12# you may not use this file except in compliance with the License.
13# You may obtain a copy of the License at
14#
15# http://www.apache.org/licenses/LICENSE-2.0
16#
17# Unless required by applicable law or agreed to in writing, software
18# distributed under the License is distributed on an "AS IS" BASIS,
19# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20# See the License for the specific language governing permissions and
21# limitations under the License.
22
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023# increment this whenever we make important changes to this script
Conley Owensc5aa4d32012-10-26 11:34:11 -070024VERSION = (1, 19)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070025
26# increment this if the MAINTAINER_KEYS block is modified
David Pursehouse8f62fb72012-11-14 12:09:38 +090027KEYRING_VERSION = (1, 1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028MAINTAINER_KEYS = """
29
30 Repo Maintainer <repo@android.kernel.org>
31-----BEGIN PGP PUBLIC KEY BLOCK-----
32Version: GnuPG v1.4.2.2 (GNU/Linux)
33
34mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
35WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
36VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
37xI1WfzLqdJjsm1Nq98L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wWeez/RueN4ig59gRTtkcc0PR
5435tX2DR8+xCCFVW/NcJ4PSePYzCuuLvp1vEDHnj41R52Fz51hgddT4rBsp0nL+5I
55socSOIIezw8T9vVzMY4ArCKFAVu2IVyBcahTfBS8q5EM63mONU6UVJEozfGljiMw
56xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
57ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
58Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
59FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
60+WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
61w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
62Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
63p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
640V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
655xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
66HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
67zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
68TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
69=CMiZ
70-----END PGP PUBLIC KEY BLOCK-----
Conley Owens55e4d462012-10-01 16:12:28 -070071
72 Conley Owens <cco3@android.com>
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4t3JmMOnWrnKSvL+5iuRj12p9WmanCHzw3Ee7ztf
92/aU/q+FTpr3DLerb6S8xbv86ySgnJT6o5CyL2DCWRtnYQyGVi0ZmLzEouAYiO0hs
93z0AAu28Mj+12g2WwePRz6gfM9rHtI37ylYW3oT/9M9mO9ei/Bc/1D7Dz6qNV+0vg
94uSVJxM2Bl6GalHPZLhHntFEdIA6EdoUAEQEAAYkBHwQYAQIACQUCUGIs/AIbDAAK
95CRAZJpRVM4hxpNfkB/0W/hP5WK/NETXBlWXXW7JPaWO2c5kGwD0lnj5RRmridyo1
96vbm5PdM91jOsDQYqRu6YOoYBnDnEhB2wL2bPh34HWwwrA+LwB8hlcAV2z1bdwyfl
973R823fReKN3QcvLHzmvZPrF4Rk97M9UIyKS0RtnfTWykRgDWHIsrtQPoNwsXrWoT
989LrM2v+1+9mp3vuXnE473/NHxmiWEQH9Ez+O/mOxQ7rSOlqGRiKq/IBZCfioJOtV
99fTQeIu/yASZnsLBqr6SJEGwYBoWcyjG++k4fyw8ocOAo4uGDYbxgN7yYfNQ0OH7o
100V6pfUgqKLWa/aK7/N1ZHnPdFLD8Xt0Dmy4BPwrKC
101=O7am
102-----END PGP PUBLIC KEY BLOCK-----
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700103"""
104
105GIT = 'git' # our git command
Conley Owensc5aa4d32012-10-26 11:34:11 -0700106MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700107repodir = '.repo' # name of repo's private directory
Conley Owensc9129d92012-10-01 16:12:28 -0700108S_repo = 'repo' # special repo repository
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700109S_manifests = 'manifests' # special manifest repository
110REPO_MAIN = S_repo + '/main.py' # main script
111
112
113import optparse
114import os
115import re
Sarah Owens60798a32012-10-25 17:53:09 -0700116import stat
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700117import subprocess
118import sys
Sarah Owens1f7627f2012-10-31 09:21:55 -0700119try:
120 import urllib2
121except ImportError:
122 # For python3
123 import urllib.request
124 import urllib.error
125else:
126 # For python2
127 import imp
128 urllib = imp.new_module('urllib')
129 urllib.request = urllib2
130 urllib.error = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700131
132home_dot_repo = os.path.expanduser('~/.repoconfig')
133gpg_dir = os.path.join(home_dot_repo, 'gnupg')
134
135extra_args = []
136init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
137
138# Logging
139group = init_optparse.add_option_group('Logging options')
140group.add_option('-q', '--quiet',
141 dest="quiet", action="store_true", default=False,
142 help="be quiet")
143
144# Manifest
145group = init_optparse.add_option_group('Manifest options')
146group.add_option('-u', '--manifest-url',
147 dest='manifest_url',
148 help='manifest repository location', metavar='URL')
149group.add_option('-b', '--manifest-branch',
150 dest='manifest_branch',
151 help='manifest branch or revision', metavar='REVISION')
152group.add_option('-m', '--manifest-name',
153 dest='manifest_name',
154 help='initial manifest file', metavar='NAME.xml')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800155group.add_option('--mirror',
156 dest='mirror', action='store_true',
David Pursehouse3794a782012-11-15 06:17:30 +0900157 help='create a replica of the remote repositories '
158 'rather than a client working directory')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200159group.add_option('--reference',
160 dest='reference',
161 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700162group.add_option('--depth', type='int', default=None,
163 dest='depth',
164 help='create a shallow clone with given depth; see git clone')
Colin Cross5acde752012-03-28 20:15:45 -0700165group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700166 dest='groups', default='default',
David Holmer0a1c6a12012-11-14 19:19:00 -0500167 help='restrict manifest projects to ones with specified '
168 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
Colin Cross5acde752012-03-28 20:15:45 -0700169 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700170group.add_option('-p', '--platform',
171 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700172 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700173 'platform group [auto|all|none|linux|darwin|...]',
174 metavar='PLATFORM')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700175
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700176
177# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700178group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700179group.add_option('--repo-url',
180 dest='repo_url',
181 help='repo repository location', metavar='URL')
182group.add_option('--repo-branch',
183 dest='repo_branch',
184 help='repo branch or revision', metavar='REVISION')
185group.add_option('--no-repo-verify',
186 dest='no_repo_verify', action='store_true',
187 help='do not verify repo source code')
188
Victor Boivie841be342011-04-05 11:31:10 +0200189# Other
190group = init_optparse.add_option_group('Other options')
191group.add_option('--config-name',
192 dest='config_name', action="store_true", default=False,
193 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700194
195class CloneFailure(Exception):
196 """Indicate the remote clone of repo itself failed.
197 """
198
199
200def _Init(args):
201 """Installs repo by cloning it over the network.
202 """
203 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800204 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700205 init_optparse.print_usage()
206 sys.exit(1)
207
208 url = opt.repo_url
209 if not url:
210 url = REPO_URL
211 extra_args.append('--repo-url=%s' % url)
212
213 branch = opt.repo_branch
214 if not branch:
215 branch = REPO_REV
216 extra_args.append('--repo-branch=%s' % branch)
217
218 if branch.startswith('refs/heads/'):
219 branch = branch[len('refs/heads/'):]
220 if branch.startswith('refs/'):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700221 print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700222 raise CloneFailure()
223
224 if not os.path.isdir(repodir):
225 try:
226 os.mkdir(repodir)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700227 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700228 print('fatal: cannot make %s directory: %s'
229 % (repodir, e.strerror), file=sys.stderr)
David Pursehouse3794a782012-11-15 06:17:30 +0900230 # Don't raise CloneFailure; that would delete the
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700231 # name. Instead exit immediately.
232 #
233 sys.exit(1)
234
235 _CheckGitVersion()
236 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700237 if NeedSetupGnuPG():
238 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700239 else:
240 can_verify = True
241
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700242 dst = os.path.abspath(os.path.join(repodir, S_repo))
243 _Clone(url, dst, opt.quiet)
244
245 if can_verify and not opt.no_repo_verify:
246 rev = _Verify(dst, branch, opt.quiet)
247 else:
248 rev = 'refs/remotes/origin/%s^0' % branch
249
250 _Checkout(dst, branch, rev, opt.quiet)
251 except CloneFailure:
252 if opt.quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700253 print('fatal: repo init failed; run without --quiet to see why',
254 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700255 raise
256
257
258def _CheckGitVersion():
259 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700260 try:
261 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700262 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700263 print(file=sys.stderr)
264 print("fatal: '%s' is not available" % GIT, file=sys.stderr)
265 print('fatal: %s' % e, file=sys.stderr)
266 print(file=sys.stderr)
267 print('Please make sure %s is installed and in your path.' % GIT,
268 file=sys.stderr)
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700269 raise CloneFailure()
270
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700271 ver_str = proc.stdout.read().strip()
272 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700273 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700274
275 if not ver_str.startswith('git version '):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700276 print('error: "%s" unsupported' % ver_str, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700277 raise CloneFailure()
278
279 ver_str = ver_str[len('git version '):].strip()
David Pursehouse685f0802012-11-14 08:34:39 +0900280 ver_act = tuple(map(int, ver_str.split('.')[0:3]))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700281 if ver_act < MIN_GIT_VERSION:
David Pursehouse685f0802012-11-14 08:34:39 +0900282 need = '.'.join(map(str, MIN_GIT_VERSION))
Sarah Owenscecd1d82012-11-01 22:59:27 -0700283 print('fatal: git %s or later required' % need, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700284 raise CloneFailure()
285
286
Conley Owensc9129d92012-10-01 16:12:28 -0700287def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700288 if not os.path.isdir(home_dot_repo):
289 return True
290
291 kv = os.path.join(home_dot_repo, 'keyring-version')
292 if not os.path.exists(kv):
293 return True
294
295 kv = open(kv).read()
296 if not kv:
297 return True
298
David Pursehouse685f0802012-11-14 08:34:39 +0900299 kv = tuple(map(int, kv.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700300 if kv < KEYRING_VERSION:
301 return True
302 return False
303
304
Conley Owensc9129d92012-10-01 16:12:28 -0700305def SetupGnuPG(quiet):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700306 if not os.path.isdir(home_dot_repo):
307 try:
308 os.mkdir(home_dot_repo)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700309 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700310 print('fatal: cannot make %s directory: %s'
311 % (home_dot_repo, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700312 sys.exit(1)
313
314 if not os.path.isdir(gpg_dir):
315 try:
Sarah Owens60798a32012-10-25 17:53:09 -0700316 os.mkdir(gpg_dir, stat.S_IRWXU)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700317 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700318 print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
319 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700320 sys.exit(1)
321
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800322 env = os.environ.copy()
323 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700324
325 cmd = ['gpg', '--import']
326 try:
327 proc = subprocess.Popen(cmd,
328 env = env,
329 stdin = subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700330 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700331 if not quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700332 print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
333 print('warning: Installing it is strongly encouraged.', file=sys.stderr)
334 print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700335 return False
336
337 proc.stdin.write(MAINTAINER_KEYS)
338 proc.stdin.close()
339
340 if proc.wait() != 0:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700341 print('fatal: registering repo maintainer keys failed', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700342 sys.exit(1)
David Pursehouse98ffba12012-11-14 11:18:00 +0900343 print()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700344
345 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
David Pursehouse685f0802012-11-14 08:34:39 +0900346 fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700347 fd.close()
348 return True
349
350
351def _SetConfig(local, name, value):
352 """Set a git configuration option to the specified value.
353 """
354 cmd = [GIT, 'config', name, value]
355 if subprocess.Popen(cmd, cwd = local).wait() != 0:
356 raise CloneFailure()
357
358
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700359def _InitHttp():
360 handlers = []
361
Sarah Owens1f7627f2012-10-31 09:21:55 -0700362 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700363 try:
364 import netrc
365 n = netrc.netrc()
366 for host in n.hosts:
367 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800368 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
369 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700370 except:
371 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700372 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
373 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700374
375 if 'http_proxy' in os.environ:
376 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700377 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700378 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700379 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
380 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
381 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700382
383def _Fetch(url, local, src, quiet):
384 if not quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700385 print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700386
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700387 cmd = [GIT, 'fetch']
388 if quiet:
389 cmd.append('--quiet')
390 err = subprocess.PIPE
391 else:
392 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700393 cmd.append(src)
394 cmd.append('+refs/heads/*:refs/remotes/origin/*')
395 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700396
397 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
398 if err:
399 proc.stderr.read()
400 proc.stderr.close()
401 if proc.wait() != 0:
402 raise CloneFailure()
403
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700404def _DownloadBundle(url, local, quiet):
405 if not url.endswith('/'):
406 url += '/'
407 url += 'clone.bundle'
408
409 proc = subprocess.Popen(
410 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
411 cwd = local,
412 stdout = subprocess.PIPE)
413 for line in proc.stdout:
414 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
415 if m:
416 new_url = m.group(1)
417 old_url = m.group(2)
418 if url.startswith(old_url):
419 url = new_url + url[len(old_url):]
420 break
421 proc.stdout.close()
422 proc.wait()
423
424 if not url.startswith('http:') and not url.startswith('https:'):
425 return False
426
427 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
428 try:
429 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700430 r = urllib.request.urlopen(url)
431 except urllib.error.HTTPError as e:
David Pursehouse87b9d9b2012-11-26 18:30:32 +0900432 if e.code in [403, 404]:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700433 return False
Sarah Owenscecd1d82012-11-01 22:59:27 -0700434 print('fatal: Cannot get %s' % url, file=sys.stderr)
435 print('fatal: HTTP error %s' % e.code, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700436 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700437 except urllib.error.URLError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700438 print('fatal: Cannot get %s' % url, file=sys.stderr)
439 print('fatal: error %s' % e.reason, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700440 raise CloneFailure()
441 try:
442 if not quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700443 print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700444 while True:
445 buf = r.read(8192)
446 if buf == '':
447 return True
448 dest.write(buf)
449 finally:
450 r.close()
451 finally:
452 dest.close()
453
454def _ImportBundle(local):
455 path = os.path.join(local, '.git', 'clone.bundle')
456 try:
457 _Fetch(local, local, path, True)
458 finally:
459 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700460
461def _Clone(url, local, quiet):
462 """Clones a git repository to a new subdirectory of repodir
463 """
464 try:
465 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700466 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700467 print('fatal: cannot make %s directory: %s' % (local, e.strerror),
468 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700469 raise CloneFailure()
470
471 cmd = [GIT, 'init', '--quiet']
472 try:
473 proc = subprocess.Popen(cmd, cwd = local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700474 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700475 print(file=sys.stderr)
476 print("fatal: '%s' is not available" % GIT, file=sys.stderr)
477 print('fatal: %s' % e, file=sys.stderr)
478 print(file=sys.stderr)
479 print('Please make sure %s is installed and in your path.' % GIT,
480 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700481 raise CloneFailure()
482 if proc.wait() != 0:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700483 print('fatal: could not create %s' % local, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700484 raise CloneFailure()
485
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700486 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700487 _SetConfig(local, 'remote.origin.url', url)
488 _SetConfig(local, 'remote.origin.fetch',
489 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700490 if _DownloadBundle(url, local, quiet):
491 _ImportBundle(local)
492 else:
493 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700494
495
496def _Verify(cwd, branch, quiet):
497 """Verify the branch has been signed by a tag.
498 """
499 cmd = [GIT, 'describe', 'origin/%s' % branch]
500 proc = subprocess.Popen(cmd,
501 stdout=subprocess.PIPE,
502 stderr=subprocess.PIPE,
503 cwd = cwd)
504 cur = proc.stdout.read().strip()
505 proc.stdout.close()
506
507 proc.stderr.read()
508 proc.stderr.close()
509
510 if proc.wait() != 0 or not cur:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700511 print(file=sys.stderr)
512 print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700513 raise CloneFailure()
514
515 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
516 if m:
517 cur = m.group(1)
518 if not quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700519 print(file=sys.stderr)
520 print("info: Ignoring branch '%s'; using tagged release '%s'"
521 % (branch, cur), file=sys.stderr)
522 print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700523
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800524 env = os.environ.copy()
525 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700526
527 cmd = [GIT, 'tag', '-v', cur]
528 proc = subprocess.Popen(cmd,
529 stdout = subprocess.PIPE,
530 stderr = subprocess.PIPE,
531 cwd = cwd,
532 env = env)
533 out = proc.stdout.read()
534 proc.stdout.close()
535
536 err = proc.stderr.read()
537 proc.stderr.close()
538
539 if proc.wait() != 0:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700540 print(file=sys.stderr)
541 print(out, file=sys.stderr)
542 print(err, file=sys.stderr)
543 print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700544 raise CloneFailure()
545 return '%s^0' % cur
546
547
548def _Checkout(cwd, branch, rev, quiet):
549 """Checkout an upstream branch into the repository and track it.
550 """
551 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
552 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
553 raise CloneFailure()
554
555 _SetConfig(cwd, 'branch.default.remote', 'origin')
556 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
557
558 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
559 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
560 raise CloneFailure()
561
562 cmd = [GIT, 'read-tree', '--reset', '-u']
563 if not quiet:
564 cmd.append('-v')
565 cmd.append('HEAD')
566 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
567 raise CloneFailure()
568
569
570def _FindRepo():
571 """Look for a repo installation, starting at the current directory.
572 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200573 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700574 repo = None
575
Anthony Newnamdf14a702011-01-09 17:31:57 -0800576 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200577 while curdir != '/' \
578 and curdir != olddir \
Anthony Newnamdf14a702011-01-09 17:31:57 -0800579 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200580 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700581 if not os.path.isfile(repo):
582 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200583 olddir = curdir
584 curdir = os.path.dirname(curdir)
585 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700586
587
588class _Options:
589 help = False
590
591
592def _ParseArguments(args):
593 cmd = None
594 opt = _Options()
595 arg = []
596
Sarah Owensa6053d52012-11-01 13:36:50 -0700597 for i in range(len(args)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700598 a = args[i]
599 if a == '-h' or a == '--help':
600 opt.help = True
601
602 elif not a.startswith('-'):
603 cmd = a
604 arg = args[i + 1:]
605 break
606 return cmd, opt, arg
607
608
609def _Usage():
Sarah Owenscecd1d82012-11-01 22:59:27 -0700610 print(
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700611"""usage: repo COMMAND [ARGS]
612
613repo is not yet installed. Use "repo init" to install it here.
614
615The most commonly used repo commands are:
616
617 init Install repo in the current working directory
618 help Display detailed help on a command
619
620For access to the full online help, install repo ("repo init").
Sarah Owenscecd1d82012-11-01 22:59:27 -0700621""", file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700622 sys.exit(1)
623
624
625def _Help(args):
626 if args:
627 if args[0] == 'init':
628 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100629 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700630 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700631 print("error: '%s' is not a bootstrap command.\n"
632 ' For access to online help, install repo ("repo init").'
633 % args[0], file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700634 else:
635 _Usage()
636 sys.exit(1)
637
638
639def _NotInstalled():
Sarah Owenscecd1d82012-11-01 22:59:27 -0700640 print('error: repo is not installed. Use "repo init" to install it here.',
641 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700642 sys.exit(1)
643
644
645def _NoCommands(cmd):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700646 print("""error: command '%s' requires repo to be installed first.
647 Use "repo init" to install it here.""" % cmd, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700648 sys.exit(1)
649
650
651def _RunSelf(wrapper_path):
652 my_dir = os.path.dirname(wrapper_path)
653 my_main = os.path.join(my_dir, 'main.py')
654 my_git = os.path.join(my_dir, '.git')
655
656 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700657 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700658 'project.py',
659 'subcmds']:
660 if not os.path.exists(os.path.join(my_dir, name)):
661 return None, None
662 return my_main, my_git
663 return None, None
664
665
666def _SetDefaultsTo(gitdir):
667 global REPO_URL
668 global REPO_REV
669
670 REPO_URL = gitdir
671 proc = subprocess.Popen([GIT,
672 '--git-dir=%s' % gitdir,
673 'symbolic-ref',
674 'HEAD'],
675 stdout = subprocess.PIPE,
676 stderr = subprocess.PIPE)
677 REPO_REV = proc.stdout.read().strip()
678 proc.stdout.close()
679
680 proc.stderr.read()
681 proc.stderr.close()
682
683 if proc.wait() != 0:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700684 print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700685 sys.exit(1)
686
687
688def main(orig_args):
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200689 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700690 cmd, opt, args = _ParseArguments(orig_args)
691
692 wrapper_path = os.path.abspath(__file__)
693 my_main, my_git = _RunSelf(wrapper_path)
694
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200695 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700696 if opt.help:
697 _Usage()
698 if cmd == 'help':
699 _Help(args)
700 if not cmd:
701 _NotInstalled()
702 if cmd == 'init':
703 if my_git:
704 _SetDefaultsTo(my_git)
705 try:
706 _Init(args)
707 except CloneFailure:
708 for root, dirs, files in os.walk(repodir, topdown=False):
709 for name in files:
710 os.remove(os.path.join(root, name))
711 for name in dirs:
712 os.rmdir(os.path.join(root, name))
713 os.rmdir(repodir)
714 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200715 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700716 else:
717 _NoCommands(cmd)
718
719 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200720 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700721
David Pursehouse685f0802012-11-14 08:34:39 +0900722 ver_str = '.'.join(map(str, VERSION))
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200723 me = [repo_main,
724 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700725 '--wrapper-version=%s' % ver_str,
726 '--wrapper-path=%s' % wrapper_path,
727 '--']
728 me.extend(orig_args)
729 me.extend(extra_args)
730 try:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200731 os.execv(repo_main, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700732 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700733 print("fatal: unable to start %s" % repo_main, file=sys.stderr)
734 print("fatal: %s" % e, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700735 sys.exit(148)
736
737
738if __name__ == '__main__':
739 main(sys.argv[1:])