main.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. #
  4. # Copyright (C) 2008 The Android Open Source Project
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. """The repo tool.
  18. People shouldn't run this directly; instead, they should use the `repo` wrapper
  19. which takes care of execing this entry point.
  20. """
  21. from __future__ import print_function
  22. import getpass
  23. import netrc
  24. import optparse
  25. import os
  26. import shlex
  27. import sys
  28. import textwrap
  29. import time
  30. from pyversion import is_python3
  31. if is_python3():
  32. import urllib.request
  33. else:
  34. import imp
  35. import urllib2
  36. urllib = imp.new_module('urllib')
  37. urllib.request = urllib2
  38. try:
  39. import kerberos
  40. except ImportError:
  41. kerberos = None
  42. from color import SetDefaultColoring
  43. import event_log
  44. from repo_trace import SetTrace
  45. from git_command import user_agent
  46. from git_config import init_ssh, close_ssh, RepoConfig
  47. from command import InteractiveCommand
  48. from command import MirrorSafeCommand
  49. from command import GitcAvailableCommand, GitcClientCommand
  50. from subcmds.version import Version
  51. from editor import Editor
  52. from error import DownloadError
  53. from error import InvalidProjectGroupsError
  54. from error import ManifestInvalidRevisionError
  55. from error import ManifestParseError
  56. from error import NoManifestException
  57. from error import NoSuchProjectError
  58. from error import RepoChangedException
  59. import gitc_utils
  60. from manifest_xml import GitcManifest, XmlManifest
  61. from pager import RunPager, TerminatePager
  62. from wrapper import WrapperPath, Wrapper
  63. from subcmds import all_commands
  64. if not is_python3():
  65. input = raw_input # noqa: F821
  66. # NB: These do not need to be kept in sync with the repo launcher script.
  67. # These may be much newer as it allows the repo launcher to roll between
  68. # different repo releases while source versions might require a newer python.
  69. #
  70. # The soft version is when we start warning users that the version is old and
  71. # we'll be dropping support for it. We'll refuse to work with versions older
  72. # than the hard version.
  73. #
  74. # python-3.6 is in Ubuntu Bionic.
  75. MIN_PYTHON_VERSION_SOFT = (3, 6)
  76. MIN_PYTHON_VERSION_HARD = (3, 4)
  77. if sys.version_info.major < 3:
  78. print('repo: error: Python 2 is no longer supported; '
  79. 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
  80. file=sys.stderr)
  81. sys.exit(1)
  82. else:
  83. if sys.version_info < MIN_PYTHON_VERSION_HARD:
  84. print('repo: error: Python 3 version is too old; '
  85. 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
  86. file=sys.stderr)
  87. sys.exit(1)
  88. elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
  89. print('repo: warning: your Python 3 version is no longer supported; '
  90. 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
  91. file=sys.stderr)
  92. global_options = optparse.OptionParser(
  93. usage='repo [-p|--paginate|--no-pager] COMMAND [ARGS]',
  94. add_help_option=False)
  95. global_options.add_option('-h', '--help', action='store_true',
  96. help='show this help message and exit')
  97. global_options.add_option('-p', '--paginate',
  98. dest='pager', action='store_true',
  99. help='display command output in the pager')
  100. global_options.add_option('--no-pager',
  101. dest='pager', action='store_false',
  102. help='disable the pager')
  103. global_options.add_option('--color',
  104. choices=('auto', 'always', 'never'), default=None,
  105. help='control color usage: auto, always, never')
  106. global_options.add_option('--trace',
  107. dest='trace', action='store_true',
  108. help='trace git command execution (REPO_TRACE=1)')
  109. global_options.add_option('--trace-python',
  110. dest='trace_python', action='store_true',
  111. help='trace python command execution')
  112. global_options.add_option('--time',
  113. dest='time', action='store_true',
  114. help='time repo command execution')
  115. global_options.add_option('--version',
  116. dest='show_version', action='store_true',
  117. help='display this version of repo')
  118. global_options.add_option('--event-log',
  119. dest='event_log', action='store',
  120. help='filename of event log to append timeline to')
  121. class _Repo(object):
  122. def __init__(self, repodir):
  123. self.repodir = repodir
  124. self.commands = all_commands
  125. def _ParseArgs(self, argv):
  126. """Parse the main `repo` command line options."""
  127. name = None
  128. glob = []
  129. for i in range(len(argv)):
  130. if not argv[i].startswith('-'):
  131. name = argv[i]
  132. if i > 0:
  133. glob = argv[:i]
  134. argv = argv[i + 1:]
  135. break
  136. if not name:
  137. glob = argv
  138. name = 'help'
  139. argv = []
  140. gopts, _gargs = global_options.parse_args(glob)
  141. name, alias_args = self._ExpandAlias(name)
  142. argv = alias_args + argv
  143. if gopts.help:
  144. global_options.print_help()
  145. commands = ' '.join(sorted(self.commands))
  146. wrapped_commands = textwrap.wrap(commands, width=77)
  147. print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
  148. print('\nRun `repo help <command>` for command-specific details.')
  149. global_options.exit()
  150. return (name, gopts, argv)
  151. def _ExpandAlias(self, name):
  152. """Look up user registered aliases."""
  153. # We don't resolve aliases for existing subcommands. This matches git.
  154. if name in self.commands:
  155. return name, []
  156. key = 'alias.%s' % (name,)
  157. alias = RepoConfig.ForRepository(self.repodir).GetString(key)
  158. if alias is None:
  159. alias = RepoConfig.ForUser().GetString(key)
  160. if alias is None:
  161. return name, []
  162. args = alias.strip().split(' ', 1)
  163. name = args[0]
  164. if len(args) == 2:
  165. args = shlex.split(args[1])
  166. else:
  167. args = []
  168. return name, args
  169. def _Run(self, name, gopts, argv):
  170. """Execute the requested subcommand."""
  171. result = 0
  172. if gopts.trace:
  173. SetTrace()
  174. if gopts.show_version:
  175. if name == 'help':
  176. name = 'version'
  177. else:
  178. print('fatal: invalid usage of --version', file=sys.stderr)
  179. return 1
  180. SetDefaultColoring(gopts.color)
  181. try:
  182. cmd = self.commands[name]()
  183. except KeyError:
  184. print("repo: '%s' is not a repo command. See 'repo help'." % name,
  185. file=sys.stderr)
  186. return 1
  187. cmd.repodir = self.repodir
  188. cmd.manifest = XmlManifest(cmd.repodir)
  189. cmd.gitc_manifest = None
  190. gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
  191. if gitc_client_name:
  192. cmd.gitc_manifest = GitcManifest(cmd.repodir, gitc_client_name)
  193. cmd.manifest.isGitcClient = True
  194. Editor.globalConfig = cmd.manifest.globalConfig
  195. if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
  196. print("fatal: '%s' requires a working directory" % name,
  197. file=sys.stderr)
  198. return 1
  199. if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
  200. print("fatal: '%s' requires GITC to be available" % name,
  201. file=sys.stderr)
  202. return 1
  203. if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
  204. print("fatal: '%s' requires a GITC client" % name,
  205. file=sys.stderr)
  206. return 1
  207. try:
  208. copts, cargs = cmd.OptionParser.parse_args(argv)
  209. copts = cmd.ReadEnvironmentOptions(copts)
  210. except NoManifestException as e:
  211. print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
  212. file=sys.stderr)
  213. print('error: manifest missing or unreadable -- please run init',
  214. file=sys.stderr)
  215. return 1
  216. if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
  217. config = cmd.manifest.globalConfig
  218. if gopts.pager:
  219. use_pager = True
  220. else:
  221. use_pager = config.GetBoolean('pager.%s' % name)
  222. if use_pager is None:
  223. use_pager = cmd.WantPager(copts)
  224. if use_pager:
  225. RunPager(config)
  226. start = time.time()
  227. cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
  228. cmd.event_log.SetParent(cmd_event)
  229. try:
  230. cmd.ValidateOptions(copts, cargs)
  231. result = cmd.Execute(copts, cargs)
  232. except (DownloadError, ManifestInvalidRevisionError,
  233. NoManifestException) as e:
  234. print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
  235. file=sys.stderr)
  236. if isinstance(e, NoManifestException):
  237. print('error: manifest missing or unreadable -- please run init',
  238. file=sys.stderr)
  239. result = 1
  240. except NoSuchProjectError as e:
  241. if e.name:
  242. print('error: project %s not found' % e.name, file=sys.stderr)
  243. else:
  244. print('error: no project in current directory', file=sys.stderr)
  245. result = 1
  246. except InvalidProjectGroupsError as e:
  247. if e.name:
  248. print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
  249. else:
  250. print('error: project group must be enabled for the project in the current directory',
  251. file=sys.stderr)
  252. result = 1
  253. except SystemExit as e:
  254. if e.code:
  255. result = e.code
  256. raise
  257. finally:
  258. finish = time.time()
  259. elapsed = finish - start
  260. hours, remainder = divmod(elapsed, 3600)
  261. minutes, seconds = divmod(remainder, 60)
  262. if gopts.time:
  263. if hours == 0:
  264. print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
  265. else:
  266. print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
  267. file=sys.stderr)
  268. cmd.event_log.FinishEvent(cmd_event, finish,
  269. result is None or result == 0)
  270. if gopts.event_log:
  271. cmd.event_log.Write(os.path.abspath(
  272. os.path.expanduser(gopts.event_log)))
  273. return result
  274. def _CheckWrapperVersion(ver_str, repo_path):
  275. """Verify the repo launcher is new enough for this checkout.
  276. Args:
  277. ver_str: The version string passed from the repo launcher when it ran us.
  278. repo_path: The path to the repo launcher that loaded us.
  279. """
  280. # Refuse to work with really old wrapper versions. We don't test these,
  281. # so might as well require a somewhat recent sane version.
  282. # v1.15 of the repo launcher was released in ~Mar 2012.
  283. MIN_REPO_VERSION = (1, 15)
  284. min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
  285. if not repo_path:
  286. repo_path = '~/bin/repo'
  287. if not ver_str:
  288. print('no --wrapper-version argument', file=sys.stderr)
  289. sys.exit(1)
  290. # Pull out the version of the repo launcher we know about to compare.
  291. exp = Wrapper().VERSION
  292. ver = tuple(map(int, ver_str.split('.')))
  293. exp_str = '.'.join(map(str, exp))
  294. if ver < MIN_REPO_VERSION:
  295. print("""
  296. repo: error:
  297. !!! Your version of repo %s is too old.
  298. !!! We need at least version %s.
  299. !!! A new version of repo (%s) is available.
  300. !!! You must upgrade before you can continue:
  301. cp %s %s
  302. """ % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
  303. sys.exit(1)
  304. if exp > ver:
  305. print('\n... A new version of repo (%s) is available.' % (exp_str,),
  306. file=sys.stderr)
  307. if os.access(repo_path, os.W_OK):
  308. print("""\
  309. ... You should upgrade soon:
  310. cp %s %s
  311. """ % (WrapperPath(), repo_path), file=sys.stderr)
  312. else:
  313. print("""\
  314. ... New version is available at: %s
  315. ... The launcher is run from: %s
  316. !!! The launcher is not writable. Please talk to your sysadmin or distro
  317. !!! to get an update installed.
  318. """ % (WrapperPath(), repo_path), file=sys.stderr)
  319. def _CheckRepoDir(repo_dir):
  320. if not repo_dir:
  321. print('no --repo-dir argument', file=sys.stderr)
  322. sys.exit(1)
  323. def _PruneOptions(argv, opt):
  324. i = 0
  325. while i < len(argv):
  326. a = argv[i]
  327. if a == '--':
  328. break
  329. if a.startswith('--'):
  330. eq = a.find('=')
  331. if eq > 0:
  332. a = a[0:eq]
  333. if not opt.has_option(a):
  334. del argv[i]
  335. continue
  336. i += 1
  337. class _UserAgentHandler(urllib.request.BaseHandler):
  338. def http_request(self, req):
  339. req.add_header('User-Agent', user_agent.repo)
  340. return req
  341. def https_request(self, req):
  342. req.add_header('User-Agent', user_agent.repo)
  343. return req
  344. def _AddPasswordFromUserInput(handler, msg, req):
  345. # If repo could not find auth info from netrc, try to get it from user input
  346. url = req.get_full_url()
  347. user, password = handler.passwd.find_user_password(None, url)
  348. if user is None:
  349. print(msg)
  350. try:
  351. user = input('User: ')
  352. password = getpass.getpass()
  353. except KeyboardInterrupt:
  354. return
  355. handler.passwd.add_password(None, url, user, password)
  356. class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
  357. def http_error_401(self, req, fp, code, msg, headers):
  358. _AddPasswordFromUserInput(self, msg, req)
  359. return urllib.request.HTTPBasicAuthHandler.http_error_401(
  360. self, req, fp, code, msg, headers)
  361. def http_error_auth_reqed(self, authreq, host, req, headers):
  362. try:
  363. old_add_header = req.add_header
  364. def _add_header(name, val):
  365. val = val.replace('\n', '')
  366. old_add_header(name, val)
  367. req.add_header = _add_header
  368. return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
  369. self, authreq, host, req, headers)
  370. except Exception:
  371. reset = getattr(self, 'reset_retry_count', None)
  372. if reset is not None:
  373. reset()
  374. elif getattr(self, 'retried', None):
  375. self.retried = 0
  376. raise
  377. class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
  378. def http_error_401(self, req, fp, code, msg, headers):
  379. _AddPasswordFromUserInput(self, msg, req)
  380. return urllib.request.HTTPDigestAuthHandler.http_error_401(
  381. self, req, fp, code, msg, headers)
  382. def http_error_auth_reqed(self, auth_header, host, req, headers):
  383. try:
  384. old_add_header = req.add_header
  385. def _add_header(name, val):
  386. val = val.replace('\n', '')
  387. old_add_header(name, val)
  388. req.add_header = _add_header
  389. return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
  390. self, auth_header, host, req, headers)
  391. except Exception:
  392. reset = getattr(self, 'reset_retry_count', None)
  393. if reset is not None:
  394. reset()
  395. elif getattr(self, 'retried', None):
  396. self.retried = 0
  397. raise
  398. class _KerberosAuthHandler(urllib.request.BaseHandler):
  399. def __init__(self):
  400. self.retried = 0
  401. self.context = None
  402. self.handler_order = urllib.request.BaseHandler.handler_order - 50
  403. def http_error_401(self, req, fp, code, msg, headers):
  404. host = req.get_host()
  405. retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  406. return retry
  407. def http_error_auth_reqed(self, auth_header, host, req, headers):
  408. try:
  409. spn = "HTTP@%s" % host
  410. authdata = self._negotiate_get_authdata(auth_header, headers)
  411. if self.retried > 3:
  412. raise urllib.request.HTTPError(req.get_full_url(), 401,
  413. "Negotiate auth failed", headers, None)
  414. else:
  415. self.retried += 1
  416. neghdr = self._negotiate_get_svctk(spn, authdata)
  417. if neghdr is None:
  418. return None
  419. req.add_unredirected_header('Authorization', neghdr)
  420. response = self.parent.open(req)
  421. srvauth = self._negotiate_get_authdata(auth_header, response.info())
  422. if self._validate_response(srvauth):
  423. return response
  424. except kerberos.GSSError:
  425. return None
  426. except Exception:
  427. self.reset_retry_count()
  428. raise
  429. finally:
  430. self._clean_context()
  431. def reset_retry_count(self):
  432. self.retried = 0
  433. def _negotiate_get_authdata(self, auth_header, headers):
  434. authhdr = headers.get(auth_header, None)
  435. if authhdr is not None:
  436. for mech_tuple in authhdr.split(","):
  437. mech, __, authdata = mech_tuple.strip().partition(" ")
  438. if mech.lower() == "negotiate":
  439. return authdata.strip()
  440. return None
  441. def _negotiate_get_svctk(self, spn, authdata):
  442. if authdata is None:
  443. return None
  444. result, self.context = kerberos.authGSSClientInit(spn)
  445. if result < kerberos.AUTH_GSS_COMPLETE:
  446. return None
  447. result = kerberos.authGSSClientStep(self.context, authdata)
  448. if result < kerberos.AUTH_GSS_CONTINUE:
  449. return None
  450. response = kerberos.authGSSClientResponse(self.context)
  451. return "Negotiate %s" % response
  452. def _validate_response(self, authdata):
  453. if authdata is None:
  454. return None
  455. result = kerberos.authGSSClientStep(self.context, authdata)
  456. if result == kerberos.AUTH_GSS_COMPLETE:
  457. return True
  458. return None
  459. def _clean_context(self):
  460. if self.context is not None:
  461. kerberos.authGSSClientClean(self.context)
  462. self.context = None
  463. def init_http():
  464. handlers = [_UserAgentHandler()]
  465. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  466. try:
  467. n = netrc.netrc()
  468. for host in n.hosts:
  469. p = n.hosts[host]
  470. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  471. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  472. except netrc.NetrcParseError:
  473. pass
  474. except IOError:
  475. pass
  476. handlers.append(_BasicAuthHandler(mgr))
  477. handlers.append(_DigestAuthHandler(mgr))
  478. if kerberos:
  479. handlers.append(_KerberosAuthHandler())
  480. if 'http_proxy' in os.environ:
  481. url = os.environ['http_proxy']
  482. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  483. if 'REPO_CURL_VERBOSE' in os.environ:
  484. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  485. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  486. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  487. def _Main(argv):
  488. result = 0
  489. opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
  490. opt.add_option("--repo-dir", dest="repodir",
  491. help="path to .repo/")
  492. opt.add_option("--wrapper-version", dest="wrapper_version",
  493. help="version of the wrapper script")
  494. opt.add_option("--wrapper-path", dest="wrapper_path",
  495. help="location of the wrapper script")
  496. _PruneOptions(argv, opt)
  497. opt, argv = opt.parse_args(argv)
  498. _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
  499. _CheckRepoDir(opt.repodir)
  500. Version.wrapper_version = opt.wrapper_version
  501. Version.wrapper_path = opt.wrapper_path
  502. repo = _Repo(opt.repodir)
  503. try:
  504. try:
  505. init_ssh()
  506. init_http()
  507. name, gopts, argv = repo._ParseArgs(argv)
  508. run = lambda: repo._Run(name, gopts, argv) or 0
  509. if gopts.trace_python:
  510. import trace
  511. tracer = trace.Trace(count=False, trace=True, timing=True,
  512. ignoredirs=set(sys.path[1:]))
  513. result = tracer.runfunc(run)
  514. else:
  515. result = run()
  516. finally:
  517. close_ssh()
  518. except KeyboardInterrupt:
  519. print('aborted by user', file=sys.stderr)
  520. result = 1
  521. except ManifestParseError as mpe:
  522. print('fatal: %s' % mpe, file=sys.stderr)
  523. result = 1
  524. except RepoChangedException as rce:
  525. # If repo changed, re-exec ourselves.
  526. #
  527. argv = list(sys.argv)
  528. argv.extend(rce.extra_args)
  529. try:
  530. os.execv(sys.executable, [__file__] + argv)
  531. except OSError as e:
  532. print('fatal: cannot restart repo after upgrade', file=sys.stderr)
  533. print('fatal: %s' % e, file=sys.stderr)
  534. result = 128
  535. TerminatePager()
  536. sys.exit(result)
  537. if __name__ == '__main__':
  538. _Main(sys.argv[1:])