Release 0.11: set __version_details__ to "repository"
[docutils.git] / tools / quicktest.py
blob70df51ca43ef406bee36483a37bb9cedb548b5e1
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__))
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 in ['--attributes', '-A']:
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()