sync.py 7.7 KB

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