quicktest.py 6.8 KB

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