Skip to content

Commit

Permalink
refactor: use pathlib instead of os.path (#224)
Browse files Browse the repository at this point in the history
* refactor: use pathlib instead of os.path

* refactor: use path.home() instead of expanduser

* fix: add missing parenthesis to method call

* tests: patch Path.home instead of os.path.expanduser

* tests: remove os import and fix test_get_cache_dir_default

---------

Co-authored-by: K.B.Dharun Krishna <[email protected]>
  • Loading branch information
vitorhcl and kbdharun authored Feb 24, 2024
1 parent 9b683be commit 68acf05
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 23 deletions.
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

0 comments on commit 68acf05

Please sign in to comment.