init.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 re
  17. import shutil
  18. import sys
  19. from color import Coloring
  20. from command import InteractiveCommand, MirrorSafeCommand
  21. from error import ManifestParseError
  22. from project import SyncBuffer
  23. from git_config import GitConfig
  24. from git_command import git_require, MIN_GIT_VERSION
  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 -b argument can be used to select the manifest branch
  37. to checkout and use. If no branch is specified, master is assumed.
  38. The optional -m argument can be used to specify an alternate manifest
  39. to be used. If no manifest is specified, the manifest default.xml
  40. will be used.
  41. The --reference option can be used to point to a directory that
  42. has the content of a --mirror sync. This will make the working
  43. directory use as much data as possible from the local reference
  44. directory when fetching from the server. This will make the sync
  45. go a lot faster by reducing data traffic on the network.
  46. Switching Manifest Branches
  47. ---------------------------
  48. To switch to another manifest branch, `repo init -b otherbranch`
  49. may be used in an existing client. However, as this only updates the
  50. manifest, a subsequent `repo sync` (or `repo sync -d`) is necessary
  51. to update the working directory files.
  52. """
  53. def _Options(self, p):
  54. # Logging
  55. g = p.add_option_group('Logging options')
  56. g.add_option('-q', '--quiet',
  57. dest="quiet", action="store_true", default=False,
  58. help="be quiet")
  59. # Manifest
  60. g = p.add_option_group('Manifest options')
  61. g.add_option('-u', '--manifest-url',
  62. dest='manifest_url',
  63. help='manifest repository location', metavar='URL')
  64. g.add_option('-b', '--manifest-branch',
  65. dest='manifest_branch',
  66. help='manifest branch or revision', metavar='REVISION')
  67. g.add_option('-m', '--manifest-name',
  68. dest='manifest_name', default='default.xml',
  69. help='initial manifest file', metavar='NAME.xml')
  70. g.add_option('--mirror',
  71. dest='mirror', action='store_true',
  72. help='mirror the forrest')
  73. g.add_option('--reference',
  74. dest='reference',
  75. help='location of mirror directory', metavar='DIR')
  76. g.add_option('--depth', type='int', default=None,
  77. dest='depth',
  78. help='create a shallow clone with given depth; see git clone')
  79. g.add_option('-g', '--groups',
  80. dest='groups', default='default',
  81. help='restrict manifest projects to ones with a specified group',
  82. metavar='GROUP')
  83. # Tool
  84. g = p.add_option_group('repo Version options')
  85. g.add_option('--repo-url',
  86. dest='repo_url',
  87. help='repo repository location', metavar='URL')
  88. g.add_option('--repo-branch',
  89. dest='repo_branch',
  90. help='repo branch or revision', metavar='REVISION')
  91. g.add_option('--no-repo-verify',
  92. dest='no_repo_verify', action='store_true',
  93. help='do not verify repo source code')
  94. # Other
  95. g = p.add_option_group('Other options')
  96. g.add_option('--config-name',
  97. dest='config_name', action="store_true", default=False,
  98. help='Always prompt for name/e-mail')
  99. def _SyncManifest(self, opt):
  100. m = self.manifest.manifestProject
  101. is_new = not m.Exists
  102. if is_new:
  103. if not opt.manifest_url:
  104. print >>sys.stderr, 'fatal: manifest url (-u) is required.'
  105. sys.exit(1)
  106. if not opt.quiet:
  107. print >>sys.stderr, 'Get %s' \
  108. % GitConfig.ForUser().UrlInsteadOf(opt.manifest_url)
  109. m._InitGitDir()
  110. if opt.manifest_branch:
  111. m.revisionExpr = opt.manifest_branch
  112. else:
  113. m.revisionExpr = 'refs/heads/master'
  114. else:
  115. if opt.manifest_branch:
  116. m.revisionExpr = opt.manifest_branch
  117. else:
  118. m.PreSync()
  119. if opt.manifest_url:
  120. r = m.GetRemote(m.remote.name)
  121. r.url = opt.manifest_url
  122. r.ResetFetch()
  123. r.Save()
  124. groups = re.split('[,\s]+', opt.groups)
  125. groups = [x for x in groups if x]
  126. groupstr = ','.join(groups)
  127. if groupstr == 'default':
  128. groupstr = None
  129. m.config.SetString('manifest.groups', groupstr)
  130. if opt.reference:
  131. m.config.SetString('repo.reference', opt.reference)
  132. if opt.mirror:
  133. if is_new:
  134. m.config.SetString('repo.mirror', 'true')
  135. else:
  136. print >>sys.stderr, 'fatal: --mirror not supported on existing client'
  137. sys.exit(1)
  138. if not m.Sync_NetworkHalf(is_new=is_new):
  139. r = m.GetRemote(m.remote.name)
  140. print >>sys.stderr, 'fatal: cannot obtain manifest %s' % r.url
  141. # Better delete the manifest git dir if we created it; otherwise next
  142. # time (when user fixes problems) we won't go through the "is_new" logic.
  143. if is_new:
  144. shutil.rmtree(m.gitdir)
  145. sys.exit(1)
  146. syncbuf = SyncBuffer(m.config)
  147. m.Sync_LocalHalf(syncbuf)
  148. syncbuf.Finish()
  149. if is_new or m.CurrentBranch is None:
  150. if not m.StartBranch('default'):
  151. print >>sys.stderr, 'fatal: cannot create default in manifest'
  152. sys.exit(1)
  153. def _LinkManifest(self, name):
  154. if not name:
  155. print >>sys.stderr, 'fatal: manifest name (-m) is required.'
  156. sys.exit(1)
  157. try:
  158. self.manifest.Link(name)
  159. except ManifestParseError, e:
  160. print >>sys.stderr, "fatal: manifest '%s' not available" % name
  161. print >>sys.stderr, 'fatal: %s' % str(e)
  162. sys.exit(1)
  163. def _Prompt(self, prompt, value):
  164. mp = self.manifest.manifestProject
  165. sys.stdout.write('%-10s [%s]: ' % (prompt, value))
  166. a = sys.stdin.readline().strip()
  167. if a == '':
  168. return value
  169. return a
  170. def _ShouldConfigureUser(self):
  171. gc = self.manifest.globalConfig
  172. mp = self.manifest.manifestProject
  173. # If we don't have local settings, get from global.
  174. if not mp.config.Has('user.name') or not mp.config.Has('user.email'):
  175. if not gc.Has('user.name') or not gc.Has('user.email'):
  176. return True
  177. mp.config.SetString('user.name', gc.GetString('user.name'))
  178. mp.config.SetString('user.email', gc.GetString('user.email'))
  179. print ''
  180. print 'Your identity is: %s <%s>' % (mp.config.GetString('user.name'),
  181. mp.config.GetString('user.email'))
  182. print 'If you want to change this, please re-run \'repo init\' with --config-name'
  183. return False
  184. def _ConfigureUser(self):
  185. mp = self.manifest.manifestProject
  186. while True:
  187. print ''
  188. name = self._Prompt('Your Name', mp.UserName)
  189. email = self._Prompt('Your Email', mp.UserEmail)
  190. print ''
  191. print 'Your identity is: %s <%s>' % (name, email)
  192. sys.stdout.write('is this correct [y/N]? ')
  193. a = sys.stdin.readline().strip()
  194. if a in ('yes', 'y', 't', 'true'):
  195. break
  196. if name != mp.UserName:
  197. mp.config.SetString('user.name', name)
  198. if email != mp.UserEmail:
  199. mp.config.SetString('user.email', email)
  200. def _HasColorSet(self, gc):
  201. for n in ['ui', 'diff', 'status']:
  202. if gc.Has('color.%s' % n):
  203. return True
  204. return False
  205. def _ConfigureColor(self):
  206. gc = self.manifest.globalConfig
  207. if self._HasColorSet(gc):
  208. return
  209. class _Test(Coloring):
  210. def __init__(self):
  211. Coloring.__init__(self, gc, 'test color display')
  212. self._on = True
  213. out = _Test()
  214. print ''
  215. print "Testing colorized output (for 'repo diff', 'repo status'):"
  216. for c in ['black','red','green','yellow','blue','magenta','cyan']:
  217. out.write(' ')
  218. out.printer(fg=c)(' %-6s ', c)
  219. out.write(' ')
  220. out.printer(fg='white', bg='black')(' %s ' % 'white')
  221. out.nl()
  222. for c in ['bold','dim','ul','reverse']:
  223. out.write(' ')
  224. out.printer(fg='black', attr=c)(' %-6s ', c)
  225. out.nl()
  226. sys.stdout.write('Enable color display in this user account (y/N)? ')
  227. a = sys.stdin.readline().strip().lower()
  228. if a in ('y', 'yes', 't', 'true', 'on'):
  229. gc.SetString('color.ui', 'auto')
  230. def _ConfigureDepth(self, opt):
  231. """Configure the depth we'll sync down.
  232. Args:
  233. opt: Options from optparse. We care about opt.depth.
  234. """
  235. # Opt.depth will be non-None if user actually passed --depth to repo init.
  236. if opt.depth is not None:
  237. if opt.depth > 0:
  238. # Positive values will set the depth.
  239. depth = str(opt.depth)
  240. else:
  241. # Negative numbers will clear the depth; passing None to SetString
  242. # will do that.
  243. depth = None
  244. # We store the depth in the main manifest project.
  245. self.manifest.manifestProject.config.SetString('repo.depth', depth)
  246. def Execute(self, opt, args):
  247. git_require(MIN_GIT_VERSION, fail=True)
  248. self._SyncManifest(opt)
  249. self._LinkManifest(opt.manifest_name)
  250. if os.isatty(0) and os.isatty(1) and not self.manifest.IsMirror:
  251. if opt.config_name or self._ShouldConfigureUser():
  252. self._ConfigureUser()
  253. self._ConfigureColor()
  254. self._ConfigureDepth(opt)
  255. if self.manifest.IsMirror:
  256. type = 'mirror '
  257. else:
  258. type = ''
  259. print ''
  260. print 'repo %sinitialized in %s' % (type, self.manifest.topdir)