init.py 15 KB

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