-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* wip * working on cache * finish cache * test windows * test mac * additional windows * use different windows path
- Loading branch information
1 parent
5911b48
commit 7fe9303
Showing
8 changed files
with
147 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
from __future__ import annotations | ||
|
||
import os | ||
from pathlib import Path | ||
from typing import Iterator, MutableMapping | ||
|
||
_SVG_CACHE: MutableMapping[str, bytes] | None = None | ||
|
||
|
||
def svg_cache() -> MutableMapping[str, bytes]: # pragma: no cover | ||
"""Return a cache for SVG files.""" | ||
global _SVG_CACHE | ||
if _SVG_CACHE is None: | ||
try: | ||
_SVG_CACHE = _SVGCache() | ||
except Exception: | ||
_SVG_CACHE = {} | ||
return _SVG_CACHE | ||
|
||
|
||
def clear_cache() -> None: | ||
"""Clear the pyconify svg cache.""" | ||
import shutil | ||
|
||
shutil.rmtree(get_cache_directory(), ignore_errors=True) | ||
global _SVG_CACHE | ||
_SVG_CACHE = None | ||
|
||
|
||
def get_cache_directory(app_name: str = "pyconify") -> Path: | ||
"""Return the pyconify svg cache directory.""" | ||
if os.name == "posix": | ||
return Path.home() / ".cache" / app_name | ||
elif os.name == "nt": | ||
appdata = os.environ.get("LOCALAPPDATA", "~/AppData/Local") | ||
return Path(appdata).expanduser() / app_name | ||
# Fallback to a directory in the user's home directory | ||
return Path.home() / f".{app_name}" # pragma: no cover | ||
|
||
|
||
def cache_key(args: tuple, kwargs: dict) -> str: | ||
"""Generate a key for the cache based on the function arguments.""" | ||
_keys: tuple = args | ||
if kwargs: | ||
for item in sorted(kwargs.items()): | ||
if item[1] is not None: | ||
_keys += item | ||
return "-".join(map(str, _keys)) | ||
|
||
|
||
class _SVGCache(MutableMapping[str, bytes]): | ||
"""A simple directory cache for SVG files.""" | ||
|
||
def __init__(self, directory: str | Path | None = None) -> None: | ||
super().__init__() | ||
if not directory: | ||
directory = get_cache_directory() / "svg_cache" # pragma: no cover | ||
self.path = Path(directory).expanduser().resolve() | ||
self.path.mkdir(parents=True, exist_ok=True) | ||
self._extention = ".svg" | ||
|
||
def __setitem__(self, _key: str, _value: bytes) -> None: | ||
self.path.joinpath(f"{_key}{self._extention}").write_bytes(_value) | ||
|
||
def __getitem__(self, _key: str) -> bytes: | ||
try: | ||
return self.path.joinpath(f"{_key}{self._extention}").read_bytes() | ||
except FileNotFoundError: | ||
raise KeyError(_key) from None | ||
|
||
def __iter__(self) -> Iterator[str]: | ||
yield from (x.stem for x in self.path.glob(f"*{self._extention}")) | ||
|
||
def __delitem__(self, _key: str) -> None: | ||
self.path.joinpath(f"{_key}{self._extention}").unlink() | ||
|
||
def __len__(self) -> int: | ||
return len(list(self.path.glob("*{self._extention}"))) | ||
|
||
def __contains__(self, _key: object) -> bool: | ||
return self.path.joinpath(f"{_key}{self._extention}").exists() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
from typing import Iterator | ||
from unittest.mock import patch | ||
|
||
import pytest | ||
from pyconify import api | ||
|
||
|
||
@pytest.fixture(autouse=True, scope="session") | ||
def no_cache() -> Iterator[None]: | ||
TEST_CACHE: dict = {} | ||
with patch.object(api, "svg_cache", lambda: TEST_CACHE): | ||
yield | ||
assert TEST_CACHE |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
from pathlib import Path | ||
|
||
import pytest | ||
from pyconify._cache import _SVGCache, clear_cache, get_cache_directory | ||
|
||
|
||
def test_cache(tmp_path) -> None: | ||
assert isinstance(get_cache_directory(), Path) | ||
clear_cache() | ||
|
||
cache = _SVGCache(tmp_path) | ||
KEY, VAL = "testkey", b"testval" | ||
cache[KEY] = VAL | ||
assert cache[KEY] == VAL | ||
assert cache.path.joinpath(f"{KEY}.svg").exists() | ||
assert list(cache) == [KEY] | ||
assert KEY in cache | ||
del cache[KEY] | ||
assert not cache.path.joinpath(f"{KEY}.svg").exists() | ||
|
||
with pytest.raises(KeyError): | ||
cache["not a key"] |