main.py 5.4 KB

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