main.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. from trace import SetTrace
  32. from git_command import git, GitCommand
  33. from git_config import init_ssh, close_ssh
  34. from command import InteractiveCommand
  35. from command import MirrorSafeCommand
  36. from subcmds.version import Version
  37. from editor import Editor
  38. from error import DownloadError
  39. from error import ManifestInvalidRevisionError
  40. from error import ManifestParseError
  41. from error import NoManifestException
  42. from error import NoSuchProjectError
  43. from error import RepoChangedException
  44. from manifest_xml import XmlManifest
  45. from pager import RunPager
  46. from wrapper import WrapperPath, Wrapper
  47. from subcmds import all_commands
  48. if not is_python3():
  49. # pylint:disable=W0622
  50. input = raw_input
  51. # pylint:enable=W0622
  52. global_options = optparse.OptionParser(
  53. usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]"
  54. )
  55. global_options.add_option('-p', '--paginate',
  56. dest='pager', action='store_true',
  57. help='display command output in the pager')
  58. global_options.add_option('--no-pager',
  59. dest='no_pager', action='store_true',
  60. help='disable the pager')
  61. global_options.add_option('--trace',
  62. dest='trace', action='store_true',
  63. help='trace git command execution')
  64. global_options.add_option('--time',
  65. dest='time', action='store_true',
  66. help='time repo command execution')
  67. global_options.add_option('--version',
  68. dest='show_version', action='store_true',
  69. help='display this version of repo')
  70. class _Repo(object):
  71. def __init__(self, repodir):
  72. self.repodir = repodir
  73. self.commands = all_commands
  74. # add 'branch' as an alias for 'branches'
  75. all_commands['branch'] = all_commands['branches']
  76. def _Run(self, argv):
  77. result = 0
  78. name = None
  79. glob = []
  80. for i in range(len(argv)):
  81. if not argv[i].startswith('-'):
  82. name = argv[i]
  83. if i > 0:
  84. glob = argv[:i]
  85. argv = argv[i + 1:]
  86. break
  87. if not name:
  88. glob = argv
  89. name = 'help'
  90. argv = []
  91. gopts, _gargs = global_options.parse_args(glob)
  92. if gopts.trace:
  93. SetTrace()
  94. if gopts.show_version:
  95. if name == 'help':
  96. name = 'version'
  97. else:
  98. print('fatal: invalid usage of --version', file=sys.stderr)
  99. return 1
  100. try:
  101. cmd = self.commands[name]
  102. except KeyError:
  103. print("repo: '%s' is not a repo command. See 'repo help'." % name,
  104. file=sys.stderr)
  105. return 1
  106. cmd.repodir = self.repodir
  107. cmd.manifest = XmlManifest(cmd.repodir)
  108. Editor.globalConfig = cmd.manifest.globalConfig
  109. if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
  110. print("fatal: '%s' requires a working directory" % name,
  111. file=sys.stderr)
  112. return 1
  113. copts, cargs = cmd.OptionParser.parse_args(argv)
  114. copts = cmd.ReadEnvironmentOptions(copts)
  115. if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
  116. config = cmd.manifest.globalConfig
  117. if gopts.pager:
  118. use_pager = True
  119. else:
  120. use_pager = config.GetBoolean('pager.%s' % name)
  121. if use_pager is None:
  122. use_pager = cmd.WantPager(copts)
  123. if use_pager:
  124. RunPager(config)
  125. start = time.time()
  126. try:
  127. result = cmd.Execute(copts, cargs)
  128. except DownloadError as e:
  129. print('error: %s' % str(e), file=sys.stderr)
  130. result = 1
  131. except ManifestInvalidRevisionError as e:
  132. print('error: %s' % str(e), file=sys.stderr)
  133. result = 1
  134. except NoManifestException as e:
  135. print('error: manifest required for this command -- please run init',
  136. file=sys.stderr)
  137. result = 1
  138. except NoSuchProjectError as e:
  139. if e.name:
  140. print('error: project %s not found' % e.name, file=sys.stderr)
  141. else:
  142. print('error: no project in current directory', file=sys.stderr)
  143. result = 1
  144. finally:
  145. elapsed = time.time() - start
  146. hours, remainder = divmod(elapsed, 3600)
  147. minutes, seconds = divmod(remainder, 60)
  148. if gopts.time:
  149. if hours == 0:
  150. print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
  151. else:
  152. print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
  153. file=sys.stderr)
  154. return result
  155. def _MyRepoPath():
  156. return os.path.dirname(__file__)
  157. def _CheckWrapperVersion(ver, repo_path):
  158. if not repo_path:
  159. repo_path = '~/bin/repo'
  160. if not ver:
  161. print('no --wrapper-version argument', file=sys.stderr)
  162. sys.exit(1)
  163. exp = Wrapper().VERSION
  164. ver = tuple(map(int, ver.split('.')))
  165. if len(ver) == 1:
  166. ver = (0, ver[0])
  167. exp_str = '.'.join(map(str, exp))
  168. if exp[0] > ver[0] or ver < (0, 4):
  169. print("""
  170. !!! A new repo command (%5s) is available. !!!
  171. !!! You must upgrade before you can continue: !!!
  172. cp %s %s
  173. """ % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
  174. sys.exit(1)
  175. if exp > ver:
  176. print("""
  177. ... A new repo command (%5s) is available.
  178. ... You should upgrade soon:
  179. cp %s %s
  180. """ % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
  181. def _CheckRepoDir(repo_dir):
  182. if not repo_dir:
  183. print('no --repo-dir argument', file=sys.stderr)
  184. sys.exit(1)
  185. def _PruneOptions(argv, opt):
  186. i = 0
  187. while i < len(argv):
  188. a = argv[i]
  189. if a == '--':
  190. break
  191. if a.startswith('--'):
  192. eq = a.find('=')
  193. if eq > 0:
  194. a = a[0:eq]
  195. if not opt.has_option(a):
  196. del argv[i]
  197. continue
  198. i += 1
  199. _user_agent = None
  200. def _UserAgent():
  201. global _user_agent
  202. if _user_agent is None:
  203. py_version = sys.version_info
  204. os_name = sys.platform
  205. if os_name == 'linux2':
  206. os_name = 'Linux'
  207. elif os_name == 'win32':
  208. os_name = 'Win32'
  209. elif os_name == 'cygwin':
  210. os_name = 'Cygwin'
  211. elif os_name == 'darwin':
  212. os_name = 'Darwin'
  213. p = GitCommand(
  214. None, ['describe', 'HEAD'],
  215. cwd = _MyRepoPath(),
  216. capture_stdout = True)
  217. if p.Wait() == 0:
  218. repo_version = p.stdout
  219. if len(repo_version) > 0 and repo_version[-1] == '\n':
  220. repo_version = repo_version[0:-1]
  221. if len(repo_version) > 0 and repo_version[0] == 'v':
  222. repo_version = repo_version[1:]
  223. else:
  224. repo_version = 'unknown'
  225. _user_agent = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
  226. repo_version,
  227. os_name,
  228. '.'.join(map(str, git.version_tuple())),
  229. py_version[0], py_version[1], py_version[2])
  230. return _user_agent
  231. class _UserAgentHandler(urllib.request.BaseHandler):
  232. def http_request(self, req):
  233. req.add_header('User-Agent', _UserAgent())
  234. return req
  235. def https_request(self, req):
  236. req.add_header('User-Agent', _UserAgent())
  237. return req
  238. def _AddPasswordFromUserInput(handler, msg, req):
  239. # If repo could not find auth info from netrc, try to get it from user input
  240. url = req.get_full_url()
  241. user, password = handler.passwd.find_user_password(None, url)
  242. if user is None:
  243. print(msg)
  244. try:
  245. user = input('User: ')
  246. password = getpass.getpass()
  247. except KeyboardInterrupt:
  248. return
  249. handler.passwd.add_password(None, url, user, password)
  250. class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
  251. def http_error_401(self, req, fp, code, msg, headers):
  252. _AddPasswordFromUserInput(self, msg, req)
  253. return urllib.request.HTTPBasicAuthHandler.http_error_401(
  254. self, req, fp, code, msg, headers)
  255. def http_error_auth_reqed(self, authreq, host, req, headers):
  256. try:
  257. old_add_header = req.add_header
  258. def _add_header(name, val):
  259. val = val.replace('\n', '')
  260. old_add_header(name, val)
  261. req.add_header = _add_header
  262. return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
  263. self, authreq, host, req, headers)
  264. except:
  265. reset = getattr(self, 'reset_retry_count', None)
  266. if reset is not None:
  267. reset()
  268. elif getattr(self, 'retried', None):
  269. self.retried = 0
  270. raise
  271. class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
  272. def http_error_401(self, req, fp, code, msg, headers):
  273. _AddPasswordFromUserInput(self, msg, req)
  274. return urllib.request.HTTPDigestAuthHandler.http_error_401(
  275. self, req, fp, code, msg, headers)
  276. def http_error_auth_reqed(self, auth_header, host, req, headers):
  277. try:
  278. old_add_header = req.add_header
  279. def _add_header(name, val):
  280. val = val.replace('\n', '')
  281. old_add_header(name, val)
  282. req.add_header = _add_header
  283. return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
  284. self, auth_header, host, req, headers)
  285. except:
  286. reset = getattr(self, 'reset_retry_count', None)
  287. if reset is not None:
  288. reset()
  289. elif getattr(self, 'retried', None):
  290. self.retried = 0
  291. raise
  292. def init_http():
  293. handlers = [_UserAgentHandler()]
  294. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  295. try:
  296. n = netrc.netrc()
  297. for host in n.hosts:
  298. p = n.hosts[host]
  299. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  300. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  301. except netrc.NetrcParseError:
  302. pass
  303. except IOError:
  304. pass
  305. handlers.append(_BasicAuthHandler(mgr))
  306. handlers.append(_DigestAuthHandler(mgr))
  307. if 'http_proxy' in os.environ:
  308. url = os.environ['http_proxy']
  309. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  310. if 'REPO_CURL_VERBOSE' in os.environ:
  311. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  312. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  313. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  314. def _Main(argv):
  315. result = 0
  316. opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
  317. opt.add_option("--repo-dir", dest="repodir",
  318. help="path to .repo/")
  319. opt.add_option("--wrapper-version", dest="wrapper_version",
  320. help="version of the wrapper script")
  321. opt.add_option("--wrapper-path", dest="wrapper_path",
  322. help="location of the wrapper script")
  323. _PruneOptions(argv, opt)
  324. opt, argv = opt.parse_args(argv)
  325. _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
  326. _CheckRepoDir(opt.repodir)
  327. Version.wrapper_version = opt.wrapper_version
  328. Version.wrapper_path = opt.wrapper_path
  329. repo = _Repo(opt.repodir)
  330. try:
  331. try:
  332. init_ssh()
  333. init_http()
  334. result = repo._Run(argv) or 0
  335. finally:
  336. close_ssh()
  337. except KeyboardInterrupt:
  338. print('aborted by user', file=sys.stderr)
  339. result = 1
  340. except ManifestParseError as mpe:
  341. print('fatal: %s' % mpe, file=sys.stderr)
  342. result = 1
  343. except RepoChangedException as rce:
  344. # If repo changed, re-exec ourselves.
  345. #
  346. argv = list(sys.argv)
  347. argv.extend(rce.extra_args)
  348. try:
  349. os.execv(__file__, argv)
  350. except OSError as e:
  351. print('fatal: cannot restart repo after upgrade', file=sys.stderr)
  352. print('fatal: %s' % e, file=sys.stderr)
  353. result = 128
  354. sys.exit(result)
  355. if __name__ == '__main__':
  356. _Main(sys.argv[1:])