repo 39 KB

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