Skip to content

refactor: use pathlib instead of os.path #224

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions tests/test_tldr.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import io
import os
from pathlib import Path

import pytest
import sys
import tldr
Expand Down Expand Up @@ -120,17 +121,17 @@ def test_get_platform(platform, expected):

def test_get_cache_dir_xdg(monkeypatch):
monkeypatch.setenv("XDG_CACHE_HOME", "/tmp/cache")
assert tldr.get_cache_dir() == "/tmp/cache/tldr"
assert tldr.get_cache_dir() == Path("/tmp/cache/tldr")


def test_get_cache_dir_home(monkeypatch):
monkeypatch.delenv("XDG_CACHE_HOME", raising=False)
monkeypatch.setenv("HOME", "/tmp/home")
assert tldr.get_cache_dir() == "/tmp/home/.cache/tldr"
assert tldr.get_cache_dir() == Path("/tmp/home/.cache/tldr")


def test_get_cache_dir_default(monkeypatch):
monkeypatch.delenv("XDG_CACHE_HOME", raising=False)
monkeypatch.delenv("HOME", raising=False)
monkeypatch.setattr(os.path, 'expanduser', lambda _: '/tmp/expanduser')
assert tldr.get_cache_dir() == "/tmp/expanduser/.cache/tldr"
monkeypatch.setattr(Path, 'home', lambda: Path('/tmp/expanduser'))
assert tldr.get_cache_dir() == Path("/tmp/expanduser/.cache/tldr")
37 changes: 19 additions & 18 deletions tldr.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os
import re
from argparse import ArgumentParser
from pathlib import Path
from zipfile import ZipFile
from datetime import datetime
from io import BytesIO
Expand Down Expand Up @@ -78,28 +79,28 @@ def get_default_language() -> str:
return default_lang


def get_cache_dir() -> str:
def get_cache_dir() -> Path:
if os.environ.get('XDG_CACHE_HOME', False):
return os.path.join(os.environ.get('XDG_CACHE_HOME'), 'tldr')
return Path(os.environ.get('XDG_CACHE_HOME')) / 'tldr'
if os.environ.get('HOME', False):
return os.path.join(os.environ.get('HOME'), '.cache', 'tldr')
return os.path.join(os.path.expanduser("~"), ".cache", "tldr")
return Path(os.environ.get('HOME')) / '.cache' / 'tldr'
return Path.home() / '.cache' / 'tldr'


def get_cache_file_path(command: str, platform: str, language: str) -> str:
def get_cache_file_path(command: str, platform: str, language: str) -> Path:
pages_dir = "pages"
if language and language != 'en':
pages_dir += "." + language
return os.path.join(get_cache_dir(), pages_dir, platform, command) + ".md"
return get_cache_dir() / pages_dir / platform / f"{command}.md"


def load_page_from_cache(command: str, platform: str, language: str) -> Optional[str]:
try:
with open(get_cache_file_path(
with get_cache_file_path(
command,
platform,
language), 'rb'
) as cache_file:
language
).open('rb') as cache_file:
cache_file_contents = cache_file.read()
return cache_file_contents
except Exception:
Expand All @@ -114,8 +115,8 @@ def store_page_to_cache(
) -> Optional[str]:
try:
cache_file_path = get_cache_file_path(command, platform, language)
os.makedirs(os.path.dirname(cache_file_path), exist_ok=True)
with open(cache_file_path, "wb") as cache_file:
cache_file_path.parent.mkdir(exist_ok=True)
with cache_file_path.open("wb") as cache_file:
cache_file.write(page)
except Exception:
pass
Expand All @@ -124,7 +125,7 @@ def store_page_to_cache(
def have_recent_cache(command: str, platform: str, language: str) -> bool:
try:
cache_file_path = get_cache_file_path(command, platform, language)
last_modified = datetime.fromtimestamp(os.path.getmtime(cache_file_path))
last_modified = datetime.fromtimestamp(cache_file_path.stat().st_mtime)
hours_passed = (datetime.now() - last_modified).total_seconds() / 3600
return hours_passed <= MAX_CACHE_AGE
except Exception:
Expand Down Expand Up @@ -309,12 +310,12 @@ def get_commands(platforms: Optional[List[str]] = None) -> List[str]:
platforms = get_platform_list()

commands = []
if os.path.exists(get_cache_dir()):
if get_cache_dir().exists():
for platform in platforms:
path = os.path.join(get_cache_dir(), 'pages', platform)
if not os.path.exists(path):
path = get_cache_dir() / 'pages' / platform
if not path.exists():
continue
commands += [file[:-3] for file in os.listdir(path) if file.endswith(".md")]
commands += [file.stem for file in path.iterdir() if file.suffix == '.md']
return commands


Expand Down Expand Up @@ -513,8 +514,8 @@ def main() -> None:
print('\n'.join(get_commands(options.platform)))
elif options.render:
for command in options.command:
if os.path.exists(command):
with open(command, encoding='utf-8') as open_file:
if Path(command).exists():
with command.open(encoding='utf-8') as open_file:
output(open_file.read().encode('utf-8').splitlines(),
plain=options.markdown)
elif options.search:
Expand Down