]>
jfr.im git - yt-dlp.git/blob - yt_dlp/cache.py
9 from .compat
import compat_getenv
10 from .utils
import expand_path
, write_json_file
14 def __init__(self
, ydl
):
17 def _get_root_dir(self
):
18 res
= self
._ydl
.params
.get('cachedir')
20 cache_root
= compat_getenv('XDG_CACHE_HOME', '~/.cache')
21 res
= os
.path
.join(cache_root
, 'yt-dlp')
22 return expand_path(res
)
24 def _get_cache_fn(self
, section
, key
, dtype
):
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
29 self
._get
_root
_dir
(), section
, f
'{key}.{dtype}')
33 return self
._ydl
.params
.get('cachedir') is not False
35 def store(self
, section
, key
, data
, dtype
='json'):
36 assert dtype
in ('json',)
41 fn
= self
._get
_cache
_fn
(section
, key
, dtype
)
44 os
.makedirs(os
.path
.dirname(fn
))
45 except OSError as ose
:
46 if ose
.errno
!= errno
.EEXIST
:
48 self
._ydl
.write_debug(f
'Saving {section}.{key} to cache')
49 write_json_file(data
, fn
)
51 tb
= traceback
.format_exc()
52 self
._ydl
.report_warning(f
'Writing cache to {fn!r} failed: {tb}')
54 def load(self
, section
, key
, dtype
='json', default
=None):
55 assert dtype
in ('json',)
60 cache_fn
= self
._get
_cache
_fn
(section
, key
, dtype
)
61 with contextlib
.suppress(OSError):
63 with open(cache_fn
, encoding
='utf-8') as cachef
:
64 self
._ydl
.write_debug(f
'Loading {section}.{key} from cache')
65 return json
.load(cachef
)
68 file_size
= os
.path
.getsize(cache_fn
)
71 self
._ydl
.report_warning(f
'Cache retrieval from {cache_fn} failed ({file_size})')
77 self
._ydl
.to_screen('Cache is disabled (Did you combine --no-cache-dir and --rm-cache-dir?)')
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
)
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('.')