main.py 10.0 KB

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