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