sync.py 9.8 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. from optparse import SUPPRESS_HELP
  16. import os
  17. import re
  18. import shutil
  19. import subprocess
  20. import sys
  21. import time
  22. from git_command import GIT
  23. from project import HEAD
  24. from project import Project
  25. from project import RemoteSpec
  26. from command import Command, MirrorSafeCommand
  27. from error import RepoChangedException, GitError
  28. from project import R_HEADS
  29. from project import SyncBuffer
  30. from progress import Progress
  31. class Sync(Command, MirrorSafeCommand):
  32. common = True
  33. helpSummary = "Update working tree to the latest revision"
  34. helpUsage = """
  35. %prog [<project>...]
  36. """
  37. helpDescription = """
  38. The '%prog' command synchronizes local project directories
  39. with the remote repositories specified in the manifest. If a local
  40. project does not yet exist, it will clone a new local directory from
  41. the remote repository and set up tracking branches as specified in
  42. the manifest. If the local project already exists, '%prog'
  43. will update the remote branches and rebase any new local changes
  44. on top of the new remote changes.
  45. '%prog' will synchronize all projects listed at the command
  46. line. Projects can be specified either by name, or by a relative
  47. or absolute path to the project's local directory. If no projects
  48. are specified, '%prog' will synchronize all projects listed in
  49. the manifest.
  50. The -d/--detach option can be used to switch specified projects
  51. back to the manifest revision. This option is especially helpful
  52. if the project is currently on a topic branch, but the manifest
  53. revision is temporarily needed.
  54. SSH Connections
  55. ---------------
  56. If at least one project remote URL uses an SSH connection (ssh://,
  57. git+ssh://, or user@host:path syntax) repo will automatically
  58. enable the SSH ControlMaster option when connecting to that host.
  59. This feature permits other projects in the same '%prog' session to
  60. reuse the same SSH tunnel, saving connection setup overheads.
  61. To disable this behavior on UNIX platforms, set the GIT_SSH
  62. environment variable to 'ssh'. For example:
  63. export GIT_SSH=ssh
  64. %prog
  65. Compatibility
  66. ~~~~~~~~~~~~~
  67. This feature is automatically disabled on Windows, due to the lack
  68. of UNIX domain socket support.
  69. This feature is not compatible with url.insteadof rewrites in the
  70. user's ~/.gitconfig. '%prog' is currently not able to perform the
  71. rewrite early enough to establish the ControlMaster tunnel.
  72. If the remote SSH daemon is Gerrit Code Review, version 2.0.10 or
  73. later is required to fix a server side protocol bug.
  74. """
  75. def _Options(self, p):
  76. p.add_option('-l','--local-only',
  77. dest='local_only', action='store_true',
  78. help="only update working tree, don't fetch")
  79. p.add_option('-n','--network-only',
  80. dest='network_only', action='store_true',
  81. help="fetch only, don't update working tree")
  82. p.add_option('-d','--detach',
  83. dest='detach_head', action='store_true',
  84. help='detach projects back to manifest revision')
  85. g = p.add_option_group('repo Version options')
  86. g.add_option('--no-repo-verify',
  87. dest='no_repo_verify', action='store_true',
  88. help='do not verify repo source code')
  89. g.add_option('--repo-upgraded',
  90. dest='repo_upgraded', action='store_true',
  91. help=SUPPRESS_HELP)
  92. def _Fetch(self, projects):
  93. fetched = set()
  94. pm = Progress('Fetching projects', len(projects))
  95. for project in projects:
  96. pm.update()
  97. if project.Sync_NetworkHalf():
  98. fetched.add(project.gitdir)
  99. else:
  100. print >>sys.stderr, 'error: Cannot fetch %s' % project.name
  101. sys.exit(1)
  102. pm.end()
  103. return fetched
  104. def UpdateProjectList(self):
  105. new_project_paths = []
  106. for project in self.manifest.projects.values():
  107. if project.relpath:
  108. new_project_paths.append(project.relpath)
  109. file_name = 'project.list'
  110. file_path = os.path.join(self.manifest.repodir, file_name)
  111. old_project_paths = []
  112. if os.path.exists(file_path):
  113. fd = open(file_path, 'r')
  114. try:
  115. old_project_paths = fd.read().split('\n')
  116. finally:
  117. fd.close()
  118. for path in old_project_paths:
  119. if not path:
  120. continue
  121. if path not in new_project_paths:
  122. project = Project(
  123. manifest = self.manifest,
  124. name = path,
  125. remote = RemoteSpec('origin'),
  126. gitdir = os.path.join(self.manifest.topdir,
  127. path, '.git'),
  128. worktree = os.path.join(self.manifest.topdir, path),
  129. relpath = path,
  130. revisionExpr = 'HEAD',
  131. revisionId = None)
  132. if project.IsDirty():
  133. print >>sys.stderr, 'error: Cannot remove project "%s": \
  134. uncommitted changes are present' % project.relpath
  135. print >>sys.stderr, ' commit changes, then run sync again'
  136. return -1
  137. else:
  138. print >>sys.stderr, 'Deleting obsolete path %s' % project.worktree
  139. shutil.rmtree(project.worktree)
  140. # Try deleting parent subdirs if they are empty
  141. dir = os.path.dirname(project.worktree)
  142. while dir != self.manifest.topdir:
  143. try:
  144. os.rmdir(dir)
  145. except OSError:
  146. break
  147. dir = os.path.dirname(dir)
  148. fd = open(file_path, 'w')
  149. try:
  150. fd.write('\n'.join(new_project_paths))
  151. fd.write('\n')
  152. finally:
  153. fd.close()
  154. return 0
  155. def Execute(self, opt, args):
  156. if opt.network_only and opt.detach_head:
  157. print >>sys.stderr, 'error: cannot combine -n and -d'
  158. sys.exit(1)
  159. if opt.network_only and opt.local_only:
  160. print >>sys.stderr, 'error: cannot combine -n and -l'
  161. sys.exit(1)
  162. rp = self.manifest.repoProject
  163. rp.PreSync()
  164. mp = self.manifest.manifestProject
  165. mp.PreSync()
  166. if opt.repo_upgraded:
  167. _PostRepoUpgrade(self.manifest)
  168. all = self.GetProjects(args, missing_ok=True)
  169. if not opt.local_only:
  170. to_fetch = []
  171. now = time.time()
  172. if (24 * 60 * 60) <= (now - rp.LastFetch):
  173. to_fetch.append(rp)
  174. to_fetch.append(mp)
  175. to_fetch.extend(all)
  176. fetched = self._Fetch(to_fetch)
  177. _PostRepoFetch(rp, opt.no_repo_verify)
  178. if opt.network_only:
  179. # bail out now; the rest touches the working tree
  180. return
  181. if mp.HasChanges:
  182. syncbuf = SyncBuffer(mp.config)
  183. mp.Sync_LocalHalf(syncbuf)
  184. if not syncbuf.Finish():
  185. sys.exit(1)
  186. self.manifest._Unload()
  187. all = self.GetProjects(args, missing_ok=True)
  188. missing = []
  189. for project in all:
  190. if project.gitdir not in fetched:
  191. missing.append(project)
  192. self._Fetch(missing)
  193. if self.manifest.IsMirror:
  194. # bail out now, we have no working tree
  195. return
  196. if self.UpdateProjectList():
  197. sys.exit(1)
  198. syncbuf = SyncBuffer(mp.config,
  199. detach_head = opt.detach_head)
  200. pm = Progress('Syncing work tree', len(all))
  201. for project in all:
  202. pm.update()
  203. if project.worktree:
  204. project.Sync_LocalHalf(syncbuf)
  205. pm.end()
  206. print >>sys.stderr
  207. if not syncbuf.Finish():
  208. sys.exit(1)
  209. def _PostRepoUpgrade(manifest):
  210. for project in manifest.projects.values():
  211. if project.Exists:
  212. project.PostRepoUpgrade()
  213. def _PostRepoFetch(rp, no_repo_verify=False, verbose=False):
  214. if rp.HasChanges:
  215. print >>sys.stderr, 'info: A new version of repo is available'
  216. print >>sys.stderr, ''
  217. if no_repo_verify or _VerifyTag(rp):
  218. syncbuf = SyncBuffer(rp.config)
  219. rp.Sync_LocalHalf(syncbuf)
  220. if not syncbuf.Finish():
  221. sys.exit(1)
  222. print >>sys.stderr, 'info: Restarting repo with latest version'
  223. raise RepoChangedException(['--repo-upgraded'])
  224. else:
  225. print >>sys.stderr, 'warning: Skipped upgrade to unverified version'
  226. else:
  227. if verbose:
  228. print >>sys.stderr, 'repo version %s is current' % rp.work_git.describe(HEAD)
  229. def _VerifyTag(project):
  230. gpg_dir = os.path.expanduser('~/.repoconfig/gnupg')
  231. if not os.path.exists(gpg_dir):
  232. print >>sys.stderr,\
  233. """warning: GnuPG was not available during last "repo init"
  234. warning: Cannot automatically authenticate repo."""
  235. return True
  236. try:
  237. cur = project.bare_git.describe(project.GetRevisionId())
  238. except GitError:
  239. cur = None
  240. if not cur \
  241. or re.compile(r'^.*-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur):
  242. rev = project.revisionExpr
  243. if rev.startswith(R_HEADS):
  244. rev = rev[len(R_HEADS):]
  245. print >>sys.stderr
  246. print >>sys.stderr,\
  247. "warning: project '%s' branch '%s' is not signed" \
  248. % (project.name, rev)
  249. return False
  250. env = dict(os.environ)
  251. env['GIT_DIR'] = project.gitdir
  252. env['GNUPGHOME'] = gpg_dir
  253. cmd = [GIT, 'tag', '-v', cur]
  254. proc = subprocess.Popen(cmd,
  255. stdout = subprocess.PIPE,
  256. stderr = subprocess.PIPE,
  257. env = env)
  258. out = proc.stdout.read()
  259. proc.stdout.close()
  260. err = proc.stderr.read()
  261. proc.stderr.close()
  262. if proc.wait() != 0:
  263. print >>sys.stderr
  264. print >>sys.stderr, out
  265. print >>sys.stderr, err
  266. print >>sys.stderr
  267. return False
  268. return True