]>
Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/cache.py
1 from __future__
import unicode_literals
11 from .compat
import compat_getenv
19 def __init__(self
, ydl
):
22 def _get_root_dir(self
):
23 res
= self
._ydl
.params
.get('cachedir')
25 cache_root
= compat_getenv('XDG_CACHE_HOME', '~/.cache')
26 res
= os
.path
.join(cache_root
, 'youtube-dl')
27 return expand_path(res
)
29 def _get_cache_fn(self
, section
, key
, dtype
):
30 assert re
.match(r
'^[a-zA-Z0-9_.-]+$', section
), \
31 'invalid section %r' % section
32 assert re
.match(r
'^[a-zA-Z0-9_.-]+$', key
), 'invalid key %r' % key
34 self
._get
_root
_dir
(), section
, '%s.%s' % (key
, dtype
))
38 return self
._ydl
.params
.get('cachedir') is not False
40 def store(self
, section
, key
, data
, dtype
='json'):
41 assert dtype
in ('json',)
46 fn
= self
._get
_cache
_fn
(section
, key
, dtype
)
49 os
.makedirs(os
.path
.dirname(fn
))
50 except OSError as ose
:
51 if ose
.errno
!= errno
.EEXIST
:
53 write_json_file(data
, fn
)
55 tb
= traceback
.format_exc()
56 self
._ydl
.report_warning(
57 'Writing cache to %r failed: %s' % (fn
, tb
))
59 def load(self
, section
, key
, dtype
='json', default
=None):
60 assert dtype
in ('json',)
65 cache_fn
= self
._get
_cache
_fn
(section
, key
, dtype
)
68 with io
.open(cache_fn
, 'r', encoding
='utf-8') as cachef
:
69 return json
.load(cachef
)
72 file_size
= os
.path
.getsize(cache_fn
)
73 except (OSError, IOError) as oe
:
75 self
._ydl
.report_warning(
76 'Cache retrieval from %s failed (%s)' % (cache_fn
, file_size
))
78 pass # No cache available
84 self
._ydl
.to_screen('Cache is disabled (Did you combine --no-cache-dir and --rm-cache-dir?)')
87 cachedir
= self
._get
_root
_dir
()
88 if not any((term
in cachedir
) for term
in ('cache', 'tmp')):
89 raise Exception('Not removing directory %s - this does not look like a cache dir' % cachedir
)
92 'Removing cache dir %s .' % cachedir
, skip_eol
=True)
93 if os
.path
.exists(cachedir
):
94 self
._ydl
.to_screen('.', skip_eol
=True)
95 shutil
.rmtree(cachedir
)
96 self
._ydl
.to_screen('.')