| 1 |
#!/usr/bin/env python3 |
| 2 |
""" |
| 3 |
Parse a reST file into HTML in a very forgiving way. |
| 4 |
|
| 5 |
The script is meant to render specialized reST documents, such as Sphinx |
| 6 |
files, preserving the content, while not emulating the original rendering. |
| 7 |
|
| 8 |
The script is currently tested against docutils 0.7-0.10. Other versions may |
| 9 |
break it as it deals with the parser at a relatively low level. Use |
| 10 |
--test-patch to verify if the script works as expected with your library |
| 11 |
version. |
| 12 |
""" |
| 13 |
|
| 14 |
import sys |
| 15 |
|
| 16 |
import docutils |
| 17 |
from docutils import nodes, utils, SettingsSpec |
| 18 |
from docutils.core import publish_cmdline, publish_string, default_description |
| 19 |
from docutils.parsers.rst import Directive, directives, roles |
| 20 |
from docutils.writers.html4css1 import HTMLTranslator, Writer |
| 21 |
from docutils.parsers.rst.states import Body, Inliner |
| 22 |
from docutils.frontend import validate_boolean |
| 23 |
|
| 24 |
class any_directive(nodes.General, nodes.FixedTextElement): |
| 25 |
"""A generic directive to deal with any unknown directive we may find.""" |
| 26 |
pass |
| 27 |
|
| 28 |
class AnyDirective(Directive): |
| 29 |
"""A directive returning its unaltered body.""" |
| 30 |
optional_arguments = 100 # should suffice |
| 31 |
has_content = True |
| 32 |
|
| 33 |
def run(self): |
| 34 |
if self.name in self.state.document.settings.dir_ignore: |
| 35 |
return [] |
| 36 |
|
| 37 |
children = [] |
| 38 |
|
| 39 |
if self.name not in self.state.document.settings.dir_notitle: |
| 40 |
children.append(nodes.strong(self.name, "%s: " % self.name)) |
| 41 |
# keep the arguments, drop the options |
| 42 |
for a in self.arguments: |
| 43 |
if a.startswith(':') and a.endswith(':'): |
| 44 |
break |
| 45 |
children.append(nodes.emphasis(a, "%s " % a)) |
| 46 |
|
| 47 |
if self.name in self.state.document.settings.dir_nested: |
| 48 |
if self.content: |
| 49 |
container = nodes.Element() |
| 50 |
self.state.nested_parse(self.content, self.content_offset, |
| 51 |
container) |
| 52 |
children.extend(container.children) |
| 53 |
else: |
| 54 |
content = '\n'.join(self.content) |
| 55 |
children.append(nodes.literal_block(content, content)) |
| 56 |
|
| 57 |
node = any_directive(self.block_text, '', *children, dir_name=self.name) |
| 58 |
|
| 59 |
return [node] |
| 60 |
|
| 61 |
|
| 62 |
class any_role(nodes.Inline, nodes.TextElement): |
| 63 |
"""A generic role to deal with any unknown role we may find.""" |
| 64 |
pass |
| 65 |
|
| 66 |
class AnyRole: |
| 67 |
"""A role to be rendered as a generic element with a specific class.""" |
| 68 |
def __init__(self, role_name): |
| 69 |
self.role_name = role_name |
| 70 |
|
| 71 |
def __call__(self, role, rawtext, text, lineno, inliner, |
| 72 |
options={}, content=[]): |
| 73 |
roles.set_classes(options) |
| 74 |
options['role_name'] = self.role_name |
| 75 |
node = any_role(rawtext, utils.unescape(text), **options) |
| 76 |
return [node], [] |
| 77 |
|
| 78 |
|
| 79 |
def catchall_directive(self, match, **option_presets): |
| 80 |
"""Directive dispatch method. |
| 81 |
|
| 82 |
Replacement for Body.directive(): if a directive is not known, build one |
| 83 |
on the fly instead of reporting an error. |
| 84 |
""" |
| 85 |
type_name = match.group(1) |
| 86 |
directive_class, messages = directives.directive( |
| 87 |
type_name, self.memo.language, self.document) |
| 88 |
|
| 89 |
# in case it's missing, register a generic directive |
| 90 |
if not directive_class: |
| 91 |
directives.register_directive(type_name, AnyDirective) |
| 92 |
directive_class, messages = directives.directive( |
| 93 |
type_name, self.memo.language, self.document) |
| 94 |
assert directive_class, "can't find just defined directive" |
| 95 |
|
| 96 |
self.parent += messages |
| 97 |
return self.run_directive( |
| 98 |
directive_class, match, type_name, option_presets) |
| 99 |
|
| 100 |
|
| 101 |
def catchall_interpreted(self, rawsource, text, role, lineno): |
| 102 |
"""Interpreted text role dispatch method. |
| 103 |
|
| 104 |
Replacement for Inliner.interpreted(): if a role is not known, build one |
| 105 |
on the fly instead of reporting an error. |
| 106 |
""" |
| 107 |
role_fn, messages = roles.role(role, self.language, lineno, |
| 108 |
self.reporter) |
| 109 |
# in case it's missing, register a generic role |
| 110 |
if not role_fn: |
| 111 |
role_obj = AnyRole(role) |
| 112 |
roles.register_canonical_role(role, role_obj) |
| 113 |
role_fn, messages = roles.role( |
| 114 |
role, self.language, lineno, self.reporter) |
| 115 |
assert role_fn, "can't find just defined role" |
| 116 |
|
| 117 |
nodes, messages2 = role_fn(role, rawsource, text, lineno, self) |
| 118 |
return nodes, messages + messages2 |
| 119 |
|
| 120 |
|
| 121 |
def patch_docutils(): |
| 122 |
"""Change the docutils parser behaviour.""" |
| 123 |
# Patch the constructs dispatch table |
| 124 |
for i, (f, p) in enumerate(Body.explicit.constructs): |
| 125 |
if f is Body.directive is f: |
| 126 |
Body.explicit.constructs[i] = (catchall_directive, p) |
| 127 |
break |
| 128 |
else: |
| 129 |
assert False, "can't find directive dispatch entry" |
| 130 |
|
| 131 |
# Patch the parser so that when an unknown directive is found, a generic one |
| 132 |
# is generated on the fly. |
| 133 |
Body.directive = catchall_directive |
| 134 |
|
| 135 |
# Patch the parser so that when an unknown interpreted text role is found, |
| 136 |
# a generic one is generated on the fly. |
| 137 |
Inliner.interpreted = catchall_interpreted |
| 138 |
|
| 139 |
|
| 140 |
class MyTranslator(HTMLTranslator): |
| 141 |
"""An HTML translator that can render with any_role/any_directive. |
| 142 |
""" |
| 143 |
def visit_any_directive(self, node): |
| 144 |
cls = node.get('dir_name') |
| 145 |
cls = cls and 'directive-%s' % cls or 'directive' |
| 146 |
self.body.append(self.starttag(node, 'div', CLASS=cls)) |
| 147 |
|
| 148 |
def depart_any_directive(self, node): |
| 149 |
self.body.append('\n</div>\n') |
| 150 |
|
| 151 |
def visit_any_role(self, node): |
| 152 |
cls = node.get('role_name') |
| 153 |
cls = cls and 'role-%s' % cls or 'role' |
| 154 |
self.body.append(self.starttag(node, 'span', '', CLASS=cls)) |
| 155 |
|
| 156 |
def depart_any_role(self, node): |
| 157 |
self.body.append('</span>') |
| 158 |
|
| 159 |
|
| 160 |
class LenientSettingsSpecs(SettingsSpec): |
| 161 |
settings_spec = ("Lenient parsing options", None, ( |
| 162 |
("Directive whose content should be interpreted as reST. " |
| 163 |
"By default emit the content as unparsed text block. " |
| 164 |
"Can be specified more than once", |
| 165 |
["--dir-nested"], |
| 166 |
{'metavar': 'NAME', 'default': [], 'action': 'append'}), |
| 167 |
("Directive that should produce no output. " |
| 168 |
"Can be specified more than once", |
| 169 |
["--dir-ignore"], |
| 170 |
{'metavar': 'NAME', 'default': [], 'action': 'append'}), |
| 171 |
("Only emit the content of the directive, no title and options. " |
| 172 |
"Can be specified more than once", |
| 173 |
["--dir-notitle"], |
| 174 |
{'metavar': 'NAME', 'default': [], 'action': 'append'}), |
| 175 |
("Verify that lenient customization works fine. " |
| 176 |
"Immediately return with 0 (success) or 1 (error). " |
| 177 |
"In case of error, print a report on stdout.", |
| 178 |
['--test-patch'], |
| 179 |
{'action': 'store_true', 'validator': validate_boolean}), |
| 180 |
)) |
| 181 |
|
| 182 |
|
| 183 |
def main(): |
| 184 |
|
| 185 |
# Create a writer to deal with the generic element we may have created. |
| 186 |
writer = Writer() |
| 187 |
writer.translator_class = MyTranslator |
| 188 |
|
| 189 |
description = ( |
| 190 |
'Generates (X)HTML documents from standalone reStructuredText ' |
| 191 |
'sources. Be forgiving against unknown elements. ' |
| 192 |
+ default_description) |
| 193 |
|
| 194 |
# the parser processes the settings too late: we want to decide earlier if |
| 195 |
# we are running or testing. |
| 196 |
if ('--test-patch' in sys.argv |
| 197 |
and not ('-h' in sys.argv or '--help' in sys.argv)): |
| 198 |
return test_patch(writer) |
| 199 |
|
| 200 |
else: |
| 201 |
# Make docutils lenient. |
| 202 |
patch_docutils() |
| 203 |
|
| 204 |
overrides = { |
| 205 |
# If Pygments is missing, code-block directives are swallowed |
| 206 |
# with Docutils >= 0.9. |
| 207 |
'syntax_highlight': 'none', |
| 208 |
|
| 209 |
# not available on Docutils < 0.8 so can't pass as an option |
| 210 |
'math_output': 'HTML', |
| 211 |
} |
| 212 |
|
| 213 |
publish_cmdline(writer=writer, description=description, |
| 214 |
settings_spec=LenientSettingsSpecs, settings_overrides=overrides) |
| 215 |
return 0 |
| 216 |
|
| 217 |
def test_patch(writer): |
| 218 |
"""Verify that patching docutils works as expected.""" |
| 219 |
TEST_SOURCE = """` |
| 220 |
Hello `role`:norole: |
| 221 |
|
| 222 |
.. nodirective:: |
| 223 |
""" |
| 224 |
rv = 0 |
| 225 |
problems = [] |
| 226 |
exc = None |
| 227 |
|
| 228 |
# patch and use lenient docutils |
| 229 |
try: |
| 230 |
try: |
| 231 |
patch_docutils() |
| 232 |
except Exception as exc: |
| 233 |
problems.append("error during library patching") |
| 234 |
raise |
| 235 |
|
| 236 |
try: |
| 237 |
out = publish_string(TEST_SOURCE, |
| 238 |
writer=writer, settings_spec=LenientSettingsSpecs, |
| 239 |
settings_overrides={'output_encoding': 'unicode'}) |
| 240 |
except Exception as exc: |
| 241 |
problems.append("error while running patched docutils") |
| 242 |
raise |
| 243 |
|
| 244 |
except: |
| 245 |
pass |
| 246 |
|
| 247 |
# verify conform output |
| 248 |
else: |
| 249 |
out = out.replace("'", '"') |
| 250 |
if '<span class="role-norole">' not in out: |
| 251 |
problems.append( |
| 252 |
"unknown role didn't produce the expected output") |
| 253 |
|
| 254 |
if '<div class="directive-nodirective">' not in out: |
| 255 |
problems.append( |
| 256 |
"unknown directive didn't produce the expected output") |
| 257 |
|
| 258 |
# report problems if any |
| 259 |
if problems: |
| 260 |
rv = 1 |
| 261 |
print("Patching docutils failed!", file=sys.stderr) |
| 262 |
for problem in problems: |
| 263 |
print("-", problem, file=sys.stderr) |
| 264 |
|
| 265 |
if rv: |
| 266 |
print("\nVersions:", \ |
| 267 |
'docutils:', docutils.__version__, docutils.__version_details__, \ |
| 268 |
'\nPython:', sys.version, file=sys.stderr) |
| 269 |
|
| 270 |
if exc: |
| 271 |
if '--traceback' in sys.argv: |
| 272 |
print(file=sys.stderr) |
| 273 |
import traceback |
| 274 |
traceback.print_exc() |
| 275 |
else: |
| 276 |
print("\nUse --traceback to display the error stack trace.", file=sys.stderr) |
| 277 |
|
| 278 |
return rv |
| 279 |
|
| 280 |
if __name__ == '__main__': |
| 281 |
sys.exit(main()) |
| 282 |
|