init.py 13 KB

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