22from __future__ import unicode_literals , print_function
33import sys
44import os
5+ import errno
56import subprocess
67import re
78from 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+
66106def 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+
91139DEFAULT_COLORS = {
92140 'blank' : 'white on_blue' ,
93141 'name' : 'cyan on_blue bold' ,
@@ -117,7 +165,7 @@ def colors_of(key):
117165def 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