sync.py 24 KB

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