repo 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. #!/usr/bin/env python
  2. # repo default configuration
  3. #
  4. import os
  5. REPO_URL = os.environ.get('REPO_URL', None)
  6. if not REPO_URL:
  7. REPO_URL = 'https://gerrit.googlesource.com/git-repo'
  8. REPO_REV = 'stable'
  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. # increment this whenever we make important changes to this script
  23. VERSION = (1, 24)
  24. # increment this if the MAINTAINER_KEYS block is modified
  25. KEYRING_VERSION = (1, 2)
  26. # Each individual key entry is created by using:
  27. # gpg --armor --export keyid
  28. MAINTAINER_KEYS = """
  29. Repo Maintainer <repo@android.kernel.org>
  30. -----BEGIN PGP PUBLIC KEY BLOCK-----
  31. Version: GnuPG v1.4.2.2 (GNU/Linux)
  32. mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
  33. WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
  34. VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
  35. xI1WfzLqdJjsm1Nq98L0cLcD/iNsILCuw44PRds3J75YP0pze7YF/6WFMB6QSFGu
  36. aUX1FsTTztKNXGms8i5b2l1B8JaLRWq/jOnZzyl1zrUJhkc0JgyZW5oNLGyWGhKD
  37. Fxp5YpHuIuMImopWEMFIRQNrvlg+YVK8t3FpdI1RY0LYqha8pPzANhEYgSfoVzOb
  38. fbfbA/4ioOrxy8ifSoga7ITyZMA+XbW8bx33WXutO9N7SPKS/AK2JpasSEVLZcON
  39. ae5hvAEGVXKxVPDjJBmIc2cOe7kOKSi3OxLzBqrjS2rnjiP4o0ekhZIe4+ocwVOg
  40. e0PLlH5avCqihGRhpoqDRsmpzSHzJIxtoeb+GgGEX8KkUs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xNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
  57. FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
  58. +WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
  59. w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
  60. Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
  61. p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
  62. 0V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
  63. 5xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
  64. HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
  65. zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
  66. TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
  67. =CMiZ
  68. -----END PGP PUBLIC KEY BLOCK-----
  69. Conley Owens <cco3@android.com>
  70. -----BEGIN PGP PUBLIC KEY BLOCK-----
  71. Version: GnuPG v1.4.11 (GNU/Linux)
  72. mQENBFHRvc8BCADFg45Xx/y6QDC+T7Y/gGc7vx0ww7qfOwIKlAZ9xG3qKunMxo+S
  73. hPCnzEl3cq+6I1Ww/ndop/HB3N3toPXRCoN8Vs4/Hc7by+SnaLFnacrm+tV5/OgT
  74. V37Lzt8lhay1Kl+YfpFwHYYpIEBLFV9knyfRXS/428W2qhdzYfvB15/AasRmwmor
  75. py4NIzSs8UD/SPr1ihqNCdZM76+MQyN5HMYXW/ALZXUF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EM0Xw8drr4omg2fUoK1J33ozlA/RxeA/lJ
  92. I3KnyCDTpXuIeBKPGkdL8uMATC9Z8DnBBajRlftNDVZS3Hz4G09G9QpMojvJkFJV
  93. By+01Flw/X+eeN8NpqSuLV4W+AjEO8at/VvgKr1AFvBRdZ7GkpI1o6DgPe7ZqX+1
  94. dzQZt3e13W0rVBb/bUgx9iSLoeWP3aq/k+/GRGOR+S6F6BBSl0SQ2EF2+dIywb1x
  95. JuinEP+AwLAUZ1Bsx9ISC0Agpk2VeHXPL3FGhroEmoMvBzO0kTFGyoeT7PR/BfKv
  96. +H/g3HsL2LOB9uoIm8/5p2TTU5ttYCXMHhQZ81AY
  97. =AUp4
  98. -----END PGP PUBLIC KEY BLOCK-----
  99. """
  100. GIT = 'git' # our git command
  101. MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
  102. repodir = '.repo' # name of repo's private directory
  103. S_repo = 'repo' # special repo repository
  104. S_manifests = 'manifests' # special manifest repository
  105. REPO_MAIN = S_repo + '/main.py' # main script
  106. MIN_PYTHON_VERSION = (2, 6) # minimum supported python version
  107. GITC_CONFIG_FILE = '/gitc/.config'
  108. GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
  109. import errno
  110. import optparse
  111. import platform
  112. import re
  113. import shutil
  114. import stat
  115. import subprocess
  116. import sys
  117. if sys.version_info[0] == 3:
  118. import urllib.request
  119. import urllib.error
  120. else:
  121. import imp
  122. import urllib2
  123. urllib = imp.new_module('urllib')
  124. urllib.request = urllib2
  125. urllib.error = urllib2
  126. def _print(*objects, **kwargs):
  127. sep = kwargs.get('sep', ' ')
  128. end = kwargs.get('end', '\n')
  129. out = kwargs.get('file', sys.stdout)
  130. out.write(sep.join(objects) + end)
  131. # On Windows stderr is buffered, so flush to maintain the order of error messages.
  132. if out == sys.stderr and platform.system() == "Windows":
  133. out.flush()
  134. # Python version check
  135. ver = sys.version_info
  136. if (ver[0], ver[1]) < MIN_PYTHON_VERSION:
  137. _print('error: Python version %s unsupported.\n'
  138. 'Please use Python 2.6 - 2.7 instead.'
  139. % sys.version.split(' ')[0], file=sys.stderr)
  140. sys.exit(1)
  141. home_dot_repo = os.path.expanduser('~/.repoconfig')
  142. gpg_dir = os.path.join(home_dot_repo, 'gnupg')
  143. extra_args = []
  144. init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
  145. # Logging
  146. group = init_optparse.add_option_group('Logging options')
  147. group.add_option('-q', '--quiet',
  148. dest="quiet", action="store_true", default=False,
  149. help="be quiet")
  150. # Manifest
  151. group = init_optparse.add_option_group('Manifest options')
  152. group.add_option('-u', '--manifest-url',
  153. dest='manifest_url',
  154. help='manifest repository location', metavar='URL')
  155. group.add_option('-b', '--manifest-branch',
  156. dest='manifest_branch',
  157. help='manifest branch or revision', metavar='REVISION')
  158. group.add_option('-m', '--manifest-name',
  159. dest='manifest_name',
  160. help='initial manifest file', metavar='NAME.xml')
  161. group.add_option('-c', '--current-branch',
  162. dest='current_branch_only', action='store_true',
  163. help='fetch only current manifest branch from server')
  164. group.add_option('--mirror',
  165. dest='mirror', action='store_true',
  166. help='create a replica of the remote repositories '
  167. 'rather than a client working directory')
  168. group.add_option('--reference',
  169. dest='reference',
  170. help='location of mirror directory', metavar='DIR')
  171. group.add_option('--dissociate',
  172. dest='dissociate', action='store_true',
  173. help='dissociate from reference mirrors after clone')
  174. group.add_option('--depth', type='int', default=None,
  175. dest='depth',
  176. help='create a shallow clone with given depth; see git clone')
  177. group.add_option('--archive',
  178. dest='archive', action='store_true',
  179. help='checkout an archive instead of a git repository for '
  180. 'each project. See git archive.')
  181. group.add_option('--submodules',
  182. dest='submodules', action='store_true',
  183. help='sync any submodules associated with the manifest repo')
  184. group.add_option('-g', '--groups',
  185. dest='groups', default='default',
  186. help='restrict manifest projects to ones with specified '
  187. 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
  188. metavar='GROUP')
  189. group.add_option('-p', '--platform',
  190. dest='platform', default="auto",
  191. help='restrict manifest projects to ones with a specified '
  192. 'platform group [auto|all|none|linux|darwin|...]',
  193. metavar='PLATFORM')
  194. group.add_option('--no-clone-bundle',
  195. dest='no_clone_bundle', action='store_true',
  196. help='disable use of /clone.bundle on HTTP/HTTPS')
  197. group.add_option('--no-tags',
  198. dest='no_tags', action='store_true',
  199. help="don't fetch tags in the manifest")
  200. # Tool
  201. group = init_optparse.add_option_group('repo Version options')
  202. group.add_option('--repo-url',
  203. dest='repo_url',
  204. help='repo repository location', metavar='URL')
  205. group.add_option('--repo-branch',
  206. dest='repo_branch',
  207. help='repo branch or revision', metavar='REVISION')
  208. group.add_option('--no-repo-verify',
  209. dest='no_repo_verify', action='store_true',
  210. help='do not verify repo source code')
  211. # Other
  212. group = init_optparse.add_option_group('Other options')
  213. group.add_option('--config-name',
  214. dest='config_name', action="store_true", default=False,
  215. help='Always prompt for name/e-mail')
  216. def _GitcInitOptions(init_optparse_arg):
  217. init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
  218. g = init_optparse_arg.add_option_group('GITC options')
  219. g.add_option('-f', '--manifest-file',
  220. dest='manifest_file',
  221. help='Optional manifest file to use for this GITC client.')
  222. g.add_option('-c', '--gitc-client',
  223. dest='gitc_client',
  224. help='The name of the gitc_client instance to create or modify.')
  225. _gitc_manifest_dir = None
  226. def get_gitc_manifest_dir():
  227. global _gitc_manifest_dir
  228. if _gitc_manifest_dir is None:
  229. _gitc_manifest_dir = ''
  230. try:
  231. with open(GITC_CONFIG_FILE, 'r') as gitc_config:
  232. for line in gitc_config:
  233. match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
  234. if match:
  235. _gitc_manifest_dir = match.group('gitc_manifest_dir')
  236. except IOError:
  237. pass
  238. return _gitc_manifest_dir
  239. def gitc_parse_clientdir(gitc_fs_path):
  240. """Parse a path in the GITC FS and return its client name.
  241. @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
  242. @returns: The GITC client name
  243. """
  244. if gitc_fs_path == GITC_FS_ROOT_DIR:
  245. return None
  246. if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
  247. manifest_dir = get_gitc_manifest_dir()
  248. if manifest_dir == '':
  249. return None
  250. if manifest_dir[-1] != '/':
  251. manifest_dir += '/'
  252. if gitc_fs_path == manifest_dir:
  253. return None
  254. if not gitc_fs_path.startswith(manifest_dir):
  255. return None
  256. return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
  257. return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
  258. class CloneFailure(Exception):
  259. """Indicate the remote clone of repo itself failed.
  260. """
  261. def _Init(args, gitc_init=False):
  262. """Installs repo by cloning it over the network.
  263. """
  264. if gitc_init:
  265. _GitcInitOptions(init_optparse)
  266. opt, args = init_optparse.parse_args(args)
  267. if args:
  268. init_optparse.print_usage()
  269. sys.exit(1)
  270. url = opt.repo_url
  271. if not url:
  272. url = REPO_URL
  273. extra_args.append('--repo-url=%s' % url)
  274. branch = opt.repo_branch
  275. if not branch:
  276. branch = REPO_REV
  277. extra_args.append('--repo-branch=%s' % branch)
  278. if branch.startswith('refs/heads/'):
  279. branch = branch[len('refs/heads/'):]
  280. if branch.startswith('refs/'):
  281. _print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
  282. raise CloneFailure()
  283. try:
  284. if gitc_init:
  285. gitc_manifest_dir = get_gitc_manifest_dir()
  286. if not gitc_manifest_dir:
  287. _print('fatal: GITC filesystem is not available. Exiting...',
  288. file=sys.stderr)
  289. sys.exit(1)
  290. gitc_client = opt.gitc_client
  291. if not gitc_client:
  292. gitc_client = gitc_parse_clientdir(os.getcwd())
  293. if not gitc_client:
  294. _print('fatal: GITC client (-c) is required.', file=sys.stderr)
  295. sys.exit(1)
  296. client_dir = os.path.join(gitc_manifest_dir, gitc_client)
  297. if not os.path.exists(client_dir):
  298. os.makedirs(client_dir)
  299. os.chdir(client_dir)
  300. if os.path.exists(repodir):
  301. # This GITC Client has already initialized repo so continue.
  302. return
  303. os.mkdir(repodir)
  304. except OSError as e:
  305. if e.errno != errno.EEXIST:
  306. _print('fatal: cannot make %s directory: %s'
  307. % (repodir, e.strerror), file=sys.stderr)
  308. # Don't raise CloneFailure; that would delete the
  309. # name. Instead exit immediately.
  310. #
  311. sys.exit(1)
  312. _CheckGitVersion()
  313. try:
  314. if NeedSetupGnuPG():
  315. can_verify = SetupGnuPG(opt.quiet)
  316. else:
  317. can_verify = True
  318. dst = os.path.abspath(os.path.join(repodir, S_repo))
  319. _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
  320. if can_verify and not opt.no_repo_verify:
  321. rev = _Verify(dst, branch, opt.quiet)
  322. else:
  323. rev = 'refs/remotes/origin/%s^0' % branch
  324. _Checkout(dst, branch, rev, opt.quiet)
  325. if not os.path.isfile(os.path.join(dst, 'repo')):
  326. _print("warning: '%s' does not look like a git-repo repository, is "
  327. "REPO_URL set correctly?" % url, file=sys.stderr)
  328. except CloneFailure:
  329. if opt.quiet:
  330. _print('fatal: repo init failed; run without --quiet to see why',
  331. file=sys.stderr)
  332. raise
  333. def ParseGitVersion(ver_str):
  334. if not ver_str.startswith('git version '):
  335. return None
  336. num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
  337. to_tuple = []
  338. for num_str in num_ver_str.split('.')[:3]:
  339. if num_str.isdigit():
  340. to_tuple.append(int(num_str))
  341. else:
  342. to_tuple.append(0)
  343. return tuple(to_tuple)
  344. def _CheckGitVersion():
  345. cmd = [GIT, '--version']
  346. try:
  347. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  348. except OSError as e:
  349. _print(file=sys.stderr)
  350. _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
  351. _print('fatal: %s' % e, file=sys.stderr)
  352. _print(file=sys.stderr)
  353. _print('Please make sure %s is installed and in your path.' % GIT,
  354. file=sys.stderr)
  355. raise CloneFailure()
  356. ver_str = proc.stdout.read().strip()
  357. proc.stdout.close()
  358. proc.wait()
  359. ver_act = ParseGitVersion(ver_str)
  360. if ver_act is None:
  361. _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
  362. raise CloneFailure()
  363. if ver_act < MIN_GIT_VERSION:
  364. need = '.'.join(map(str, MIN_GIT_VERSION))
  365. _print('fatal: git %s or later required' % need, file=sys.stderr)
  366. raise CloneFailure()
  367. def NeedSetupGnuPG():
  368. if not os.path.isdir(home_dot_repo):
  369. return True
  370. kv = os.path.join(home_dot_repo, 'keyring-version')
  371. if not os.path.exists(kv):
  372. return True
  373. kv = open(kv).read()
  374. if not kv:
  375. return True
  376. kv = tuple(map(int, kv.split('.')))
  377. if kv < KEYRING_VERSION:
  378. return True
  379. return False
  380. def SetupGnuPG(quiet):
  381. try:
  382. os.mkdir(home_dot_repo)
  383. except OSError as e:
  384. if e.errno != errno.EEXIST:
  385. _print('fatal: cannot make %s directory: %s'
  386. % (home_dot_repo, e.strerror), file=sys.stderr)
  387. sys.exit(1)
  388. try:
  389. os.mkdir(gpg_dir, stat.S_IRWXU)
  390. except OSError as e:
  391. if e.errno != errno.EEXIST:
  392. _print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
  393. file=sys.stderr)
  394. sys.exit(1)
  395. env = os.environ.copy()
  396. try:
  397. env['GNUPGHOME'] = gpg_dir
  398. except UnicodeEncodeError:
  399. env['GNUPGHOME'] = gpg_dir.encode()
  400. cmd = ['gpg', '--import']
  401. try:
  402. proc = subprocess.Popen(cmd,
  403. env=env,
  404. stdin=subprocess.PIPE)
  405. except OSError as e:
  406. if not quiet:
  407. _print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
  408. _print('warning: Installing it is strongly encouraged.', file=sys.stderr)
  409. _print(file=sys.stderr)
  410. return False
  411. proc.stdin.write(MAINTAINER_KEYS)
  412. proc.stdin.close()
  413. if proc.wait() != 0:
  414. _print('fatal: registering repo maintainer keys failed', file=sys.stderr)
  415. sys.exit(1)
  416. _print()
  417. fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
  418. fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
  419. fd.close()
  420. return True
  421. def _SetConfig(local, name, value):
  422. """Set a git configuration option to the specified value.
  423. """
  424. cmd = [GIT, 'config', name, value]
  425. if subprocess.Popen(cmd, cwd=local).wait() != 0:
  426. raise CloneFailure()
  427. def _InitHttp():
  428. handlers = []
  429. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  430. try:
  431. import netrc
  432. n = netrc.netrc()
  433. for host in n.hosts:
  434. p = n.hosts[host]
  435. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  436. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  437. except:
  438. pass
  439. handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
  440. handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
  441. if 'http_proxy' in os.environ:
  442. url = os.environ['http_proxy']
  443. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  444. if 'REPO_CURL_VERBOSE' in os.environ:
  445. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  446. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  447. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  448. def _Fetch(url, local, src, quiet):
  449. if not quiet:
  450. _print('Get %s' % url, file=sys.stderr)
  451. cmd = [GIT, 'fetch']
  452. if quiet:
  453. cmd.append('--quiet')
  454. err = subprocess.PIPE
  455. else:
  456. err = None
  457. cmd.append(src)
  458. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  459. cmd.append('+refs/tags/*:refs/tags/*')
  460. proc = subprocess.Popen(cmd, cwd=local, stderr=err)
  461. if err:
  462. proc.stderr.read()
  463. proc.stderr.close()
  464. if proc.wait() != 0:
  465. raise CloneFailure()
  466. def _DownloadBundle(url, local, quiet):
  467. if not url.endswith('/'):
  468. url += '/'
  469. url += 'clone.bundle'
  470. proc = subprocess.Popen(
  471. [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
  472. cwd=local,
  473. stdout=subprocess.PIPE)
  474. for line in proc.stdout:
  475. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  476. if m:
  477. new_url = m.group(1)
  478. old_url = m.group(2)
  479. if url.startswith(old_url):
  480. url = new_url + url[len(old_url):]
  481. break
  482. proc.stdout.close()
  483. proc.wait()
  484. if not url.startswith('http:') and not url.startswith('https:'):
  485. return False
  486. dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
  487. try:
  488. try:
  489. r = urllib.request.urlopen(url)
  490. except urllib.error.HTTPError as e:
  491. if e.code in [401, 403, 404, 501]:
  492. return False
  493. _print('fatal: Cannot get %s' % url, file=sys.stderr)
  494. _print('fatal: HTTP error %s' % e.code, file=sys.stderr)
  495. raise CloneFailure()
  496. except urllib.error.URLError as e:
  497. _print('fatal: Cannot get %s' % url, file=sys.stderr)
  498. _print('fatal: error %s' % e.reason, file=sys.stderr)
  499. raise CloneFailure()
  500. try:
  501. if not quiet:
  502. _print('Get %s' % url, file=sys.stderr)
  503. while True:
  504. buf = r.read(8192)
  505. if buf == '':
  506. return True
  507. dest.write(buf)
  508. finally:
  509. r.close()
  510. finally:
  511. dest.close()
  512. def _ImportBundle(local):
  513. path = os.path.join(local, '.git', 'clone.bundle')
  514. try:
  515. _Fetch(local, local, path, True)
  516. finally:
  517. os.remove(path)
  518. def _Clone(url, local, quiet, clone_bundle):
  519. """Clones a git repository to a new subdirectory of repodir
  520. """
  521. try:
  522. os.mkdir(local)
  523. except OSError as e:
  524. _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
  525. file=sys.stderr)
  526. raise CloneFailure()
  527. cmd = [GIT, 'init', '--quiet']
  528. try:
  529. proc = subprocess.Popen(cmd, cwd=local)
  530. except OSError as e:
  531. _print(file=sys.stderr)
  532. _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
  533. _print('fatal: %s' % e, file=sys.stderr)
  534. _print(file=sys.stderr)
  535. _print('Please make sure %s is installed and in your path.' % GIT,
  536. file=sys.stderr)
  537. raise CloneFailure()
  538. if proc.wait() != 0:
  539. _print('fatal: could not create %s' % local, file=sys.stderr)
  540. raise CloneFailure()
  541. _InitHttp()
  542. _SetConfig(local, 'remote.origin.url', url)
  543. _SetConfig(local,
  544. 'remote.origin.fetch',
  545. '+refs/heads/*:refs/remotes/origin/*')
  546. if clone_bundle and _DownloadBundle(url, local, quiet):
  547. _ImportBundle(local)
  548. _Fetch(url, local, 'origin', quiet)
  549. def _Verify(cwd, branch, quiet):
  550. """Verify the branch has been signed by a tag.
  551. """
  552. cmd = [GIT, 'describe', 'origin/%s' % branch]
  553. proc = subprocess.Popen(cmd,
  554. stdout=subprocess.PIPE,
  555. stderr=subprocess.PIPE,
  556. cwd=cwd)
  557. cur = proc.stdout.read().strip()
  558. proc.stdout.close()
  559. proc.stderr.read()
  560. proc.stderr.close()
  561. if proc.wait() != 0 or not cur:
  562. _print(file=sys.stderr)
  563. _print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
  564. raise CloneFailure()
  565. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  566. if m:
  567. cur = m.group(1)
  568. if not quiet:
  569. _print(file=sys.stderr)
  570. _print("info: Ignoring branch '%s'; using tagged release '%s'"
  571. % (branch, cur), file=sys.stderr)
  572. _print(file=sys.stderr)
  573. env = os.environ.copy()
  574. try:
  575. env['GNUPGHOME'] = gpg_dir
  576. except UnicodeEncodeError:
  577. env['GNUPGHOME'] = gpg_dir.encode()
  578. cmd = [GIT, 'tag', '-v', cur]
  579. proc = subprocess.Popen(cmd,
  580. stdout=subprocess.PIPE,
  581. stderr=subprocess.PIPE,
  582. cwd=cwd,
  583. env=env)
  584. out = proc.stdout.read()
  585. proc.stdout.close()
  586. err = proc.stderr.read()
  587. proc.stderr.close()
  588. if proc.wait() != 0:
  589. _print(file=sys.stderr)
  590. _print(out, file=sys.stderr)
  591. _print(err, file=sys.stderr)
  592. _print(file=sys.stderr)
  593. raise CloneFailure()
  594. return '%s^0' % cur
  595. def _Checkout(cwd, branch, rev, quiet):
  596. """Checkout an upstream branch into the repository and track it.
  597. """
  598. cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
  599. if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
  600. raise CloneFailure()
  601. _SetConfig(cwd, 'branch.default.remote', 'origin')
  602. _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
  603. cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
  604. if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
  605. raise CloneFailure()
  606. cmd = [GIT, 'read-tree', '--reset', '-u']
  607. if not quiet:
  608. cmd.append('-v')
  609. cmd.append('HEAD')
  610. if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
  611. raise CloneFailure()
  612. def _FindRepo():
  613. """Look for a repo installation, starting at the current directory.
  614. """
  615. curdir = os.getcwd()
  616. repo = None
  617. olddir = None
  618. while curdir != '/' \
  619. and curdir != olddir \
  620. and not repo:
  621. repo = os.path.join(curdir, repodir, REPO_MAIN)
  622. if not os.path.isfile(repo):
  623. repo = None
  624. olddir = curdir
  625. curdir = os.path.dirname(curdir)
  626. return (repo, os.path.join(curdir, repodir))
  627. class _Options(object):
  628. help = False
  629. def _ParseArguments(args):
  630. cmd = None
  631. opt = _Options()
  632. arg = []
  633. for i in range(len(args)):
  634. a = args[i]
  635. if a == '-h' or a == '--help':
  636. opt.help = True
  637. elif not a.startswith('-'):
  638. cmd = a
  639. arg = args[i + 1:]
  640. break
  641. return cmd, opt, arg
  642. def _Usage():
  643. gitc_usage = ""
  644. if get_gitc_manifest_dir():
  645. gitc_usage = " gitc-init Initialize a GITC Client.\n"
  646. _print(
  647. """usage: repo COMMAND [ARGS]
  648. repo is not yet installed. Use "repo init" to install it here.
  649. The most commonly used repo commands are:
  650. init Install repo in the current working directory
  651. """ + gitc_usage +
  652. """ help Display detailed help on a command
  653. For access to the full online help, install repo ("repo init").
  654. """, file=sys.stderr)
  655. sys.exit(1)
  656. def _Help(args):
  657. if args:
  658. if args[0] == 'init':
  659. init_optparse.print_help()
  660. sys.exit(0)
  661. elif args[0] == 'gitc-init':
  662. _GitcInitOptions(init_optparse)
  663. init_optparse.print_help()
  664. sys.exit(0)
  665. else:
  666. _print("error: '%s' is not a bootstrap command.\n"
  667. ' For access to online help, install repo ("repo init").'
  668. % args[0], file=sys.stderr)
  669. else:
  670. _Usage()
  671. sys.exit(1)
  672. def _NotInstalled():
  673. _print('error: repo is not installed. Use "repo init" to install it here.',
  674. file=sys.stderr)
  675. sys.exit(1)
  676. def _NoCommands(cmd):
  677. _print("""error: command '%s' requires repo to be installed first.
  678. Use "repo init" to install it here.""" % cmd, file=sys.stderr)
  679. sys.exit(1)
  680. def _RunSelf(wrapper_path):
  681. my_dir = os.path.dirname(wrapper_path)
  682. my_main = os.path.join(my_dir, 'main.py')
  683. my_git = os.path.join(my_dir, '.git')
  684. if os.path.isfile(my_main) and os.path.isdir(my_git):
  685. for name in ['git_config.py',
  686. 'project.py',
  687. 'subcmds']:
  688. if not os.path.exists(os.path.join(my_dir, name)):
  689. return None, None
  690. return my_main, my_git
  691. return None, None
  692. def _SetDefaultsTo(gitdir):
  693. global REPO_URL
  694. global REPO_REV
  695. REPO_URL = gitdir
  696. proc = subprocess.Popen([GIT,
  697. '--git-dir=%s' % gitdir,
  698. 'symbolic-ref',
  699. 'HEAD'],
  700. stdout=subprocess.PIPE,
  701. stderr=subprocess.PIPE)
  702. REPO_REV = proc.stdout.read().strip()
  703. proc.stdout.close()
  704. proc.stderr.read()
  705. proc.stderr.close()
  706. if proc.wait() != 0:
  707. _print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
  708. sys.exit(1)
  709. def main(orig_args):
  710. cmd, opt, args = _ParseArguments(orig_args)
  711. repo_main, rel_repo_dir = None, None
  712. # Don't use the local repo copy, make sure to switch to the gitc client first.
  713. if cmd != 'gitc-init':
  714. repo_main, rel_repo_dir = _FindRepo()
  715. wrapper_path = os.path.abspath(__file__)
  716. my_main, my_git = _RunSelf(wrapper_path)
  717. cwd = os.getcwd()
  718. if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
  719. _print('error: repo cannot be used in the GITC local manifest directory.'
  720. '\nIf you want to work on this GITC client please rerun this '
  721. 'command from the corresponding client under /gitc/',
  722. file=sys.stderr)
  723. sys.exit(1)
  724. if not repo_main:
  725. if opt.help:
  726. _Usage()
  727. if cmd == 'help':
  728. _Help(args)
  729. if not cmd:
  730. _NotInstalled()
  731. if cmd == 'init' or cmd == 'gitc-init':
  732. if my_git:
  733. _SetDefaultsTo(my_git)
  734. try:
  735. _Init(args, gitc_init=(cmd == 'gitc-init'))
  736. except CloneFailure:
  737. path = os.path.join(repodir, S_repo)
  738. _print("fatal: cloning the git-repo repository failed, will remove "
  739. "'%s' " % path, file=sys.stderr)
  740. shutil.rmtree(path, ignore_errors=True)
  741. sys.exit(1)
  742. repo_main, rel_repo_dir = _FindRepo()
  743. else:
  744. _NoCommands(cmd)
  745. if my_main:
  746. repo_main = my_main
  747. ver_str = '.'.join(map(str, VERSION))
  748. me = [sys.executable, repo_main,
  749. '--repo-dir=%s' % rel_repo_dir,
  750. '--wrapper-version=%s' % ver_str,
  751. '--wrapper-path=%s' % wrapper_path,
  752. '--']
  753. me.extend(orig_args)
  754. me.extend(extra_args)
  755. try:
  756. if platform.system() == "Windows":
  757. sys.exit(subprocess.call(me))
  758. else:
  759. os.execv(sys.executable, me)
  760. except OSError as e:
  761. _print("fatal: unable to start %s" % repo_main, file=sys.stderr)
  762. _print("fatal: %s" % e, file=sys.stderr)
  763. sys.exit(148)
  764. if __name__ == '__main__':
  765. if ver[0] == 3:
  766. _print('warning: Python 3 support is currently experimental. YMMV.\n'
  767. 'Please use Python 2.6 - 2.7 instead.',
  768. file=sys.stderr)
  769. main(sys.argv[1:])