init.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2008 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from __future__ import print_function
  17. import optparse
  18. import os
  19. import platform
  20. import re
  21. import sys
  22. from pyversion import is_python3
  23. if is_python3():
  24. import urllib.parse
  25. else:
  26. import imp
  27. import urlparse
  28. urllib = imp.new_module('urllib')
  29. urllib.parse = urlparse
  30. from color import Coloring
  31. from command import InteractiveCommand, MirrorSafeCommand
  32. from error import ManifestParseError
  33. from project import SyncBuffer
  34. from git_config import GitConfig
  35. from git_command import git_require, MIN_GIT_VERSION_SOFT, MIN_GIT_VERSION_HARD
  36. import platform_utils
  37. from wrapper import Wrapper
  38. class Init(InteractiveCommand, MirrorSafeCommand):
  39. common = True
  40. helpSummary = "Initialize repo in the current directory"
  41. helpUsage = """
  42. %prog [options]
  43. """
  44. helpDescription = """
  45. The '%prog' command is run once to install and initialize repo.
  46. The latest repo source code and manifest collection is downloaded
  47. from the server and is installed in the .repo/ directory in the
  48. current working directory.
  49. The optional -b argument can be used to select the manifest branch
  50. to checkout and use. If no branch is specified, master is assumed.
  51. The optional -m argument can be used to specify an alternate manifest
  52. to be used. If no manifest is specified, the manifest default.xml
  53. will be used.
  54. The --reference option can be used to point to a directory that
  55. has the content of a --mirror sync. This will make the working
  56. directory use as much data as possible from the local reference
  57. directory when fetching from the server. This will make the sync
  58. go a lot faster by reducing data traffic on the network.
  59. The --dissociate option can be used to borrow the objects from
  60. the directory specified with the --reference option only to reduce
  61. network transfer, and stop borrowing from them after a first clone
  62. is made by making necessary local copies of borrowed objects.
  63. The --no-clone-bundle option disables any attempt to use
  64. $URL/clone.bundle to bootstrap a new Git repository from a
  65. resumeable bundle file on a content delivery network. This
  66. may be necessary if there are problems with the local Python
  67. HTTP client or proxy configuration, but the Git binary works.
  68. # Switching Manifest Branches
  69. To switch to another manifest branch, `repo init -b otherbranch`
  70. may be used in an existing client. However, as this only updates the
  71. manifest, a subsequent `repo sync` (or `repo sync -d`) is necessary
  72. to update the working directory files.
  73. """
  74. def _Options(self, p, gitc_init=False):
  75. # Logging
  76. g = p.add_option_group('Logging options')
  77. g.add_option('-v', '--verbose',
  78. dest='output_mode', action='store_true',
  79. help='show all output')
  80. g.add_option('-q', '--quiet',
  81. dest='output_mode', action='store_false',
  82. help='only show errors')
  83. # Manifest
  84. g = p.add_option_group('Manifest options')
  85. g.add_option('-u', '--manifest-url',
  86. dest='manifest_url',
  87. help='manifest repository location', metavar='URL')
  88. g.add_option('-b', '--manifest-branch',
  89. dest='manifest_branch',
  90. help='manifest branch or revision', metavar='REVISION')
  91. cbr_opts = ['--current-branch']
  92. # The gitc-init subcommand allocates -c itself, but a lot of init users
  93. # want -c, so try to satisfy both as best we can.
  94. if not gitc_init:
  95. cbr_opts += ['-c']
  96. g.add_option(*cbr_opts,
  97. dest='current_branch_only', action='store_true',
  98. help='fetch only current manifest branch from server')
  99. g.add_option('-m', '--manifest-name',
  100. dest='manifest_name', default='default.xml',
  101. help='initial manifest file', metavar='NAME.xml')
  102. g.add_option('--mirror',
  103. dest='mirror', action='store_true',
  104. help='create a replica of the remote repositories '
  105. 'rather than a client working directory')
  106. g.add_option('--reference',
  107. dest='reference',
  108. help='location of mirror directory', metavar='DIR')
  109. g.add_option('--dissociate',
  110. dest='dissociate', action='store_true',
  111. help='dissociate from reference mirrors after clone')
  112. g.add_option('--depth', type='int', default=None,
  113. dest='depth',
  114. help='create a shallow clone with given depth; see git clone')
  115. g.add_option('--partial-clone', action='store_true',
  116. dest='partial_clone',
  117. help='perform partial clone (https://git-scm.com/'
  118. 'docs/gitrepository-layout#_code_partialclone_code)')
  119. g.add_option('--clone-filter', action='store', default='blob:none',
  120. dest='clone_filter',
  121. help='filter for use with --partial-clone [default: %default]')
  122. # TODO(vapier): Expose option with real help text once this has been in the
  123. # wild for a while w/out significant bug reports. Goal is by ~Sep 2020.
  124. g.add_option('--worktree', action='store_true',
  125. help=optparse.SUPPRESS_HELP)
  126. g.add_option('--archive',
  127. dest='archive', action='store_true',
  128. help='checkout an archive instead of a git repository for '
  129. 'each project. See git archive.')
  130. g.add_option('--submodules',
  131. dest='submodules', action='store_true',
  132. help='sync any submodules associated with the manifest repo')
  133. g.add_option('-g', '--groups',
  134. dest='groups', default='default',
  135. help='restrict manifest projects to ones with specified '
  136. 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
  137. metavar='GROUP')
  138. g.add_option('-p', '--platform',
  139. dest='platform', default='auto',
  140. help='restrict manifest projects to ones with a specified '
  141. 'platform group [auto|all|none|linux|darwin|...]',
  142. metavar='PLATFORM')
  143. g.add_option('--clone-bundle', action='store_true',
  144. help='force use of /clone.bundle on HTTP/HTTPS (default if not --partial-clone)')
  145. g.add_option('--no-clone-bundle',
  146. dest='clone_bundle', action='store_false',
  147. help='disable use of /clone.bundle on HTTP/HTTPS (default if --partial-clone)')
  148. g.add_option('--no-tags',
  149. dest='tags', default=True, action='store_false',
  150. help="don't fetch tags in the manifest")
  151. # Tool
  152. g = p.add_option_group('repo Version options')
  153. g.add_option('--repo-url',
  154. dest='repo_url',
  155. help='repo repository location', metavar='URL')
  156. g.add_option('--repo-rev', metavar='REV',
  157. help='repo branch or revision')
  158. g.add_option('--repo-branch', dest='repo_rev',
  159. help=optparse.SUPPRESS_HELP)
  160. g.add_option('--no-repo-verify',
  161. dest='repo_verify', default=True, action='store_false',
  162. help='do not verify repo source code')
  163. # Other
  164. g = p.add_option_group('Other options')
  165. g.add_option('--config-name',
  166. dest='config_name', action="store_true", default=False,
  167. help='Always prompt for name/e-mail')
  168. def _RegisteredEnvironmentOptions(self):
  169. return {'REPO_MANIFEST_URL': 'manifest_url',
  170. 'REPO_MIRROR_LOCATION': 'reference'}
  171. def _SyncManifest(self, opt):
  172. m = self.manifest.manifestProject
  173. is_new = not m.Exists
  174. if is_new:
  175. if not opt.manifest_url:
  176. print('fatal: manifest url (-u) is required.', file=sys.stderr)
  177. sys.exit(1)
  178. if not opt.quiet:
  179. print('Downloading manifest from %s' %
  180. (GitConfig.ForUser().UrlInsteadOf(opt.manifest_url),),
  181. file=sys.stderr)
  182. # The manifest project object doesn't keep track of the path on the
  183. # server where this git is located, so let's save that here.
  184. mirrored_manifest_git = None
  185. if opt.reference:
  186. manifest_git_path = urllib.parse.urlparse(opt.manifest_url).path[1:]
  187. mirrored_manifest_git = os.path.join(opt.reference, manifest_git_path)
  188. if not mirrored_manifest_git.endswith(".git"):
  189. mirrored_manifest_git += ".git"
  190. if not os.path.exists(mirrored_manifest_git):
  191. mirrored_manifest_git = os.path.join(opt.reference,
  192. '.repo/manifests.git')
  193. m._InitGitDir(mirror_git=mirrored_manifest_git)
  194. if opt.manifest_branch:
  195. m.revisionExpr = opt.manifest_branch
  196. else:
  197. m.revisionExpr = 'refs/heads/master'
  198. else:
  199. if opt.manifest_branch:
  200. m.revisionExpr = opt.manifest_branch
  201. else:
  202. m.PreSync()
  203. self._ConfigureDepth(opt)
  204. if opt.manifest_url:
  205. r = m.GetRemote(m.remote.name)
  206. r.url = opt.manifest_url
  207. r.ResetFetch()
  208. r.Save()
  209. groups = re.split(r'[,\s]+', opt.groups)
  210. all_platforms = ['linux', 'darwin', 'windows']
  211. platformize = lambda x: 'platform-' + x
  212. if opt.platform == 'auto':
  213. if (not opt.mirror and
  214. not m.config.GetString('repo.mirror') == 'true'):
  215. groups.append(platformize(platform.system().lower()))
  216. elif opt.platform == 'all':
  217. groups.extend(map(platformize, all_platforms))
  218. elif opt.platform in all_platforms:
  219. groups.append(platformize(opt.platform))
  220. elif opt.platform != 'none':
  221. print('fatal: invalid platform flag', file=sys.stderr)
  222. sys.exit(1)
  223. groups = [x for x in groups if x]
  224. groupstr = ','.join(groups)
  225. if opt.platform == 'auto' and groupstr == 'default,platform-' + platform.system().lower():
  226. groupstr = None
  227. m.config.SetString('manifest.groups', groupstr)
  228. if opt.reference:
  229. m.config.SetString('repo.reference', opt.reference)
  230. if opt.dissociate:
  231. m.config.SetString('repo.dissociate', 'true')
  232. if opt.worktree:
  233. if opt.mirror:
  234. print('fatal: --mirror and --worktree are incompatible',
  235. file=sys.stderr)
  236. sys.exit(1)
  237. if opt.submodules:
  238. print('fatal: --submodules and --worktree are incompatible',
  239. file=sys.stderr)
  240. sys.exit(1)
  241. m.config.SetString('repo.worktree', 'true')
  242. if is_new:
  243. m.use_git_worktrees = True
  244. print('warning: --worktree is experimental!', file=sys.stderr)
  245. if opt.archive:
  246. if is_new:
  247. m.config.SetString('repo.archive', 'true')
  248. else:
  249. print('fatal: --archive is only supported when initializing a new '
  250. 'workspace.', file=sys.stderr)
  251. print('Either delete the .repo folder in this workspace, or initialize '
  252. 'in another location.', file=sys.stderr)
  253. sys.exit(1)
  254. if opt.mirror:
  255. if is_new:
  256. m.config.SetString('repo.mirror', 'true')
  257. else:
  258. print('fatal: --mirror is only supported when initializing a new '
  259. 'workspace.', file=sys.stderr)
  260. print('Either delete the .repo folder in this workspace, or initialize '
  261. 'in another location.', file=sys.stderr)
  262. sys.exit(1)
  263. if opt.partial_clone:
  264. if opt.mirror:
  265. print('fatal: --mirror and --partial-clone are mutually exclusive',
  266. file=sys.stderr)
  267. sys.exit(1)
  268. m.config.SetString('repo.partialclone', 'true')
  269. if opt.clone_filter:
  270. m.config.SetString('repo.clonefilter', opt.clone_filter)
  271. else:
  272. opt.clone_filter = None
  273. if opt.clone_bundle is None:
  274. opt.clone_bundle = False if opt.partial_clone else True
  275. else:
  276. m.config.SetString('repo.clonebundle', 'true' if opt.clone_bundle else 'false')
  277. if opt.submodules:
  278. m.config.SetString('repo.submodules', 'true')
  279. if not m.Sync_NetworkHalf(is_new=is_new, quiet=opt.quiet, verbose=opt.verbose,
  280. clone_bundle=opt.clone_bundle,
  281. current_branch_only=opt.current_branch_only,
  282. tags=opt.tags, submodules=opt.submodules,
  283. clone_filter=opt.clone_filter):
  284. r = m.GetRemote(m.remote.name)
  285. print('fatal: cannot obtain manifest %s' % r.url, file=sys.stderr)
  286. # Better delete the manifest git dir if we created it; otherwise next
  287. # time (when user fixes problems) we won't go through the "is_new" logic.
  288. if is_new:
  289. platform_utils.rmtree(m.gitdir)
  290. sys.exit(1)
  291. if opt.manifest_branch:
  292. m.MetaBranchSwitch(submodules=opt.submodules)
  293. syncbuf = SyncBuffer(m.config)
  294. m.Sync_LocalHalf(syncbuf, submodules=opt.submodules)
  295. syncbuf.Finish()
  296. if is_new or m.CurrentBranch is None:
  297. if not m.StartBranch('default'):
  298. print('fatal: cannot create default in manifest', file=sys.stderr)
  299. sys.exit(1)
  300. def _LinkManifest(self, name):
  301. if not name:
  302. print('fatal: manifest name (-m) is required.', file=sys.stderr)
  303. sys.exit(1)
  304. try:
  305. self.manifest.Link(name)
  306. except ManifestParseError as e:
  307. print("fatal: manifest '%s' not available" % name, file=sys.stderr)
  308. print('fatal: %s' % str(e), file=sys.stderr)
  309. sys.exit(1)
  310. def _Prompt(self, prompt, value):
  311. print('%-10s [%s]: ' % (prompt, value), end='')
  312. # TODO: When we require Python 3, use flush=True w/print above.
  313. sys.stdout.flush()
  314. a = sys.stdin.readline().strip()
  315. if a == '':
  316. return value
  317. return a
  318. def _ShouldConfigureUser(self, opt):
  319. gc = self.manifest.globalConfig
  320. mp = self.manifest.manifestProject
  321. # If we don't have local settings, get from global.
  322. if not mp.config.Has('user.name') or not mp.config.Has('user.email'):
  323. if not gc.Has('user.name') or not gc.Has('user.email'):
  324. return True
  325. mp.config.SetString('user.name', gc.GetString('user.name'))
  326. mp.config.SetString('user.email', gc.GetString('user.email'))
  327. if not opt.quiet:
  328. print()
  329. print('Your identity is: %s <%s>' % (mp.config.GetString('user.name'),
  330. mp.config.GetString('user.email')))
  331. print("If you want to change this, please re-run 'repo init' with --config-name")
  332. return False
  333. def _ConfigureUser(self, opt):
  334. mp = self.manifest.manifestProject
  335. while True:
  336. if not opt.quiet:
  337. print()
  338. name = self._Prompt('Your Name', mp.UserName)
  339. email = self._Prompt('Your Email', mp.UserEmail)
  340. if not opt.quiet:
  341. print()
  342. print('Your identity is: %s <%s>' % (name, email))
  343. print('is this correct [y/N]? ', end='')
  344. # TODO: When we require Python 3, use flush=True w/print above.
  345. sys.stdout.flush()
  346. a = sys.stdin.readline().strip().lower()
  347. if a in ('yes', 'y', 't', 'true'):
  348. break
  349. if name != mp.UserName:
  350. mp.config.SetString('user.name', name)
  351. if email != mp.UserEmail:
  352. mp.config.SetString('user.email', email)
  353. def _HasColorSet(self, gc):
  354. for n in ['ui', 'diff', 'status']:
  355. if gc.Has('color.%s' % n):
  356. return True
  357. return False
  358. def _ConfigureColor(self):
  359. gc = self.manifest.globalConfig
  360. if self._HasColorSet(gc):
  361. return
  362. class _Test(Coloring):
  363. def __init__(self):
  364. Coloring.__init__(self, gc, 'test color display')
  365. self._on = True
  366. out = _Test()
  367. print()
  368. print("Testing colorized output (for 'repo diff', 'repo status'):")
  369. for c in ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan']:
  370. out.write(' ')
  371. out.printer(fg=c)(' %-6s ', c)
  372. out.write(' ')
  373. out.printer(fg='white', bg='black')(' %s ' % 'white')
  374. out.nl()
  375. for c in ['bold', 'dim', 'ul', 'reverse']:
  376. out.write(' ')
  377. out.printer(fg='black', attr=c)(' %-6s ', c)
  378. out.nl()
  379. print('Enable color display in this user account (y/N)? ', end='')
  380. # TODO: When we require Python 3, use flush=True w/print above.
  381. sys.stdout.flush()
  382. a = sys.stdin.readline().strip().lower()
  383. if a in ('y', 'yes', 't', 'true', 'on'):
  384. gc.SetString('color.ui', 'auto')
  385. def _ConfigureDepth(self, opt):
  386. """Configure the depth we'll sync down.
  387. Args:
  388. opt: Options from optparse. We care about opt.depth.
  389. """
  390. # Opt.depth will be non-None if user actually passed --depth to repo init.
  391. if opt.depth is not None:
  392. if opt.depth > 0:
  393. # Positive values will set the depth.
  394. depth = str(opt.depth)
  395. else:
  396. # Negative numbers will clear the depth; passing None to SetString
  397. # will do that.
  398. depth = None
  399. # We store the depth in the main manifest project.
  400. self.manifest.manifestProject.config.SetString('repo.depth', depth)
  401. def _DisplayResult(self, opt):
  402. if self.manifest.IsMirror:
  403. init_type = 'mirror '
  404. else:
  405. init_type = ''
  406. if not opt.quiet:
  407. print()
  408. print('repo %shas been initialized in %s' %
  409. (init_type, self.manifest.topdir))
  410. current_dir = os.getcwd()
  411. if current_dir != self.manifest.topdir:
  412. print('If this is not the directory in which you want to initialize '
  413. 'repo, please run:')
  414. print(' rm -r %s/.repo' % self.manifest.topdir)
  415. print('and try again.')
  416. def ValidateOptions(self, opt, args):
  417. if opt.reference:
  418. opt.reference = os.path.expanduser(opt.reference)
  419. # Check this here, else manifest will be tagged "not new" and init won't be
  420. # possible anymore without removing the .repo/manifests directory.
  421. if opt.archive and opt.mirror:
  422. self.OptionParser.error('--mirror and --archive cannot be used together.')
  423. def Execute(self, opt, args):
  424. git_require(MIN_GIT_VERSION_HARD, fail=True)
  425. if not git_require(MIN_GIT_VERSION_SOFT):
  426. print('repo: warning: git-%s+ will soon be required; please upgrade your '
  427. 'version of git to maintain support.'
  428. % ('.'.join(str(x) for x in MIN_GIT_VERSION_SOFT),),
  429. file=sys.stderr)
  430. opt.quiet = opt.output_mode is False
  431. opt.verbose = opt.output_mode is True
  432. rp = self.manifest.repoProject
  433. # Handle new --repo-url requests.
  434. if opt.repo_url:
  435. remote = rp.GetRemote('origin')
  436. remote.url = opt.repo_url
  437. remote.Save()
  438. # Handle new --repo-rev requests.
  439. if opt.repo_rev:
  440. wrapper = Wrapper()
  441. remote_ref, rev = wrapper.check_repo_rev(
  442. rp.gitdir, opt.repo_rev, repo_verify=opt.repo_verify, quiet=opt.quiet)
  443. branch = rp.GetBranch('default')
  444. branch.merge = remote_ref
  445. rp.work_git.update_ref('refs/heads/default', rev)
  446. branch.Save()
  447. if opt.worktree:
  448. # Older versions of git supported worktree, but had dangerous gc bugs.
  449. git_require((2, 15, 0), fail=True, msg='git gc worktree corruption')
  450. self._SyncManifest(opt)
  451. self._LinkManifest(opt.manifest_name)
  452. if os.isatty(0) and os.isatty(1) and not self.manifest.IsMirror:
  453. if opt.config_name or self._ShouldConfigureUser(opt):
  454. self._ConfigureUser(opt)
  455. self._ConfigureColor()
  456. self._DisplayResult(opt)