main.py 20 KB

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