main.py 16 KB

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