sync.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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 __future__ import print_function
  16. import json
  17. import netrc
  18. from optparse import SUPPRESS_HELP
  19. import os
  20. import re
  21. import shutil
  22. import socket
  23. import subprocess
  24. import sys
  25. import time
  26. from pyversion import is_python3
  27. if is_python3():
  28. import urllib.parse
  29. import xmlrpc.client
  30. else:
  31. import imp
  32. import urlparse
  33. import xmlrpclib
  34. urllib = imp.new_module('urllib')
  35. urllib.parse = urlparse
  36. xmlrpc = imp.new_module('xmlrpc')
  37. xmlrpc.client = xmlrpclib
  38. try:
  39. import threading as _threading
  40. except ImportError:
  41. import dummy_threading as _threading
  42. try:
  43. import resource
  44. def _rlimit_nofile():
  45. return resource.getrlimit(resource.RLIMIT_NOFILE)
  46. except ImportError:
  47. def _rlimit_nofile():
  48. return (256, 256)
  49. try:
  50. import multiprocessing
  51. except ImportError:
  52. multiprocessing = None
  53. from git_command import GIT, git_require
  54. from git_refs import R_HEADS, HEAD
  55. from project import Project
  56. from project import RemoteSpec
  57. from command import Command, MirrorSafeCommand
  58. from error import RepoChangedException, GitError, ManifestParseError
  59. from project import SyncBuffer
  60. from progress import Progress
  61. from wrapper import Wrapper
  62. _ONE_DAY_S = 24 * 60 * 60
  63. class _FetchError(Exception):
  64. """Internal error thrown in _FetchHelper() when we don't want stack trace."""
  65. pass
  66. class Sync(Command, MirrorSafeCommand):
  67. jobs = 1
  68. common = True
  69. helpSummary = "Update working tree to the latest revision"
  70. helpUsage = """
  71. %prog [<project>...]
  72. """
  73. helpDescription = """
  74. The '%prog' command synchronizes local project directories
  75. with the remote repositories specified in the manifest. If a local
  76. project does not yet exist, it will clone a new local directory from
  77. the remote repository and set up tracking branches as specified in
  78. the manifest. If the local project already exists, '%prog'
  79. will update the remote branches and rebase any new local changes
  80. on top of the new remote changes.
  81. '%prog' will synchronize all projects listed at the command
  82. line. Projects can be specified either by name, or by a relative
  83. or absolute path to the project's local directory. If no projects
  84. are specified, '%prog' will synchronize all projects listed in
  85. the manifest.
  86. The -d/--detach option can be used to switch specified projects
  87. back to the manifest revision. This option is especially helpful
  88. if the project is currently on a topic branch, but the manifest
  89. revision is temporarily needed.
  90. The -s/--smart-sync option can be used to sync to a known good
  91. build as specified by the manifest-server element in the current
  92. manifest. The -t/--smart-tag option is similar and allows you to
  93. specify a custom tag/label.
  94. The -u/--manifest-server-username and -p/--manifest-server-password
  95. options can be used to specify a username and password to authenticate
  96. with the manifest server when using the -s or -t option.
  97. If -u and -p are not specified when using the -s or -t option, '%prog'
  98. will attempt to read authentication credentials for the manifest server
  99. from the user's .netrc file.
  100. '%prog' will not use authentication credentials from -u/-p or .netrc
  101. if the manifest server specified in the manifest file already includes
  102. credentials.
  103. The -f/--force-broken option can be used to proceed with syncing
  104. other projects if a project sync fails.
  105. The --no-clone-bundle option disables any attempt to use
  106. $URL/clone.bundle to bootstrap a new Git repository from a
  107. resumeable bundle file on a content delivery network. This
  108. may be necessary if there are problems with the local Python
  109. HTTP client or proxy configuration, but the Git binary works.
  110. The --fetch-submodules option enables fetching Git submodules
  111. of a project from server.
  112. SSH Connections
  113. ---------------
  114. If at least one project remote URL uses an SSH connection (ssh://,
  115. git+ssh://, or user@host:path syntax) repo will automatically
  116. enable the SSH ControlMaster option when connecting to that host.
  117. This feature permits other projects in the same '%prog' session to
  118. reuse the same SSH tunnel, saving connection setup overheads.
  119. To disable this behavior on UNIX platforms, set the GIT_SSH
  120. environment variable to 'ssh'. For example:
  121. export GIT_SSH=ssh
  122. %prog
  123. Compatibility
  124. ~~~~~~~~~~~~~
  125. This feature is automatically disabled on Windows, due to the lack
  126. of UNIX domain socket support.
  127. This feature is not compatible with url.insteadof rewrites in the
  128. user's ~/.gitconfig. '%prog' is currently not able to perform the
  129. rewrite early enough to establish the ControlMaster tunnel.
  130. If the remote SSH daemon is Gerrit Code Review, version 2.0.10 or
  131. later is required to fix a server side protocol bug.
  132. """
  133. def _Options(self, p, show_smart=True):
  134. try:
  135. self.jobs = self.manifest.default.sync_j
  136. except ManifestParseError:
  137. self.jobs = 1
  138. p.add_option('-f', '--force-broken',
  139. dest='force_broken', action='store_true',
  140. help="continue sync even if a project fails to sync")
  141. p.add_option('-l', '--local-only',
  142. dest='local_only', action='store_true',
  143. help="only update working tree, don't fetch")
  144. p.add_option('-n', '--network-only',
  145. dest='network_only', action='store_true',
  146. help="fetch only, don't update working tree")
  147. p.add_option('-d', '--detach',
  148. dest='detach_head', action='store_true',
  149. help='detach projects back to manifest revision')
  150. p.add_option('-c', '--current-branch',
  151. dest='current_branch_only', action='store_true',
  152. help='fetch only current branch from server')
  153. p.add_option('-q', '--quiet',
  154. dest='quiet', action='store_true',
  155. help='be more quiet')
  156. p.add_option('-j', '--jobs',
  157. dest='jobs', action='store', type='int',
  158. help="projects to fetch simultaneously (default %d)" % self.jobs)
  159. p.add_option('-m', '--manifest-name',
  160. dest='manifest_name',
  161. help='temporary manifest to use for this sync', metavar='NAME.xml')
  162. p.add_option('--no-clone-bundle',
  163. dest='no_clone_bundle', action='store_true',
  164. help='disable use of /clone.bundle on HTTP/HTTPS')
  165. p.add_option('-u', '--manifest-server-username', action='store',
  166. dest='manifest_server_username',
  167. help='username to authenticate with the manifest server')
  168. p.add_option('-p', '--manifest-server-password', action='store',
  169. dest='manifest_server_password',
  170. help='password to authenticate with the manifest server')
  171. p.add_option('--fetch-submodules',
  172. dest='fetch_submodules', action='store_true',
  173. help='fetch submodules from server')
  174. p.add_option('--no-tags',
  175. dest='no_tags', action='store_true',
  176. help="don't fetch tags")
  177. if show_smart:
  178. p.add_option('-s', '--smart-sync',
  179. dest='smart_sync', action='store_true',
  180. help='smart sync using manifest from a known good build')
  181. p.add_option('-t', '--smart-tag',
  182. dest='smart_tag', action='store',
  183. help='smart sync using manifest from a known tag')
  184. g = p.add_option_group('repo Version options')
  185. g.add_option('--no-repo-verify',
  186. dest='no_repo_verify', action='store_true',
  187. help='do not verify repo source code')
  188. g.add_option('--repo-upgraded',
  189. dest='repo_upgraded', action='store_true',
  190. help=SUPPRESS_HELP)
  191. def _FetchProjectList(self, opt, projects, *args, **kwargs):
  192. """Main function of the fetch threads when jobs are > 1.
  193. Delegates most of the work to _FetchHelper.
  194. Args:
  195. opt: Program options returned from optparse. See _Options().
  196. projects: Projects to fetch.
  197. *args, **kwargs: Remaining arguments to pass to _FetchHelper. See the
  198. _FetchHelper docstring for details.
  199. """
  200. for project in projects:
  201. success = self._FetchHelper(opt, project, *args, **kwargs)
  202. if not success and not opt.force_broken:
  203. break
  204. def _FetchHelper(self, opt, project, lock, fetched, pm, sem, err_event):
  205. """Fetch git objects for a single project.
  206. Args:
  207. opt: Program options returned from optparse. See _Options().
  208. project: Project object for the project to fetch.
  209. lock: Lock for accessing objects that are shared amongst multiple
  210. _FetchHelper() threads.
  211. fetched: set object that we will add project.gitdir to when we're done
  212. (with our lock held).
  213. pm: Instance of a Project object. We will call pm.update() (with our
  214. lock held).
  215. sem: We'll release() this semaphore when we exit so that another thread
  216. can be started up.
  217. err_event: We'll set this event in the case of an error (after printing
  218. out info about the error).
  219. Returns:
  220. Whether the fetch was successful.
  221. """
  222. # We'll set to true once we've locked the lock.
  223. did_lock = False
  224. if not opt.quiet:
  225. print('Fetching project %s' % project.name)
  226. # Encapsulate everything in a try/except/finally so that:
  227. # - We always set err_event in the case of an exception.
  228. # - We always make sure we call sem.release().
  229. # - We always make sure we unlock the lock if we locked it.
  230. try:
  231. try:
  232. start = time.time()
  233. success = project.Sync_NetworkHalf(
  234. quiet=opt.quiet,
  235. current_branch_only=opt.current_branch_only,
  236. clone_bundle=not opt.no_clone_bundle,
  237. no_tags=opt.no_tags, archive=self.manifest.IsArchive)
  238. self._fetch_times.Set(project, time.time() - start)
  239. # Lock around all the rest of the code, since printing, updating a set
  240. # and Progress.update() are not thread safe.
  241. lock.acquire()
  242. did_lock = True
  243. if not success:
  244. print('error: Cannot fetch %s' % project.name, file=sys.stderr)
  245. if opt.force_broken:
  246. print('warn: --force-broken, continuing to sync',
  247. file=sys.stderr)
  248. else:
  249. raise _FetchError()
  250. fetched.add(project.gitdir)
  251. pm.update()
  252. except _FetchError:
  253. err_event.set()
  254. except:
  255. err_event.set()
  256. raise
  257. finally:
  258. if did_lock:
  259. lock.release()
  260. sem.release()
  261. return success
  262. def _Fetch(self, projects, opt):
  263. fetched = set()
  264. lock = _threading.Lock()
  265. pm = Progress('Fetching projects', len(projects))
  266. objdir_project_map = dict()
  267. for project in projects:
  268. objdir_project_map.setdefault(project.objdir, []).append(project)
  269. threads = set()
  270. sem = _threading.Semaphore(self.jobs)
  271. err_event = _threading.Event()
  272. for project_list in objdir_project_map.values():
  273. # Check for any errors before running any more tasks.
  274. # ...we'll let existing threads finish, though.
  275. if err_event.isSet() and not opt.force_broken:
  276. break
  277. sem.acquire()
  278. kwargs = dict(opt=opt,
  279. projects=project_list,
  280. lock=lock,
  281. fetched=fetched,
  282. pm=pm,
  283. sem=sem,
  284. err_event=err_event)
  285. if self.jobs > 1:
  286. t = _threading.Thread(target = self._FetchProjectList,
  287. kwargs = kwargs)
  288. # Ensure that Ctrl-C will not freeze the repo process.
  289. t.daemon = True
  290. threads.add(t)
  291. t.start()
  292. else:
  293. self._FetchProjectList(**kwargs)
  294. for t in threads:
  295. t.join()
  296. # If we saw an error, exit with code 1 so that other scripts can check.
  297. if err_event.isSet():
  298. print('\nerror: Exited sync due to fetch errors', file=sys.stderr)
  299. sys.exit(1)
  300. pm.end()
  301. self._fetch_times.Save()
  302. if not self.manifest.IsArchive:
  303. self._GCProjects(projects)
  304. return fetched
  305. def _GCProjects(self, projects):
  306. gitdirs = {}
  307. for project in projects:
  308. gitdirs[project.gitdir] = project.bare_git
  309. has_dash_c = git_require((1, 7, 2))
  310. if multiprocessing and has_dash_c:
  311. cpu_count = multiprocessing.cpu_count()
  312. else:
  313. cpu_count = 1
  314. jobs = min(self.jobs, cpu_count)
  315. if jobs < 2:
  316. for bare_git in gitdirs.values():
  317. bare_git.gc('--auto')
  318. return
  319. config = {'pack.threads': cpu_count / jobs if cpu_count > jobs else 1}
  320. threads = set()
  321. sem = _threading.Semaphore(jobs)
  322. err_event = _threading.Event()
  323. def GC(bare_git):
  324. try:
  325. try:
  326. bare_git.gc('--auto', config=config)
  327. except GitError:
  328. err_event.set()
  329. except:
  330. err_event.set()
  331. raise
  332. finally:
  333. sem.release()
  334. for bare_git in gitdirs.values():
  335. if err_event.isSet():
  336. break
  337. sem.acquire()
  338. t = _threading.Thread(target=GC, args=(bare_git,))
  339. t.daemon = True
  340. threads.add(t)
  341. t.start()
  342. for t in threads:
  343. t.join()
  344. if err_event.isSet():
  345. print('\nerror: Exited sync due to gc errors', file=sys.stderr)
  346. sys.exit(1)
  347. def _ReloadManifest(self, manifest_name=None):
  348. if manifest_name:
  349. # Override calls _Unload already
  350. self.manifest.Override(manifest_name)
  351. else:
  352. self.manifest._Unload()
  353. def UpdateProjectList(self):
  354. new_project_paths = []
  355. for project in self.GetProjects(None, missing_ok=True):
  356. if project.relpath:
  357. new_project_paths.append(project.relpath)
  358. file_name = 'project.list'
  359. file_path = os.path.join(self.manifest.repodir, file_name)
  360. old_project_paths = []
  361. if os.path.exists(file_path):
  362. fd = open(file_path, 'r')
  363. try:
  364. old_project_paths = fd.read().split('\n')
  365. finally:
  366. fd.close()
  367. for path in old_project_paths:
  368. if not path:
  369. continue
  370. if path not in new_project_paths:
  371. # If the path has already been deleted, we don't need to do it
  372. if os.path.exists(self.manifest.topdir + '/' + path):
  373. gitdir = os.path.join(self.manifest.topdir, path, '.git')
  374. project = Project(
  375. manifest = self.manifest,
  376. name = path,
  377. remote = RemoteSpec('origin'),
  378. gitdir = gitdir,
  379. objdir = gitdir,
  380. worktree = os.path.join(self.manifest.topdir, path),
  381. relpath = path,
  382. revisionExpr = 'HEAD',
  383. revisionId = None,
  384. groups = None)
  385. if project.IsDirty():
  386. print('error: Cannot remove project "%s": uncommitted changes '
  387. 'are present' % project.relpath, file=sys.stderr)
  388. print(' commit changes, then run sync again',
  389. file=sys.stderr)
  390. return -1
  391. else:
  392. print('Deleting obsolete path %s' % project.worktree,
  393. file=sys.stderr)
  394. shutil.rmtree(project.worktree)
  395. # Try deleting parent subdirs if they are empty
  396. project_dir = os.path.dirname(project.worktree)
  397. while project_dir != self.manifest.topdir:
  398. try:
  399. os.rmdir(project_dir)
  400. except OSError:
  401. break
  402. project_dir = os.path.dirname(project_dir)
  403. new_project_paths.sort()
  404. fd = open(file_path, 'w')
  405. try:
  406. fd.write('\n'.join(new_project_paths))
  407. fd.write('\n')
  408. finally:
  409. fd.close()
  410. return 0
  411. def Execute(self, opt, args):
  412. if opt.jobs:
  413. self.jobs = opt.jobs
  414. if self.jobs > 1:
  415. soft_limit, _ = _rlimit_nofile()
  416. self.jobs = min(self.jobs, (soft_limit - 5) / 3)
  417. if opt.network_only and opt.detach_head:
  418. print('error: cannot combine -n and -d', file=sys.stderr)
  419. sys.exit(1)
  420. if opt.network_only and opt.local_only:
  421. print('error: cannot combine -n and -l', file=sys.stderr)
  422. sys.exit(1)
  423. if opt.manifest_name and opt.smart_sync:
  424. print('error: cannot combine -m and -s', file=sys.stderr)
  425. sys.exit(1)
  426. if opt.manifest_name and opt.smart_tag:
  427. print('error: cannot combine -m and -t', file=sys.stderr)
  428. sys.exit(1)
  429. if opt.manifest_server_username or opt.manifest_server_password:
  430. if not (opt.smart_sync or opt.smart_tag):
  431. print('error: -u and -p may only be combined with -s or -t',
  432. file=sys.stderr)
  433. sys.exit(1)
  434. if None in [opt.manifest_server_username, opt.manifest_server_password]:
  435. print('error: both -u and -p must be given', file=sys.stderr)
  436. sys.exit(1)
  437. if opt.manifest_name:
  438. self.manifest.Override(opt.manifest_name)
  439. manifest_name = opt.manifest_name
  440. if opt.smart_sync or opt.smart_tag:
  441. if not self.manifest.manifest_server:
  442. print('error: cannot smart sync: no manifest server defined in '
  443. 'manifest', file=sys.stderr)
  444. sys.exit(1)
  445. manifest_server = self.manifest.manifest_server
  446. if not opt.quiet:
  447. print('Using manifest server %s' % manifest_server)
  448. if not '@' in manifest_server:
  449. username = None
  450. password = None
  451. if opt.manifest_server_username and opt.manifest_server_password:
  452. username = opt.manifest_server_username
  453. password = opt.manifest_server_password
  454. else:
  455. try:
  456. info = netrc.netrc()
  457. except IOError:
  458. print('.netrc file does not exist or could not be opened',
  459. file=sys.stderr)
  460. else:
  461. try:
  462. parse_result = urllib.parse.urlparse(manifest_server)
  463. if parse_result.hostname:
  464. username, _account, password = \
  465. info.authenticators(parse_result.hostname)
  466. except TypeError:
  467. # TypeError is raised when the given hostname is not present
  468. # in the .netrc file.
  469. print('No credentials found for %s in .netrc'
  470. % parse_result.hostname, file=sys.stderr)
  471. except netrc.NetrcParseError as e:
  472. print('Error parsing .netrc file: %s' % e, file=sys.stderr)
  473. if (username and password):
  474. manifest_server = manifest_server.replace('://', '://%s:%s@' %
  475. (username, password),
  476. 1)
  477. try:
  478. server = xmlrpc.client.Server(manifest_server)
  479. if opt.smart_sync:
  480. p = self.manifest.manifestProject
  481. b = p.GetBranch(p.CurrentBranch)
  482. branch = b.merge
  483. if branch.startswith(R_HEADS):
  484. branch = branch[len(R_HEADS):]
  485. env = os.environ.copy()
  486. if 'SYNC_TARGET' in env:
  487. target = env['SYNC_TARGET']
  488. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  489. elif 'TARGET_PRODUCT' in env and 'TARGET_BUILD_VARIANT' in env:
  490. target = '%s-%s' % (env['TARGET_PRODUCT'],
  491. env['TARGET_BUILD_VARIANT'])
  492. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  493. else:
  494. [success, manifest_str] = server.GetApprovedManifest(branch)
  495. else:
  496. assert(opt.smart_tag)
  497. [success, manifest_str] = server.GetManifest(opt.smart_tag)
  498. if success:
  499. manifest_name = "smart_sync_override.xml"
  500. manifest_path = os.path.join(self.manifest.manifestProject.worktree,
  501. manifest_name)
  502. try:
  503. f = open(manifest_path, 'w')
  504. try:
  505. f.write(manifest_str)
  506. finally:
  507. f.close()
  508. except IOError:
  509. print('error: cannot write manifest to %s' % manifest_path,
  510. file=sys.stderr)
  511. sys.exit(1)
  512. self._ReloadManifest(manifest_name)
  513. else:
  514. print('error: manifest server RPC call failed: %s' %
  515. manifest_str, file=sys.stderr)
  516. sys.exit(1)
  517. except (socket.error, IOError, xmlrpc.client.Fault) as e:
  518. print('error: cannot connect to manifest server %s:\n%s'
  519. % (self.manifest.manifest_server, e), file=sys.stderr)
  520. sys.exit(1)
  521. except xmlrpc.client.ProtocolError as e:
  522. print('error: cannot connect to manifest server %s:\n%d %s'
  523. % (self.manifest.manifest_server, e.errcode, e.errmsg),
  524. file=sys.stderr)
  525. sys.exit(1)
  526. rp = self.manifest.repoProject
  527. rp.PreSync()
  528. mp = self.manifest.manifestProject
  529. mp.PreSync()
  530. if opt.repo_upgraded:
  531. _PostRepoUpgrade(self.manifest, quiet=opt.quiet)
  532. if not opt.local_only:
  533. mp.Sync_NetworkHalf(quiet=opt.quiet,
  534. current_branch_only=opt.current_branch_only,
  535. no_tags=opt.no_tags)
  536. if mp.HasChanges:
  537. syncbuf = SyncBuffer(mp.config)
  538. mp.Sync_LocalHalf(syncbuf)
  539. if not syncbuf.Finish():
  540. sys.exit(1)
  541. self._ReloadManifest(manifest_name)
  542. if opt.jobs is None:
  543. self.jobs = self.manifest.default.sync_j
  544. all_projects = self.GetProjects(args,
  545. missing_ok=True,
  546. submodules_ok=opt.fetch_submodules)
  547. self._fetch_times = _FetchTimes(self.manifest)
  548. if not opt.local_only:
  549. to_fetch = []
  550. now = time.time()
  551. if _ONE_DAY_S <= (now - rp.LastFetch):
  552. to_fetch.append(rp)
  553. to_fetch.extend(all_projects)
  554. to_fetch.sort(key=self._fetch_times.Get, reverse=True)
  555. fetched = self._Fetch(to_fetch, opt)
  556. _PostRepoFetch(rp, opt.no_repo_verify)
  557. if opt.network_only:
  558. # bail out now; the rest touches the working tree
  559. return
  560. # Iteratively fetch missing and/or nested unregistered submodules
  561. previously_missing_set = set()
  562. while True:
  563. self._ReloadManifest(manifest_name)
  564. all_projects = self.GetProjects(args,
  565. missing_ok=True,
  566. submodules_ok=opt.fetch_submodules)
  567. missing = []
  568. for project in all_projects:
  569. if project.gitdir not in fetched:
  570. missing.append(project)
  571. if not missing:
  572. break
  573. # Stop us from non-stopped fetching actually-missing repos: If set of
  574. # missing repos has not been changed from last fetch, we break.
  575. missing_set = set(p.name for p in missing)
  576. if previously_missing_set == missing_set:
  577. break
  578. previously_missing_set = missing_set
  579. fetched.update(self._Fetch(missing, opt))
  580. if self.manifest.IsMirror or self.manifest.IsArchive:
  581. # bail out now, we have no working tree
  582. return
  583. if self.UpdateProjectList():
  584. sys.exit(1)
  585. syncbuf = SyncBuffer(mp.config,
  586. detach_head = opt.detach_head)
  587. pm = Progress('Syncing work tree', len(all_projects))
  588. for project in all_projects:
  589. pm.update()
  590. if project.worktree:
  591. project.Sync_LocalHalf(syncbuf)
  592. pm.end()
  593. print(file=sys.stderr)
  594. if not syncbuf.Finish():
  595. sys.exit(1)
  596. # If there's a notice that's supposed to print at the end of the sync, print
  597. # it now...
  598. if self.manifest.notice:
  599. print(self.manifest.notice)
  600. def _PostRepoUpgrade(manifest, quiet=False):
  601. wrapper = Wrapper()
  602. if wrapper.NeedSetupGnuPG():
  603. wrapper.SetupGnuPG(quiet)
  604. for project in manifest.projects:
  605. if project.Exists:
  606. project.PostRepoUpgrade()
  607. def _PostRepoFetch(rp, no_repo_verify=False, verbose=False):
  608. if rp.HasChanges:
  609. print('info: A new version of repo is available', file=sys.stderr)
  610. print(file=sys.stderr)
  611. if no_repo_verify or _VerifyTag(rp):
  612. syncbuf = SyncBuffer(rp.config)
  613. rp.Sync_LocalHalf(syncbuf)
  614. if not syncbuf.Finish():
  615. sys.exit(1)
  616. print('info: Restarting repo with latest version', file=sys.stderr)
  617. raise RepoChangedException(['--repo-upgraded'])
  618. else:
  619. print('warning: Skipped upgrade to unverified version', file=sys.stderr)
  620. else:
  621. if verbose:
  622. print('repo version %s is current' % rp.work_git.describe(HEAD),
  623. file=sys.stderr)
  624. def _VerifyTag(project):
  625. gpg_dir = os.path.expanduser('~/.repoconfig/gnupg')
  626. if not os.path.exists(gpg_dir):
  627. print('warning: GnuPG was not available during last "repo init"\n'
  628. 'warning: Cannot automatically authenticate repo."""',
  629. file=sys.stderr)
  630. return True
  631. try:
  632. cur = project.bare_git.describe(project.GetRevisionId())
  633. except GitError:
  634. cur = None
  635. if not cur \
  636. or re.compile(r'^.*-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur):
  637. rev = project.revisionExpr
  638. if rev.startswith(R_HEADS):
  639. rev = rev[len(R_HEADS):]
  640. print(file=sys.stderr)
  641. print("warning: project '%s' branch '%s' is not signed"
  642. % (project.name, rev), file=sys.stderr)
  643. return False
  644. env = os.environ.copy()
  645. env['GIT_DIR'] = project.gitdir.encode()
  646. env['GNUPGHOME'] = gpg_dir.encode()
  647. cmd = [GIT, 'tag', '-v', cur]
  648. proc = subprocess.Popen(cmd,
  649. stdout = subprocess.PIPE,
  650. stderr = subprocess.PIPE,
  651. env = env)
  652. out = proc.stdout.read()
  653. proc.stdout.close()
  654. err = proc.stderr.read()
  655. proc.stderr.close()
  656. if proc.wait() != 0:
  657. print(file=sys.stderr)
  658. print(out, file=sys.stderr)
  659. print(err, file=sys.stderr)
  660. print(file=sys.stderr)
  661. return False
  662. return True
  663. class _FetchTimes(object):
  664. _ALPHA = 0.5
  665. def __init__(self, manifest):
  666. self._path = os.path.join(manifest.repodir, '.repo_fetchtimes.json')
  667. self._times = None
  668. self._seen = set()
  669. def Get(self, project):
  670. self._Load()
  671. return self._times.get(project.name, _ONE_DAY_S)
  672. def Set(self, project, t):
  673. self._Load()
  674. name = project.name
  675. old = self._times.get(name, t)
  676. self._seen.add(name)
  677. a = self._ALPHA
  678. self._times[name] = (a*t) + ((1-a) * old)
  679. def _Load(self):
  680. if self._times is None:
  681. try:
  682. f = open(self._path)
  683. try:
  684. self._times = json.load(f)
  685. finally:
  686. f.close()
  687. except (IOError, ValueError):
  688. try:
  689. os.remove(self._path)
  690. except OSError:
  691. pass
  692. self._times = {}
  693. def Save(self):
  694. if self._times is None:
  695. return
  696. to_delete = []
  697. for name in self._times:
  698. if name not in self._seen:
  699. to_delete.append(name)
  700. for name in to_delete:
  701. del self._times[name]
  702. try:
  703. f = open(self._path, 'w')
  704. try:
  705. json.dump(self._times, f, indent=2)
  706. finally:
  707. f.close()
  708. except (IOError, TypeError):
  709. try:
  710. os.remove(self._path)
  711. except OSError:
  712. pass