main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 RequiresGitcCommand
  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, RequiresGitcCommand) 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. try:
  135. copts, cargs = cmd.OptionParser.parse_args(argv)
  136. copts = cmd.ReadEnvironmentOptions(copts)
  137. except NoManifestException as e:
  138. print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
  139. file=sys.stderr)
  140. print('error: manifest missing or unreadable -- please run init',
  141. file=sys.stderr)
  142. return 1
  143. if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
  144. config = cmd.manifest.globalConfig
  145. if gopts.pager:
  146. use_pager = True
  147. else:
  148. use_pager = config.GetBoolean('pager.%s' % name)
  149. if use_pager is None:
  150. use_pager = cmd.WantPager(copts)
  151. if use_pager:
  152. RunPager(config)
  153. start = time.time()
  154. try:
  155. result = cmd.Execute(copts, cargs)
  156. except (DownloadError, ManifestInvalidRevisionError,
  157. NoManifestException) as e:
  158. print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
  159. file=sys.stderr)
  160. if isinstance(e, NoManifestException):
  161. print('error: manifest missing or unreadable -- please run init',
  162. file=sys.stderr)
  163. result = 1
  164. except NoSuchProjectError as e:
  165. if e.name:
  166. print('error: project %s not found' % e.name, file=sys.stderr)
  167. else:
  168. print('error: no project in current directory', file=sys.stderr)
  169. result = 1
  170. except InvalidProjectGroupsError as e:
  171. if e.name:
  172. print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
  173. else:
  174. print('error: project group must be enabled for the project in the current directory', file=sys.stderr)
  175. result = 1
  176. finally:
  177. elapsed = time.time() - start
  178. hours, remainder = divmod(elapsed, 3600)
  179. minutes, seconds = divmod(remainder, 60)
  180. if gopts.time:
  181. if hours == 0:
  182. print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
  183. else:
  184. print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
  185. file=sys.stderr)
  186. return result
  187. def _MyRepoPath():
  188. return os.path.dirname(__file__)
  189. def _CheckWrapperVersion(ver, repo_path):
  190. if not repo_path:
  191. repo_path = '~/bin/repo'
  192. if not ver:
  193. print('no --wrapper-version argument', file=sys.stderr)
  194. sys.exit(1)
  195. exp = Wrapper().VERSION
  196. ver = tuple(map(int, ver.split('.')))
  197. if len(ver) == 1:
  198. ver = (0, ver[0])
  199. exp_str = '.'.join(map(str, exp))
  200. if exp[0] > ver[0] or ver < (0, 4):
  201. print("""
  202. !!! A new repo command (%5s) is available. !!!
  203. !!! You must upgrade before you can continue: !!!
  204. cp %s %s
  205. """ % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
  206. sys.exit(1)
  207. if exp > ver:
  208. print("""
  209. ... A new repo command (%5s) is available.
  210. ... You should upgrade soon:
  211. cp %s %s
  212. """ % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
  213. def _CheckRepoDir(repo_dir):
  214. if not repo_dir:
  215. print('no --repo-dir argument', file=sys.stderr)
  216. sys.exit(1)
  217. def _PruneOptions(argv, opt):
  218. i = 0
  219. while i < len(argv):
  220. a = argv[i]
  221. if a == '--':
  222. break
  223. if a.startswith('--'):
  224. eq = a.find('=')
  225. if eq > 0:
  226. a = a[0:eq]
  227. if not opt.has_option(a):
  228. del argv[i]
  229. continue
  230. i += 1
  231. _user_agent = None
  232. def _UserAgent():
  233. global _user_agent
  234. if _user_agent is None:
  235. py_version = sys.version_info
  236. os_name = sys.platform
  237. if os_name == 'linux2':
  238. os_name = 'Linux'
  239. elif os_name == 'win32':
  240. os_name = 'Win32'
  241. elif os_name == 'cygwin':
  242. os_name = 'Cygwin'
  243. elif os_name == 'darwin':
  244. os_name = 'Darwin'
  245. p = GitCommand(
  246. None, ['describe', 'HEAD'],
  247. cwd = _MyRepoPath(),
  248. capture_stdout = True)
  249. if p.Wait() == 0:
  250. repo_version = p.stdout
  251. if len(repo_version) > 0 and repo_version[-1] == '\n':
  252. repo_version = repo_version[0:-1]
  253. if len(repo_version) > 0 and repo_version[0] == 'v':
  254. repo_version = repo_version[1:]
  255. else:
  256. repo_version = 'unknown'
  257. _user_agent = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
  258. repo_version,
  259. os_name,
  260. '.'.join(map(str, git.version_tuple())),
  261. py_version[0], py_version[1], py_version[2])
  262. return _user_agent
  263. class _UserAgentHandler(urllib.request.BaseHandler):
  264. def http_request(self, req):
  265. req.add_header('User-Agent', _UserAgent())
  266. return req
  267. def https_request(self, req):
  268. req.add_header('User-Agent', _UserAgent())
  269. return req
  270. def _AddPasswordFromUserInput(handler, msg, req):
  271. # If repo could not find auth info from netrc, try to get it from user input
  272. url = req.get_full_url()
  273. user, password = handler.passwd.find_user_password(None, url)
  274. if user is None:
  275. print(msg)
  276. try:
  277. user = input('User: ')
  278. password = getpass.getpass()
  279. except KeyboardInterrupt:
  280. return
  281. handler.passwd.add_password(None, url, user, password)
  282. class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
  283. def http_error_401(self, req, fp, code, msg, headers):
  284. _AddPasswordFromUserInput(self, msg, req)
  285. return urllib.request.HTTPBasicAuthHandler.http_error_401(
  286. self, req, fp, code, msg, headers)
  287. def http_error_auth_reqed(self, authreq, host, req, headers):
  288. try:
  289. old_add_header = req.add_header
  290. def _add_header(name, val):
  291. val = val.replace('\n', '')
  292. old_add_header(name, val)
  293. req.add_header = _add_header
  294. return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
  295. self, authreq, host, req, headers)
  296. except:
  297. reset = getattr(self, 'reset_retry_count', None)
  298. if reset is not None:
  299. reset()
  300. elif getattr(self, 'retried', None):
  301. self.retried = 0
  302. raise
  303. class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
  304. def http_error_401(self, req, fp, code, msg, headers):
  305. _AddPasswordFromUserInput(self, msg, req)
  306. return urllib.request.HTTPDigestAuthHandler.http_error_401(
  307. self, req, fp, code, msg, headers)
  308. def http_error_auth_reqed(self, auth_header, host, req, headers):
  309. try:
  310. old_add_header = req.add_header
  311. def _add_header(name, val):
  312. val = val.replace('\n', '')
  313. old_add_header(name, val)
  314. req.add_header = _add_header
  315. return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
  316. self, auth_header, host, req, headers)
  317. except:
  318. reset = getattr(self, 'reset_retry_count', None)
  319. if reset is not None:
  320. reset()
  321. elif getattr(self, 'retried', None):
  322. self.retried = 0
  323. raise
  324. class _KerberosAuthHandler(urllib.request.BaseHandler):
  325. def __init__(self):
  326. self.retried = 0
  327. self.context = None
  328. self.handler_order = urllib.request.BaseHandler.handler_order - 50
  329. def http_error_401(self, req, fp, code, msg, headers):
  330. host = req.get_host()
  331. retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  332. return retry
  333. def http_error_auth_reqed(self, auth_header, host, req, headers):
  334. try:
  335. spn = "HTTP@%s" % host
  336. authdata = self._negotiate_get_authdata(auth_header, headers)
  337. if self.retried > 3:
  338. raise urllib.request.HTTPError(req.get_full_url(), 401,
  339. "Negotiate auth failed", headers, None)
  340. else:
  341. self.retried += 1
  342. neghdr = self._negotiate_get_svctk(spn, authdata)
  343. if neghdr is None:
  344. return None
  345. req.add_unredirected_header('Authorization', neghdr)
  346. response = self.parent.open(req)
  347. srvauth = self._negotiate_get_authdata(auth_header, response.info())
  348. if self._validate_response(srvauth):
  349. return response
  350. except kerberos.GSSError:
  351. return None
  352. except:
  353. self.reset_retry_count()
  354. raise
  355. finally:
  356. self._clean_context()
  357. def reset_retry_count(self):
  358. self.retried = 0
  359. def _negotiate_get_authdata(self, auth_header, headers):
  360. authhdr = headers.get(auth_header, None)
  361. if authhdr is not None:
  362. for mech_tuple in authhdr.split(","):
  363. mech, __, authdata = mech_tuple.strip().partition(" ")
  364. if mech.lower() == "negotiate":
  365. return authdata.strip()
  366. return None
  367. def _negotiate_get_svctk(self, spn, authdata):
  368. if authdata is None:
  369. return None
  370. result, self.context = kerberos.authGSSClientInit(spn)
  371. if result < kerberos.AUTH_GSS_COMPLETE:
  372. return None
  373. result = kerberos.authGSSClientStep(self.context, authdata)
  374. if result < kerberos.AUTH_GSS_CONTINUE:
  375. return None
  376. response = kerberos.authGSSClientResponse(self.context)
  377. return "Negotiate %s" % response
  378. def _validate_response(self, authdata):
  379. if authdata is None:
  380. return None
  381. result = kerberos.authGSSClientStep(self.context, authdata)
  382. if result == kerberos.AUTH_GSS_COMPLETE:
  383. return True
  384. return None
  385. def _clean_context(self):
  386. if self.context is not None:
  387. kerberos.authGSSClientClean(self.context)
  388. self.context = None
  389. def init_http():
  390. handlers = [_UserAgentHandler()]
  391. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  392. try:
  393. n = netrc.netrc()
  394. for host in n.hosts:
  395. p = n.hosts[host]
  396. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  397. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  398. except netrc.NetrcParseError:
  399. pass
  400. except IOError:
  401. pass
  402. handlers.append(_BasicAuthHandler(mgr))
  403. handlers.append(_DigestAuthHandler(mgr))
  404. if kerberos:
  405. handlers.append(_KerberosAuthHandler())
  406. if 'http_proxy' in os.environ:
  407. url = os.environ['http_proxy']
  408. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  409. if 'REPO_CURL_VERBOSE' in os.environ:
  410. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  411. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  412. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  413. def _Main(argv):
  414. result = 0
  415. opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
  416. opt.add_option("--repo-dir", dest="repodir",
  417. help="path to .repo/")
  418. opt.add_option("--wrapper-version", dest="wrapper_version",
  419. help="version of the wrapper script")
  420. opt.add_option("--wrapper-path", dest="wrapper_path",
  421. help="location of the wrapper script")
  422. _PruneOptions(argv, opt)
  423. opt, argv = opt.parse_args(argv)
  424. _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
  425. _CheckRepoDir(opt.repodir)
  426. Version.wrapper_version = opt.wrapper_version
  427. Version.wrapper_path = opt.wrapper_path
  428. repo = _Repo(opt.repodir)
  429. try:
  430. try:
  431. init_ssh()
  432. init_http()
  433. result = repo._Run(argv) or 0
  434. finally:
  435. close_ssh()
  436. except KeyboardInterrupt:
  437. print('aborted by user', file=sys.stderr)
  438. result = 1
  439. except ManifestParseError as mpe:
  440. print('fatal: %s' % mpe, file=sys.stderr)
  441. result = 1
  442. except RepoChangedException as rce:
  443. # If repo changed, re-exec ourselves.
  444. #
  445. argv = list(sys.argv)
  446. argv.extend(rce.extra_args)
  447. try:
  448. os.execv(__file__, argv)
  449. except OSError as e:
  450. print('fatal: cannot restart repo after upgrade', file=sys.stderr)
  451. print('fatal: %s' % e, file=sys.stderr)
  452. result = 128
  453. sys.exit(result)
  454. if __name__ == '__main__':
  455. _Main(sys.argv[1:])