main.py 16 KB

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