main.py 6.6 KB

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