repo 32 KB

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