|
9 | 9 | from importlib.util import find_spec
|
10 | 10 |
|
11 | 11 |
|
12 |
| -CACHE_AVAILABLE = find_spec('platformdirs') is not None |
13 |
| - |
14 |
| - |
15 | 12 | class Cache:
|
16 | 13 | """Cache for arbitrary content, one file per entry."""
|
17 | 14 |
|
@@ -64,31 +61,52 @@ def set_(self, url: str, value: str, encoding: str = 'utf-8') -> None: # noqa:
|
64 | 61 | def clean(self) -> None:
|
65 | 62 | """Clean expired entries from the cache."""
|
66 | 63 | for fname in os.listdir(self.cache_dir):
|
| 64 | + if fname == '.gitignore': |
| 65 | + continue |
67 | 66 | fpath = os.path.join(self.cache_dir, fname)
|
68 | 67 | creation_time = self.get_creation_time_from_fpath(fpath)
|
69 | 68 | if time.time() > creation_time + self.expiration_seconds:
|
70 | 69 | os.remove(fpath)
|
71 | 70 |
|
72 | 71 |
|
73 |
| -def get_cache_directory() -> str | None: |
74 |
| - """Get the cache directory.""" |
75 |
| - if not CACHE_AVAILABLE: |
| 72 | +def get_cache_directory(cache_dir: str) -> str | None: |
| 73 | + """Get cache directory.""" |
| 74 | + if cache_dir: |
| 75 | + return cache_dir |
| 76 | + |
| 77 | + if not is_platformdirs_installed(): |
76 | 78 | return None
|
77 | 79 |
|
78 | 80 | try:
|
79 | 81 | from platformdirs import user_data_dir
|
80 | 82 | except ImportError:
|
81 | 83 | return None
|
| 84 | + else: |
| 85 | + return user_data_dir('mkdocs-include-markdown-plugin') |
| 86 | + |
| 87 | + |
| 88 | +def initialize_cache(expiration_seconds: int, cache_dir: str) -> Cache | None: |
| 89 | + """Initialize a cache instance.""" |
| 90 | + cache_directory = get_cache_directory(cache_dir) |
| 91 | + |
| 92 | + if cache_directory is None: |
| 93 | + return None |
82 | 94 |
|
83 |
| - cache_dir = user_data_dir('mkdocs-include-markdown-plugin') |
84 |
| - os.makedirs(cache_dir, exist_ok=True) |
| 95 | + os.makedirs(cache_directory, exist_ok=True) |
85 | 96 |
|
86 |
| - return cache_dir |
| 97 | + # Add a `.gitignore` file to prevent the cache directory from being |
| 98 | + # included in the repository. This is needed because the cache directory |
| 99 | + # can be configured as a relative path with `cache_dir` setting. |
| 100 | + gitignore = os.path.join(cache_directory, '.gitignore') |
| 101 | + if not os.path.exists(gitignore): |
| 102 | + with open(gitignore, 'wb') as f: |
| 103 | + f.write(b'*\n') |
87 | 104 |
|
| 105 | + cache = Cache(cache_directory, expiration_seconds) |
| 106 | + cache.clean() |
| 107 | + return cache |
88 | 108 |
|
89 |
| -def initialize_cache(expiration_seconds: int) -> Cache | None: |
90 |
| - """Initialize a cache instance.""" |
91 |
| - cache_dir = get_cache_directory() |
92 |
| - return None if cache_dir is None else Cache( |
93 |
| - cache_dir, expiration_seconds, |
94 |
| - ) |
| 109 | + |
| 110 | +def is_platformdirs_installed() -> bool: |
| 111 | + """Check if `platformdirs` package is installed without importing it.""" |
| 112 | + return find_spec('platformdirs') is not None |
0 commit comments