sync.py 28 KB

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