repo 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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/qs/qs-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, 5)
  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. def GetParser(gitc_init=False):
  218. """Setup the CLI parser."""
  219. if gitc_init:
  220. usage = 'repo gitc-init -u url -c client [options]'
  221. else:
  222. usage = 'repo init -u url [options]'
  223. parser = optparse.OptionParser(usage=usage)
  224. # Logging.
  225. group = parser.add_option_group('Logging options')
  226. group.add_option('-v', '--verbose',
  227. dest='output_mode', action='store_true',
  228. help='show all output')
  229. group.add_option('-q', '--quiet',
  230. dest='output_mode', action='store_false',
  231. help='only show errors')
  232. # Manifest.
  233. group = parser.add_option_group('Manifest options')
  234. group.add_option('-u', '--manifest-url',
  235. help='manifest repository location', metavar='URL')
  236. group.add_option('-b', '--manifest-branch',
  237. help='manifest branch or revision', metavar='REVISION')
  238. group.add_option('-m', '--manifest-name',
  239. help='initial manifest file', metavar='NAME.xml')
  240. cbr_opts = ['--current-branch']
  241. # The gitc-init subcommand allocates -c itself, but a lot of init users
  242. # want -c, so try to satisfy both as best we can.
  243. if not gitc_init:
  244. cbr_opts += ['-c']
  245. group.add_option(*cbr_opts,
  246. dest='current_branch_only', action='store_true',
  247. help='fetch only current manifest branch from server')
  248. group.add_option('--mirror', action='store_true',
  249. help='create a replica of the remote repositories '
  250. 'rather than a client working directory')
  251. group.add_option('--reference',
  252. help='location of mirror directory', metavar='DIR')
  253. group.add_option('--dissociate', action='store_true',
  254. help='dissociate from reference mirrors after clone')
  255. group.add_option('--depth', type='int', default=None,
  256. help='create a shallow clone with given depth; '
  257. 'see git clone')
  258. group.add_option('--partial-clone', action='store_true',
  259. help='perform partial clone (https://git-scm.com/'
  260. 'docs/gitrepository-layout#_code_partialclone_code)')
  261. group.add_option('--clone-filter', action='store', default='blob:none',
  262. help='filter for use with --partial-clone '
  263. '[default: %default]')
  264. group.add_option('--worktree', action='store_true',
  265. help=optparse.SUPPRESS_HELP)
  266. group.add_option('--archive', action='store_true',
  267. help='checkout an archive instead of a git repository for '
  268. 'each project. See git archive.')
  269. group.add_option('--submodules', action='store_true',
  270. help='sync any submodules associated with the manifest repo')
  271. group.add_option('-g', '--groups', default='default',
  272. help='restrict manifest projects to ones with specified '
  273. 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
  274. metavar='GROUP')
  275. group.add_option('-p', '--platform', default='auto',
  276. help='restrict manifest projects to ones with a specified '
  277. 'platform group [auto|all|none|linux|darwin|...]',
  278. metavar='PLATFORM')
  279. group.add_option('--no-clone-bundle',
  280. dest='clone_bundle', default=True, action='store_false',
  281. help='disable use of /clone.bundle on HTTP/HTTPS')
  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. url = opt.repo_url or REPO_URL
  429. rev = opt.repo_rev or REPO_REV
  430. try:
  431. if gitc_init:
  432. gitc_manifest_dir = get_gitc_manifest_dir()
  433. if not gitc_manifest_dir:
  434. print('fatal: GITC filesystem is not available. Exiting...',
  435. file=sys.stderr)
  436. sys.exit(1)
  437. gitc_client = opt.gitc_client
  438. if not gitc_client:
  439. gitc_client = gitc_parse_clientdir(os.getcwd())
  440. if not gitc_client:
  441. print('fatal: GITC client (-c) is required.', file=sys.stderr)
  442. sys.exit(1)
  443. client_dir = os.path.join(gitc_manifest_dir, gitc_client)
  444. if not os.path.exists(client_dir):
  445. os.makedirs(client_dir)
  446. os.chdir(client_dir)
  447. if os.path.exists(repodir):
  448. # This GITC Client has already initialized repo so continue.
  449. return
  450. os.mkdir(repodir)
  451. except OSError as e:
  452. if e.errno != errno.EEXIST:
  453. print('fatal: cannot make %s directory: %s'
  454. % (repodir, e.strerror), file=sys.stderr)
  455. # Don't raise CloneFailure; that would delete the
  456. # name. Instead exit immediately.
  457. #
  458. sys.exit(1)
  459. _CheckGitVersion()
  460. try:
  461. if not opt.quiet:
  462. print('Downloading Repo source from', url)
  463. dst = os.path.abspath(os.path.join(repodir, S_repo))
  464. _Clone(url, dst, opt.clone_bundle, opt.quiet, opt.verbose)
  465. remote_ref, rev = check_repo_rev(dst, rev, opt.repo_verify, quiet=opt.quiet)
  466. _Checkout(dst, remote_ref, rev, opt.quiet)
  467. if not os.path.isfile(os.path.join(dst, 'repo')):
  468. print("warning: '%s' does not look like a git-repo repository, is "
  469. "REPO_URL set correctly?" % url, file=sys.stderr)
  470. except CloneFailure:
  471. if opt.quiet:
  472. print('fatal: repo init failed; run without --quiet to see why',
  473. file=sys.stderr)
  474. raise
  475. def run_git(*args, **kwargs):
  476. """Run git and return execution details."""
  477. kwargs.setdefault('capture_output', True)
  478. kwargs.setdefault('check', True)
  479. try:
  480. return run_command([GIT] + list(args), **kwargs)
  481. except OSError as e:
  482. print(file=sys.stderr)
  483. print('repo: error: "%s" is not available' % GIT, file=sys.stderr)
  484. print('repo: error: %s' % e, file=sys.stderr)
  485. print(file=sys.stderr)
  486. print('Please make sure %s is installed and in your path.' % GIT,
  487. file=sys.stderr)
  488. sys.exit(1)
  489. except RunError:
  490. raise CloneFailure()
  491. # The git version info broken down into components for easy analysis.
  492. # Similar to Python's sys.version_info.
  493. GitVersion = collections.namedtuple(
  494. 'GitVersion', ('major', 'minor', 'micro', 'full'))
  495. def ParseGitVersion(ver_str=None):
  496. if ver_str is None:
  497. # Load the version ourselves.
  498. ver_str = run_git('--version').stdout
  499. if not ver_str.startswith('git version '):
  500. return None
  501. full_version = ver_str[len('git version '):].strip()
  502. num_ver_str = full_version.split('-')[0]
  503. to_tuple = []
  504. for num_str in num_ver_str.split('.')[:3]:
  505. if num_str.isdigit():
  506. to_tuple.append(int(num_str))
  507. else:
  508. to_tuple.append(0)
  509. to_tuple.append(full_version)
  510. return GitVersion(*to_tuple)
  511. def _CheckGitVersion():
  512. ver_act = ParseGitVersion()
  513. if ver_act is None:
  514. print('fatal: unable to detect git version', file=sys.stderr)
  515. raise CloneFailure()
  516. if ver_act < MIN_GIT_VERSION:
  517. need = '.'.join(map(str, MIN_GIT_VERSION))
  518. print('fatal: git %s or later required; found %s' % (need, ver_act.full),
  519. file=sys.stderr)
  520. raise CloneFailure()
  521. def SetGitTrace2ParentSid(env=None):
  522. """Set up GIT_TRACE2_PARENT_SID for git tracing."""
  523. # We roughly follow the format git itself uses in trace2/tr2_sid.c.
  524. # (1) Be unique (2) be valid filename (3) be fixed length.
  525. #
  526. # Since we always export this variable, we try to avoid more expensive calls.
  527. # e.g. We don't attempt hostname lookups or hashing the results.
  528. if env is None:
  529. env = os.environ
  530. KEY = 'GIT_TRACE2_PARENT_SID'
  531. now = datetime.datetime.utcnow()
  532. value = 'repo-%s-P%08x' % (now.strftime('%Y%m%dT%H%M%SZ'), os.getpid())
  533. # If it's already set, then append ourselves.
  534. if KEY in env:
  535. value = env[KEY] + '/' + value
  536. _setenv(KEY, value, env=env)
  537. def _setenv(key, value, env=None):
  538. """Set |key| in the OS environment |env| to |value|."""
  539. if env is None:
  540. env = os.environ
  541. # Environment handling across systems is messy.
  542. try:
  543. env[key] = value
  544. except UnicodeEncodeError:
  545. env[key] = value.encode()
  546. def NeedSetupGnuPG():
  547. if not os.path.isdir(home_dot_repo):
  548. return True
  549. kv = os.path.join(home_dot_repo, 'keyring-version')
  550. if not os.path.exists(kv):
  551. return True
  552. kv = open(kv).read()
  553. if not kv:
  554. return True
  555. kv = tuple(map(int, kv.split('.')))
  556. if kv < KEYRING_VERSION:
  557. return True
  558. return False
  559. def SetupGnuPG(quiet):
  560. try:
  561. os.mkdir(home_dot_repo)
  562. except OSError as e:
  563. if e.errno != errno.EEXIST:
  564. print('fatal: cannot make %s directory: %s'
  565. % (home_dot_repo, e.strerror), file=sys.stderr)
  566. sys.exit(1)
  567. try:
  568. os.mkdir(gpg_dir, stat.S_IRWXU)
  569. except OSError as e:
  570. if e.errno != errno.EEXIST:
  571. print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
  572. file=sys.stderr)
  573. sys.exit(1)
  574. if not quiet:
  575. print('repo: Updating release signing keys to keyset ver %s' %
  576. ('.'.join(str(x) for x in KEYRING_VERSION),))
  577. # NB: We use --homedir (and cwd below) because some environments (Windows) do
  578. # not correctly handle full native paths. We avoid the issue by changing to
  579. # the right dir with cwd=gpg_dir before executing gpg, and then telling gpg to
  580. # use the cwd (.) as its homedir which leaves the path resolution logic to it.
  581. cmd = ['gpg', '--homedir', '.', '--import']
  582. try:
  583. # gpg can be pretty chatty. Always capture the output and if something goes
  584. # wrong, the builtin check failure will dump stdout & stderr for debugging.
  585. run_command(cmd, stdin=subprocess.PIPE, capture_output=True,
  586. cwd=gpg_dir, check=True,
  587. input=MAINTAINER_KEYS.encode('utf-8'))
  588. except OSError:
  589. if not quiet:
  590. print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
  591. print('warning: Installing it is strongly encouraged.', file=sys.stderr)
  592. print(file=sys.stderr)
  593. return False
  594. with open(os.path.join(home_dot_repo, 'keyring-version'), 'w') as fd:
  595. fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
  596. return True
  597. def _SetConfig(cwd, name, value):
  598. """Set a git configuration option to the specified value.
  599. """
  600. run_git('config', name, value, cwd=cwd)
  601. def _GetRepoConfig(name):
  602. """Read a repo configuration option."""
  603. config = os.path.join(home_dot_repo, 'config')
  604. if not os.path.exists(config):
  605. return None
  606. cmd = ['config', '--file', config, '--get', name]
  607. ret = run_git(*cmd, check=False)
  608. if ret.returncode == 0:
  609. return ret.stdout
  610. elif ret.returncode == 1:
  611. return None
  612. else:
  613. print('repo: error: git %s failed:\n%s' % (' '.join(cmd), ret.stderr),
  614. file=sys.stderr)
  615. raise RunError()
  616. def _InitHttp():
  617. handlers = []
  618. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  619. try:
  620. import netrc
  621. n = netrc.netrc()
  622. for host in n.hosts:
  623. p = n.hosts[host]
  624. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  625. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  626. except Exception:
  627. pass
  628. handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
  629. handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
  630. if 'http_proxy' in os.environ:
  631. url = os.environ['http_proxy']
  632. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  633. if 'REPO_CURL_VERBOSE' in os.environ:
  634. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  635. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  636. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  637. def _Fetch(url, cwd, src, quiet, verbose):
  638. cmd = ['fetch']
  639. if not verbose:
  640. cmd.append('--quiet')
  641. err = None
  642. if not quiet and sys.stdout.isatty():
  643. cmd.append('--progress')
  644. elif not verbose:
  645. err = subprocess.PIPE
  646. cmd.append(src)
  647. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  648. cmd.append('+refs/tags/*:refs/tags/*')
  649. run_git(*cmd, stderr=err, capture_output=False, cwd=cwd)
  650. def _DownloadBundle(url, cwd, quiet, verbose):
  651. if not url.endswith('/'):
  652. url += '/'
  653. url += 'clone.bundle'
  654. ret = run_git('config', '--get-regexp', 'url.*.insteadof', cwd=cwd,
  655. check=False)
  656. for line in ret.stdout.splitlines():
  657. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  658. if m:
  659. new_url = m.group(1)
  660. old_url = m.group(2)
  661. if url.startswith(old_url):
  662. url = new_url + url[len(old_url):]
  663. break
  664. if not url.startswith('http:') and not url.startswith('https:'):
  665. return False
  666. dest = open(os.path.join(cwd, '.git', 'clone.bundle'), 'w+b')
  667. try:
  668. try:
  669. r = urllib.request.urlopen(url)
  670. except urllib.error.HTTPError as e:
  671. if e.code in [401, 403, 404, 501]:
  672. return False
  673. print('fatal: Cannot get %s' % url, file=sys.stderr)
  674. print('fatal: HTTP error %s' % e.code, file=sys.stderr)
  675. raise CloneFailure()
  676. except urllib.error.URLError as e:
  677. print('fatal: Cannot get %s' % url, file=sys.stderr)
  678. print('fatal: error %s' % e.reason, file=sys.stderr)
  679. raise CloneFailure()
  680. try:
  681. if verbose:
  682. print('Downloading clone bundle %s' % url, file=sys.stderr)
  683. while True:
  684. buf = r.read(8192)
  685. if not buf:
  686. return True
  687. dest.write(buf)
  688. finally:
  689. r.close()
  690. finally:
  691. dest.close()
  692. def _ImportBundle(cwd):
  693. path = os.path.join(cwd, '.git', 'clone.bundle')
  694. try:
  695. _Fetch(cwd, cwd, path, True, False)
  696. finally:
  697. os.remove(path)
  698. def _Clone(url, cwd, clone_bundle, quiet, verbose):
  699. """Clones a git repository to a new subdirectory of repodir
  700. """
  701. if verbose:
  702. print('Cloning git repository', url)
  703. try:
  704. os.mkdir(cwd)
  705. except OSError as e:
  706. print('fatal: cannot make %s directory: %s' % (cwd, e.strerror),
  707. file=sys.stderr)
  708. raise CloneFailure()
  709. run_git('init', '--quiet', cwd=cwd)
  710. _InitHttp()
  711. _SetConfig(cwd, 'remote.origin.url', url)
  712. _SetConfig(cwd,
  713. 'remote.origin.fetch',
  714. '+refs/heads/*:refs/remotes/origin/*')
  715. if clone_bundle and _DownloadBundle(url, cwd, quiet, verbose):
  716. _ImportBundle(cwd)
  717. _Fetch(url, cwd, 'origin', quiet, verbose)
  718. def resolve_repo_rev(cwd, committish):
  719. """Figure out what REPO_REV represents.
  720. We support:
  721. * refs/heads/xxx: Branch.
  722. * refs/tags/xxx: Tag.
  723. * xxx: Branch or tag or commit.
  724. Args:
  725. cwd: The git checkout to run in.
  726. committish: The REPO_REV argument to resolve.
  727. Returns:
  728. A tuple of (remote ref, commit) as makes sense for the committish.
  729. For branches, this will look like ('refs/heads/stable', <revision>).
  730. For tags, this will look like ('refs/tags/v1.0', <revision>).
  731. For commits, this will be (<revision>, <revision>).
  732. """
  733. def resolve(committish):
  734. ret = run_git('rev-parse', '--verify', '%s^{commit}' % (committish,),
  735. cwd=cwd, check=False)
  736. return None if ret.returncode else ret.stdout.strip()
  737. # An explicit branch.
  738. if committish.startswith('refs/heads/'):
  739. remote_ref = committish
  740. committish = committish[len('refs/heads/'):]
  741. rev = resolve('refs/remotes/origin/%s' % committish)
  742. if rev is None:
  743. print('repo: error: unknown branch "%s"' % (committish,),
  744. file=sys.stderr)
  745. raise CloneFailure()
  746. return (remote_ref, rev)
  747. # An explicit tag.
  748. if committish.startswith('refs/tags/'):
  749. remote_ref = committish
  750. committish = committish[len('refs/tags/'):]
  751. rev = resolve(remote_ref)
  752. if rev is None:
  753. print('repo: error: unknown tag "%s"' % (committish,),
  754. file=sys.stderr)
  755. raise CloneFailure()
  756. return (remote_ref, rev)
  757. # See if it's a short branch name.
  758. rev = resolve('refs/remotes/origin/%s' % committish)
  759. if rev:
  760. return ('refs/heads/%s' % (committish,), rev)
  761. # See if it's a tag.
  762. rev = resolve('refs/tags/%s' % committish)
  763. if rev:
  764. return ('refs/tags/%s' % (committish,), rev)
  765. # See if it's a commit.
  766. rev = resolve(committish)
  767. if rev and rev.lower().startswith(committish.lower()):
  768. return (rev, rev)
  769. # Give up!
  770. print('repo: error: unable to resolve "%s"' % (committish,), file=sys.stderr)
  771. raise CloneFailure()
  772. def verify_rev(cwd, remote_ref, rev, quiet):
  773. """Verify the commit has been signed by a tag."""
  774. ret = run_git('describe', rev, cwd=cwd)
  775. cur = ret.stdout.strip()
  776. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  777. if m:
  778. cur = m.group(1)
  779. if not quiet:
  780. print(file=sys.stderr)
  781. print("warning: '%s' is not signed; falling back to signed release '%s'"
  782. % (remote_ref, cur), file=sys.stderr)
  783. print(file=sys.stderr)
  784. env = os.environ.copy()
  785. _setenv('GNUPGHOME', gpg_dir, env)
  786. run_git('tag', '-v', cur, cwd=cwd, env=env)
  787. return '%s^0' % cur
  788. def _Checkout(cwd, remote_ref, rev, quiet):
  789. """Checkout an upstream branch into the repository and track it.
  790. """
  791. run_git('update-ref', 'refs/heads/default', rev, cwd=cwd)
  792. _SetConfig(cwd, 'branch.default.remote', 'origin')
  793. _SetConfig(cwd, 'branch.default.merge', remote_ref)
  794. run_git('symbolic-ref', 'HEAD', 'refs/heads/default', cwd=cwd)
  795. cmd = ['read-tree', '--reset', '-u']
  796. if not quiet:
  797. cmd.append('-v')
  798. cmd.append('HEAD')
  799. run_git(*cmd, cwd=cwd)
  800. def _FindRepo():
  801. """Look for a repo installation, starting at the current directory.
  802. """
  803. curdir = os.getcwd()
  804. repo = None
  805. olddir = None
  806. while curdir != '/' \
  807. and curdir != olddir \
  808. and not repo:
  809. repo = os.path.join(curdir, repodir, REPO_MAIN)
  810. if not os.path.isfile(repo):
  811. repo = None
  812. olddir = curdir
  813. curdir = os.path.dirname(curdir)
  814. return (repo, os.path.join(curdir, repodir))
  815. class _Options(object):
  816. help = False
  817. version = False
  818. def _ExpandAlias(name):
  819. """Look up user registered aliases."""
  820. # We don't resolve aliases for existing subcommands. This matches git.
  821. if name in {'gitc-init', 'help', 'init'}:
  822. return name, []
  823. alias = _GetRepoConfig('alias.%s' % (name,))
  824. if alias is None:
  825. return name, []
  826. args = alias.strip().split(' ', 1)
  827. name = args[0]
  828. if len(args) == 2:
  829. args = shlex.split(args[1])
  830. else:
  831. args = []
  832. return name, args
  833. def _ParseArguments(args):
  834. cmd = None
  835. opt = _Options()
  836. arg = []
  837. for i in range(len(args)):
  838. a = args[i]
  839. if a == '-h' or a == '--help':
  840. opt.help = True
  841. elif a == '--version':
  842. opt.version = True
  843. elif a == '--trace':
  844. trace.set(True)
  845. elif not a.startswith('-'):
  846. cmd = a
  847. arg = args[i + 1:]
  848. break
  849. return cmd, opt, arg
  850. def _Usage():
  851. gitc_usage = ""
  852. if get_gitc_manifest_dir():
  853. gitc_usage = " gitc-init Initialize a GITC Client.\n"
  854. print(
  855. """usage: repo COMMAND [ARGS]
  856. repo is not yet installed. Use "repo init" to install it here.
  857. The most commonly used repo commands are:
  858. init Install repo in the current working directory
  859. """ + gitc_usage +
  860. """ help Display detailed help on a command
  861. For access to the full online help, install repo ("repo init").
  862. """)
  863. sys.exit(0)
  864. def _Help(args):
  865. if args:
  866. if args[0] in {'init', 'gitc-init'}:
  867. parser = GetParser(gitc_init=args[0] == 'gitc-init')
  868. parser.print_help()
  869. sys.exit(0)
  870. else:
  871. print("error: '%s' is not a bootstrap command.\n"
  872. ' For access to online help, install repo ("repo init").'
  873. % args[0], file=sys.stderr)
  874. else:
  875. _Usage()
  876. sys.exit(1)
  877. def _Version():
  878. """Show version information."""
  879. print('<repo not installed>')
  880. print('repo launcher version %s' % ('.'.join(str(x) for x in VERSION),))
  881. print(' (from %s)' % (__file__,))
  882. print('git %s' % (ParseGitVersion().full,))
  883. print('Python %s' % sys.version)
  884. uname = platform.uname()
  885. if sys.version_info.major < 3:
  886. # Python 3 returns a named tuple, but Python 2 is simpler.
  887. print(uname)
  888. else:
  889. print('OS %s %s (%s)' % (uname.system, uname.release, uname.version))
  890. print('CPU %s (%s)' %
  891. (uname.machine, uname.processor if uname.processor else 'unknown'))
  892. sys.exit(0)
  893. def _NotInstalled():
  894. print('error: repo is not installed. Use "repo init" to install it here.',
  895. file=sys.stderr)
  896. sys.exit(1)
  897. def _NoCommands(cmd):
  898. print("""error: command '%s' requires repo to be installed first.
  899. Use "repo init" to install it here.""" % cmd, file=sys.stderr)
  900. sys.exit(1)
  901. def _RunSelf(wrapper_path):
  902. my_dir = os.path.dirname(wrapper_path)
  903. my_main = os.path.join(my_dir, 'main.py')
  904. my_git = os.path.join(my_dir, '.git')
  905. if os.path.isfile(my_main) and os.path.isdir(my_git):
  906. for name in ['git_config.py',
  907. 'project.py',
  908. 'subcmds']:
  909. if not os.path.exists(os.path.join(my_dir, name)):
  910. return None, None
  911. return my_main, my_git
  912. return None, None
  913. def _SetDefaultsTo(gitdir):
  914. global REPO_URL
  915. global REPO_REV
  916. REPO_URL = gitdir
  917. ret = run_git('--git-dir=%s' % gitdir, 'symbolic-ref', 'HEAD', check=False)
  918. if ret.returncode:
  919. # If we're not tracking a branch (bisect/etc...), then fall back to commit.
  920. print('repo: warning: %s has no current branch; using HEAD' % gitdir,
  921. file=sys.stderr)
  922. try:
  923. ret = run_git('rev-parse', 'HEAD', cwd=gitdir)
  924. except CloneFailure:
  925. print('fatal: %s has invalid HEAD' % gitdir, file=sys.stderr)
  926. sys.exit(1)
  927. REPO_REV = ret.stdout.strip()
  928. def main(orig_args):
  929. cmd, opt, args = _ParseArguments(orig_args)
  930. # We run this early as we run some git commands ourselves.
  931. SetGitTrace2ParentSid()
  932. repo_main, rel_repo_dir = None, None
  933. # Don't use the local repo copy, make sure to switch to the gitc client first.
  934. if cmd != 'gitc-init':
  935. repo_main, rel_repo_dir = _FindRepo()
  936. wrapper_path = os.path.abspath(__file__)
  937. my_main, my_git = _RunSelf(wrapper_path)
  938. cwd = os.getcwd()
  939. if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
  940. print('error: repo cannot be used in the GITC local manifest directory.'
  941. '\nIf you want to work on this GITC client please rerun this '
  942. 'command from the corresponding client under /gitc/',
  943. file=sys.stderr)
  944. sys.exit(1)
  945. if not repo_main:
  946. # Only expand aliases here since we'll be parsing the CLI ourselves.
  947. # If we had repo_main, alias expansion would happen in main.py.
  948. cmd, alias_args = _ExpandAlias(cmd)
  949. args = alias_args + args
  950. if opt.help:
  951. _Usage()
  952. if cmd == 'help':
  953. _Help(args)
  954. if opt.version or cmd == 'version':
  955. _Version()
  956. if not cmd:
  957. _NotInstalled()
  958. if cmd == 'init' or cmd == 'gitc-init':
  959. if my_git:
  960. _SetDefaultsTo(my_git)
  961. try:
  962. _Init(args, gitc_init=(cmd == 'gitc-init'))
  963. except CloneFailure:
  964. path = os.path.join(repodir, S_repo)
  965. print("fatal: cloning the git-repo repository failed, will remove "
  966. "'%s' " % path, file=sys.stderr)
  967. shutil.rmtree(path, ignore_errors=True)
  968. sys.exit(1)
  969. repo_main, rel_repo_dir = _FindRepo()
  970. else:
  971. _NoCommands(cmd)
  972. if my_main:
  973. repo_main = my_main
  974. ver_str = '.'.join(map(str, VERSION))
  975. me = [sys.executable, repo_main,
  976. '--repo-dir=%s' % rel_repo_dir,
  977. '--wrapper-version=%s' % ver_str,
  978. '--wrapper-path=%s' % wrapper_path,
  979. '--']
  980. me.extend(orig_args)
  981. exec_command(me)
  982. print("fatal: unable to start %s" % repo_main, file=sys.stderr)
  983. sys.exit(148)
  984. if __name__ == '__main__':
  985. main(sys.argv[1:])