| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
""" |
| 9 |
The ``quicktest.py`` tool is used for testing the reStructuredText |
| 10 |
parser. It does not use a Docutils Reader or Writer or the standard |
| 11 |
Docutils command-line options. Rather, it does its own I/O and calls |
| 12 |
the parser directly. No transforms are applied to the parsed |
| 13 |
document. Possible output forms output include: |
| 14 |
|
| 15 |
--pretty Pretty-printed pseudo-XML (default) |
| 16 |
|
| 17 |
--test Test data (Python list of input and pseudo-XML output strings; |
| 18 |
useful for creating new test cases) |
| 19 |
--xml Pretty-printed native XML |
| 20 |
--rawxml Raw native XML (with or without a stylesheet reference) |
| 21 |
--help Usage hint and complete list of supported options. |
| 22 |
|
| 23 |
.. Caution:: ``quicktest.py`` uses Python's default encoding. |
| 24 |
Input and output encoding depend on UTF-8 mode, |
| 25 |
Python version, locale setting, and operating system |
| 26 |
(cf. :PEP:`540`, :PEP:`538`, :PEP:`597`, and :PEP:`686`). |
| 27 |
""" |
| 28 |
|
| 29 |
from __future__ import annotations |
| 30 |
|
| 31 |
try: |
| 32 |
import locale |
| 33 |
locale.setlocale(locale.LC_ALL, '') |
| 34 |
except Exception: |
| 35 |
pass |
| 36 |
|
| 37 |
import getopt |
| 38 |
import sys |
| 39 |
|
| 40 |
import docutils |
| 41 |
from docutils import frontend |
| 42 |
from docutils.utils import new_document |
| 43 |
from docutils.parsers.rst import Parser |
| 44 |
|
| 45 |
TYPE_CHECKING = False |
| 46 |
if TYPE_CHECKING: |
| 47 |
from collections.abc import Callable |
| 48 |
from typing import TextIO, TypedDict |
| 49 |
|
| 50 |
from docutils import nodes |
| 51 |
|
| 52 |
class _OptArgs(TypedDict): |
| 53 |
debug: bool |
| 54 |
attributes: bool |
| 55 |
styledxml: str |
| 56 |
|
| 57 |
_FormatFunc = Callable[[str, nodes.document, _OptArgs], str] |
| 58 |
|
| 59 |
|
| 60 |
usage_header = """\ |
| 61 |
quicktest.py: Quickly test the reStructuredText parser. This is not an |
| 62 |
interface to the full functionality of Docutils. Use one of the ``rst2*.py`` |
| 63 |
front-end tools instead. |
| 64 |
|
| 65 |
Usage:: |
| 66 |
|
| 67 |
quicktest.py [options] [<source> [<destination>]] |
| 68 |
|
| 69 |
``source`` is the name of the file to use as input (default is stdin). |
| 70 |
``destination`` is the name of the file to create as output (default is |
| 71 |
stdout). |
| 72 |
|
| 73 |
Options: |
| 74 |
""" |
| 75 |
|
| 76 |
options = [('pretty', 'p', |
| 77 |
'output pretty pseudo-xml: no "&abc;" entities (default)'), |
| 78 |
('test', 't', 'output test-ready data (input & expected output, ' |
| 79 |
'ready to be copied to a parser test module)'), |
| 80 |
('rawxml', 'r', 'output raw XML'), |
| 81 |
('styledxml=', 's', 'output raw XML with XSL style sheet ' |
| 82 |
'reference (filename supplied in the option argument)'), |
| 83 |
('xml', 'x', 'output pretty XML (indented)'), |
| 84 |
('attributes', 'A', 'dump document attributes after processing'), |
| 85 |
('debug', 'd', 'debug mode (lots of output)'), |
| 86 |
('version', 'V', 'show Docutils version then exit'), |
| 87 |
('help', 'h', 'show help text then exit')] |
| 88 |
"""See ``distutils.fancy_getopt.FancyGetopt.__init__`` for a description of |
| 89 |
the data structure: (long option, short option, description).""" |
| 90 |
|
| 91 |
|
| 92 |
def usage() -> None: |
| 93 |
print(usage_header) |
| 94 |
for longopt, shortopt, description in options: |
| 95 |
if longopt[-1:] == '=': |
| 96 |
opts = '-%s arg, --%sarg' % (shortopt, longopt) |
| 97 |
else: |
| 98 |
opts = '-%s, --%s' % (shortopt, longopt) |
| 99 |
sys.stdout.write('%-15s' % opts) |
| 100 |
if len(opts) > 14: |
| 101 |
sys.stdout.write('%-16s' % '\n') |
| 102 |
while len(description) > 60: |
| 103 |
limit = description.rindex(' ', 0, 60) |
| 104 |
print(description[:limit].strip()) |
| 105 |
description = description[limit + 1:] |
| 106 |
sys.stdout.write('%-15s' % ' ') |
| 107 |
print(description) |
| 108 |
|
| 109 |
|
| 110 |
def _pretty(input_: str, document: nodes.document, optargs: _OptArgs) -> str: |
| 111 |
return document.pformat() |
| 112 |
|
| 113 |
|
| 114 |
def _rawxml(input_: str, document: nodes.document, optargs: _OptArgs) -> str: |
| 115 |
return document.asdom().toxml() |
| 116 |
|
| 117 |
|
| 118 |
def _styledxml(input_: str, document: nodes.document, optargs: _OptArgs |
| 119 |
) -> str: |
| 120 |
docnode = document.asdom().childNodes[0] |
| 121 |
return '\n'.join(('<?xml version="1.0" encoding="ISO-8859-1"?>', |
| 122 |
'<?xml-stylesheet type="text/xsl" href="%s"?>' |
| 123 |
% optargs['styledxml'], |
| 124 |
docnode.toxml())) |
| 125 |
|
| 126 |
|
| 127 |
def _prettyxml(input_: str, document: nodes.document, optargs: _OptArgs |
| 128 |
) -> str: |
| 129 |
return document.asdom().toprettyxml(' ', '\n') |
| 130 |
|
| 131 |
|
| 132 |
def _test(input_: str, document: nodes.document, optargs: _OptArgs) -> str: |
| 133 |
tq = '"""' |
| 134 |
output = document.pformat() |
| 135 |
return """\ |
| 136 |
totest['change_this_test_name'] = [ |
| 137 |
[%s\\ |
| 138 |
%s |
| 139 |
%s, |
| 140 |
%s\\ |
| 141 |
%s |
| 142 |
%s], |
| 143 |
] |
| 144 |
""" % (tq, escape(input_.rstrip()), tq, tq, escape(output.rstrip()), tq) |
| 145 |
|
| 146 |
|
| 147 |
def escape(text: str) -> str: |
| 148 |
""" |
| 149 |
Return `text` in triple-double-quoted Python string form. |
| 150 |
""" |
| 151 |
text = text.replace('\\', '\\\\') |
| 152 |
text = text.replace('"""', '""\\"') |
| 153 |
text = text.replace(' \n', ' \\n\\\n') |
| 154 |
return text |
| 155 |
|
| 156 |
|
| 157 |
_output_formatters: dict[str, _FormatFunc] = { |
| 158 |
'rawxml': _rawxml, |
| 159 |
'styledxml': _styledxml, |
| 160 |
'xml': _prettyxml, |
| 161 |
'pretty': _pretty, |
| 162 |
'test': _test, |
| 163 |
} |
| 164 |
|
| 165 |
|
| 166 |
def format(output_format: str, |
| 167 |
input_: str, |
| 168 |
document: nodes.document, |
| 169 |
optargs: _OptArgs, |
| 170 |
) -> str: |
| 171 |
formatter = _output_formatters[output_format] |
| 172 |
return formatter(input_, document, optargs) |
| 173 |
|
| 174 |
|
| 175 |
def posix_get_args(argv: list[str]) -> tuple[TextIO, TextIO, str, _OptArgs]: |
| 176 |
output_format = 'pretty' |
| 177 |
|
| 178 |
shortopts = ''.join(option[1] + ':' * (option[0][-1:] == '=') |
| 179 |
for option in options if option[1]) |
| 180 |
longopts = [option[0] for option in options if option[0]] |
| 181 |
try: |
| 182 |
opts, args = getopt.getopt(argv, shortopts, longopts) |
| 183 |
except getopt.GetoptError: |
| 184 |
usage() |
| 185 |
sys.exit(2) |
| 186 |
optargs = {'debug': False, 'attributes': False} |
| 187 |
for o, a in opts: |
| 188 |
if o in ['-h', '--help']: |
| 189 |
usage() |
| 190 |
sys.exit() |
| 191 |
elif o in ['-V', '--version']: |
| 192 |
sys.stderr.write('quicktest.py (Docutils %s%s)\n' % |
| 193 |
(docutils.__version__, |
| 194 |
docutils.__version_details__ |
| 195 |
and ' [%s]'%docutils.__version_details__ or '')) |
| 196 |
sys.exit() |
| 197 |
elif o in ['-r', '--rawxml']: |
| 198 |
output_format = 'rawxml' |
| 199 |
elif o in ['-s', '--styledxml']: |
| 200 |
output_format = 'styledxml' |
| 201 |
optargs['styledxml'] = a |
| 202 |
elif o in ['-x', '--xml']: |
| 203 |
output_format = 'xml' |
| 204 |
elif o in ['-p', '--pretty']: |
| 205 |
output_format = 'pretty' |
| 206 |
elif o in ['-t', '--test']: |
| 207 |
output_format = 'test' |
| 208 |
elif o in ['--attributes', '-A']: |
| 209 |
optargs['attributes'] = True |
| 210 |
elif o in ['-d', '--debug']: |
| 211 |
optargs['debug'] = True |
| 212 |
else: |
| 213 |
raise getopt.GetoptError("getopt should have saved us!") |
| 214 |
if len(args) > 2: |
| 215 |
print('Maximum 2 arguments allowed.') |
| 216 |
usage() |
| 217 |
sys.exit(1) |
| 218 |
input_file = sys.stdin |
| 219 |
output_file = sys.stdout |
| 220 |
if args: |
| 221 |
input_file = open(args.pop(0)) |
| 222 |
if args: |
| 223 |
output_file = open(args.pop(0), 'w') |
| 224 |
return input_file, output_file, output_format, optargs |
| 225 |
|
| 226 |
|
| 227 |
def main() -> None: |
| 228 |
|
| 229 |
( |
| 230 |
input_file, output_file, output_format, optargs, |
| 231 |
) = posix_get_args(sys.argv[1:]) |
| 232 |
settings = frontend.get_default_settings(Parser) |
| 233 |
settings.debug = optargs['debug'] |
| 234 |
parser = Parser() |
| 235 |
input_ = input_file.read() |
| 236 |
document = new_document(input_file.name, settings) |
| 237 |
parser.parse(input_, document) |
| 238 |
output = format(output_format, input_, document, optargs) |
| 239 |
output_file.write(output) |
| 240 |
if optargs['attributes']: |
| 241 |
import pprint |
| 242 |
pprint.pprint(document.__dict__) |
| 243 |
|
| 244 |
|
| 245 |
if __name__ == '__main__': |
| 246 |
sys.stderr = sys.stdout |
| 247 |
main() |