repo 31 KB

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