main.py 15 KB

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