sync.py 12 KB

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