fix warnings and json dumping of cacheprovider

This commit is contained in:
Ronny Pfannschmidt 2018-06-19 10:28:36 +02:00
parent ab80e0fba0
commit 1226cdab47
1 changed files with 12 additions and 12 deletions

View File

@ -17,17 +17,14 @@ from os.path import sep as _sep, altsep as _altsep
from textwrap import dedent from textwrap import dedent
from . import paths from . import paths
from .compat import _PY2 as PY2
import logging
log = logging.getLogger(__name__)
@attr.s @attr.s
class Cache(object): class Cache(object):
_cachedir = attr.ib(repr=False) _cachedir = attr.ib(repr=False)
_warn = attr.ib(repr=False)
@classmethod @classmethod
def for_config(cls, config): def for_config(cls, config):
@ -35,12 +32,15 @@ class Cache(object):
if config.getoption("cacheclear") and cachedir.exists(): if config.getoption("cacheclear") and cachedir.exists():
shutil.rmtree(str(cachedir)) shutil.rmtree(str(cachedir))
cachedir.mkdir() cachedir.mkdir()
return cls(cachedir) return cls(cachedir, config.warn)
@staticmethod @staticmethod
def cache_dir_from_config(config): def cache_dir_from_config(config):
return paths.resolve_from_str(config.getini("cache_dir"), config.rootdir) return paths.resolve_from_str(config.getini("cache_dir"), config.rootdir)
def warn(self, fmt, **args):
self._warn(code="I9", message=fmt.format(**args) if args else fmt)
def makedir(self, name): def makedir(self, name):
""" return a directory path object with the given name. If the """ return a directory path object with the given name. If the
directory does not yet exist, it will be created. You can use it directory does not yet exist, it will be created. You can use it
@ -75,7 +75,7 @@ class Cache(object):
try: try:
with path.open("r") as f: with path.open("r") as f:
return json.load(f) return json.load(f)
except (ValueError, IOError): except (ValueError, IOError, OSError):
return default return default
def set(self, key, value): def set(self, key, value):
@ -90,13 +90,13 @@ class Cache(object):
path = self._getvaluepath(key) path = self._getvaluepath(key)
try: try:
path.parent.mkdir(exist_ok=True, parents=True) path.parent.mkdir(exist_ok=True, parents=True)
except IOError: except (IOError, OSError):
log.warning("could not create cache path %s", path) self.warn("could not create cache path {path}", path=path)
return return
try: try:
f = path.open("w") f = path.open("wb" if PY2 else "w")
except py.error.ENOTDIR: except (IOError, OSError):
log.warning("cache could not write path %s", path) self.warn("cache could not write path {path}", path=path)
else: else:
with f: with f:
json.dump(value, f, indent=2, sort_keys=True) json.dump(value, f, indent=2, sort_keys=True)