main.py 8.4 KB

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