Skip to content

Commit fb1362f

Browse files
Added caching feature
1 parent 24f154e commit fb1362f

File tree

1 file changed

+50
-2
lines changed

1 file changed

+50
-2
lines changed

tldr.py

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from __future__ import unicode_literals, print_function
33
import sys
44
import os
5+
import errno
56
import subprocess
67
import re
78
from argparse import ArgumentParser
@@ -63,8 +64,54 @@ def get_terminal_size_tput():
6364
}
6465

6566

67+
def get_cache_file_path(command, platform):
68+
cache_file_name = command + "_" + platform + ".md"
69+
cache_file_path = os.path.join(
70+
os.path.expanduser("~"), "tldr_cache", cache_file_name)
71+
return cache_file_path
72+
73+
74+
def load_page_from_cache(command, platform):
75+
try:
76+
with open(get_cache_file_path(command, platform)) as cache_file:
77+
cache_file_contents = cache_file.read()
78+
return cache_file_contents
79+
except Exception:
80+
pass
81+
82+
83+
def store_page_to_cache(page, command, platform):
84+
def mkdir_p(path):
85+
"""
86+
Create all the intermediate directories in a path.
87+
Similar to the `mkdir -p` command.
88+
"""
89+
try:
90+
os.makedirs(path)
91+
except OSError as exc: # Python >2.5
92+
if exc.errno == errno.EEXIST and os.path.isdir(path):
93+
pass
94+
else:
95+
raise
96+
97+
try:
98+
cache_file_path = get_cache_file_path(command, platform)
99+
mkdir_p(os.path.dirname(cache_file_path))
100+
with open(cache_file_path, "w") as cache_file:
101+
cache_file.write(page)
102+
except Exception:
103+
pass
104+
105+
66106
def get_page_for_platform(command, platform):
67-
data = urlopen(remote + "/" + platform + "/" + quote(command) + ".md")
107+
page_url = remote + "/" + platform + "/" + quote(command) + ".md"
108+
try:
109+
data = urlopen(page_url).read()
110+
except Exception:
111+
data = load_page_from_cache(command, platform)
112+
if data is None:
113+
raise
114+
store_page_to_cache(data, command, platform)
68115
return data
69116

70117

@@ -88,6 +135,7 @@ def get_page(command, platform=None):
88135
print(command + " documentation is not available\n"
89136
"Consider contributing Pull Request to https://github.com/tldr-pages/tldr")
90137

138+
91139
DEFAULT_COLORS = {
92140
'blank': 'white on_blue',
93141
'name': 'cyan on_blue bold',
@@ -117,7 +165,7 @@ def colors_of(key):
117165
def output(page):
118166
# Need a better fancy method?
119167
if page is not None:
120-
for line in page:
168+
for line in page.splitlines():
121169
line = line.rstrip().decode('utf-8')
122170
if len(line) < 1:
123171
cprint(line.ljust(columns), *colors_of('blank'))

0 commit comments

Comments
 (0)