init.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import print_function
  16. import os
  17. import platform
  18. import re
  19. import shutil
  20. import sys
  21. from color import Coloring
  22. from command import InteractiveCommand, MirrorSafeCommand
  23. from error import ManifestParseError
  24. from project import SyncBuffer
  25. from git_config import GitConfig
  26. from git_command import git_require, MIN_GIT_VERSION
  27. class Init(InteractiveCommand, MirrorSafeCommand):
  28. common = True
  29. helpSummary = "Initialize repo in the current directory"
  30. helpUsage = """
  31. %prog [options]
  32. """
  33. helpDescription = """
  34. The '%prog' command is run once to install and initialize repo.
  35. The latest repo source code and manifest collection is downloaded
  36. from the server and is installed in the .repo/ directory in the
  37. current working directory.
  38. The optional -b argument can be used to select the manifest branch
  39. to checkout and use. If no branch is specified, master is assumed.
  40. The optional -m argument can be used to specify an alternate manifest
  41. to be used. If no manifest is specified, the manifest default.xml
  42. will be used.
  43. The --reference option can be used to point to a directory that
  44. has the content of a --mirror sync. This will make the working
  45. directory use as much data as possible from the local reference
  46. directory when fetching from the server. This will make the sync
  47. go a lot faster by reducing data traffic on the network.
  48. Switching Manifest Branches
  49. ---------------------------
  50. To switch to another manifest branch, `repo init -b otherbranch`
  51. may be used in an existing client. However, as this only updates the
  52. manifest, a subsequent `repo sync` (or `repo sync -d`) is necessary
  53. to update the working directory files.
  54. """
  55. def _Options(self, p):
  56. # Logging
  57. g = p.add_option_group('Logging options')
  58. g.add_option('-q', '--quiet',
  59. dest="quiet", action="store_true", default=False,
  60. help="be quiet")
  61. # Manifest
  62. g = p.add_option_group('Manifest options')
  63. g.add_option('-u', '--manifest-url',
  64. dest='manifest_url',
  65. help='manifest repository location', metavar='URL')
  66. g.add_option('-b', '--manifest-branch',
  67. dest='manifest_branch',
  68. help='manifest branch or revision', metavar='REVISION')
  69. g.add_option('-m', '--manifest-name',
  70. dest='manifest_name', default='default.xml',
  71. help='initial manifest file', metavar='NAME.xml')
  72. g.add_option('--mirror',
  73. dest='mirror', action='store_true',
  74. help='create a replica of the remote repositories '
  75. 'rather than a client working directory')
  76. g.add_option('--reference',
  77. dest='reference',
  78. help='location of mirror directory', metavar='DIR')
  79. g.add_option('--depth', type='int', default=None,
  80. dest='depth',
  81. help='create a shallow clone with given depth; see git clone')
  82. g.add_option('-g', '--groups',
  83. dest='groups', default='all,-notdefault',
  84. help='restrict manifest projects to ones with a specified group',
  85. metavar='GROUP')
  86. g.add_option('-p', '--platform',
  87. dest='platform', default='auto',
  88. help='restrict manifest projects to ones with a specified '
  89. 'platform group [auto|all|none|linux|darwin|...]',
  90. metavar='PLATFORM')
  91. # Tool
  92. g = p.add_option_group('repo Version options')
  93. g.add_option('--repo-url',
  94. dest='repo_url',
  95. help='repo repository location', metavar='URL')
  96. g.add_option('--repo-branch',
  97. dest='repo_branch',
  98. help='repo branch or revision', metavar='REVISION')
  99. g.add_option('--no-repo-verify',
  100. dest='no_repo_verify', action='store_true',
  101. help='do not verify repo source code')
  102. # Other
  103. g = p.add_option_group('Other options')
  104. g.add_option('--config-name',
  105. dest='config_name', action="store_true", default=False,
  106. help='Always prompt for name/e-mail')
  107. def _RegisteredEnvironmentOptions(self):
  108. return {'REPO_MANIFEST_URL': 'manifest_url',
  109. 'REPO_MIRROR_LOCATION': 'reference'}
  110. def _SyncManifest(self, opt):
  111. m = self.manifest.manifestProject
  112. is_new = not m.Exists
  113. if is_new:
  114. if not opt.manifest_url:
  115. print('fatal: manifest url (-u) is required.', file=sys.stderr)
  116. sys.exit(1)
  117. if not opt.quiet:
  118. print('Get %s' % GitConfig.ForUser().UrlInsteadOf(opt.manifest_url),
  119. file=sys.stderr)
  120. m._InitGitDir()
  121. if opt.manifest_branch:
  122. m.revisionExpr = opt.manifest_branch
  123. else:
  124. m.revisionExpr = 'refs/heads/master'
  125. else:
  126. if opt.manifest_branch:
  127. m.revisionExpr = opt.manifest_branch
  128. else:
  129. m.PreSync()
  130. if opt.manifest_url:
  131. r = m.GetRemote(m.remote.name)
  132. r.url = opt.manifest_url
  133. r.ResetFetch()
  134. r.Save()
  135. groups = re.split(r'[,\s]+', opt.groups)
  136. all_platforms = ['linux', 'darwin']
  137. platformize = lambda x: 'platform-' + x
  138. if opt.platform == 'auto':
  139. if (not opt.mirror and
  140. not m.config.GetString('repo.mirror') == 'true'):
  141. groups.append(platformize(platform.system().lower()))
  142. elif opt.platform == 'all':
  143. groups.extend(map(platformize, all_platforms))
  144. elif opt.platform in all_platforms:
  145. groups.extend(platformize(opt.platform))
  146. elif opt.platform != 'none':
  147. print('fatal: invalid platform flag', file=sys.stderr)
  148. sys.exit(1)
  149. groups = [x for x in groups if x]
  150. groupstr = ','.join(groups)
  151. if opt.platform == 'auto' and groupstr == 'all,-notdefault,platform-' + platform.system().lower():
  152. groupstr = None
  153. m.config.SetString('manifest.groups', groupstr)
  154. if opt.reference:
  155. m.config.SetString('repo.reference', opt.reference)
  156. if opt.mirror:
  157. if is_new:
  158. m.config.SetString('repo.mirror', 'true')
  159. else:
  160. print('fatal: --mirror is only supported when initializing a new '
  161. 'workspace.', file=sys.stderr)
  162. print('Either delete the .repo folder in this workspace, or initialize '
  163. 'in another location.', file=sys.stderr)
  164. sys.exit(1)
  165. if not m.Sync_NetworkHalf(is_new=is_new):
  166. r = m.GetRemote(m.remote.name)
  167. print('fatal: cannot obtain manifest %s' % r.url, file=sys.stderr)
  168. # Better delete the manifest git dir if we created it; otherwise next
  169. # time (when user fixes problems) we won't go through the "is_new" logic.
  170. if is_new:
  171. shutil.rmtree(m.gitdir)
  172. sys.exit(1)
  173. if opt.manifest_branch:
  174. m.MetaBranchSwitch(opt.manifest_branch)
  175. syncbuf = SyncBuffer(m.config)
  176. m.Sync_LocalHalf(syncbuf)
  177. syncbuf.Finish()
  178. if is_new or m.CurrentBranch is None:
  179. if not m.StartBranch('default'):
  180. print('fatal: cannot create default in manifest', file=sys.stderr)
  181. sys.exit(1)
  182. def _LinkManifest(self, name):
  183. if not name:
  184. print('fatal: manifest name (-m) is required.', file=sys.stderr)
  185. sys.exit(1)
  186. try:
  187. self.manifest.Link(name)
  188. except ManifestParseError as e:
  189. print("fatal: manifest '%s' not available" % name, file=sys.stderr)
  190. print('fatal: %s' % str(e), file=sys.stderr)
  191. sys.exit(1)
  192. def _Prompt(self, prompt, value):
  193. sys.stdout.write('%-10s [%s]: ' % (prompt, value))
  194. a = sys.stdin.readline().strip()
  195. if a == '':
  196. return value
  197. return a
  198. def _ShouldConfigureUser(self):
  199. gc = self.manifest.globalConfig
  200. mp = self.manifest.manifestProject
  201. # If we don't have local settings, get from global.
  202. if not mp.config.Has('user.name') or not mp.config.Has('user.email'):
  203. if not gc.Has('user.name') or not gc.Has('user.email'):
  204. return True
  205. mp.config.SetString('user.name', gc.GetString('user.name'))
  206. mp.config.SetString('user.email', gc.GetString('user.email'))
  207. print()
  208. print('Your identity is: %s <%s>' % (mp.config.GetString('user.name'),
  209. mp.config.GetString('user.email')))
  210. print('If you want to change this, please re-run \'repo init\' with --config-name')
  211. return False
  212. def _ConfigureUser(self):
  213. mp = self.manifest.manifestProject
  214. while True:
  215. print()
  216. name = self._Prompt('Your Name', mp.UserName)
  217. email = self._Prompt('Your Email', mp.UserEmail)
  218. print()
  219. print('Your identity is: %s <%s>' % (name, email))
  220. sys.stdout.write('is this correct [y/N]? ')
  221. a = sys.stdin.readline().strip().lower()
  222. if a in ('yes', 'y', 't', 'true'):
  223. break
  224. if name != mp.UserName:
  225. mp.config.SetString('user.name', name)
  226. if email != mp.UserEmail:
  227. mp.config.SetString('user.email', email)
  228. def _HasColorSet(self, gc):
  229. for n in ['ui', 'diff', 'status']:
  230. if gc.Has('color.%s' % n):
  231. return True
  232. return False
  233. def _ConfigureColor(self):
  234. gc = self.manifest.globalConfig
  235. if self._HasColorSet(gc):
  236. return
  237. class _Test(Coloring):
  238. def __init__(self):
  239. Coloring.__init__(self, gc, 'test color display')
  240. self._on = True
  241. out = _Test()
  242. print()
  243. print("Testing colorized output (for 'repo diff', 'repo status'):")
  244. for c in ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan']:
  245. out.write(' ')
  246. out.printer(fg=c)(' %-6s ', c)
  247. out.write(' ')
  248. out.printer(fg='white', bg='black')(' %s ' % 'white')
  249. out.nl()
  250. for c in ['bold', 'dim', 'ul', 'reverse']:
  251. out.write(' ')
  252. out.printer(fg='black', attr=c)(' %-6s ', c)
  253. out.nl()
  254. sys.stdout.write('Enable color display in this user account (y/N)? ')
  255. a = sys.stdin.readline().strip().lower()
  256. if a in ('y', 'yes', 't', 'true', 'on'):
  257. gc.SetString('color.ui', 'auto')
  258. def _ConfigureDepth(self, opt):
  259. """Configure the depth we'll sync down.
  260. Args:
  261. opt: Options from optparse. We care about opt.depth.
  262. """
  263. # Opt.depth will be non-None if user actually passed --depth to repo init.
  264. if opt.depth is not None:
  265. if opt.depth > 0:
  266. # Positive values will set the depth.
  267. depth = str(opt.depth)
  268. else:
  269. # Negative numbers will clear the depth; passing None to SetString
  270. # will do that.
  271. depth = None
  272. # We store the depth in the main manifest project.
  273. self.manifest.manifestProject.config.SetString('repo.depth', depth)
  274. def _DisplayResult(self):
  275. if self.manifest.IsMirror:
  276. init_type = 'mirror '
  277. else:
  278. init_type = ''
  279. print()
  280. print('repo %shas been initialized in %s'
  281. % (init_type, self.manifest.topdir))
  282. current_dir = os.getcwd()
  283. if current_dir != self.manifest.topdir:
  284. print('If this is not the directory in which you want to initialize '
  285. 'repo, please run:')
  286. print(' rm -r %s/.repo' % self.manifest.topdir)
  287. print('and try again.')
  288. def Execute(self, opt, args):
  289. git_require(MIN_GIT_VERSION, fail=True)
  290. if opt.reference:
  291. opt.reference = os.path.expanduser(opt.reference)
  292. self._SyncManifest(opt)
  293. self._LinkManifest(opt.manifest_name)
  294. if os.isatty(0) and os.isatty(1) and not self.manifest.IsMirror:
  295. if opt.config_name or self._ShouldConfigureUser():
  296. self._ConfigureUser()
  297. self._ConfigureColor()
  298. self._ConfigureDepth(opt)
  299. self._DisplayResult()