sync.py 12 KB

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