Skip to content

Commit 9287bfa

Browse files
Update tldr.py : fix clear cache option thanks to @kbdharun
- Added iteration over multiple languages, handling non-English languages dynamically. - Implemented recursive directory traversal to delete files and subdirectories within cache directories. - Improved error handling with detailed messages for file and directory deletion failures. thanks to @kbdharun Co-authored-by: K.B.Dharun Krishna <[email protected]>
1 parent c710f61 commit 9287bfa

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

tldr.py

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -495,18 +495,33 @@ def clear_cache(language: Optional[List[str]] = None) -> None:
495495
if language and language[0] not in languages:
496496
languages.append(language[0])
497497
for language in languages:
498-
try:
499-
cache_location = f"{DOWNLOAD_CACHE_LOCATION[:-4]}-pages.{language}.zip"
500-
os.remove(cache_location)
501-
print(
502-
"Cleared cache for language "
503-
f"{language}"
504-
)
505-
except Exception:
506-
print(
507-
"Error: Unable to clear cache for language "
508-
f"{language} from {cache_location}"
509-
)
498+
pages_dir = f'pages.{language}' if language != 'en' else 'pages'
499+
cache_dir = get_cache_dir() / pages_dir
500+
if cache_dir.exists() and cache_dir.is_dir():
501+
# Recursively walk through the directory to delete files and subdirectories
502+
for root, dirs, files in os.walk(cache_dir, topdown=False):
503+
for name in files:
504+
file_path = Path(root) / name
505+
try:
506+
file_path.unlink() # Attempt to delete the file
507+
except Exception as e:
508+
print(f"Error: Unable to delete cache file {file_path}: {e}")
509+
for name in dirs:
510+
dir_path = Path(root) / name
511+
try:
512+
dir_path.rmdir() # Attempt to delete the directory
513+
except Exception as e:
514+
print(
515+
f"Error: Unable to delete cache directory {dir_path}: {e}"
516+
)
517+
# Attempt to remove the main cache directory after clearing its contents
518+
try:
519+
cache_dir.rmdir()
520+
print(f"Cleared cache for language {language}")
521+
except Exception as e:
522+
print(f"Error: Unable to delete cache directory {cache_dir}: {e}")
523+
else:
524+
print(f"No cache directory found for language {language}")
510525

511526

512527
def create_parser() -> ArgumentParser:

0 commit comments

Comments
 (0)