blob: 32c5895f96380556f4abd12b59b758ed1da60aff [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
37xI1WfzLqdJjsm1Nq98L0cLc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/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>
73-----B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mMOnWrnKSvL+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',
157 help='mirror the forrest')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200158group.add_option('--reference',
159 dest='reference',
160 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700161group.add_option('--depth', type='int', default=None,
162 dest='depth',
163 help='create a shallow clone with given depth; see git clone')
Colin Cross5acde752012-03-28 20:15:45 -0700164group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700165 dest='groups', default='default',
Colin Cross5acde752012-03-28 20:15:45 -0700166 help='restrict manifest projects to ones with a specified group',
167 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700168group.add_option('-p', '--platform',
169 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700170 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700171 'platform group [auto|all|none|linux|darwin|...]',
172 metavar='PLATFORM')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700173
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700174
175# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700176group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700177group.add_option('--repo-url',
178 dest='repo_url',
179 help='repo repository location', metavar='URL')
180group.add_option('--repo-branch',
181 dest='repo_branch',
182 help='repo branch or revision', metavar='REVISION')
183group.add_option('--no-repo-verify',
184 dest='no_repo_verify', action='store_true',
185 help='do not verify repo source code')
186
Victor Boivie841be342011-04-05 11:31:10 +0200187# Other
188group = init_optparse.add_option_group('Other options')
189group.add_option('--config-name',
190 dest='config_name', action="store_true", default=False,
191 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700192
193class CloneFailure(Exception):
194 """Indicate the remote clone of repo itself failed.
195 """
196
197
198def _Init(args):
199 """Installs repo by cloning it over the network.
200 """
201 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800202 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700203 init_optparse.print_usage()
204 sys.exit(1)
205
206 url = opt.repo_url
207 if not url:
208 url = REPO_URL
209 extra_args.append('--repo-url=%s' % url)
210
211 branch = opt.repo_branch
212 if not branch:
213 branch = REPO_REV
214 extra_args.append('--repo-branch=%s' % branch)
215
216 if branch.startswith('refs/heads/'):
217 branch = branch[len('refs/heads/'):]
218 if branch.startswith('refs/'):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700219 print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700220 raise CloneFailure()
221
222 if not os.path.isdir(repodir):
223 try:
224 os.mkdir(repodir)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700225 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700226 print('fatal: cannot make %s directory: %s'
227 % (repodir, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700228 # Don't faise CloneFailure; that would delete the
229 # name. Instead exit immediately.
230 #
231 sys.exit(1)
232
233 _CheckGitVersion()
234 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700235 if NeedSetupGnuPG():
236 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700237 else:
238 can_verify = True
239
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700240 dst = os.path.abspath(os.path.join(repodir, S_repo))
241 _Clone(url, dst, opt.quiet)
242
243 if can_verify and not opt.no_repo_verify:
244 rev = _Verify(dst, branch, opt.quiet)
245 else:
246 rev = 'refs/remotes/origin/%s^0' % branch
247
248 _Checkout(dst, branch, rev, opt.quiet)
249 except CloneFailure:
250 if opt.quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700251 print('fatal: repo init failed; run without --quiet to see why',
252 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700253 raise
254
255
256def _CheckGitVersion():
257 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700258 try:
259 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700260 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700261 print(file=sys.stderr)
262 print("fatal: '%s' is not available" % GIT, file=sys.stderr)
263 print('fatal: %s' % e, file=sys.stderr)
264 print(file=sys.stderr)
265 print('Please make sure %s is installed and in your path.' % GIT,
266 file=sys.stderr)
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700267 raise CloneFailure()
268
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700269 ver_str = proc.stdout.read().strip()
270 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700271 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700272
273 if not ver_str.startswith('git version '):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700274 print('error: "%s" unsupported' % ver_str, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700275 raise CloneFailure()
276
277 ver_str = ver_str[len('git version '):].strip()
David Pursehouse685f0802012-11-14 08:34:39 +0900278 ver_act = tuple(map(int, ver_str.split('.')[0:3]))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700279 if ver_act < MIN_GIT_VERSION:
David Pursehouse685f0802012-11-14 08:34:39 +0900280 need = '.'.join(map(str, MIN_GIT_VERSION))
Sarah Owenscecd1d82012-11-01 22:59:27 -0700281 print('fatal: git %s or later required' % need, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700282 raise CloneFailure()
283
284
Conley Owensc9129d92012-10-01 16:12:28 -0700285def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700286 if not os.path.isdir(home_dot_repo):
287 return True
288
289 kv = os.path.join(home_dot_repo, 'keyring-version')
290 if not os.path.exists(kv):
291 return True
292
293 kv = open(kv).read()
294 if not kv:
295 return True
296
David Pursehouse685f0802012-11-14 08:34:39 +0900297 kv = tuple(map(int, kv.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700298 if kv < KEYRING_VERSION:
299 return True
300 return False
301
302
Conley Owensc9129d92012-10-01 16:12:28 -0700303def SetupGnuPG(quiet):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700304 if not os.path.isdir(home_dot_repo):
305 try:
306 os.mkdir(home_dot_repo)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700307 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700308 print('fatal: cannot make %s directory: %s'
309 % (home_dot_repo, e.strerror), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700310 sys.exit(1)
311
312 if not os.path.isdir(gpg_dir):
313 try:
Sarah Owens60798a32012-10-25 17:53:09 -0700314 os.mkdir(gpg_dir, stat.S_IRWXU)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700315 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700316 print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
317 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700318 sys.exit(1)
319
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800320 env = os.environ.copy()
321 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700322
323 cmd = ['gpg', '--import']
324 try:
325 proc = subprocess.Popen(cmd,
326 env = env,
327 stdin = subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700328 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700329 if not quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700330 print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
331 print('warning: Installing it is strongly encouraged.', file=sys.stderr)
332 print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700333 return False
334
335 proc.stdin.write(MAINTAINER_KEYS)
336 proc.stdin.close()
337
338 if proc.wait() != 0:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700339 print('fatal: registering repo maintainer keys failed', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700340 sys.exit(1)
David Pursehouse98ffba12012-11-14 11:18:00 +0900341 print()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700342
343 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
David Pursehouse685f0802012-11-14 08:34:39 +0900344 fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700345 fd.close()
346 return True
347
348
349def _SetConfig(local, name, value):
350 """Set a git configuration option to the specified value.
351 """
352 cmd = [GIT, 'config', name, value]
353 if subprocess.Popen(cmd, cwd = local).wait() != 0:
354 raise CloneFailure()
355
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700356
357def _InitHttp():
358 handlers = []
359
Sarah Owens1f7627f2012-10-31 09:21:55 -0700360 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700361 try:
362 import netrc
363 n = netrc.netrc()
364 for host in n.hosts:
365 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800366 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
367 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700368 except:
369 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700370 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
371 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700372
373 if 'http_proxy' in os.environ:
374 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700375 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700376 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700377 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
378 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
379 urllib.request.install_opener(urllib.request.build_opener(*handlers))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700380
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700381def _Fetch(url, local, src, quiet):
382 if not quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700383 print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700384
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700385 cmd = [GIT, 'fetch']
386 if quiet:
387 cmd.append('--quiet')
388 err = subprocess.PIPE
389 else:
390 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700391 cmd.append(src)
392 cmd.append('+refs/heads/*:refs/remotes/origin/*')
393 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700394
395 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
396 if err:
397 proc.stderr.read()
398 proc.stderr.close()
399 if proc.wait() != 0:
400 raise CloneFailure()
401
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700402def _DownloadBundle(url, local, quiet):
403 if not url.endswith('/'):
404 url += '/'
405 url += 'clone.bundle'
406
407 proc = subprocess.Popen(
408 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
409 cwd = local,
410 stdout = subprocess.PIPE)
411 for line in proc.stdout:
412 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
413 if m:
414 new_url = m.group(1)
415 old_url = m.group(2)
416 if url.startswith(old_url):
417 url = new_url + url[len(old_url):]
418 break
419 proc.stdout.close()
420 proc.wait()
421
422 if not url.startswith('http:') and not url.startswith('https:'):
423 return False
424
425 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
426 try:
427 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700428 r = urllib.request.urlopen(url)
429 except urllib.error.HTTPError as e:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700430 if e.code == 404:
431 return False
Sarah Owenscecd1d82012-11-01 22:59:27 -0700432 print('fatal: Cannot get %s' % url, file=sys.stderr)
433 print('fatal: HTTP error %s' % e.code, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700434 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700435 except urllib.error.URLError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700436 print('fatal: Cannot get %s' % url, file=sys.stderr)
437 print('fatal: error %s' % e.reason, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700438 raise CloneFailure()
439 try:
440 if not quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700441 print('Get %s' % url, file=sys.stderr)
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700442 while True:
443 buf = r.read(8192)
444 if buf == '':
445 return True
446 dest.write(buf)
447 finally:
448 r.close()
449 finally:
450 dest.close()
451
452def _ImportBundle(local):
453 path = os.path.join(local, '.git', 'clone.bundle')
454 try:
455 _Fetch(local, local, path, True)
456 finally:
457 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700458
459def _Clone(url, local, quiet):
460 """Clones a git repository to a new subdirectory of repodir
461 """
462 try:
463 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700464 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700465 print('fatal: cannot make %s directory: %s' % (local, e.strerror),
466 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700467 raise CloneFailure()
468
469 cmd = [GIT, 'init', '--quiet']
470 try:
471 proc = subprocess.Popen(cmd, cwd = local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700472 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700473 print(file=sys.stderr)
474 print("fatal: '%s' is not available" % GIT, file=sys.stderr)
475 print('fatal: %s' % e, file=sys.stderr)
476 print(file=sys.stderr)
477 print('Please make sure %s is installed and in your path.' % GIT,
478 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700479 raise CloneFailure()
480 if proc.wait() != 0:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700481 print('fatal: could not create %s' % local, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700482 raise CloneFailure()
483
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700484 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700485 _SetConfig(local, 'remote.origin.url', url)
486 _SetConfig(local, 'remote.origin.fetch',
487 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700488 if _DownloadBundle(url, local, quiet):
489 _ImportBundle(local)
490 else:
491 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700492
493
494def _Verify(cwd, branch, quiet):
495 """Verify the branch has been signed by a tag.
496 """
497 cmd = [GIT, 'describe', 'origin/%s' % branch]
498 proc = subprocess.Popen(cmd,
499 stdout=subprocess.PIPE,
500 stderr=subprocess.PIPE,
501 cwd = cwd)
502 cur = proc.stdout.read().strip()
503 proc.stdout.close()
504
505 proc.stderr.read()
506 proc.stderr.close()
507
508 if proc.wait() != 0 or not cur:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700509 print(file=sys.stderr)
510 print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700511 raise CloneFailure()
512
513 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
514 if m:
515 cur = m.group(1)
516 if not quiet:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700517 print(file=sys.stderr)
518 print("info: Ignoring branch '%s'; using tagged release '%s'"
519 % (branch, cur), file=sys.stderr)
520 print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700521
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800522 env = os.environ.copy()
523 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700524
525 cmd = [GIT, 'tag', '-v', cur]
526 proc = subprocess.Popen(cmd,
527 stdout = subprocess.PIPE,
528 stderr = subprocess.PIPE,
529 cwd = cwd,
530 env = env)
531 out = proc.stdout.read()
532 proc.stdout.close()
533
534 err = proc.stderr.read()
535 proc.stderr.close()
536
537 if proc.wait() != 0:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700538 print(file=sys.stderr)
539 print(out, file=sys.stderr)
540 print(err, file=sys.stderr)
541 print(file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700542 raise CloneFailure()
543 return '%s^0' % cur
544
545
546def _Checkout(cwd, branch, rev, quiet):
547 """Checkout an upstream branch into the repository and track it.
548 """
549 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
550 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
551 raise CloneFailure()
552
553 _SetConfig(cwd, 'branch.default.remote', 'origin')
554 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
555
556 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
557 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
558 raise CloneFailure()
559
560 cmd = [GIT, 'read-tree', '--reset', '-u']
561 if not quiet:
562 cmd.append('-v')
563 cmd.append('HEAD')
564 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
565 raise CloneFailure()
566
567
568def _FindRepo():
569 """Look for a repo installation, starting at the current directory.
570 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200571 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700572 repo = None
573
Anthony Newnamdf14a702011-01-09 17:31:57 -0800574 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200575 while curdir != '/' \
576 and curdir != olddir \
Anthony Newnamdf14a702011-01-09 17:31:57 -0800577 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200578 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700579 if not os.path.isfile(repo):
580 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200581 olddir = curdir
582 curdir = os.path.dirname(curdir)
583 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700584
585
586class _Options:
587 help = False
588
589
590def _ParseArguments(args):
591 cmd = None
592 opt = _Options()
593 arg = []
594
Sarah Owensa6053d52012-11-01 13:36:50 -0700595 for i in range(len(args)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700596 a = args[i]
597 if a == '-h' or a == '--help':
598 opt.help = True
599
600 elif not a.startswith('-'):
601 cmd = a
602 arg = args[i + 1:]
603 break
604 return cmd, opt, arg
605
606
607def _Usage():
Sarah Owenscecd1d82012-11-01 22:59:27 -0700608 print(
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700609"""usage: repo COMMAND [ARGS]
610
611repo is not yet installed. Use "repo init" to install it here.
612
613The most commonly used repo commands are:
614
615 init Install repo in the current working directory
616 help Display detailed help on a command
617
618For access to the full online help, install repo ("repo init").
Sarah Owenscecd1d82012-11-01 22:59:27 -0700619""", file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700620 sys.exit(1)
621
622
623def _Help(args):
624 if args:
625 if args[0] == 'init':
626 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100627 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700628 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700629 print("error: '%s' is not a bootstrap command.\n"
630 ' For access to online help, install repo ("repo init").'
631 % args[0], file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700632 else:
633 _Usage()
634 sys.exit(1)
635
636
637def _NotInstalled():
Sarah Owenscecd1d82012-11-01 22:59:27 -0700638 print('error: repo is not installed. Use "repo init" to install it here.',
639 file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700640 sys.exit(1)
641
642
643def _NoCommands(cmd):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700644 print("""error: command '%s' requires repo to be installed first.
645 Use "repo init" to install it here.""" % cmd, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700646 sys.exit(1)
647
648
649def _RunSelf(wrapper_path):
650 my_dir = os.path.dirname(wrapper_path)
651 my_main = os.path.join(my_dir, 'main.py')
652 my_git = os.path.join(my_dir, '.git')
653
654 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700655 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700656 'project.py',
657 'subcmds']:
658 if not os.path.exists(os.path.join(my_dir, name)):
659 return None, None
660 return my_main, my_git
661 return None, None
662
663
664def _SetDefaultsTo(gitdir):
665 global REPO_URL
666 global REPO_REV
667
668 REPO_URL = gitdir
669 proc = subprocess.Popen([GIT,
670 '--git-dir=%s' % gitdir,
671 'symbolic-ref',
672 'HEAD'],
673 stdout = subprocess.PIPE,
674 stderr = subprocess.PIPE)
675 REPO_REV = proc.stdout.read().strip()
676 proc.stdout.close()
677
678 proc.stderr.read()
679 proc.stderr.close()
680
681 if proc.wait() != 0:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700682 print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700683 sys.exit(1)
684
685
686def main(orig_args):
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200687 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700688 cmd, opt, args = _ParseArguments(orig_args)
689
690 wrapper_path = os.path.abspath(__file__)
691 my_main, my_git = _RunSelf(wrapper_path)
692
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200693 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700694 if opt.help:
695 _Usage()
696 if cmd == 'help':
697 _Help(args)
698 if not cmd:
699 _NotInstalled()
700 if cmd == 'init':
701 if my_git:
702 _SetDefaultsTo(my_git)
703 try:
704 _Init(args)
705 except CloneFailure:
706 for root, dirs, files in os.walk(repodir, topdown=False):
707 for name in files:
708 os.remove(os.path.join(root, name))
709 for name in dirs:
710 os.rmdir(os.path.join(root, name))
711 os.rmdir(repodir)
712 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200713 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700714 else:
715 _NoCommands(cmd)
716
717 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200718 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700719
David Pursehouse685f0802012-11-14 08:34:39 +0900720 ver_str = '.'.join(map(str, VERSION))
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200721 me = [repo_main,
722 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700723 '--wrapper-version=%s' % ver_str,
724 '--wrapper-path=%s' % wrapper_path,
725 '--']
726 me.extend(orig_args)
727 me.extend(extra_args)
728 try:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200729 os.execv(repo_main, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700730 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700731 print("fatal: unable to start %s" % repo_main, file=sys.stderr)
732 print("fatal: %s" % e, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700733 sys.exit(148)
734
735
736if __name__ == '__main__':
737 main(sys.argv[1:])