repo 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #
  4. # Copyright (C) 2008 The Android Open Source Project
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. """Repo launcher.
  18. This is a standalone tool that people may copy to anywhere in their system.
  19. It is used to get an initial repo client checkout, and after that it runs the
  20. copy of repo in the checkout.
  21. """
  22. from __future__ import print_function
  23. import datetime
  24. import os
  25. import platform
  26. import shlex
  27. import subprocess
  28. import sys
  29. # Keep basic logic in sync with repo_trace.py.
  30. class Trace(object):
  31. """Trace helper logic."""
  32. REPO_TRACE = 'REPO_TRACE'
  33. def __init__(self):
  34. self.set(os.environ.get(self.REPO_TRACE) == '1')
  35. def set(self, value):
  36. self.enabled = bool(value)
  37. def print(self, *args, **kwargs):
  38. if self.enabled:
  39. print(*args, **kwargs)
  40. trace = Trace()
  41. def exec_command(cmd):
  42. """Execute |cmd| or return None on failure."""
  43. trace.print(':', ' '.join(cmd))
  44. try:
  45. if platform.system() == 'Windows':
  46. ret = subprocess.call(cmd)
  47. sys.exit(ret)
  48. else:
  49. os.execvp(cmd[0], cmd)
  50. except Exception:
  51. pass
  52. def check_python_version():
  53. """Make sure the active Python version is recent enough."""
  54. def reexec(prog):
  55. exec_command([prog] + sys.argv)
  56. MIN_PYTHON_VERSION = (3, 6)
  57. ver = sys.version_info
  58. major = ver.major
  59. minor = ver.minor
  60. # Abort on very old Python 2 versions.
  61. if (major, minor) < (2, 7):
  62. print('repo: error: Your Python version is too old. '
  63. 'Please use Python {}.{} or newer instead.'.format(
  64. *MIN_PYTHON_VERSION), file=sys.stderr)
  65. sys.exit(1)
  66. # Try to re-exec the version specific Python 3 if needed.
  67. if (major, minor) < MIN_PYTHON_VERSION:
  68. # Python makes releases ~once a year, so try our min version +10 to help
  69. # bridge the gap. This is the fallback anyways so perf isn't critical.
  70. min_major, min_minor = MIN_PYTHON_VERSION
  71. for inc in range(0, 10):
  72. reexec('python{}.{}'.format(min_major, min_minor + inc))
  73. # Try the generic Python 3 wrapper, but only if it's new enough. We don't
  74. # want to go from (still supported) Python 2.7 to (unsupported) Python 3.5.
  75. try:
  76. proc = subprocess.Popen(
  77. ['python3', '-c', 'import sys; '
  78. 'print(sys.version_info.major, sys.version_info.minor)'],
  79. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  80. (output, _) = proc.communicate()
  81. python3_ver = tuple(int(x) for x in output.decode('utf-8').split())
  82. except (OSError, subprocess.CalledProcessError):
  83. python3_ver = None
  84. # The python3 version looks like it's new enough, so give it a try.
  85. if python3_ver and python3_ver >= MIN_PYTHON_VERSION:
  86. reexec('python3')
  87. # We're still here, so diagnose things for the user.
  88. if major < 3:
  89. print('repo: warning: Python 2 is no longer supported; '
  90. 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION),
  91. file=sys.stderr)
  92. else:
  93. print('repo: error: Python 3 version is too old; '
  94. 'Please use Python {}.{} or newer.'.format(*MIN_PYTHON_VERSION),
  95. file=sys.stderr)
  96. sys.exit(1)
  97. if __name__ == '__main__':
  98. check_python_version()
  99. # repo default configuration
  100. #
  101. REPO_URL = os.environ.get('REPO_URL', None)
  102. if not REPO_URL:
  103. # REPO_URL = 'https://gerrit.googlesource.com/git-repo'
  104. REPO_URL = 'http://git.qsopen.com/git-repo'
  105. REPO_REV = os.environ.get('REPO_REV')
  106. if not REPO_REV:
  107. # REPO_REV = 'stable'
  108. REPO_REV = 'qs'
  109. # increment this whenever we make important changes to this script
  110. VERSION = (2, 4)
  111. # increment this if the MAINTAINER_KEYS block is modified
  112. KEYRING_VERSION = (2, 3)
  113. # Each individual key entry is created by using:
  114. # gpg --armor --export keyid
  115. MAINTAINER_KEYS = """
  116. Repo Maintainer <repo@android.kernel.org>
  117. -----BEGIN PGP PUBLIC KEY BLOCK-----
  118. mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
  119. WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
  120. VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
  121. xI1WfzLqdJjsm1Nq98L0cLcD/iNsILCuw44PRds3J75YP0pze7YF/6WFMB6QSFGu
  122. aUX1FsTTztKNXGms8i5b2l1B8JaLRWq/jOnZzyl1zrUJhkc0JgyZW5oNLGyWGhKD
  123. Fxp5YpHuIuMImopWEMFIRQNrvlg+YVK8t3FpdI1RY0LYqha8pPzANhEYgSfoVzOb
  124. fbfbA/4ioOrxy8ifSoga7ITyZMA+XbW8bx33WXutO9N7SPKS/AK2JpasSEVLZcON
  125. ae5hvAEGVXKxVPDjJBmIc2cOe7kOKSi3OxLzBqrjS2rnjiP4o0ekhZIe4+ocwVOg
  126. e0PLlH5avCqihGRhpoqDRsmpzSHzJIxtoeb+GgGEX8KkUsVAhbQpUmVwbyBNYWlu
  127. dGFpbmVyIDxyZXBvQGFuZHJvaWQua2VybmVsLm9yZz6IYAQTEQIAIAUCSPe6AQIb
  128. AwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEBZTDV6SD1xl1GEAn0x/OKQpy7qI
  129. 6G73NJviU0IUMtftAKCFMUhGb/0bZvQ8Rm3QCUpWHyEIu7kEDQRI97ogEBAA2wI6
  130. 5fs9y/rMwD6dkD/vK9v4C9mOn1IL5JCPYMJBVSci+9ED4ChzYvfq7wOcj9qIvaE0
  131. GwCt2ar7Q56me5J+byhSb32Rqsw/r3Vo5cZMH80N4cjesGuSXOGyEWTe4HYoxnHv
  132. gF4EKI2LK7xfTUcxMtlyn52sUpkfKsCpUhFvdmbAiJE+jCkQZr1Z8u2KphV79Ou+
  133. P1N5IXY/XWOlq48Qf4MWCYlJFrB07xjUjLKMPDNDnm58L5byDrP/eHysKexpbakL
  134. xCmYyfT6DV1SWLblpd2hie0sL3YejdtuBMYMS2rI7Yxb8kGuqkz+9l1qhwJtei94
  135. 5MaretDy/d/JH/pRYkRf7L+ke7dpzrP+aJmcz9P1e6gq4NJsWejaALVASBiioqNf
  136. QmtqSVzF1wkR5avZkFHuYvj6V/t1RrOZTXxkSk18KFMJRBZrdHFCWbc5qrVxUB6e
  137. N5pja0NFIUCigLBV1c6I2DwiuboMNh18VtJJh+nwWeez/RueN4ig59gRTtkcc0PR
  138. 35tX2DR8+xCCFVW/NcJ4PSePYzCuuLvp1vEDHnj41R52Fz51hgddT4rBsp0nL+5I
  139. socSOIIezw8T9vVzMY4ArCKFAVu2IVyBcahTfBS8q5EM63mONU6UVJEozfGljiMw
  140. xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
  141. ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
  142. Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
  143. FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
  144. +WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
  145. w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
  146. Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
  147. p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
  148. 0V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
  149. 5xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
  150. HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
  151. zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
  152. TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2uQIN
  153. BF5FqOoBEAC8aRtWEtXzeuoQhdFrLTqYs2dy6kl9y+j3DMQYAMs8je582qzUigIO
  154. ZZxq7T/3WQgghsdw9yPvdzlw9tKdet2TJkR1mtBfSjZQrkKwR0pQP4AD7t/90Whu
  155. R8Wlu8ysapE2hLxMH5Y2znRQX2LkUYmk0K2ik9AgZEh3AFEg3YLl2pGnSjeSp3ch
  156. cLX2n/rVZf5LXluZGRG+iov1Ka+8m+UqzohMA1DYNECJW6KPgXsNX++i8/iwZVic
  157. PWzhRJSQC+QiAZNsKT6HNNKs97YCUVzhjBLnRSxRBPkr0hS/VMWY2V4pbASljWyd
  158. GYmlDcxheLne0yjes0bJAdvig5rB42FOV0FCM4bDYOVwKfZ7SpzGCYXxtlwe0XNG
  159. tLW9WA6tICVqNZ/JNiRTBLrsGSkyrEhDPKnIHlHRI5Zux6IHwMVB0lQKHjSop+t6
  160. oyubqWcPCGGYdz2QGQHNz7huC/Zn0wS4hsoiSwPv6HCq3jNyUkOJ7wZ3ouv60p2I
  161. kPurgviVaRaPSKTYdKfkcJOtFeqOh1na5IHkXsD9rNctB7tSgfsm0G6qJIVe3ZmJ
  162. 7QAyHBfuLrAWCq5xS8EHDlvxPdAD8EEsa9T32YxcHKIkxr1eSwrUrKb8cPhWq1pp
  163. Jiylw6G1fZ02VKixqmPC4oFMyg1PO8L2tcQTrnVmZvfFGiaekHKdhQARAQABiQKW
  164. BBgRAgAgFiEEi7mteT6OYVOvD5pEFlMNXpIPXGUFAl5FqOoCGwICQAkQFlMNXpIP
  165. XGXBdCAEGQEKAB0WIQSjShO+jna/9GoMAi2i51qCSquWJAUCXkWo6gAKCRCi51qC
  166. SquWJLzgD/0YEZYS7yKxhP+kk94TcTYMBMSZpU5KFClB77yu4SI1LeXq4ocBT4sp
  167. EPaOsQiIx//j59J67b7CBe4UeRA6D2n0pw+bCKuc731DFi5X9C1zq3a7E67SQ2yd
  168. FbYE2fnpVnMqb62g4sTh7JmdxEtXCWBUWL0OEoWouBW1PkFDHx2kYLC7YpZt3+4t
  169. VtNhSfV8NS6PF8ep3JXHVd2wsC3DQtggeId5GM44o8N0SkwQHNjK8ZD+VZ74ZnhZ
  170. HeyHskomiOC61LrZWQvxD6VqtfnBQ5GvONO8QuhkiFwMMOnpPVj2k7ngSkd5o27K
  171. 6c53ZESOlR4bAfl0i3RZYC9B5KerGkBE3dTgTzmGjOaahl2eLz4LDPdTwMtS+sAU
  172. 1hPPvZTQeYDdV62bOWUyteMoJu354GgZPQ9eItWYixpNCyOGNcJXl6xk3/OuoP6f
  173. MciFV8aMxs/7mUR8q1Ei3X9MKu+bbODYj2rC1tMkLj1OaAJkfvRuYrKsQpoUsn4q
  174. VT9+aciNpU/I7M30watlWo7RfUFI3zaGdMDcMFju1cWt2Un8E3gtscGufzbz1Z5Z
  175. Gak+tCOWUyuYNWX3noit7Dk6+3JGHGaQettldNu2PLM9SbIXd2EaqK/eEv9BS3dd
  176. ItkZwzyZXSaQ9UqAceY1AHskJJ5KVXIRLuhP5jBWWo3fnRMyMYt2nwNBAJ9B9TA8
  177. VlBniwIl5EzCvOFOTGrtewCdHOvr3N3ieypGz1BzyCN9tJMO3G24MwReRal9Fgkr
  178. BgEEAdpHDwEBB0BhPE/je6OuKgWzJ1mnrUmHhn4IMOHp+58+T5kHU3Oy6YjXBBgR
  179. AgAgFiEEi7mteT6OYVOvD5pEFlMNXpIPXGUFAl5FqX0CGwIAgQkQFlMNXpIPXGV2
  180. IAQZFggAHRYhBOH5BA16P22vrIl809O5XaJD5Io5BQJeRal9AAoJENO5XaJD5Io5
  181. MEkA/3uLmiwANOcgE0zB9zga0T/KkYhYOWFx7zRyDhrTf9spAPwIfSBOAGtwxjLO
  182. DCce5OaQJl/YuGHvXq2yx5h7T8pdAZ+PAJ4qfIk2LLSidsplTDXOKhOQAuOqUQCf
  183. cZ7aFsJF4PtcDrfdejyAxbtsSHI=
  184. =82Tj
  185. -----END PGP PUBLIC KEY BLOCK-----
  186. """
  187. GIT = 'git' # our git command
  188. # NB: The version of git that the repo launcher requires may be much older than
  189. # the version of git that the main repo source tree requires. Keeping this at
  190. # an older version also makes it easier for users to upgrade/rollback as needed.
  191. #
  192. # git-1.7 is in (EOL) Ubuntu Precise.
  193. MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
  194. repodir = '.repo' # name of repo's private directory
  195. S_repo = 'repo' # special repo repository
  196. S_manifests = 'manifests' # special manifest repository
  197. REPO_MAIN = S_repo + '/main.py' # main script
  198. GITC_CONFIG_FILE = '/gitc/.config'
  199. GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
  200. import collections
  201. import errno
  202. import optparse
  203. import re
  204. import shutil
  205. import stat
  206. if sys.version_info[0] == 3:
  207. import urllib.request
  208. import urllib.error
  209. else:
  210. import imp
  211. import urllib2
  212. urllib = imp.new_module('urllib')
  213. urllib.request = urllib2
  214. urllib.error = urllib2
  215. home_dot_repo = os.path.expanduser('~/.repoconfig')
  216. gpg_dir = os.path.join(home_dot_repo, 'gnupg')
  217. extra_args = []
  218. def GetParser(gitc_init=False):
  219. """Setup the CLI parser."""
  220. if gitc_init:
  221. usage = 'repo gitc-init -u url -c client [options]'
  222. else:
  223. usage = 'repo init -u url [options]'
  224. parser = optparse.OptionParser(usage=usage)
  225. # Logging.
  226. group = parser.add_option_group('Logging options')
  227. group.add_option('-v', '--verbose',
  228. dest='output_mode', action='store_true',
  229. help='show all output')
  230. group.add_option('-q', '--quiet',
  231. dest='output_mode', action='store_false',
  232. help='only show errors')
  233. # Manifest.
  234. group = parser.add_option_group('Manifest options')
  235. group.add_option('-u', '--manifest-url',
  236. help='manifest repository location', metavar='URL')
  237. group.add_option('-b', '--manifest-branch',
  238. help='manifest branch or revision', metavar='REVISION')
  239. group.add_option('-m', '--manifest-name',
  240. help='initial manifest file', metavar='NAME.xml')
  241. cbr_opts = ['--current-branch']
  242. # The gitc-init subcommand allocates -c itself, but a lot of init users
  243. # want -c, so try to satisfy both as best we can.
  244. if not gitc_init:
  245. cbr_opts += ['-c']
  246. group.add_option(*cbr_opts,
  247. dest='current_branch_only', action='store_true',
  248. help='fetch only current manifest branch from server')
  249. group.add_option('--mirror', action='store_true',
  250. help='create a replica of the remote repositories '
  251. 'rather than a client working directory')
  252. group.add_option('--reference',
  253. help='location of mirror directory', metavar='DIR')
  254. group.add_option('--dissociate', action='store_true',
  255. help='dissociate from reference mirrors after clone')
  256. group.add_option('--depth', type='int', default=None,
  257. help='create a shallow clone with given depth; '
  258. 'see git clone')
  259. group.add_option('--partial-clone', action='store_true',
  260. help='perform partial clone (https://git-scm.com/'
  261. 'docs/gitrepository-layout#_code_partialclone_code)')
  262. group.add_option('--clone-filter', action='store', default='blob:none',
  263. help='filter for use with --partial-clone '
  264. '[default: %default]')
  265. group.add_option('--worktree', action='store_true',
  266. help=optparse.SUPPRESS_HELP)
  267. group.add_option('--archive', action='store_true',
  268. help='checkout an archive instead of a git repository for '
  269. 'each project. See git archive.')
  270. group.add_option('--submodules', action='store_true',
  271. help='sync any submodules associated with the manifest repo')
  272. group.add_option('-g', '--groups', default='default',
  273. help='restrict manifest projects to ones with specified '
  274. 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
  275. metavar='GROUP')
  276. group.add_option('-p', '--platform', default='auto',
  277. help='restrict manifest projects to ones with a specified '
  278. 'platform group [auto|all|none|linux|darwin|...]',
  279. metavar='PLATFORM')
  280. group.add_option('--no-clone-bundle',
  281. dest='clone_bundle', default=True, action='store_false',
  282. help='disable use of /clone.bundle on HTTP/HTTPS')
  283. group.add_option('--no-tags',
  284. dest='tags', default=True, action='store_false',
  285. help="don't fetch tags in the manifest")
  286. # Tool.
  287. group = parser.add_option_group('repo Version options')
  288. group.add_option('--repo-url', metavar='URL',
  289. help='repo repository location ($REPO_URL)')
  290. group.add_option('--repo-branch', metavar='REVISION',
  291. help='repo branch or revision ($REPO_REV)')
  292. group.add_option('--no-repo-verify',
  293. dest='repo_verify', default=True, action='store_false',
  294. help='do not verify repo source code')
  295. # Other.
  296. group = parser.add_option_group('Other options')
  297. group.add_option('--config-name',
  298. action='store_true', default=False,
  299. help='Always prompt for name/e-mail')
  300. # gitc-init specific settings.
  301. if gitc_init:
  302. group = parser.add_option_group('GITC options')
  303. group.add_option('-f', '--manifest-file',
  304. help='Optional manifest file to use for this GITC client.')
  305. group.add_option('-c', '--gitc-client',
  306. help='Name of the gitc_client instance to create or modify.')
  307. return parser
  308. # This is a poor replacement for subprocess.run until we require Python 3.6+.
  309. RunResult = collections.namedtuple(
  310. 'RunResult', ('returncode', 'stdout', 'stderr'))
  311. class RunError(Exception):
  312. """Error when running a command failed."""
  313. def run_command(cmd, **kwargs):
  314. """Run |cmd| and return its output."""
  315. check = kwargs.pop('check', False)
  316. if kwargs.pop('capture_output', False):
  317. kwargs.setdefault('stdout', subprocess.PIPE)
  318. kwargs.setdefault('stderr', subprocess.PIPE)
  319. cmd_input = kwargs.pop('input', None)
  320. def decode(output):
  321. """Decode |output| to text."""
  322. if output is None:
  323. return output
  324. try:
  325. return output.decode('utf-8')
  326. except UnicodeError:
  327. print('repo: warning: Invalid UTF-8 output:\ncmd: %r\n%r' % (cmd, output),
  328. file=sys.stderr)
  329. # TODO(vapier): Once we require Python 3, use 'backslashreplace'.
  330. return output.decode('utf-8', 'replace')
  331. # Run & package the results.
  332. proc = subprocess.Popen(cmd, **kwargs)
  333. (stdout, stderr) = proc.communicate(input=cmd_input)
  334. dbg = ': ' + ' '.join(cmd)
  335. if cmd_input is not None:
  336. dbg += ' 0<|'
  337. if stdout == subprocess.PIPE:
  338. dbg += ' 1>|'
  339. if stderr == subprocess.PIPE:
  340. dbg += ' 2>|'
  341. elif stderr == subprocess.STDOUT:
  342. dbg += ' 2>&1'
  343. trace.print(dbg)
  344. ret = RunResult(proc.returncode, decode(stdout), decode(stderr))
  345. # If things failed, print useful debugging output.
  346. if check and ret.returncode:
  347. print('repo: error: "%s" failed with exit status %s' %
  348. (cmd[0], ret.returncode), file=sys.stderr)
  349. print(' cwd: %s\n cmd: %r' %
  350. (kwargs.get('cwd', os.getcwd()), cmd), file=sys.stderr)
  351. def _print_output(name, output):
  352. if output:
  353. print(' %s:\n >> %s' % (name, '\n >> '.join(output.splitlines())),
  354. file=sys.stderr)
  355. _print_output('stdout', ret.stdout)
  356. _print_output('stderr', ret.stderr)
  357. raise RunError(ret)
  358. return ret
  359. _gitc_manifest_dir = None
  360. def get_gitc_manifest_dir():
  361. global _gitc_manifest_dir
  362. if _gitc_manifest_dir is None:
  363. _gitc_manifest_dir = ''
  364. try:
  365. with open(GITC_CONFIG_FILE, 'r') as gitc_config:
  366. for line in gitc_config:
  367. match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
  368. if match:
  369. _gitc_manifest_dir = match.group('gitc_manifest_dir')
  370. except IOError:
  371. pass
  372. return _gitc_manifest_dir
  373. def gitc_parse_clientdir(gitc_fs_path):
  374. """Parse a path in the GITC FS and return its client name.
  375. @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
  376. @returns: The GITC client name
  377. """
  378. if gitc_fs_path == GITC_FS_ROOT_DIR:
  379. return None
  380. if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
  381. manifest_dir = get_gitc_manifest_dir()
  382. if manifest_dir == '':
  383. return None
  384. if manifest_dir[-1] != '/':
  385. manifest_dir += '/'
  386. if gitc_fs_path == manifest_dir:
  387. return None
  388. if not gitc_fs_path.startswith(manifest_dir):
  389. return None
  390. return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
  391. return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
  392. class CloneFailure(Exception):
  393. """Indicate the remote clone of repo itself failed.
  394. """
  395. def _Init(args, gitc_init=False):
  396. """Installs repo by cloning it over the network.
  397. """
  398. parser = GetParser(gitc_init=gitc_init)
  399. opt, args = parser.parse_args(args)
  400. if args:
  401. parser.print_usage()
  402. sys.exit(1)
  403. opt.quiet = opt.output_mode is False
  404. opt.verbose = opt.output_mode is True
  405. url = opt.repo_url
  406. if not url:
  407. url = REPO_URL
  408. extra_args.append('--repo-url=%s' % url)
  409. branch = opt.repo_branch
  410. if not branch:
  411. branch = REPO_REV
  412. extra_args.append('--repo-branch=%s' % branch)
  413. if branch.startswith('refs/heads/'):
  414. branch = branch[len('refs/heads/'):]
  415. if branch.startswith('refs/'):
  416. print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
  417. raise CloneFailure()
  418. try:
  419. if gitc_init:
  420. gitc_manifest_dir = get_gitc_manifest_dir()
  421. if not gitc_manifest_dir:
  422. print('fatal: GITC filesystem is not available. Exiting...',
  423. file=sys.stderr)
  424. sys.exit(1)
  425. gitc_client = opt.gitc_client
  426. if not gitc_client:
  427. gitc_client = gitc_parse_clientdir(os.getcwd())
  428. if not gitc_client:
  429. print('fatal: GITC client (-c) is required.', file=sys.stderr)
  430. sys.exit(1)
  431. client_dir = os.path.join(gitc_manifest_dir, gitc_client)
  432. if not os.path.exists(client_dir):
  433. os.makedirs(client_dir)
  434. os.chdir(client_dir)
  435. if os.path.exists(repodir):
  436. # This GITC Client has already initialized repo so continue.
  437. return
  438. os.mkdir(repodir)
  439. except OSError as e:
  440. if e.errno != errno.EEXIST:
  441. print('fatal: cannot make %s directory: %s'
  442. % (repodir, e.strerror), file=sys.stderr)
  443. # Don't raise CloneFailure; that would delete the
  444. # name. Instead exit immediately.
  445. #
  446. sys.exit(1)
  447. _CheckGitVersion()
  448. try:
  449. if not opt.repo_verify:
  450. do_verify = False
  451. else:
  452. if NeedSetupGnuPG():
  453. do_verify = SetupGnuPG(opt.quiet)
  454. else:
  455. do_verify = True
  456. if not opt.quiet:
  457. print('Downloading Repo source from', url)
  458. dst = os.path.abspath(os.path.join(repodir, S_repo))
  459. _Clone(url, dst, opt.clone_bundle, opt.quiet, opt.verbose)
  460. if do_verify:
  461. rev = _Verify(dst, branch, opt.quiet)
  462. else:
  463. rev = 'refs/remotes/origin/%s^0' % branch
  464. _Checkout(dst, branch, rev, opt.quiet)
  465. if not os.path.isfile(os.path.join(dst, 'repo')):
  466. print("warning: '%s' does not look like a git-repo repository, is "
  467. "REPO_URL set correctly?" % url, file=sys.stderr)
  468. except CloneFailure:
  469. if opt.quiet:
  470. print('fatal: repo init failed; run without --quiet to see why',
  471. file=sys.stderr)
  472. raise
  473. def run_git(*args, **kwargs):
  474. """Run git and return execution details."""
  475. kwargs.setdefault('capture_output', True)
  476. kwargs.setdefault('check', True)
  477. try:
  478. return run_command([GIT] + list(args), **kwargs)
  479. except OSError as e:
  480. print(file=sys.stderr)
  481. print('repo: error: "%s" is not available' % GIT, file=sys.stderr)
  482. print('repo: error: %s' % e, file=sys.stderr)
  483. print(file=sys.stderr)
  484. print('Please make sure %s is installed and in your path.' % GIT,
  485. file=sys.stderr)
  486. sys.exit(1)
  487. except RunError:
  488. raise CloneFailure()
  489. # The git version info broken down into components for easy analysis.
  490. # Similar to Python's sys.version_info.
  491. GitVersion = collections.namedtuple(
  492. 'GitVersion', ('major', 'minor', 'micro', 'full'))
  493. def ParseGitVersion(ver_str=None):
  494. if ver_str is None:
  495. # Load the version ourselves.
  496. ver_str = run_git('--version').stdout
  497. if not ver_str.startswith('git version '):
  498. return None
  499. full_version = ver_str[len('git version '):].strip()
  500. num_ver_str = full_version.split('-')[0]
  501. to_tuple = []
  502. for num_str in num_ver_str.split('.')[:3]:
  503. if num_str.isdigit():
  504. to_tuple.append(int(num_str))
  505. else:
  506. to_tuple.append(0)
  507. to_tuple.append(full_version)
  508. return GitVersion(*to_tuple)
  509. def _CheckGitVersion():
  510. ver_act = ParseGitVersion()
  511. if ver_act is None:
  512. print('fatal: unable to detect git version', file=sys.stderr)
  513. raise CloneFailure()
  514. if ver_act < MIN_GIT_VERSION:
  515. need = '.'.join(map(str, MIN_GIT_VERSION))
  516. print('fatal: git %s or later required' % need, file=sys.stderr)
  517. raise CloneFailure()
  518. def SetGitTrace2ParentSid(env=None):
  519. """Set up GIT_TRACE2_PARENT_SID for git tracing."""
  520. # We roughly follow the format git itself uses in trace2/tr2_sid.c.
  521. # (1) Be unique (2) be valid filename (3) be fixed length.
  522. #
  523. # Since we always export this variable, we try to avoid more expensive calls.
  524. # e.g. We don't attempt hostname lookups or hashing the results.
  525. if env is None:
  526. env = os.environ
  527. KEY = 'GIT_TRACE2_PARENT_SID'
  528. now = datetime.datetime.utcnow()
  529. value = 'repo-%s-P%08x' % (now.strftime('%Y%m%dT%H%M%SZ'), os.getpid())
  530. # If it's already set, then append ourselves.
  531. if KEY in env:
  532. value = env[KEY] + '/' + value
  533. _setenv(KEY, value, env=env)
  534. def _setenv(key, value, env=None):
  535. """Set |key| in the OS environment |env| to |value|."""
  536. if env is None:
  537. env = os.environ
  538. # Environment handling across systems is messy.
  539. try:
  540. env[key] = value
  541. except UnicodeEncodeError:
  542. env[key] = value.encode()
  543. def NeedSetupGnuPG():
  544. if not os.path.isdir(home_dot_repo):
  545. return True
  546. kv = os.path.join(home_dot_repo, 'keyring-version')
  547. if not os.path.exists(kv):
  548. return True
  549. kv = open(kv).read()
  550. if not kv:
  551. return True
  552. kv = tuple(map(int, kv.split('.')))
  553. if kv < KEYRING_VERSION:
  554. return True
  555. return False
  556. def SetupGnuPG(quiet):
  557. try:
  558. os.mkdir(home_dot_repo)
  559. except OSError as e:
  560. if e.errno != errno.EEXIST:
  561. print('fatal: cannot make %s directory: %s'
  562. % (home_dot_repo, e.strerror), file=sys.stderr)
  563. sys.exit(1)
  564. try:
  565. os.mkdir(gpg_dir, stat.S_IRWXU)
  566. except OSError as e:
  567. if e.errno != errno.EEXIST:
  568. print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
  569. file=sys.stderr)
  570. sys.exit(1)
  571. if not quiet:
  572. print('repo: Updating release signing keys to keyset ver %s' %
  573. ('.'.join(str(x) for x in KEYRING_VERSION),))
  574. # NB: We use --homedir (and cwd below) because some environments (Windows) do
  575. # not correctly handle full native paths. We avoid the issue by changing to
  576. # the right dir with cwd=gpg_dir before executing gpg, and then telling gpg to
  577. # use the cwd (.) as its homedir which leaves the path resolution logic to it.
  578. cmd = ['gpg', '--homedir', '.', '--import']
  579. try:
  580. # gpg can be pretty chatty. Always capture the output and if something goes
  581. # wrong, the builtin check failure will dump stdout & stderr for debugging.
  582. run_command(cmd, stdin=subprocess.PIPE, capture_output=True,
  583. cwd=gpg_dir, check=True,
  584. input=MAINTAINER_KEYS.encode('utf-8'))
  585. except OSError:
  586. if not quiet:
  587. print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
  588. print('warning: Installing it is strongly encouraged.', file=sys.stderr)
  589. print(file=sys.stderr)
  590. return False
  591. with open(os.path.join(home_dot_repo, 'keyring-version'), 'w') as fd:
  592. fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
  593. return True
  594. def _SetConfig(cwd, name, value):
  595. """Set a git configuration option to the specified value.
  596. """
  597. run_git('config', name, value, cwd=cwd)
  598. def _GetRepoConfig(name):
  599. """Read a repo configuration option."""
  600. config = os.path.join(home_dot_repo, 'config')
  601. if not os.path.exists(config):
  602. return None
  603. cmd = ['config', '--file', config, '--get', name]
  604. ret = run_git(*cmd, check=False)
  605. if ret.returncode == 0:
  606. return ret.stdout
  607. elif ret.returncode == 1:
  608. return None
  609. else:
  610. print('repo: error: git %s failed:\n%s' % (' '.join(cmd), ret.stderr),
  611. file=sys.stderr)
  612. raise RunError()
  613. def _InitHttp():
  614. handlers = []
  615. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  616. try:
  617. import netrc
  618. n = netrc.netrc()
  619. for host in n.hosts:
  620. p = n.hosts[host]
  621. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  622. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  623. except Exception:
  624. pass
  625. handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
  626. handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
  627. if 'http_proxy' in os.environ:
  628. url = os.environ['http_proxy']
  629. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  630. if 'REPO_CURL_VERBOSE' in os.environ:
  631. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  632. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  633. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  634. def _Fetch(url, cwd, src, quiet, verbose):
  635. cmd = ['fetch']
  636. if quiet:
  637. cmd.append('--quiet')
  638. err = subprocess.PIPE
  639. else:
  640. err = None
  641. cmd.append(src)
  642. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  643. cmd.append('+refs/tags/*:refs/tags/*')
  644. run_git(*cmd, stderr=err, cwd=cwd)
  645. def _DownloadBundle(url, cwd, quiet, verbose):
  646. if not url.endswith('/'):
  647. url += '/'
  648. url += 'clone.bundle'
  649. ret = run_git('config', '--get-regexp', 'url.*.insteadof', cwd=cwd,
  650. check=False)
  651. for line in ret.stdout.splitlines():
  652. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  653. if m:
  654. new_url = m.group(1)
  655. old_url = m.group(2)
  656. if url.startswith(old_url):
  657. url = new_url + url[len(old_url):]
  658. break
  659. if not url.startswith('http:') and not url.startswith('https:'):
  660. return False
  661. dest = open(os.path.join(cwd, '.git', 'clone.bundle'), 'w+b')
  662. try:
  663. try:
  664. r = urllib.request.urlopen(url)
  665. except urllib.error.HTTPError as e:
  666. if e.code in [401, 403, 404, 501]:
  667. return False
  668. print('fatal: Cannot get %s' % url, file=sys.stderr)
  669. print('fatal: HTTP error %s' % e.code, file=sys.stderr)
  670. raise CloneFailure()
  671. except urllib.error.URLError as e:
  672. print('fatal: Cannot get %s' % url, file=sys.stderr)
  673. print('fatal: error %s' % e.reason, file=sys.stderr)
  674. raise CloneFailure()
  675. try:
  676. if verbose:
  677. print('Downloading clone bundle %s' % url, file=sys.stderr)
  678. while True:
  679. buf = r.read(8192)
  680. if not buf:
  681. return True
  682. dest.write(buf)
  683. finally:
  684. r.close()
  685. finally:
  686. dest.close()
  687. def _ImportBundle(cwd):
  688. path = os.path.join(cwd, '.git', 'clone.bundle')
  689. try:
  690. _Fetch(cwd, cwd, path, True, False)
  691. finally:
  692. os.remove(path)
  693. def _Clone(url, cwd, clone_bundle, quiet, verbose):
  694. """Clones a git repository to a new subdirectory of repodir
  695. """
  696. if verbose:
  697. print('Cloning git repository', url)
  698. try:
  699. os.mkdir(cwd)
  700. except OSError as e:
  701. print('fatal: cannot make %s directory: %s' % (cwd, e.strerror),
  702. file=sys.stderr)
  703. raise CloneFailure()
  704. run_git('init', '--quiet', cwd=cwd)
  705. _InitHttp()
  706. _SetConfig(cwd, 'remote.origin.url', url)
  707. _SetConfig(cwd,
  708. 'remote.origin.fetch',
  709. '+refs/heads/*:refs/remotes/origin/*')
  710. if clone_bundle and _DownloadBundle(url, cwd, quiet, verbose):
  711. _ImportBundle(cwd)
  712. _Fetch(url, cwd, 'origin', quiet, verbose)
  713. def _Verify(cwd, branch, quiet):
  714. """Verify the branch has been signed by a tag.
  715. """
  716. try:
  717. ret = run_git('describe', 'origin/%s' % branch, cwd=cwd)
  718. cur = ret.stdout.strip()
  719. except CloneFailure:
  720. print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
  721. raise
  722. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  723. if m:
  724. cur = m.group(1)
  725. if not quiet:
  726. print(file=sys.stderr)
  727. print("info: Ignoring branch '%s'; using tagged release '%s'"
  728. % (branch, cur), file=sys.stderr)
  729. print(file=sys.stderr)
  730. env = os.environ.copy()
  731. _setenv('GNUPGHOME', gpg_dir, env)
  732. run_git('tag', '-v', cur, cwd=cwd, env=env)
  733. return '%s^0' % cur
  734. def _Checkout(cwd, branch, rev, quiet):
  735. """Checkout an upstream branch into the repository and track it.
  736. """
  737. run_git('update-ref', 'refs/heads/default', rev, cwd=cwd)
  738. _SetConfig(cwd, 'branch.default.remote', 'origin')
  739. _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
  740. run_git('symbolic-ref', 'HEAD', 'refs/heads/default', cwd=cwd)
  741. cmd = ['read-tree', '--reset', '-u']
  742. if not quiet:
  743. cmd.append('-v')
  744. cmd.append('HEAD')
  745. run_git(*cmd, cwd=cwd)
  746. def _FindRepo():
  747. """Look for a repo installation, starting at the current directory.
  748. """
  749. curdir = os.getcwd()
  750. repo = None
  751. olddir = None
  752. while curdir != '/' \
  753. and curdir != olddir \
  754. and not repo:
  755. repo = os.path.join(curdir, repodir, REPO_MAIN)
  756. if not os.path.isfile(repo):
  757. repo = None
  758. olddir = curdir
  759. curdir = os.path.dirname(curdir)
  760. return (repo, os.path.join(curdir, repodir))
  761. class _Options(object):
  762. help = False
  763. version = False
  764. def _ExpandAlias(name):
  765. """Look up user registered aliases."""
  766. # We don't resolve aliases for existing subcommands. This matches git.
  767. if name in {'gitc-init', 'help', 'init'}:
  768. return name, []
  769. alias = _GetRepoConfig('alias.%s' % (name,))
  770. if alias is None:
  771. return name, []
  772. args = alias.strip().split(' ', 1)
  773. name = args[0]
  774. if len(args) == 2:
  775. args = shlex.split(args[1])
  776. else:
  777. args = []
  778. return name, args
  779. def _ParseArguments(args):
  780. cmd = None
  781. opt = _Options()
  782. arg = []
  783. for i in range(len(args)):
  784. a = args[i]
  785. if a == '-h' or a == '--help':
  786. opt.help = True
  787. elif a == '--version':
  788. opt.version = True
  789. elif a == '--trace':
  790. trace.set(True)
  791. elif not a.startswith('-'):
  792. cmd = a
  793. arg = args[i + 1:]
  794. break
  795. return cmd, opt, arg
  796. def _Usage():
  797. gitc_usage = ""
  798. if get_gitc_manifest_dir():
  799. gitc_usage = " gitc-init Initialize a GITC Client.\n"
  800. print(
  801. """usage: repo COMMAND [ARGS]
  802. repo is not yet installed. Use "repo init" to install it here.
  803. The most commonly used repo commands are:
  804. init Install repo in the current working directory
  805. """ + gitc_usage +
  806. """ help Display detailed help on a command
  807. For access to the full online help, install repo ("repo init").
  808. """)
  809. sys.exit(0)
  810. def _Help(args):
  811. if args:
  812. if args[0] in {'init', 'gitc-init'}:
  813. parser = GetParser(gitc_init=args[0] == 'gitc-init')
  814. parser.print_help()
  815. sys.exit(0)
  816. else:
  817. print("error: '%s' is not a bootstrap command.\n"
  818. ' For access to online help, install repo ("repo init").'
  819. % args[0], file=sys.stderr)
  820. else:
  821. _Usage()
  822. sys.exit(1)
  823. def _Version():
  824. """Show version information."""
  825. print('<repo not installed>')
  826. print('repo launcher version %s' % ('.'.join(str(x) for x in VERSION),))
  827. print(' (from %s)' % (__file__,))
  828. print('git %s' % (ParseGitVersion().full,))
  829. print('Python %s' % sys.version)
  830. sys.exit(0)
  831. def _NotInstalled():
  832. print('error: repo is not installed. Use "repo init" to install it here.',
  833. file=sys.stderr)
  834. sys.exit(1)
  835. def _NoCommands(cmd):
  836. print("""error: command '%s' requires repo to be installed first.
  837. Use "repo init" to install it here.""" % cmd, file=sys.stderr)
  838. sys.exit(1)
  839. def _RunSelf(wrapper_path):
  840. my_dir = os.path.dirname(wrapper_path)
  841. my_main = os.path.join(my_dir, 'main.py')
  842. my_git = os.path.join(my_dir, '.git')
  843. if os.path.isfile(my_main) and os.path.isdir(my_git):
  844. for name in ['git_config.py',
  845. 'project.py',
  846. 'subcmds']:
  847. if not os.path.exists(os.path.join(my_dir, name)):
  848. return None, None
  849. return my_main, my_git
  850. return None, None
  851. def _SetDefaultsTo(gitdir):
  852. global REPO_URL
  853. global REPO_REV
  854. REPO_URL = gitdir
  855. try:
  856. ret = run_git('--git-dir=%s' % gitdir, 'symbolic-ref', 'HEAD')
  857. REPO_REV = ret.stdout.strip()
  858. except CloneFailure:
  859. print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
  860. sys.exit(1)
  861. def main(orig_args):
  862. cmd, opt, args = _ParseArguments(orig_args)
  863. # We run this early as we run some git commands ourselves.
  864. SetGitTrace2ParentSid()
  865. repo_main, rel_repo_dir = None, None
  866. # Don't use the local repo copy, make sure to switch to the gitc client first.
  867. if cmd != 'gitc-init':
  868. repo_main, rel_repo_dir = _FindRepo()
  869. wrapper_path = os.path.abspath(__file__)
  870. my_main, my_git = _RunSelf(wrapper_path)
  871. cwd = os.getcwd()
  872. if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
  873. print('error: repo cannot be used in the GITC local manifest directory.'
  874. '\nIf you want to work on this GITC client please rerun this '
  875. 'command from the corresponding client under /gitc/',
  876. file=sys.stderr)
  877. sys.exit(1)
  878. if not repo_main:
  879. # Only expand aliases here since we'll be parsing the CLI ourselves.
  880. # If we had repo_main, alias expansion would happen in main.py.
  881. cmd, alias_args = _ExpandAlias(cmd)
  882. args = alias_args + args
  883. if opt.help:
  884. _Usage()
  885. if cmd == 'help':
  886. _Help(args)
  887. if opt.version or cmd == 'version':
  888. _Version()
  889. if not cmd:
  890. _NotInstalled()
  891. if cmd == 'init' or cmd == 'gitc-init':
  892. if my_git:
  893. _SetDefaultsTo(my_git)
  894. try:
  895. _Init(args, gitc_init=(cmd == 'gitc-init'))
  896. except CloneFailure:
  897. path = os.path.join(repodir, S_repo)
  898. print("fatal: cloning the git-repo repository failed, will remove "
  899. "'%s' " % path, file=sys.stderr)
  900. shutil.rmtree(path, ignore_errors=True)
  901. sys.exit(1)
  902. repo_main, rel_repo_dir = _FindRepo()
  903. else:
  904. _NoCommands(cmd)
  905. if my_main:
  906. repo_main = my_main
  907. ver_str = '.'.join(map(str, VERSION))
  908. me = [sys.executable, repo_main,
  909. '--repo-dir=%s' % rel_repo_dir,
  910. '--wrapper-version=%s' % ver_str,
  911. '--wrapper-path=%s' % wrapper_path,
  912. '--']
  913. me.extend(orig_args)
  914. me.extend(extra_args)
  915. exec_command(me)
  916. print("fatal: unable to start %s" % repo_main, file=sys.stderr)
  917. sys.exit(148)
  918. if __name__ == '__main__':
  919. main(sys.argv[1:])