| 1 |
import os |
| 2 |
from pathlib import Path |
| 3 |
from typing import TYPE_CHECKING |
| 4 |
|
| 5 |
import click |
| 6 |
|
| 7 |
if TYPE_CHECKING: |
| 8 |
from jupyter_cache.base import JupyterCacheAbstract |
| 9 |
|
| 10 |
|
| 11 |
class CacheContext: |
| 12 |
"""Context for retrieving the cache.""" |
| 13 |
|
| 14 |
def __init__(self, cache_path=None) -> None: |
| 15 |
if cache_path is None: |
| 16 |
self._cache_path = os.environ.get( |
| 17 |
"JUPYTERCACHE", os.path.join(os.getcwd(), ".jupyter_cache") |
| 18 |
) |
| 19 |
else: |
| 20 |
self._cache_path = cache_path |
| 21 |
|
| 22 |
@property |
| 23 |
def cache_path(self) -> Path: |
| 24 |
return Path(self._cache_path) |
| 25 |
|
| 26 |
def get_cache(self, ask_on_missing=True) -> "JupyterCacheAbstract": |
| 27 |
"""Get the cache.""" |
| 28 |
from jupyter_cache import get_cache |
| 29 |
|
| 30 |
if (not self.cache_path.exists()) and ask_on_missing: |
| 31 |
click.secho("Cache path: ", fg="green", nl=False) |
| 32 |
click.echo(str(self.cache_path)) |
| 33 |
if not click.confirm( |
| 34 |
"The cache does not yet exist, do you want to create it?" |
| 35 |
): |
| 36 |
raise click.Abort() |
| 37 |
|
| 38 |
# gets created lazily |
| 39 |
return get_cache(self.cache_path) |
| 40 |
|
| 41 |
def set_cache_path(self, cache_path: str) -> None: |
| 42 |
self._cache_path = cache_path |
| 43 |
|
| 44 |
|
| 45 |
pass_cache = click.make_pass_decorator(CacheContext, ensure=True) |