init.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. def _SyncManifest(self, opt):
  101. m = self.manifest.manifestProject
  102. is_new = not m.Exists
  103. manifest_server = None
  104. # The manifest url may point out a manifest section in the config
  105. key = 'repo-manifest.%s.' % opt.manifest_url
  106. if GitConfig.ForUser().GetString(key + 'url'):
  107. opt.manifest_url = GitConfig.ForUser().GetString(key + 'url')
  108. # Also copy other options to the manifest config if not specified already.
  109. if not opt.reference:
  110. opt.reference = GitConfig.ForUser().GetString(key + 'reference')
  111. manifest_server = GitConfig.ForUser().GetString(key + 'server')
  112. if is_new:
  113. if not opt.manifest_url or opt.manifest_url == 'default':
  114. print >>sys.stderr, """\
  115. fatal: missing manifest url (-u) and no default found.
  116. tip: The global git configuration key 'repo-manifest.default.url' can
  117. be used to specify a default url."""
  118. sys.exit(1)
  119. if not opt.quiet:
  120. print >>sys.stderr, 'Get %s' \
  121. % GitConfig.ForUser().UrlInsteadOf(opt.manifest_url)
  122. m._InitGitDir()
  123. if opt.manifest_branch:
  124. m.revisionExpr = opt.manifest_branch
  125. else:
  126. m.revisionExpr = 'refs/heads/master'
  127. else:
  128. if opt.manifest_branch:
  129. m.revisionExpr = opt.manifest_branch
  130. else:
  131. m.PreSync()
  132. if opt.manifest_url:
  133. r = m.GetRemote(m.remote.name)
  134. r.url = opt.manifest_url
  135. r.ResetFetch()
  136. r.Save()
  137. if manifest_server:
  138. m.config.SetString('repo.manifest-server', manifest_server)
  139. if opt.reference:
  140. m.config.SetString('repo.reference', opt.reference)
  141. if opt.mirror:
  142. if is_new:
  143. m.config.SetString('repo.mirror', 'true')
  144. else:
  145. print >>sys.stderr, 'fatal: --mirror not supported on existing client'
  146. sys.exit(1)
  147. if not m.Sync_NetworkHalf(is_new=is_new):
  148. r = m.GetRemote(m.remote.name)
  149. print >>sys.stderr, 'fatal: cannot obtain manifest %s' % r.url
  150. # Better delete the manifest git dir if we created it; otherwise next
  151. # time (when user fixes problems) we won't go through the "is_new" logic.
  152. if is_new:
  153. shutil.rmtree(m.gitdir)
  154. sys.exit(1)
  155. syncbuf = SyncBuffer(m.config)
  156. m.Sync_LocalHalf(syncbuf)
  157. syncbuf.Finish()
  158. if is_new or m.CurrentBranch is None:
  159. if not m.StartBranch('default'):
  160. print >>sys.stderr, 'fatal: cannot create default in manifest'
  161. sys.exit(1)
  162. def _LinkManifest(self, name):
  163. if not name:
  164. print >>sys.stderr, 'fatal: manifest name (-m) is required.'
  165. sys.exit(1)
  166. try:
  167. self.manifest.Link(name)
  168. except ManifestParseError, e:
  169. print >>sys.stderr, "fatal: manifest '%s' not available" % name
  170. print >>sys.stderr, 'fatal: %s' % str(e)
  171. sys.exit(1)
  172. def _Prompt(self, prompt, value):
  173. mp = self.manifest.manifestProject
  174. sys.stdout.write('%-10s [%s]: ' % (prompt, value))
  175. a = sys.stdin.readline().strip()
  176. if a == '':
  177. return value
  178. return a
  179. def _ConfigureUser(self):
  180. mp = self.manifest.manifestProject
  181. while True:
  182. print ''
  183. name = self._Prompt('Your Name', mp.UserName)
  184. email = self._Prompt('Your Email', mp.UserEmail)
  185. print ''
  186. print 'Your identity is: %s <%s>' % (name, email)
  187. sys.stdout.write('is this correct [y/N]? ')
  188. a = sys.stdin.readline().strip()
  189. if a in ('yes', 'y', 't', 'true'):
  190. break
  191. if name != mp.UserName:
  192. mp.config.SetString('user.name', name)
  193. if email != mp.UserEmail:
  194. mp.config.SetString('user.email', email)
  195. def _HasColorSet(self, gc):
  196. for n in ['ui', 'diff', 'status']:
  197. if gc.Has('color.%s' % n):
  198. return True
  199. return False
  200. def _ConfigureColor(self):
  201. gc = self.manifest.globalConfig
  202. if self._HasColorSet(gc):
  203. return
  204. class _Test(Coloring):
  205. def __init__(self):
  206. Coloring.__init__(self, gc, 'test color display')
  207. self._on = True
  208. out = _Test()
  209. print ''
  210. print "Testing colorized output (for 'repo diff', 'repo status'):"
  211. for c in ['black','red','green','yellow','blue','magenta','cyan']:
  212. out.write(' ')
  213. out.printer(fg=c)(' %-6s ', c)
  214. out.write(' ')
  215. out.printer(fg='white', bg='black')(' %s ' % 'white')
  216. out.nl()
  217. for c in ['bold','dim','ul','reverse']:
  218. out.write(' ')
  219. out.printer(fg='black', attr=c)(' %-6s ', c)
  220. out.nl()
  221. sys.stdout.write('Enable color display in this user account (y/N)? ')
  222. a = sys.stdin.readline().strip().lower()
  223. if a in ('y', 'yes', 't', 'true', 'on'):
  224. gc.SetString('color.ui', 'auto')
  225. def _ConfigureDepth(self, opt):
  226. """Configure the depth we'll sync down.
  227. Args:
  228. opt: Options from optparse. We care about opt.depth.
  229. """
  230. # Opt.depth will be non-None if user actually passed --depth to repo init.
  231. if opt.depth is not None:
  232. if opt.depth > 0:
  233. # Positive values will set the depth.
  234. depth = str(opt.depth)
  235. else:
  236. # Negative numbers will clear the depth; passing None to SetString
  237. # will do that.
  238. depth = None
  239. # We store the depth in the main manifest project.
  240. self.manifest.manifestProject.config.SetString('repo.depth', depth)
  241. def Execute(self, opt, args):
  242. git_require(MIN_GIT_VERSION, fail=True)
  243. self._SyncManifest(opt)
  244. self._LinkManifest(opt.manifest_name)
  245. if os.isatty(0) and os.isatty(1) and not self.manifest.IsMirror:
  246. self._ConfigureUser()
  247. self._ConfigureColor()
  248. self._ConfigureDepth(opt)
  249. if self.manifest.IsMirror:
  250. type = 'mirror '
  251. else:
  252. type = ''
  253. print ''
  254. print 'repo %sinitialized in %s' % (type, self.manifest.topdir)