main.py 6.0 KB

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