repo 38 KB

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