main.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. from trace import SetTrace
  28. from git_config import close_ssh
  29. from command import InteractiveCommand
  30. from command import MirrorSafeCommand
  31. from command import PagedCommand
  32. from error import ManifestInvalidRevisionError
  33. from error import NoSuchProjectError
  34. from error import RepoChangedException
  35. from pager import RunPager
  36. from subcmds import all as all_commands
  37. global_options = optparse.OptionParser(
  38. usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]"
  39. )
  40. global_options.add_option('-p', '--paginate',
  41. dest='pager', action='store_true',
  42. help='display command output in the pager')
  43. global_options.add_option('--no-pager',
  44. dest='no_pager', action='store_true',
  45. help='disable the pager')
  46. global_options.add_option('--trace',
  47. dest='trace', action='store_true',
  48. help='trace git command execution')
  49. global_options.add_option('--version',
  50. dest='show_version', action='store_true',
  51. help='display this version of repo')
  52. class _Repo(object):
  53. def __init__(self, repodir):
  54. self.repodir = repodir
  55. self.commands = all_commands
  56. def _Run(self, argv):
  57. name = None
  58. glob = []
  59. for i in xrange(0, len(argv)):
  60. if not argv[i].startswith('-'):
  61. name = argv[i]
  62. if i > 0:
  63. glob = argv[:i]
  64. argv = argv[i + 1:]
  65. break
  66. if not name:
  67. glob = argv
  68. name = 'help'
  69. argv = []
  70. gopts, gargs = global_options.parse_args(glob)
  71. if gopts.trace:
  72. SetTrace()
  73. if gopts.show_version:
  74. if name == 'help':
  75. name = 'version'
  76. else:
  77. print >>sys.stderr, 'fatal: invalid usage of --version'
  78. sys.exit(1)
  79. try:
  80. cmd = self.commands[name]
  81. except KeyError:
  82. print >>sys.stderr,\
  83. "repo: '%s' is not a repo command. See 'repo help'."\
  84. % name
  85. sys.exit(1)
  86. cmd.repodir = self.repodir
  87. if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
  88. print >>sys.stderr, \
  89. "fatal: '%s' requires a working directory"\
  90. % name
  91. sys.exit(1)
  92. copts, cargs = cmd.OptionParser.parse_args(argv)
  93. if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
  94. config = cmd.manifest.globalConfig
  95. if gopts.pager:
  96. use_pager = True
  97. else:
  98. use_pager = config.GetBoolean('pager.%s' % name)
  99. if use_pager is None:
  100. use_pager = cmd.WantPager(copts)
  101. if use_pager:
  102. RunPager(config)
  103. try:
  104. cmd.Execute(copts, cargs)
  105. except ManifestInvalidRevisionError, e:
  106. print >>sys.stderr, 'error: %s' % str(e)
  107. sys.exit(1)
  108. except NoSuchProjectError, e:
  109. if e.name:
  110. print >>sys.stderr, 'error: project %s not found' % e.name
  111. else:
  112. print >>sys.stderr, 'error: no project in current directory'
  113. sys.exit(1)
  114. def _MyWrapperPath():
  115. return os.path.join(os.path.dirname(__file__), 'repo')
  116. def _CurrentWrapperVersion():
  117. VERSION = None
  118. pat = re.compile(r'^VERSION *=')
  119. fd = open(_MyWrapperPath())
  120. for line in fd:
  121. if pat.match(line):
  122. fd.close()
  123. exec line
  124. return VERSION
  125. raise NameError, 'No VERSION in repo script'
  126. def _CheckWrapperVersion(ver, repo_path):
  127. if not repo_path:
  128. repo_path = '~/bin/repo'
  129. if not ver:
  130. print >>sys.stderr, 'no --wrapper-version argument'
  131. sys.exit(1)
  132. exp = _CurrentWrapperVersion()
  133. ver = tuple(map(lambda x: int(x), ver.split('.')))
  134. if len(ver) == 1:
  135. ver = (0, ver[0])
  136. if exp[0] > ver[0] or ver < (0, 4):
  137. exp_str = '.'.join(map(lambda x: str(x), exp))
  138. print >>sys.stderr, """
  139. !!! A new repo command (%5s) is available. !!!
  140. !!! You must upgrade before you can continue: !!!
  141. cp %s %s
  142. """ % (exp_str, _MyWrapperPath(), repo_path)
  143. sys.exit(1)
  144. if exp > ver:
  145. exp_str = '.'.join(map(lambda x: str(x), exp))
  146. print >>sys.stderr, """
  147. ... A new repo command (%5s) is available.
  148. ... You should upgrade soon:
  149. cp %s %s
  150. """ % (exp_str, _MyWrapperPath(), repo_path)
  151. def _CheckRepoDir(dir):
  152. if not dir:
  153. print >>sys.stderr, 'no --repo-dir argument'
  154. sys.exit(1)
  155. def _PruneOptions(argv, opt):
  156. i = 0
  157. while i < len(argv):
  158. a = argv[i]
  159. if a == '--':
  160. break
  161. if a.startswith('--'):
  162. eq = a.find('=')
  163. if eq > 0:
  164. a = a[0:eq]
  165. if not opt.has_option(a):
  166. del argv[i]
  167. continue
  168. i += 1
  169. def _Main(argv):
  170. opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
  171. opt.add_option("--repo-dir", dest="repodir",
  172. help="path to .repo/")
  173. opt.add_option("--wrapper-version", dest="wrapper_version",
  174. help="version of the wrapper script")
  175. opt.add_option("--wrapper-path", dest="wrapper_path",
  176. help="location of the wrapper script")
  177. _PruneOptions(argv, opt)
  178. opt, argv = opt.parse_args(argv)
  179. _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
  180. _CheckRepoDir(opt.repodir)
  181. repo = _Repo(opt.repodir)
  182. try:
  183. try:
  184. repo._Run(argv)
  185. finally:
  186. close_ssh()
  187. except KeyboardInterrupt:
  188. sys.exit(1)
  189. except RepoChangedException, rce:
  190. # If repo changed, re-exec ourselves.
  191. #
  192. argv = list(sys.argv)
  193. argv.extend(rce.extra_args)
  194. try:
  195. os.execv(__file__, argv)
  196. except OSError, e:
  197. print >>sys.stderr, 'fatal: cannot restart repo after upgrade'
  198. print >>sys.stderr, 'fatal: %s' % e
  199. sys.exit(128)
  200. if __name__ == '__main__':
  201. _Main(sys.argv[1:])