repo 28 KB

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