main.py 19 KB

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