main.py 12 KB

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