main.py 8.7 KB

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