main.py 18 KB

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