]> jfr.im git - yt-dlp.git/blame - yt_dlp/cache.py
[cleanup] Misc cleanup and refactor (#2173)
[yt-dlp.git] / yt_dlp / cache.py
CommitLineData
19a03940 1import contextlib
a0e07d31 2import errno
a0e07d31
PH
3import json
4import os
5import re
6import shutil
7import traceback
8
590bc6f6 9from .compat import compat_getenv
f8271158 10from .utils import expand_path, write_json_file
a0e07d31
PH
11
12
86e5f3ed 13class Cache:
a0e07d31
PH
14 def __init__(self, ydl):
15 self._ydl = ydl
16
17 def _get_root_dir(self):
18 res = self._ydl.params.get('cachedir')
19 if res is None:
92120217 20 cache_root = compat_getenv('XDG_CACHE_HOME', '~/.cache')
7a5c1cfe 21 res = os.path.join(cache_root, 'yt-dlp')
590bc6f6 22 return expand_path(res)
a0e07d31
PH
23
24 def _get_cache_fn(self, section, key, dtype):
674c869a
PH
25 assert re.match(r'^[a-zA-Z0-9_.-]+$', section), \
26 'invalid section %r' % section
27 assert re.match(r'^[a-zA-Z0-9_.-]+$', key), 'invalid key %r' % key
a0e07d31 28 return os.path.join(
86e5f3ed 29 self._get_root_dir(), section, f'{key}.{dtype}')
a0e07d31
PH
30
31 @property
32 def enabled(self):
33 return self._ydl.params.get('cachedir') is not False
34
35 def store(self, section, key, data, dtype='json'):
36 assert dtype in ('json',)
37
38 if not self.enabled:
39 return
40
41 fn = self._get_cache_fn(section, key, dtype)
42 try:
43 try:
44 os.makedirs(os.path.dirname(fn))
45 except OSError as ose:
46 if ose.errno != errno.EEXIST:
47 raise
e6f21b3d 48 self._ydl.write_debug(f'Saving {section}.{key} to cache')
a0e07d31
PH
49 write_json_file(data, fn)
50 except Exception:
51 tb = traceback.format_exc()
86e5f3ed 52 self._ydl.report_warning(f'Writing cache to {fn!r} failed: {tb}')
a0e07d31
PH
53
54 def load(self, section, key, dtype='json', default=None):
55 assert dtype in ('json',)
56
57 if not self.enabled:
58 return default
59
60 cache_fn = self._get_cache_fn(section, key, dtype)
19a03940 61 with contextlib.suppress(OSError):
a0e07d31 62 try:
86e5f3ed 63 with open(cache_fn, encoding='utf-8') as cachef:
e6f21b3d 64 self._ydl.write_debug(f'Loading {section}.{key} from cache')
a0e07d31
PH
65 return json.load(cachef)
66 except ValueError:
67 try:
68 file_size = os.path.getsize(cache_fn)
86e5f3ed 69 except OSError as oe:
a0e07d31 70 file_size = str(oe)
86e5f3ed 71 self._ydl.report_warning(f'Cache retrieval from {cache_fn} failed ({file_size})')
a0e07d31
PH
72
73 return default
74
75 def remove(self):
76 if not self.enabled:
77 self._ydl.to_screen('Cache is disabled (Did you combine --no-cache-dir and --rm-cache-dir?)')
78 return
79
80 cachedir = self._get_root_dir()
81 if not any((term in cachedir) for term in ('cache', 'tmp')):
82 raise Exception('Not removing directory %s - this does not look like a cache dir' % cachedir)
83
84 self._ydl.to_screen(
85 'Removing cache dir %s .' % cachedir, skip_eol=True)
86 if os.path.exists(cachedir):
87 self._ydl.to_screen('.', skip_eol=True)
88 shutil.rmtree(cachedir)
89 self._ydl.to_screen('.')