sync.py 24 KB

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