repo 39 KB

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