]>
jfr.im git - yt-dlp.git/blob - yt_dlp/cache.py
9 from .utils
import expand_path
, write_json_file
13 def __init__(self
, ydl
):
16 def _get_root_dir(self
):
17 res
= self
._ydl
.params
.get('cachedir')
19 cache_root
= os
.getenv('XDG_CACHE_HOME', '~/.cache')
20 res
= os
.path
.join(cache_root
, 'yt-dlp')
21 return expand_path(res
)
23 def _get_cache_fn(self
, section
, key
, dtype
):
24 assert re
.match(r
'^[a-zA-Z0-9_.-]+$', section
), \
25 'invalid section %r' % section
26 assert re
.match(r
'^[a-zA-Z0-9_.-]+$', key
), 'invalid key %r' % key
28 self
._get
_root
_dir
(), section
, f
'{key}.{dtype}')
32 return self
._ydl
.params
.get('cachedir') is not False
34 def store(self
, section
, key
, data
, dtype
='json'):
35 assert dtype
in ('json',)
40 fn
= self
._get
_cache
_fn
(section
, key
, dtype
)
43 os
.makedirs(os
.path
.dirname(fn
))
44 except OSError as ose
:
45 if ose
.errno
!= errno
.EEXIST
:
47 self
._ydl
.write_debug(f
'Saving {section}.{key} to cache')
48 write_json_file(data
, fn
)
50 tb
= traceback
.format_exc()
51 self
._ydl
.report_warning(f
'Writing cache to {fn!r} failed: {tb}')
53 def load(self
, section
, key
, dtype
='json', default
=None):
54 assert dtype
in ('json',)
59 cache_fn
= self
._get
_cache
_fn
(section
, key
, dtype
)
60 with contextlib
.suppress(OSError):
62 with open(cache_fn
, encoding
='utf-8') as cachef
:
63 self
._ydl
.write_debug(f
'Loading {section}.{key} from cache')
64 return json
.load(cachef
)
67 file_size
= os
.path
.getsize(cache_fn
)
70 self
._ydl
.report_warning(f
'Cache retrieval from {cache_fn} failed ({file_size})')
76 self
._ydl
.to_screen('Cache is disabled (Did you combine --no-cache-dir and --rm-cache-dir?)')
79 cachedir
= self
._get
_root
_dir
()
80 if not any((term
in cachedir
) for term
in ('cache', 'tmp')):
81 raise Exception('Not removing directory %s - this does not look like a cache dir' % cachedir
)
84 'Removing cache dir %s .' % cachedir
, skip_eol
=True)
85 if os
.path
.exists(cachedir
):
86 self
._ydl
.to_screen('.', skip_eol
=True)
87 shutil
.rmtree(cachedir
)
88 self
._ydl
.to_screen('.')