sync.py 27 KB

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