Skip to content

Commit 68acf05

Browse files
vitorhclkbdharun
andauthored
refactor: use pathlib instead of os.path (#224)
* 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]>
1 parent 9b683be commit 68acf05

File tree

2 files changed

+25
-23
lines changed

2 files changed

+25
-23
lines changed

tests/test_tldr.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import io
2-
import os
2+
from pathlib import Path
3+
34
import pytest
45
import sys
56
import tldr
@@ -120,17 +121,17 @@ def test_get_platform(platform, expected):
120121

121122
def test_get_cache_dir_xdg(monkeypatch):
122123
monkeypatch.setenv("XDG_CACHE_HOME", "/tmp/cache")
123-
assert tldr.get_cache_dir() == "/tmp/cache/tldr"
124+
assert tldr.get_cache_dir() == Path("/tmp/cache/tldr")
124125

125126

126127
def test_get_cache_dir_home(monkeypatch):
127128
monkeypatch.delenv("XDG_CACHE_HOME", raising=False)
128129
monkeypatch.setenv("HOME", "/tmp/home")
129-
assert tldr.get_cache_dir() == "/tmp/home/.cache/tldr"
130+
assert tldr.get_cache_dir() == Path("/tmp/home/.cache/tldr")
130131

131132

132133
def test_get_cache_dir_default(monkeypatch):
133134
monkeypatch.delenv("XDG_CACHE_HOME", raising=False)
134135
monkeypatch.delenv("HOME", raising=False)
135-
monkeypatch.setattr(os.path, 'expanduser', lambda _: '/tmp/expanduser')
136-
assert tldr.get_cache_dir() == "/tmp/expanduser/.cache/tldr"
136+
monkeypatch.setattr(Path, 'home', lambda: Path('/tmp/expanduser'))
137+
assert tldr.get_cache_dir() == Path("/tmp/expanduser/.cache/tldr")

tldr.py

+19-18
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import os
66
import re
77
from argparse import ArgumentParser
8+
from pathlib import Path
89
from zipfile import ZipFile
910
from datetime import datetime
1011
from io import BytesIO
@@ -78,28 +79,28 @@ def get_default_language() -> str:
7879
return default_lang
7980

8081

81-
def get_cache_dir() -> str:
82+
def get_cache_dir() -> Path:
8283
if os.environ.get('XDG_CACHE_HOME', False):
83-
return os.path.join(os.environ.get('XDG_CACHE_HOME'), 'tldr')
84+
return Path(os.environ.get('XDG_CACHE_HOME')) / 'tldr'
8485
if os.environ.get('HOME', False):
85-
return os.path.join(os.environ.get('HOME'), '.cache', 'tldr')
86-
return os.path.join(os.path.expanduser("~"), ".cache", "tldr")
86+
return Path(os.environ.get('HOME')) / '.cache' / 'tldr'
87+
return Path.home() / '.cache' / 'tldr'
8788

8889

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

9596

9697
def load_page_from_cache(command: str, platform: str, language: str) -> Optional[str]:
9798
try:
98-
with open(get_cache_file_path(
99+
with get_cache_file_path(
99100
command,
100101
platform,
101-
language), 'rb'
102-
) as cache_file:
102+
language
103+
).open('rb') as cache_file:
103104
cache_file_contents = cache_file.read()
104105
return cache_file_contents
105106
except Exception:
@@ -114,8 +115,8 @@ def store_page_to_cache(
114115
) -> Optional[str]:
115116
try:
116117
cache_file_path = get_cache_file_path(command, platform, language)
117-
os.makedirs(os.path.dirname(cache_file_path), exist_ok=True)
118-
with open(cache_file_path, "wb") as cache_file:
118+
cache_file_path.parent.mkdir(exist_ok=True)
119+
with cache_file_path.open("wb") as cache_file:
119120
cache_file.write(page)
120121
except Exception:
121122
pass
@@ -124,7 +125,7 @@ def store_page_to_cache(
124125
def have_recent_cache(command: str, platform: str, language: str) -> bool:
125126
try:
126127
cache_file_path = get_cache_file_path(command, platform, language)
127-
last_modified = datetime.fromtimestamp(os.path.getmtime(cache_file_path))
128+
last_modified = datetime.fromtimestamp(cache_file_path.stat().st_mtime)
128129
hours_passed = (datetime.now() - last_modified).total_seconds() / 3600
129130
return hours_passed <= MAX_CACHE_AGE
130131
except Exception:
@@ -309,12 +310,12 @@ def get_commands(platforms: Optional[List[str]] = None) -> List[str]:
309310
platforms = get_platform_list()
310311

311312
commands = []
312-
if os.path.exists(get_cache_dir()):
313+
if get_cache_dir().exists():
313314
for platform in platforms:
314-
path = os.path.join(get_cache_dir(), 'pages', platform)
315-
if not os.path.exists(path):
315+
path = get_cache_dir() / 'pages' / platform
316+
if not path.exists():
316317
continue
317-
commands += [file[:-3] for file in os.listdir(path) if file.endswith(".md")]
318+
commands += [file.stem for file in path.iterdir() if file.suffix == '.md']
318319
return commands
319320

320321

@@ -513,8 +514,8 @@ def main() -> None:
513514
print('\n'.join(get_commands(options.platform)))
514515
elif options.render:
515516
for command in options.command:
516-
if os.path.exists(command):
517-
with open(command, encoding='utf-8') as open_file:
517+
if Path(command).exists():
518+
with command.open(encoding='utf-8') as open_file:
518519
output(open_file.read().encode('utf-8').splitlines(),
519520
plain=options.markdown)
520521
elif options.search:

0 commit comments

Comments
 (0)