main.py 9.3 KB

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