Update documentation of length units.
[docutils.git] / docutils / tools / quicktest.py
blob527ceab10228b5fd8f72a6829e1f46c2bc03be8d
1 #!/usr/bin/env python
3 # $Id$
4 # Authors: Garth Kidd <garth@deadlybloodyserious.com>;
5 # David Goodger <goodger@python.org>
6 # Copyright: This module has been placed in the public domain.
8 try:
9 import locale
10 locale.setlocale(locale.LC_ALL, '')
11 except:
12 pass
14 import sys
15 import os
16 import getopt
17 import docutils
18 from docutils.frontend import OptionParser
19 from docutils.utils import new_document
20 from docutils.parsers.rst import Parser
23 usage_header = """\
24 quicktest.py: Quickly test the reStructuredText parser. This is not an
25 interface to the full functionality of Docutils. Use one of the ``rst2*.py``
26 front-end tools instead.
28 Usage::
30 quicktest.py [options] [<source> [<destination>]]
32 ``source`` is the name of the file to use as input (default is stdin).
33 ``destination`` is the name of the file to create as output (default is
34 stdout).
36 Options:
37 """
39 options = [('pretty', 'p',
40 'output pretty pseudo-xml: no "&abc;" entities (default)'),
41 ('test', 't', 'output test-ready data (input & expected output, '
42 'ready to be copied to a parser test module)'),
43 ('rawxml', 'r', 'output raw XML'),
44 ('styledxml=', 's', 'output raw XML with XSL style sheet '
45 'reference (filename supplied in the option argument)'),
46 ('xml', 'x', 'output pretty XML (indented)'),
47 ('attributes', 'A', 'dump document attributes after processing'),
48 ('debug', 'd', 'debug mode (lots of output)'),
49 ('version', 'V', 'show Docutils version then exit'),
50 ('help', 'h', 'show help text then exit')]
51 """See ``distutils.fancy_getopt.FancyGetopt.__init__`` for a description of
52 the data structure: (long option, short option, description)."""
54 def usage():
55 print(usage_header)
56 for longopt, shortopt, description in options:
57 if longopt[-1:] == '=':
58 opts = '-%s arg, --%sarg' % (shortopt, longopt)
59 else:
60 opts = '-%s, --%s' % (shortopt, longopt)
61 sys.stdout.write('%-15s' % opts)
62 if len(opts) > 14:
63 sys.stdout.write('%-16s' % '\n')
64 while len(description) > 60:
65 limit = description.rindex(' ', 0, 60)
66 print(description[:limit].strip())
67 description = description[limit + 1:]
68 sys.stdout.write('%-15s' % ' ')
69 print(description)
71 def _pretty(input, document, optargs):
72 return document.pformat()
74 def _rawxml(input, document, optargs):
75 return document.asdom().toxml()
77 def _styledxml(input, document, optargs):
78 docnode = document.asdom().childNodes[0]
79 return '%s\n%s\n%s' % (
80 '<?xml version="1.0" encoding="ISO-8859-1"?>',
81 '<?xml-stylesheet type="text/xsl" href="%s"?>'
82 % optargs['styledxml'], docnode.toxml())
84 def _prettyxml(input, document, optargs):
85 return document.asdom().toprettyxml(' ', '\n')
87 def _test(input, document, optargs):
88 tq = '"""'
89 output = document.pformat() # same as _pretty()
90 return """\
91 totest['change_this_test_name'] = [
92 [%s\\
94 %s,
95 %s\\
97 %s],
99 """ % ( tq, escape(input.rstrip()), tq, tq, escape(output.rstrip()), tq )
101 def escape(text):
103 Return `text` in triple-double-quoted Python string form.
105 text = text.replace('\\', '\\\\') # escape backslashes
106 text = text.replace('"""', '""\\"') # break up triple-double-quotes
107 text = text.replace(' \n', ' \\n\\\n') # protect trailing whitespace
108 return text
110 _outputFormatters = {
111 'rawxml': _rawxml,
112 'styledxml': _styledxml,
113 'xml': _prettyxml,
114 'pretty' : _pretty,
115 'test': _test
118 def format(outputFormat, input, document, optargs):
119 formatter = _outputFormatters[outputFormat]
120 return formatter(input, document, optargs)
122 def getArgs():
123 if os.name == 'mac' and len(sys.argv) <= 1:
124 return macGetArgs()
125 else:
126 return posixGetArgs(sys.argv[1:])
128 def posixGetArgs(argv):
129 outputFormat = 'pretty'
130 # convert fancy_getopt style option list to getopt.getopt() arguments
131 shortopts = ''.join([option[1] + ':' * (option[0][-1:] == '=')
132 for option in options if option[1]])
133 longopts = [option[0] for option in options if option[0]]
134 try:
135 opts, args = getopt.getopt(argv, shortopts, longopts)
136 except getopt.GetoptError:
137 usage()
138 sys.exit(2)
139 optargs = {'debug': 0, 'attributes': 0}
140 for o, a in opts:
141 if o in ['-h', '--help']:
142 usage()
143 sys.exit()
144 elif o in ['-V', '--version']:
145 sys.stderr.write('quicktest.py (Docutils %s%s)\n' %
146 (docutils.__version__,
147 docutils.__version_details__ and
148 ' [%s]'%docutils.__version_details__ or ''))
149 sys.exit()
150 elif o in ['-r', '--rawxml']:
151 outputFormat = 'rawxml'
152 elif o in ['-s', '--styledxml']:
153 outputFormat = 'styledxml'
154 optargs['styledxml'] = a
155 elif o in ['-x', '--xml']:
156 outputFormat = 'xml'
157 elif o in ['-p', '--pretty']:
158 outputFormat = 'pretty'
159 elif o in ['-t', '--test']:
160 outputFormat = 'test'
161 elif o in ['--attributes', '-A']:
162 optargs['attributes'] = 1
163 elif o in ['-d', '--debug']:
164 optargs['debug'] = 1
165 else:
166 raise getopt.GetoptError("getopt should have saved us!")
167 if len(args) > 2:
168 print('Maximum 2 arguments allowed.')
169 usage()
170 sys.exit(1)
171 inputFile = sys.stdin
172 outputFile = sys.stdout
173 if args:
174 inputFile = open(args.pop(0))
175 if args:
176 outputFile = open(args.pop(0), 'w')
177 return inputFile, outputFile, outputFormat, optargs
179 def macGetArgs():
180 import EasyDialogs
181 EasyDialogs.Message("""\
182 Use the next dialog to build a command line:
184 1. Choose an output format from the [Option] list
185 2. Click [Add]
186 3. Choose an input file: [Add existing file...]
187 4. Save the output: [Add new file...]
188 5. [OK]""")
189 optionlist = [(longopt, description)
190 for (longopt, shortopt, description) in options]
191 argv = EasyDialogs.GetArgv(optionlist=optionlist, addfolder=0)
192 return posixGetArgs(argv)
194 def main():
195 # process cmdline arguments:
196 inputFile, outputFile, outputFormat, optargs = getArgs()
197 settings = OptionParser(components=(Parser,)).get_default_values()
198 settings.debug = optargs['debug']
199 parser = Parser()
200 input = inputFile.read()
201 document = new_document(inputFile.name, settings)
202 parser.parse(input, document)
203 output = format(outputFormat, input, document, optargs)
204 outputFile.write(output)
205 if optargs['attributes']:
206 import pprint
207 pprint.pprint(document.__dict__)
210 if __name__ == '__main__':
211 sys.stderr = sys.stdout
212 main()