main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 imp
  24. import netrc
  25. import optparse
  26. import os
  27. import sys
  28. import time
  29. from pyversion import is_python3
  30. if is_python3():
  31. import urllib.request
  32. else:
  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
  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 _MyRepoPath():
  219. return os.path.dirname(__file__)
  220. def _CheckWrapperVersion(ver, repo_path):
  221. if not repo_path:
  222. repo_path = '~/bin/repo'
  223. if not ver:
  224. print('no --wrapper-version argument', file=sys.stderr)
  225. sys.exit(1)
  226. exp = Wrapper().VERSION
  227. ver = tuple(map(int, ver.split('.')))
  228. if len(ver) == 1:
  229. ver = (0, ver[0])
  230. exp_str = '.'.join(map(str, exp))
  231. if exp[0] > ver[0] or ver < (0, 4):
  232. print("""
  233. !!! A new repo command (%5s) is available. !!!
  234. !!! You must upgrade before you can continue: !!!
  235. cp %s %s
  236. """ % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
  237. sys.exit(1)
  238. if exp > ver:
  239. print("""
  240. ... A new repo command (%5s) is available.
  241. ... You should upgrade soon:
  242. cp %s %s
  243. """ % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
  244. def _CheckRepoDir(repo_dir):
  245. if not repo_dir:
  246. print('no --repo-dir argument', file=sys.stderr)
  247. sys.exit(1)
  248. def _PruneOptions(argv, opt):
  249. i = 0
  250. while i < len(argv):
  251. a = argv[i]
  252. if a == '--':
  253. break
  254. if a.startswith('--'):
  255. eq = a.find('=')
  256. if eq > 0:
  257. a = a[0:eq]
  258. if not opt.has_option(a):
  259. del argv[i]
  260. continue
  261. i += 1
  262. _user_agent = None
  263. def _UserAgent():
  264. global _user_agent
  265. if _user_agent is None:
  266. py_version = sys.version_info
  267. os_name = sys.platform
  268. if os_name == 'linux2':
  269. os_name = 'Linux'
  270. elif os_name == 'win32':
  271. os_name = 'Win32'
  272. elif os_name == 'cygwin':
  273. os_name = 'Cygwin'
  274. elif os_name == 'darwin':
  275. os_name = 'Darwin'
  276. p = GitCommand(
  277. None, ['describe', 'HEAD'],
  278. cwd = _MyRepoPath(),
  279. capture_stdout = True)
  280. if p.Wait() == 0:
  281. repo_version = p.stdout
  282. if len(repo_version) > 0 and repo_version[-1] == '\n':
  283. repo_version = repo_version[0:-1]
  284. if len(repo_version) > 0 and repo_version[0] == 'v':
  285. repo_version = repo_version[1:]
  286. else:
  287. repo_version = 'unknown'
  288. _user_agent = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
  289. repo_version,
  290. os_name,
  291. git.version_tuple().full,
  292. py_version[0], py_version[1], py_version[2])
  293. return _user_agent
  294. class _UserAgentHandler(urllib.request.BaseHandler):
  295. def http_request(self, req):
  296. req.add_header('User-Agent', _UserAgent())
  297. return req
  298. def https_request(self, req):
  299. req.add_header('User-Agent', _UserAgent())
  300. return req
  301. def _AddPasswordFromUserInput(handler, msg, req):
  302. # If repo could not find auth info from netrc, try to get it from user input
  303. url = req.get_full_url()
  304. user, password = handler.passwd.find_user_password(None, url)
  305. if user is None:
  306. print(msg)
  307. try:
  308. user = input('User: ')
  309. password = getpass.getpass()
  310. except KeyboardInterrupt:
  311. return
  312. handler.passwd.add_password(None, url, user, password)
  313. class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
  314. def http_error_401(self, req, fp, code, msg, headers):
  315. _AddPasswordFromUserInput(self, msg, req)
  316. return urllib.request.HTTPBasicAuthHandler.http_error_401(
  317. self, req, fp, code, msg, headers)
  318. def http_error_auth_reqed(self, authreq, host, req, headers):
  319. try:
  320. old_add_header = req.add_header
  321. def _add_header(name, val):
  322. val = val.replace('\n', '')
  323. old_add_header(name, val)
  324. req.add_header = _add_header
  325. return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
  326. self, authreq, host, req, headers)
  327. except:
  328. reset = getattr(self, 'reset_retry_count', None)
  329. if reset is not None:
  330. reset()
  331. elif getattr(self, 'retried', None):
  332. self.retried = 0
  333. raise
  334. class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
  335. def http_error_401(self, req, fp, code, msg, headers):
  336. _AddPasswordFromUserInput(self, msg, req)
  337. return urllib.request.HTTPDigestAuthHandler.http_error_401(
  338. self, req, fp, code, msg, headers)
  339. def http_error_auth_reqed(self, auth_header, host, req, headers):
  340. try:
  341. old_add_header = req.add_header
  342. def _add_header(name, val):
  343. val = val.replace('\n', '')
  344. old_add_header(name, val)
  345. req.add_header = _add_header
  346. return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
  347. self, auth_header, host, req, headers)
  348. except:
  349. reset = getattr(self, 'reset_retry_count', None)
  350. if reset is not None:
  351. reset()
  352. elif getattr(self, 'retried', None):
  353. self.retried = 0
  354. raise
  355. class _KerberosAuthHandler(urllib.request.BaseHandler):
  356. def __init__(self):
  357. self.retried = 0
  358. self.context = None
  359. self.handler_order = urllib.request.BaseHandler.handler_order - 50
  360. def http_error_401(self, req, fp, code, msg, headers):
  361. host = req.get_host()
  362. retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  363. return retry
  364. def http_error_auth_reqed(self, auth_header, host, req, headers):
  365. try:
  366. spn = "HTTP@%s" % host
  367. authdata = self._negotiate_get_authdata(auth_header, headers)
  368. if self.retried > 3:
  369. raise urllib.request.HTTPError(req.get_full_url(), 401,
  370. "Negotiate auth failed", headers, None)
  371. else:
  372. self.retried += 1
  373. neghdr = self._negotiate_get_svctk(spn, authdata)
  374. if neghdr is None:
  375. return None
  376. req.add_unredirected_header('Authorization', neghdr)
  377. response = self.parent.open(req)
  378. srvauth = self._negotiate_get_authdata(auth_header, response.info())
  379. if self._validate_response(srvauth):
  380. return response
  381. except kerberos.GSSError:
  382. return None
  383. except:
  384. self.reset_retry_count()
  385. raise
  386. finally:
  387. self._clean_context()
  388. def reset_retry_count(self):
  389. self.retried = 0
  390. def _negotiate_get_authdata(self, auth_header, headers):
  391. authhdr = headers.get(auth_header, None)
  392. if authhdr is not None:
  393. for mech_tuple in authhdr.split(","):
  394. mech, __, authdata = mech_tuple.strip().partition(" ")
  395. if mech.lower() == "negotiate":
  396. return authdata.strip()
  397. return None
  398. def _negotiate_get_svctk(self, spn, authdata):
  399. if authdata is None:
  400. return None
  401. result, self.context = kerberos.authGSSClientInit(spn)
  402. if result < kerberos.AUTH_GSS_COMPLETE:
  403. return None
  404. result = kerberos.authGSSClientStep(self.context, authdata)
  405. if result < kerberos.AUTH_GSS_CONTINUE:
  406. return None
  407. response = kerberos.authGSSClientResponse(self.context)
  408. return "Negotiate %s" % response
  409. def _validate_response(self, authdata):
  410. if authdata is None:
  411. return None
  412. result = kerberos.authGSSClientStep(self.context, authdata)
  413. if result == kerberos.AUTH_GSS_COMPLETE:
  414. return True
  415. return None
  416. def _clean_context(self):
  417. if self.context is not None:
  418. kerberos.authGSSClientClean(self.context)
  419. self.context = None
  420. def init_http():
  421. handlers = [_UserAgentHandler()]
  422. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  423. try:
  424. n = netrc.netrc()
  425. for host in n.hosts:
  426. p = n.hosts[host]
  427. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  428. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  429. except netrc.NetrcParseError:
  430. pass
  431. except IOError:
  432. pass
  433. handlers.append(_BasicAuthHandler(mgr))
  434. handlers.append(_DigestAuthHandler(mgr))
  435. if kerberos:
  436. handlers.append(_KerberosAuthHandler())
  437. if 'http_proxy' in os.environ:
  438. url = os.environ['http_proxy']
  439. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  440. if 'REPO_CURL_VERBOSE' in os.environ:
  441. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  442. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  443. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  444. def _Main(argv):
  445. result = 0
  446. opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
  447. opt.add_option("--repo-dir", dest="repodir",
  448. help="path to .repo/")
  449. opt.add_option("--wrapper-version", dest="wrapper_version",
  450. help="version of the wrapper script")
  451. opt.add_option("--wrapper-path", dest="wrapper_path",
  452. help="location of the wrapper script")
  453. _PruneOptions(argv, opt)
  454. opt, argv = opt.parse_args(argv)
  455. _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
  456. _CheckRepoDir(opt.repodir)
  457. Version.wrapper_version = opt.wrapper_version
  458. Version.wrapper_path = opt.wrapper_path
  459. repo = _Repo(opt.repodir)
  460. try:
  461. try:
  462. init_ssh()
  463. init_http()
  464. name, gopts, argv = repo._ParseArgs(argv)
  465. run = lambda: repo._Run(name, gopts, argv) or 0
  466. if gopts.trace_python:
  467. import trace
  468. tracer = trace.Trace(count=False, trace=True, timing=True,
  469. ignoredirs=set(sys.path[1:]))
  470. result = tracer.runfunc(run)
  471. else:
  472. result = run()
  473. finally:
  474. close_ssh()
  475. except KeyboardInterrupt:
  476. print('aborted by user', file=sys.stderr)
  477. result = 1
  478. except ManifestParseError as mpe:
  479. print('fatal: %s' % mpe, file=sys.stderr)
  480. result = 1
  481. except RepoChangedException as rce:
  482. # If repo changed, re-exec ourselves.
  483. #
  484. argv = list(sys.argv)
  485. argv.extend(rce.extra_args)
  486. try:
  487. os.execv(__file__, argv)
  488. except OSError as e:
  489. print('fatal: cannot restart repo after upgrade', file=sys.stderr)
  490. print('fatal: %s' % e, file=sys.stderr)
  491. result = 128
  492. TerminatePager()
  493. sys.exit(result)
  494. if __name__ == '__main__':
  495. _Main(sys.argv[1:])