main.py 12 KB

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