init.py 19 KB

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