##// END OF EJS Templates
big cleanup of nbconvert.utils.pandoc module. Remove useless functions, less cached values.
Daniel B. Vasquez -
Show More
@@ -27,6 +27,7 b' from IPython.testing import decorators as dec'
27 27 # Classes and functions
28 28 #-----------------------------------------------------------------------------
29 29
30
30 31 class TestPandoc(TestsBase):
31 32 """Collection of Pandoc tests"""
32 33
@@ -36,30 +37,39 b' class TestPandoc(TestsBase):'
36 37
37 38 @dec.onlyif_cmds_exist('pandoc')
38 39 def test_pandoc_available(self):
39 """ Test behaviour of pandoc_available() """
40 """ Test behaviour that pandoc functions raise PandocMissing as documented """
41 pandoc.clean_cache()
42
40 43 os.environ["PATH"] = ""
41 assert not pandoc.pandoc_available()
42 try:
43 pandoc.pandoc_available(failmode="raise")
44 except pandoc.PandocMissing:
45 assert True
44 assert pandoc_function_raised_missing(pandoc.get_pandoc_version) == True
45 assert pandoc_function_raised_missing(pandoc.check_pandoc_version) == True
46 assert pandoc_function_raised_missing(pandoc.pandoc, "", "markdown", "html") == True
46 47
48 # original_env["PATH"] should contain pandoc
47 49 os.environ["PATH"] = self.original_env["PATH"]
48 assert pandoc.pandoc_available()
49 try:
50 pandoc.pandoc_available(failmode="raise")
51 except pandoc.PandocMissing:
52 assert False
50 assert pandoc_function_raised_missing(pandoc.get_pandoc_version) == False
51 assert pandoc_function_raised_missing(pandoc.check_pandoc_version) == False
52 assert pandoc_function_raised_missing(pandoc.pandoc, "", "markdown", "html") == False
53
53 54
54 55 @dec.onlyif_cmds_exist('pandoc')
55 56 def test_minimal_version(self):
56 original_minversion = pandoc.minimal_version
57 original_minversion = pandoc._minimal_version
57 58
58 pandoc.minimal_version = "120.0"
59 pandoc._minimal_version = "120.0"
59 60 assert not pandoc.check_pandoc_version()
60 61
61 pandoc.minimal_version = pandoc.get_pandoc_version()
62 pandoc._minimal_version = pandoc.get_pandoc_version()
62 63 assert pandoc.check_pandoc_version()
63 64
64 65
65 66
67
68 def pandoc_function_raised_missing(f, *args, **kwargs):
69 try:
70 f(*args, **kwargs)
71 except pandoc.PandocMissing as e:
72 print e
73 return True
74 else:
75 return False
@@ -22,7 +22,7 b' from io import TextIOWrapper, BytesIO'
22 22 # IPython imports
23 23 from IPython.utils.py3compat import cast_bytes
24 24 from IPython.utils.version import check_version
25 from IPython.utils.process import find_cmd, FindCmdError
25 from IPython.utils.process import is_cmd_found, FindCmdError
26 26
27 27
28 28 from .exceptions import ConversionException
@@ -30,12 +30,7 b' from .exceptions import ConversionException'
30 30 #-----------------------------------------------------------------------------
31 31 # Classes and functions
32 32 #-----------------------------------------------------------------------------
33 minimal_version = "1.12.1"
34
35 # command line to make pandoc print it's version. It is also the
36 # easiest way to make pandoc return at all.
37 __pandoc_version_call = ['pandoc', '-v']
38
33 _minimal_version = "1.12.1"
39 34
40 35 def pandoc(source, fmt, to, extra_args=None, encoding='utf-8'):
41 36 """Convert an input string in format `from` to format `to` via pandoc.
@@ -74,42 +69,6 b" def pandoc(source, fmt, to, extra_args=None, encoding='utf-8'):"
74 69 return out.rstrip('\n')
75 70
76 71
77 def pandoc_available(failmode="return", warn=False):
78 """Is pandoc available. Relies on `IPython.utils.process.find_cmd`.
79
80 Parameters
81 ----------
82 - failmode : string
83 either "return" or "raise". See below.
84 - warn : bool
85 issue a user warning if pandoc is not available.
86
87 Return
88 ------
89 out : (Bool, Exception)
90 On success will return True. On failure and failmode=="return"
91 will return False-valued PandocMissing instance. If failmode is
92 anything else, the function will not return but raise PandocMissing.
93 """
94
95 try:
96 find_cmd("pandoc")
97 return True
98 except FindCmdError as e:
99 if warn:
100 warnings.warn(
101 "Pandoc cannot be found (find_cmd('pandoc') failed).\n"+
102 "Please check that pandoc is installed:\n" +
103 "http://johnmacfarlane.net/pandoc/installing.html"
104 )
105
106 exc = PandocMissing("pandoc", e)
107 if failmode == "return":
108 return exc
109 else:
110 raise exc
111
112
113 72 def get_pandoc_version():
114 73 """Gets the Pandoc version if Pandoc is installed.
115 74
@@ -123,15 +82,18 b' def get_pandoc_version():'
123 82 ----------
124 83 PandocMissing will be raised if pandoc is unavailable.
125 84 """
85 global __version
126 86
127 if __cache['version_ok'] and __cache['version']:
128 return __cache['version']
87 if __version is not None:
88 return __version
129 89 else:
130 pandoc_available(failmode="raise")
131 out = subprocess.check_output(__pandoc_version_call, universal_newlines=True)
90 if not is_cmd_found('pandoc'):
91 raise PandocMissing()
92
93 out = subprocess.check_output( ['pandoc', '-v'], universal_newlines=True)
132 94 pv_re = re.compile(r'(\d{0,3}\.\d{0,3}\.\d{0,3})')
133 __cache['version'] = version = pv_re.search(out).group(0)
134 return version
95 __version = pv_re.search(out).group(0)
96 return __version
135 97
136 98
137 99 def check_pandoc_version():
@@ -141,52 +103,33 b' def check_pandoc_version():'
141 103 ----------
142 104 PandocMissing will be raised if pandoc is unavailable.
143 105 """
144 ok = __cache['version_ok']
106 v = get_pandoc_version()
107 ok = check_version(v , _minimal_version )
145 108 if not ok:
146 __cache['version_ok'] = ok = check_version( get_pandoc_version(), minimal_version )
147 if not ok:
148 warnings.warn( "You are using an old version of pandoc (%s)\n" % __cache['version'] +
149 "Recommended version is %s.\nTry updating." % minimal_version +
150 "http://johnmacfarlane.net/pandoc/installing.html.\nContinuing with doubts...",
151 RuntimeWarning, stacklevel=2)
152 return __cache['version_ok']
109 warnings.warn( "You are using an old version of pandoc (%s)\n" % v +
110 "Recommended version is %s.\nTry updating." % _minimal_version +
111 "http://johnmacfarlane.net/pandoc/installing.html.\nContinuing with doubts...",
112 RuntimeWarning, stacklevel=2)
113 return ok
153 114
154 115 #-----------------------------------------------------------------------------
155 116 # Exception handling
156 117 #-----------------------------------------------------------------------------
157 118 class PandocMissing(ConversionException):
158 119 """Exception raised when Pandoc is missing. """
159 def __init__(self, cmd, exc, *args, **kwargs):
160 super(PandocMissing, self).__init__( "The command '%s' returned an error: %s.\n" %(" ".join(cmd), exc) +
120 def __init__(self, *args, **kwargs):
121 super(PandocMissing, self).__init__( "Pandoc wasn't found.\n" +
161 122 "Please check that pandoc is installed:\n" +
162 123 "http://johnmacfarlane.net/pandoc/installing.html" )
163 self.exc = exc
164
165 def __bool__(self):
166 return False
167
168 __nonzero__ = __bool__
169
170 124
171 125 #-----------------------------------------------------------------------------
172 126 # Internal state management
173 127 #-----------------------------------------------------------------------------
174 def clean_cache(new=False):
175 if new:
176 global __cache
177 cache = {}
178 __cache = cache
179 else:
180 cache = __cache
181 cache.clear()
182
183 cache['version_ok'] = False
184 cache['version'] = None
185 return cache
186
187 # The following holds cache values about the pandoc executable.
188 __cache = clean_cache(new=True)
128 def clean_cache():
129 global __version
130 __version = None
189 131
132 __version = None
190 133
191 134
192 135
General Comments 0
You need to be logged in to leave comments. Login now