main.py 20 KB

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