init.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. import os
  16. import shutil
  17. import sys
  18. from color import Coloring
  19. from command import InteractiveCommand, MirrorSafeCommand
  20. from error import ManifestParseError
  21. from project import SyncBuffer
  22. from git_config import GitConfig
  23. from git_command import git_require, MIN_GIT_VERSION
  24. from git_config import GitConfig
  25. class Init(InteractiveCommand, MirrorSafeCommand):
  26. common = True
  27. helpSummary = "Initialize repo in the current directory"
  28. helpUsage = """
  29. %prog [options]
  30. """
  31. helpDescription = """
  32. The '%prog' command is run once to install and initialize repo.
  33. The latest repo source code and manifest collection is downloaded
  34. from the server and is installed in the .repo/ directory in the
  35. current working directory.
  36. The optional -u argument can be used to specify a URL to the
  37. manifest project. It is also possible to have a git configuration
  38. section as below to use 'identifier' as argument to -u:
  39. [repo-manifest "identifier"]
  40. url = ...
  41. server = ...
  42. reference = ...
  43. Only the url is required - the others are optional.
  44. If no -u argument is specified, the 'repo-manifest' section named
  45. 'default' will be used if present.
  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', default='default',
  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='mirror the forrest')
  83. g.add_option('--reference',
  84. dest='reference',
  85. help='location of mirror directory', metavar='DIR')
  86. g.add_option('--depth', type='int', default=None,
  87. dest='depth',
  88. help='create a shallow clone with given depth; see git clone')
  89. # Tool
  90. g = p.add_option_group('repo Version options')
  91. g.add_option('--repo-url',
  92. dest='repo_url',
  93. help='repo repository location', metavar='URL')
  94. g.add_option('--repo-branch',
  95. dest='repo_branch',
  96. help='repo branch or revision', metavar='REVISION')
  97. g.add_option('--no-repo-verify',
  98. dest='no_repo_verify', action='store_true',
  99. help='do not verify repo source code')
  100. # Other
  101. g = p.add_option_group('Other options')
  102. g.add_option('--config-name',
  103. dest='config_name', action="store_true", default=False,
  104. help='Always prompt for name/e-mail')
  105. def _SyncManifest(self, opt):
  106. m = self.manifest.manifestProject
  107. is_new = not m.Exists
  108. manifest_server = None
  109. # The manifest url may point out a manifest section in the config
  110. key = 'repo-manifest.%s.' % opt.manifest_url
  111. if GitConfig.ForUser().GetString(key + 'url'):
  112. opt.manifest_url = GitConfig.ForUser().GetString(key + 'url')
  113. # Also copy other options to the manifest config if not specified already.
  114. if not opt.reference:
  115. opt.reference = GitConfig.ForUser().GetString(key + 'reference')
  116. manifest_server = GitConfig.ForUser().GetString(key + 'server')
  117. if is_new:
  118. if not opt.manifest_url or opt.manifest_url == 'default':
  119. print >>sys.stderr, """\
  120. fatal: missing manifest url (-u) and no default found.
  121. tip: The global git configuration key 'repo-manifest.default.url' can
  122. be used to specify a default url."""
  123. sys.exit(1)
  124. if not opt.quiet:
  125. print >>sys.stderr, 'Get %s' \
  126. % GitConfig.ForUser().UrlInsteadOf(opt.manifest_url)
  127. m._InitGitDir()
  128. if opt.manifest_branch:
  129. m.revisionExpr = opt.manifest_branch
  130. else:
  131. m.revisionExpr = 'refs/heads/master'
  132. else:
  133. if opt.manifest_branch:
  134. m.revisionExpr = opt.manifest_branch
  135. else:
  136. m.PreSync()
  137. if opt.manifest_url:
  138. r = m.GetRemote(m.remote.name)
  139. r.url = opt.manifest_url
  140. r.ResetFetch()
  141. r.Save()
  142. if manifest_server:
  143. m.config.SetString('repo.manifest-server', manifest_server)
  144. if opt.reference:
  145. m.config.SetString('repo.reference', opt.reference)
  146. if opt.mirror:
  147. if is_new:
  148. m.config.SetString('repo.mirror', 'true')
  149. else:
  150. print >>sys.stderr, 'fatal: --mirror not supported on existing client'
  151. sys.exit(1)
  152. if not m.Sync_NetworkHalf(is_new=is_new):
  153. r = m.GetRemote(m.remote.name)
  154. print >>sys.stderr, 'fatal: cannot obtain manifest %s' % r.url
  155. # Better delete the manifest git dir if we created it; otherwise next
  156. # time (when user fixes problems) we won't go through the "is_new" logic.
  157. if is_new:
  158. shutil.rmtree(m.gitdir)
  159. sys.exit(1)
  160. syncbuf = SyncBuffer(m.config)
  161. m.Sync_LocalHalf(syncbuf)
  162. syncbuf.Finish()
  163. if is_new or m.CurrentBranch is None:
  164. if not m.StartBranch('default'):
  165. print >>sys.stderr, 'fatal: cannot create default in manifest'
  166. sys.exit(1)
  167. def _LinkManifest(self, name):
  168. if not name:
  169. print >>sys.stderr, 'fatal: manifest name (-m) is required.'
  170. sys.exit(1)
  171. try:
  172. self.manifest.Link(name)
  173. except ManifestParseError, e:
  174. print >>sys.stderr, "fatal: manifest '%s' not available" % name
  175. print >>sys.stderr, 'fatal: %s' % str(e)
  176. sys.exit(1)
  177. def _Prompt(self, prompt, value):
  178. mp = self.manifest.manifestProject
  179. sys.stdout.write('%-10s [%s]: ' % (prompt, value))
  180. a = sys.stdin.readline().strip()
  181. if a == '':
  182. return value
  183. return a
  184. def _ShouldConfigureUser(self):
  185. gc = self.manifest.globalConfig
  186. mp = self.manifest.manifestProject
  187. # If we don't have local settings, get from global.
  188. if not mp.config.Has('user.name') or not mp.config.Has('user.email'):
  189. if not gc.Has('user.name') or not gc.Has('user.email'):
  190. return True
  191. mp.config.SetString('user.name', gc.GetString('user.name'))
  192. mp.config.SetString('user.email', gc.GetString('user.email'))
  193. print ''
  194. print 'Your identity is: %s <%s>' % (mp.config.GetString('user.name'),
  195. mp.config.GetString('user.email'))
  196. print 'If you want to change this, please re-run \'repo init\' with --config-name'
  197. return False
  198. def _ConfigureUser(self):
  199. mp = self.manifest.manifestProject
  200. while True:
  201. print ''
  202. name = self._Prompt('Your Name', mp.UserName)
  203. email = self._Prompt('Your Email', mp.UserEmail)
  204. print ''
  205. print 'Your identity is: %s <%s>' % (name, email)
  206. sys.stdout.write('is this correct [y/N]? ')
  207. a = sys.stdin.readline().strip()
  208. if a in ('yes', 'y', 't', 'true'):
  209. break
  210. if name != mp.UserName:
  211. mp.config.SetString('user.name', name)
  212. if email != mp.UserEmail:
  213. mp.config.SetString('user.email', email)
  214. def _HasColorSet(self, gc):
  215. for n in ['ui', 'diff', 'status']:
  216. if gc.Has('color.%s' % n):
  217. return True
  218. return False
  219. def _ConfigureColor(self):
  220. gc = self.manifest.globalConfig
  221. if self._HasColorSet(gc):
  222. return
  223. class _Test(Coloring):
  224. def __init__(self):
  225. Coloring.__init__(self, gc, 'test color display')
  226. self._on = True
  227. out = _Test()
  228. print ''
  229. print "Testing colorized output (for 'repo diff', 'repo status'):"
  230. for c in ['black','red','green','yellow','blue','magenta','cyan']:
  231. out.write(' ')
  232. out.printer(fg=c)(' %-6s ', c)
  233. out.write(' ')
  234. out.printer(fg='white', bg='black')(' %s ' % 'white')
  235. out.nl()
  236. for c in ['bold','dim','ul','reverse']:
  237. out.write(' ')
  238. out.printer(fg='black', attr=c)(' %-6s ', c)
  239. out.nl()
  240. sys.stdout.write('Enable color display in this user account (y/N)? ')
  241. a = sys.stdin.readline().strip().lower()
  242. if a in ('y', 'yes', 't', 'true', 'on'):
  243. gc.SetString('color.ui', 'auto')
  244. def _ConfigureDepth(self, opt):
  245. """Configure the depth we'll sync down.
  246. Args:
  247. opt: Options from optparse. We care about opt.depth.
  248. """
  249. # Opt.depth will be non-None if user actually passed --depth to repo init.
  250. if opt.depth is not None:
  251. if opt.depth > 0:
  252. # Positive values will set the depth.
  253. depth = str(opt.depth)
  254. else:
  255. # Negative numbers will clear the depth; passing None to SetString
  256. # will do that.
  257. depth = None
  258. # We store the depth in the main manifest project.
  259. self.manifest.manifestProject.config.SetString('repo.depth', depth)
  260. def Execute(self, opt, args):
  261. git_require(MIN_GIT_VERSION, fail=True)
  262. self._SyncManifest(opt)
  263. self._LinkManifest(opt.manifest_name)
  264. if os.isatty(0) and os.isatty(1) and not self.manifest.IsMirror:
  265. if opt.config_name or self._ShouldConfigureUser():
  266. self._ConfigureUser()
  267. self._ConfigureColor()
  268. self._ConfigureDepth(opt)
  269. if self.manifest.IsMirror:
  270. type = 'mirror '
  271. else:
  272. type = ''
  273. print ''
  274. print 'repo %sinitialized in %s' % (type, self.manifest.topdir)