sync.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. from git_command import GIT
  21. from project import HEAD
  22. from command import Command, MirrorSafeCommand
  23. from error import RepoChangedException, GitError
  24. from project import R_HEADS
  25. from project import SyncBuffer
  26. from progress import Progress
  27. class Sync(Command, MirrorSafeCommand):
  28. common = True
  29. helpSummary = "Update working tree to the latest revision"
  30. helpUsage = """
  31. %prog [<project>...]
  32. """
  33. helpDescription = """
  34. The '%prog' command synchronizes local project directories
  35. with the remote repositories specified in the manifest. If a local
  36. project does not yet exist, it will clone a new local directory from
  37. the remote repository and set up tracking branches as specified in
  38. the manifest. If the local project already exists, '%prog'
  39. will update the remote branches and rebase any new local changes
  40. on top of the new remote changes.
  41. '%prog' will synchronize all projects listed at the command
  42. line. Projects can be specified either by name, or by a relative
  43. or absolute path to the project's local directory. If no projects
  44. are specified, '%prog' will synchronize all projects listed in
  45. the manifest.
  46. The -d/--detach option can be used to switch specified projects
  47. back to the manifest revision. This option is especially helpful
  48. if the project is currently on a topic branch, but the manifest
  49. revision is temporarily needed.
  50. """
  51. def _Options(self, p):
  52. p.add_option('-l','--local-only',
  53. dest='local_only', action='store_true',
  54. help="only update working tree, don't fetch")
  55. p.add_option('-n','--network-only',
  56. dest='network_only', action='store_true',
  57. help="fetch only, don't update working tree")
  58. p.add_option('-d','--detach',
  59. dest='detach_head', action='store_true',
  60. help='detach projects back to manifest revision')
  61. p.add_option('--no-repo-verify',
  62. dest='no_repo_verify', action='store_true',
  63. help='do not verify repo source code')
  64. p.add_option('--repo-upgraded',
  65. dest='repo_upgraded', action='store_true',
  66. help=SUPPRESS_HELP)
  67. def _Fetch(self, *projects):
  68. fetched = set()
  69. pm = Progress('Fetching projects', len(projects))
  70. for project in projects:
  71. pm.update()
  72. if project.Sync_NetworkHalf():
  73. fetched.add(project.gitdir)
  74. else:
  75. print >>sys.stderr, 'error: Cannot fetch %s' % project.name
  76. sys.exit(1)
  77. pm.end()
  78. return fetched
  79. def Execute(self, opt, args):
  80. if opt.network_only and opt.detach_head:
  81. print >>sys.stderr, 'error: cannot combine -n and -d'
  82. sys.exit(1)
  83. if opt.network_only and opt.local_only:
  84. print >>sys.stderr, 'error: cannot combine -n and -l'
  85. sys.exit(1)
  86. rp = self.manifest.repoProject
  87. rp.PreSync()
  88. mp = self.manifest.manifestProject
  89. mp.PreSync()
  90. if opt.repo_upgraded:
  91. _PostRepoUpgrade(self.manifest)
  92. all = self.GetProjects(args, missing_ok=True)
  93. if not opt.local_only:
  94. fetched = self._Fetch(rp, mp, *all)
  95. _PostRepoFetch(rp, opt.no_repo_verify)
  96. if opt.network_only:
  97. # bail out now; the rest touches the working tree
  98. return
  99. if mp.HasChanges:
  100. syncbuf = SyncBuffer(mp.config)
  101. mp.Sync_LocalHalf(syncbuf)
  102. if not syncbuf.Finish():
  103. sys.exit(1)
  104. self.manifest._Unload()
  105. all = self.GetProjects(args, missing_ok=True)
  106. missing = []
  107. for project in all:
  108. if project.gitdir not in fetched:
  109. missing.append(project)
  110. self._Fetch(*missing)
  111. syncbuf = SyncBuffer(mp.config,
  112. detach_head = opt.detach_head)
  113. pm = Progress('Syncing work tree', len(all))
  114. for project in all:
  115. pm.update()
  116. if project.worktree:
  117. project.Sync_LocalHalf(syncbuf)
  118. pm.end()
  119. print >>sys.stderr
  120. if not syncbuf.Finish():
  121. sys.exit(1)
  122. def _PostRepoUpgrade(manifest):
  123. for project in manifest.projects.values():
  124. if project.Exists:
  125. project.PostRepoUpgrade()
  126. def _PostRepoFetch(rp, no_repo_verify=False, verbose=False):
  127. if rp.HasChanges:
  128. print >>sys.stderr, 'info: A new version of repo is available'
  129. print >>sys.stderr, ''
  130. if no_repo_verify or _VerifyTag(rp):
  131. syncbuf = SyncBuffer(rp.config)
  132. rp.Sync_LocalHalf(syncbuf)
  133. if not syncbuf.Finish():
  134. sys.exit(1)
  135. print >>sys.stderr, 'info: Restarting repo with latest version'
  136. raise RepoChangedException(['--repo-upgraded'])
  137. else:
  138. print >>sys.stderr, 'warning: Skipped upgrade to unverified version'
  139. else:
  140. if verbose:
  141. print >>sys.stderr, 'repo version %s is current' % rp.work_git.describe(HEAD)
  142. def _VerifyTag(project):
  143. gpg_dir = os.path.expanduser('~/.repoconfig/gnupg')
  144. if not os.path.exists(gpg_dir):
  145. print >>sys.stderr,\
  146. """warning: GnuPG was not available during last "repo init"
  147. warning: Cannot automatically authenticate repo."""
  148. return True
  149. remote = project.GetRemote(project.remote.name)
  150. ref = remote.ToLocal(project.revision)
  151. try:
  152. cur = project.bare_git.describe(ref)
  153. except GitError:
  154. cur = None
  155. if not cur \
  156. or re.compile(r'^.*-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur):
  157. rev = project.revision
  158. if rev.startswith(R_HEADS):
  159. rev = rev[len(R_HEADS):]
  160. print >>sys.stderr
  161. print >>sys.stderr,\
  162. "warning: project '%s' branch '%s' is not signed" \
  163. % (project.name, rev)
  164. return False
  165. env = dict(os.environ)
  166. env['GIT_DIR'] = project.gitdir
  167. env['GNUPGHOME'] = gpg_dir
  168. cmd = [GIT, 'tag', '-v', cur]
  169. proc = subprocess.Popen(cmd,
  170. stdout = subprocess.PIPE,
  171. stderr = subprocess.PIPE,
  172. env = env)
  173. out = proc.stdout.read()
  174. proc.stdout.close()
  175. err = proc.stderr.read()
  176. proc.stderr.close()
  177. if proc.wait() != 0:
  178. print >>sys.stderr
  179. print >>sys.stderr, out
  180. print >>sys.stderr, err
  181. print >>sys.stderr
  182. return False
  183. return True