]> jfr.im git - yt-dlp.git/blobdiff - yt_dlp/cache.py
[pp/embedthumbnail] Fix postprocessor (#10248)
[yt-dlp.git] / yt_dlp / cache.py
index 4f9fb78d3740455d6e41cce1c256b84873ab6990..71dca82b3584f9aa5d9120070825b9726bd9f96f 100644 (file)
@@ -1,10 +1,10 @@
 import contextlib
-import errno
 import json
 import os
 import re
 import shutil
 import traceback
+import urllib.parse
 
 from .utils import expand_path, traverse_obj, version_tuple, write_json_file
 from .version import __version__
@@ -22,11 +22,9 @@ def _get_root_dir(self):
         return expand_path(res)
 
     def _get_cache_fn(self, section, key, dtype):
-        assert re.match(r'^[a-zA-Z0-9_.-]+$', section), \
-            'invalid section %r' % section
-        assert re.match(r'^[a-zA-Z0-9_.-]+$', key), 'invalid key %r' % key
-        return os.path.join(
-            self._get_root_dir(), section, f'{key}.{dtype}')
+        assert re.match(r'^[\w.-]+$', section), f'invalid section {section!r}'
+        key = urllib.parse.quote(key, safe='').replace('%', ',')  # encode non-ascii characters
+        return os.path.join(self._get_root_dir(), section, f'{key}.{dtype}')
 
     @property
     def enabled(self):
@@ -40,11 +38,7 @@ def store(self, section, key, data, dtype='json'):
 
         fn = self._get_cache_fn(section, key, dtype)
         try:
-            try:
-                os.makedirs(os.path.dirname(fn))
-            except OSError as ose:
-                if ose.errno != errno.EEXIST:
-                    raise
+            os.makedirs(os.path.dirname(fn), exist_ok=True)
             self._ydl.write_debug(f'Saving {section}.{key} to cache')
             write_json_file({'yt-dlp_version': __version__, 'data': data}, fn)
         except Exception:
@@ -87,10 +81,10 @@ def remove(self):
 
         cachedir = self._get_root_dir()
         if not any((term in cachedir) for term in ('cache', 'tmp')):
-            raise Exception('Not removing directory %s - this does not look like a cache dir' % cachedir)
+            raise Exception(f'Not removing directory {cachedir} - this does not look like a cache dir')
 
         self._ydl.to_screen(
-            'Removing cache dir %s .' % cachedir, skip_eol=True)
+            f'Removing cache dir {cachedir} .', skip_eol=True)
         if os.path.exists(cachedir):
             self._ydl.to_screen('.', skip_eol=True)
             shutil.rmtree(cachedir)