main.py 20 KB

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