Prepare packaging with flit.
[pylit.git] / pylit.py
blob6a9bbb721de3561f95e3091a4d3d3a857a1e381a
1 #!/usr/bin/env python
2 # -*- coding: utf8 -*-
4 """pylit: bidirectional text <-> code converter
6 Covert between a *text source* with embedded computer code
7 and a *code source* with embedded documentation.
8 """
10 from __future__ import print_function
12 # pylit.py
13 # ********
14 # Literate programming with reStructuredText
15 # ++++++++++++++++++++++++++++++++++++++++++
17 # :Copyright: © 2005, 2007, 2015, 2021 Günter Milde.
18 # Released without warranty under the terms of the
19 # GNU General Public License (v. 3 or later)
21 # .. contents::
23 # Frontmatter
24 # ===========
26 # Changelog
27 # ---------
29 # .. class:: borderless
31 # ====== ========== ==========================================================
32 # 0.1 2005-06-29 Initial version.
33 # 0.1.1 2005-06-30 First literate version.
34 # 0.1.2 2005-07-01 Object oriented script using generators.
35 # 0.1.3 2005-07-10 Two state machine (later added 'header' state).
36 # 0.2b 2006-12-04 Start of work on version 0.2 (code restructuring).
37 # 0.2 2007-01-23 Published at ``pylit.berlios.de``.
38 # 0.2.1 2007-01-25 Outsourced non-core documentation to the PyLit pages.
39 # 0.2.2 2007-01-26 New behaviour of `diff` function.
40 # 0.2.3 2007-01-29 New `header` methods after suggestion by Riccardo Murri.
41 # 0.2.4 2007-01-31 Raise Error if code indent is too small.
42 # 0.2.5 2007-02-05 New command line option --comment-string.
43 # 0.2.6 2007-02-09 Add section with open questions,
44 # Code2Text: let only blank lines (no comment str)
45 # separate text and code,
46 # fix `Code2Text.header`.
47 # 0.2.7 2007-02-19 Simplify `Code2Text.header`,
48 # new `iter_strip` method replacing a lot of ``if``-s.
49 # 0.2.8 2007-02-22 Set `mtime` of outfile to the one of infile.
50 # 0.3 2007-02-27 New `Code2Text` converter after an idea by Riccardo Murri,
51 # explicit `option_defaults` dict for easier customisation.
52 # 0.3.1 2007-03-02 Expand hard-tabs to prevent errors in indentation,
53 # `Text2Code` now also works on blocks,
54 # removed dependency on SimpleStates module.
55 # 0.3.2 2007-03-06 Bug fix: do not set `language` in `option_defaults`
56 # renamed `code_languages` to `languages`.
57 # 0.3.3 2007-03-16 New language css,
58 # option_defaults -> defaults = optparse.Values(),
59 # simpler PylitOptions: don't store parsed values,
60 # don't parse at initialisation,
61 # OptionValues: return `None` for non-existing attributes,
62 # removed -infile and -outfile, use positional arguments.
63 # 0.3.4 2007-03-19 Documentation update,
64 # separate `execute` function.
65 # 2007-03-21 Code cleanup in `Text2Code.__iter__`.
66 # 0.3.5 2007-03-23 Removed "css" from known languages after learning that
67 # there is no C++ style "// " comment string in CSS2.
68 # 0.3.6 2007-04-24 Documentation update.
69 # 0.4 2007-05-18 Implement Converter.__iter__ as stack of iterator
70 # generators. Iterating over a converter instance now
71 # yields lines instead of blocks.
72 # Provide "hooks" for pre- and postprocessing filters.
73 # Rename states to reduce confusion with formats:
74 # "text" -> "documentation", "code" -> "code_block".
75 # 0.4.1 2007-05-22 Converter.__iter__: cleanup and reorganisation,
76 # rename parent class Converter -> TextCodeConverter.
77 # 0.4.2 2007-05-23 Merged Text2Code.converter and Code2Text.converter into
78 # TextCodeConverter.converter.
79 # 0.4.3 2007-05-30 Replaced use of defaults.code_extensions with
80 # values.languages.keys().
81 # Removed spurious `print` statement in code_block_handler.
82 # Added basic support for 'c' and 'css' languages
83 # with `dumb_c_preprocessor`_ and `dumb_c_postprocessor`_.
84 # 0.5 2007-06-06 Moved `collect_blocks`_ out of `TextCodeConverter`_,
85 # bug fix: collect all trailing blank lines into a block.
86 # Expand tabs with `expandtabs_filter`_.
87 # 0.6 2007-06-20 Configurable code-block marker (default ``::``)
88 # 0.6.1 2007-06-28 Bug fix: reset self.code_block_marker_missing.
89 # 0.7 2007-12-12 prepending an empty string to sys.path in run_doctest()
90 # to allow imports from the current working dir.
91 # 0.7.1 2008-01-07 If outfile does not exist, do a round-trip conversion
92 # and report differences (as with outfile=='-').
93 # 0.7.2 2008-01-28 Do not add missing code-block separators with
94 # `doctest_run` on the code source. Keeps lines consistent.
95 # 0.7.3 2008-04-07 Use value of code_block_marker for insertion of missing
96 # transition marker in Code2Text.code_block_handler
97 # Add "shell" to defaults.languages
98 # 0.7.4 2008-06-23 Add "latex" to defaults.languages
99 # 0.7.5 2009-05-14 Bugfix: ignore blank lines in test for end of code block
100 # 0.7.6 2009-12-15 language-dependent code-block markers (after a
101 # feature request and patch by `jrioux`),
102 # use DefaultDict for language-dependent defaults,
103 # new defaults setting `add_missing_marker`_.
104 # 0.7.7 2010-06-23 New command line option --codeindent.
105 # 0.7.8 2011-03-30 Do not overwrite custom `add_missing_marker` value,
106 # allow directive options following the 'code' directive.
107 # 0.7.9 2011-04-05 Decode doctest string if 'magic comment' gives encoding.
108 # 0.7.10 2013-06-07 Add "lua" to defaults.languages
109 # 0.7.11 2020-10-10 Return 0, if input and output file are of same age.
110 # 0.8.0 unpublishd Fix ``--execute`` behaviour and tests.
111 # Use collections.defaultdict.
112 # Change default `codeindent` to 2.
113 # ====== ========== ==========================================================
115 # ::
117 __version__ = "0.8.0dev"
119 __docformat__ = 'restructuredtext'
122 # Introduction
123 # ------------
125 # PyLit is a bidirectional converter between two formats of a computer
126 # program source:
128 # * a (reStructured) text document with program code embedded in
129 # *code blocks*, and
130 # * a compilable (or executable) code source with *documentation*
131 # embedded in comment blocks
134 # Requirements
135 # ------------
137 # ::
139 #import argparse
140 from collections import defaultdict
141 import optparse
142 import os
143 import re
144 import sys
147 # defaults
148 # ========
150 # The `defaults` object provides a central repository for default
151 # values and their customisation. ::
153 defaults = optparse.Values()
155 # It is used for
157 # * the initialisation of data arguments in TextCodeConverter_ and
158 # PylitOptions_
160 # * completion of command line options in `PylitOptions.complete_values`_.
162 # This allows the easy creation of back-ends that customise the
163 # defaults and then call `main`_ e.g.:
165 # >>> import pylit
166 # >>> pylit.defaults.comment_string = "## "
167 # >>> pylit.defaults.codeindent = 4
168 # >>> pylit.main()
169 # 0 failures in 0 tests
170 # (0, 0)
172 # The following default values are defined in pylit.py:
174 # languages
175 # ---------
177 # Mapping of code file extensions to code language::
179 defaults.languages = defaultdict(lambda: "python", # fallback language
180 {".c": "c",
181 ".cc": "c++",
182 ".css": "css",
183 ".lua": "lua",
184 ".py": "python",
185 ".sh": "shell",
186 ".sl": "slang",
187 ".sty": "latex",
188 ".tex": "latex"
191 # The result can be overridden by the ``--language`` command line option.
193 # The fallback language, used if there is no matching extension (e.g. if pylit
194 # is used as filter) and no ``--language`` is specified is ``"python"``.
195 # It can be changed programmatically by changing the ``.default_factory``
196 # attribute, e.g.
198 # >>> pylit.defaults.languages['.parrot']
199 # 'python'
200 # >>> pylit.defaults.languages.default_factory= lambda: 'c++'
201 # >>> pylit.defaults.languages['.camel']
202 # 'c++'
204 # .. _text_extension:
206 # text_extensions
207 # ---------------
209 # List of known extensions of (reStructured) text files. The first
210 # extension in this list is used by the `_get_outfile_name`_ method to
211 # generate a text output filename::
213 defaults.text_extensions = [".txt", ".rst"]
216 # comment_strings
217 # ---------------
219 # Comment strings for known languages. Used in Code2Text_ to recognise
220 # text blocks and in Text2Code_ to format text blocks as comments.
221 # Defaults to ``'# '``.
223 # **Comment strings include trailing whitespace.** ::
225 defaults.comment_strings = defaultdict(lambda: '# ',
226 {"css": '// ',
227 "c": '// ',
228 "c++": '// ',
229 "lua": '-- ',
230 "latex": '% ',
231 "python": '# ',
232 "shell": '# ',
233 "slang": '% '
237 # header_string
238 # -------------
240 # Marker string for a header code block in the text source. No trailing
241 # whitespace needed as indented code follows.
242 # Must be a valid rst directive that accepts code on the same line, e.g.
243 # ``'..admonition::'``.
245 # Default is a comment marker::
247 defaults.header_string = '..'
250 # .. _code_block_marker:
252 # code_block_markers
253 # ------------------
255 # Markup at the end of a documentation block.
256 # Default is Docutils' marker for a `literal block`_::
258 defaults.code_block_markers = defaultdict(lambda: '::')
260 # The `code_block_marker` string is `inserted into a regular expression`_.
261 # Language-specific markers can be defined programmatically, e.g. in a
262 # wrapper script.
264 # In a document where code examples are only one of several uses of
265 # literal blocks, it is more appropriate to single out the source code
266 # ,e.g. with the double colon at a separate line ("expanded form")
268 # ``defaults.code_block_marker.default = ':: *'``
270 # or a dedicated ``.. code-block::`` directive [#]_
272 # ``defaults.code_block_marker['c++'] = '.. code-block:: *c++'``
274 # The latter form also allows code in different languages kept together
275 # in one literate source file.
277 # .. [#] The ``.. code-block::`` directive is not (yet) supported by
278 # standard Docutils. It is provided by several add-ons, including
279 # the `code-block directive`_ project in the Docutils Sandbox and
280 # Sphinx_.
283 # strip
284 # -----
286 # Export to the output format stripping documentation or code blocks::
288 defaults.strip = False
290 # strip_marker
291 # ------------
293 # Strip literal marker from the end of documentation blocks when
294 # converting to code format. Makes the code more concise but looses the
295 # synchronisation of line numbers in text and code formats. Can also be used
296 # (together with the auto-completion of the code-text conversion) to change
297 # the `code_block_marker`::
299 defaults.strip_marker = False
301 # add_missing_marker
302 # ------------------
304 # When converting from code format to text format, add a `code_block_marker`
305 # at the end of documentation blocks if it is missing::
307 defaults.add_missing_marker = True
309 # Keep this at ``True``, if you want to re-convert to code format later!
312 # .. _defaults.preprocessors:
314 # preprocessors
315 # -------------
317 # Preprocess the data with language-specific filters_
318 # Set below in Filters_::
320 defaults.preprocessors = {}
322 # .. _defaults.postprocessors:
324 # postprocessors
325 # --------------
327 # Postprocess the data with language-specific filters_::
329 defaults.postprocessors = {}
331 # .. _defaults.codeindent:
333 # codeindent
334 # ----------
336 # Number of spaces to indent code blocks in `Code2Text.code_block_handler`_::
338 defaults.codeindent = 2
340 # In `Text2Code.code_block_handler`_, the codeindent is determined by the
341 # first recognised code line (header or first indented literal block
342 # of the text source).
344 # overwrite
345 # ---------
347 # What to do if the outfile already exists? (ignored if `outfile` == '-')::
349 defaults.overwrite = 'update'
351 # Recognised values:
353 # :'yes': overwrite eventually existing `outfile`,
354 # :'update': fail if the `outfile` is newer than `infile`,
355 # :'no': fail if `outfile` exists.
358 # Extensions
359 # ==========
361 # Try to import optional extensions::
363 try:
364 import pylit_elisp
365 except ImportError:
366 pass
369 # Converter Classes
370 # =================
372 # The converter classes implement a simple state machine to separate and
373 # transform documentation and code blocks. For this task, only a very limited
374 # parsing is needed. PyLit's parser assumes:
376 # * `indented literal blocks`_ in a text source are code blocks.
378 # * comment blocks in a code source where every line starts with a matching
379 # comment string are documentation blocks.
381 # TextCodeConverter
382 # -----------------
383 # ::
385 class TextCodeConverter(object):
386 """Parent class for the converters `Text2Code` and `Code2Text`.
389 # The parent class defines data attributes and functions used in both
390 # `Text2Code`_ converting a text source to executable code source, and
391 # `Code2Text`_ converting commented code to a text source.
393 # Data attributes
394 # ~~~~~~~~~~~~~~~
396 # Class default values are fetched from the `defaults`_ object and can be
397 # overridden by matching keyword arguments during class instantiation. This
398 # also works with keyword arguments to `get_converter`_ and `main`_, as these
399 # functions pass on unused keyword args to the instantiation of a converter
400 # class. ::
402 language = defaults.languages[None]
403 comment_strings = defaults.comment_strings
404 comment_string = "" # set in __init__ (if empty)
405 codeindent = defaults.codeindent
406 header_string = defaults.header_string
407 code_block_markers = defaults.code_block_markers
408 code_block_marker = "" # set in __init__ (if empty)
409 strip = defaults.strip
410 strip_marker = defaults.strip_marker
411 add_missing_marker = defaults.add_missing_marker
412 directive_option_regexp = re.compile(r' +:(\w|[-._+:])+:( |$)')
413 state = "" # type of current block, see `TextCodeConverter.convert`_
415 # Interface methods
416 # ~~~~~~~~~~~~~~~~~
418 # .. _TextCodeConverter.__init__:
420 # __init__
421 # """"""""
423 # Initialising sets the `data` attribute, an iterable object yielding lines of
424 # the source to convert. [#]_
426 # .. [#] The most common choice of data is a `file` object with the text
427 # or code source.
429 # To convert a string into a suitable object, use its splitlines()
430 # method like ``"2 lines\nof source".splitlines(True)``.
433 # Additional keyword arguments are stored as instance variables,
434 # overwriting the class defaults::
436 def __init__(self, data, **keyw):
437 """data -- iterable data object
438 (list, file, generator, string, ...)
439 **keyw -- remaining keyword arguments are
440 stored as data-attributes
442 self.data = data
443 self.__dict__.update(keyw)
445 # If empty, `code_block_marker` and `comment_string` are set according
446 # to the `language`::
448 if not self.code_block_marker:
449 self.code_block_marker = self.code_block_markers[self.language]
450 if not self.comment_string:
451 self.comment_string = self.comment_strings[self.language]
452 self.stripped_comment_string = self.comment_string.rstrip()
454 # Pre- and postprocessing filters are set (with
455 # `TextCodeConverter.get_filter`_)::
457 self.preprocessor = self.get_filter("preprocessors", self.language)
458 self.postprocessor = self.get_filter("postprocessors", self.language)
460 # .. _inserted into a regular expression:
462 # Finally, a regular_expression for the `code_block_marker` is compiled
463 # to find valid cases of `code_block_marker` in a given line and return
464 # the groups: ``\1 prefix, \2 code_block_marker, \3 remainder`` ::
466 marker = self.code_block_marker
467 if marker == '::':
468 # the default marker may occur at the end of a text line
469 self.marker_regexp = re.compile('^( *(?!\.\.).*)(::)([ \n]*)$')
470 else:
471 # marker must be on a separate line
472 self.marker_regexp = re.compile('^( *)(%s)(.*\n?)$' % marker)
474 # .. _TextCodeConverter.__iter__:
476 # __iter__
477 # """"""""
479 # Return an iterator for the instance. Iteration yields lines of converted
480 # data.
482 # The iterator is a chain of iterators acting on `self.data` that does
484 # * preprocessing
485 # * text<->code format conversion
486 # * postprocessing
488 # Pre- and postprocessing are only performed, if filters for the current
489 # language are registered in `defaults.preprocessors`_ and|or
490 # `defaults.postprocessors`_. The filters must accept an iterable as first
491 # argument and yield the processed input data line-wise.
492 # ::
494 def __iter__(self):
495 """Iterate over input data source and yield converted lines
497 return self.postprocessor(self.convert(self.preprocessor(self.data)))
500 # .. _TextCodeConverter.__call__:
502 # __call__
503 # """"""""
504 # The special `__call__` method allows the use of class instances as callable
505 # objects. It returns the converted data as list of lines::
507 def __call__(self):
508 """Iterate over state-machine and return results as list of lines"""
509 return [line for line in self]
512 # .. _TextCodeConverter.__str__:
514 # __str__
515 # """""""
516 # Return converted data as string::
518 def __str__(self):
519 return "".join(self())
522 # Helpers and convenience methods
523 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
525 # .. _TextCodeConverter.convert:
527 # convert
528 # """""""
530 # The `convert` method generates an iterator that does the actual code <-->
531 # text format conversion. The converted data is yielded line-wise and the
532 # instance's `status` argument indicates whether the current line is "header",
533 # "documentation", or "code_block"::
535 def convert(self, lines):
536 """Iterate over lines of a program document and convert
537 between "text" and "code" format
540 # Initialise internal data arguments. (Done here, so that every new iteration
541 # re-initialises them.)
543 # `state`
544 # the "type" of the currently processed block of lines. One of
546 # :"": initial state: check for header,
547 # :"header": leading code block: strip `header_string`,
548 # :"documentation": documentation part: comment out,
549 # :"code_block": literal blocks containing source code: unindent.
551 # ::
553 self.state = ""
555 # `_codeindent`
556 # * Do not confuse the internal attribute `_codeindent` with the configurable
557 # `codeindent` (without the leading underscore).
558 # * `_codeindent` is set in `Text2Code.code_block_handler`_ to the indent of
559 # first non-blank "code_block" line and stripped from all "code_block" lines
560 # in the text-to-code conversion,
561 # * `codeindent` is set in `__init__` to `defaults.codeindent`_ and added to
562 # "code_block" lines in the code-to-text conversion.
564 # ::
566 self._codeindent = 0
568 # `_textindent`
569 # * set by `Text2Code.documentation_handler`_ to the minimal indent of a
570 # documentation block,
571 # * used in `Text2Code.set_state`_ to find the end of a code block.
573 # ::
575 self._textindent = 0
577 # `_add_code_block_marker`
578 # If the last paragraph of a documentation block does not end with a
579 # code_block_marker_, it should be added (otherwise, the back-conversion
580 # fails.).
582 # `_add_code_block_marker` is set by `Code2Text.documentation_handler`_
583 # and evaluated by `Code2Text.code_block_handler`_, because the
584 # documentation_handler does not know whether the next block will be
585 # documentation (with no need for a code_block_marker) or a code block.
587 # ::
589 self._add_code_block_marker = False
593 # Determine the state of the block and convert with the matching "handler"::
595 for block in collect_blocks(expandtabs_filter(lines)):
596 try:
597 self.set_state(block)
598 except StopIteration:
599 return
600 for line in getattr(self, self.state+"_handler")(block):
601 yield line
604 # .. _TextCodeConverter.get_filter:
606 # get_filter
607 # """"""""""
608 # ::
610 def get_filter(self, filter_set, language):
611 """Return language specific filter"""
612 if self.__class__ == Text2Code:
613 key = "text2"+language
614 elif self.__class__ == Code2Text:
615 key = language+"2text"
616 else:
617 key = ""
618 try:
619 return getattr(defaults, filter_set)[key]
620 except (AttributeError, KeyError, TypeError):
621 # print("there is no %r filter in %r"%(key, filter_set))
622 pass
623 return identity_filter
626 # get_indent
627 # """"""""""
628 # Return the number of leading spaces in `line`::
630 def get_indent(self, line):
631 """Return the indentation of `string`.
633 return len(line) - len(line.lstrip())
636 # Text2Code
637 # ---------
639 # The `Text2Code` converter separates *code-blocks* [#]_ from *documentation*.
640 # Code blocks are unindented, documentation is commented (or filtered, if the
641 # ``strip`` option is True).
643 # .. [#] Only `indented literal blocks`_ are considered code-blocks. `quoted
644 # literal blocks`_, `parsed-literal blocks`_, and `doctest blocks`_ are
645 # treated as part of the documentation. This allows the inclusion of
646 # examples:
648 # >>> 23 + 3
649 # 26
651 # Mark that there is no double colon before the doctest block in the
652 # text source.
654 # The class inherits the interface and helper functions from
655 # TextCodeConverter_ and adds functions specific to the text-to-code format
656 # conversion::
658 class Text2Code(TextCodeConverter):
659 """Convert a (reStructured) text source to code source
662 # .. _Text2Code.set_state:
664 # set_state
665 # ~~~~~~~~~
666 # ::
668 def set_state(self, block):
669 """Determine state of `block`. Set `self.state`
672 # `set_state` is used inside an iteration. Hence, if we are out of data, a
673 # StopItertion exception should be raised::
675 if not block:
676 raise StopIteration
678 # The new state depends on the active state (from the last block) and
679 # features of the current block. It is either "header", "documentation", or
680 # "code_block".
682 # If the current state is "" (first block), check for
683 # the `header_string` indicating a leading code block::
685 if self.state == "":
686 # print("set state for %r"%block)
687 if block[0].startswith(self.header_string):
688 self.state = "header"
689 else:
690 self.state = "documentation"
692 # If the current state is "documentation", the next block is also
693 # documentation. The end of a documentation part is detected in the
694 # `Text2Code.documentation_handler`_::
696 # elif self.state == "documentation":
697 # self.state = "documentation"
699 # A "code_block" ends with the first less indented, non-blank line.
700 # `_textindent` is set by the documentation handler to the indent of the
701 # preceding documentation block::
703 elif self.state in ["code_block", "header"]:
704 indents = [self.get_indent(line) for line in block
705 if line.rstrip()]
706 # print("set_state:", indents, self._textindent)
707 if indents and min(indents) <= self._textindent:
708 self.state = 'documentation'
709 else:
710 self.state = 'code_block'
712 # TODO: (or not to do?) insert blank line before the first line with too-small
713 # codeindent using self.ensure_trailing_blank_line(lines, line) (would need
714 # split and push-back of the documentation part)?
716 # .. _Text2Code.header_handler:
718 # header_handler
719 # ~~~~~~~~~~~~~~
721 # Sometimes code needs to remain on the first line(s) of the document to be
722 # valid. The most common example is the "shebang" line that tells a POSIX
723 # shell how to process an executable file::
725 #!/usr/bin/env python
727 # In Python, the special comment to indicate the encoding, e.g.
728 # ``# -*- coding: iso-8859-1 -*-``, must occur before any other comment
729 # or code too.
731 # If we want to keep the line numbers in sync for text and code source, the
732 # reStructured Text markup for these header lines must start at the same line
733 # as the first header line. Therefore, header lines could not be marked as
734 # literal block (this would require the ``::`` and an empty line above the
735 # code_block).
737 # OTOH, a comment may start at the same line as the comment marker and it
738 # includes subsequent indented lines. Comments are visible in the reStructured
739 # Text source but hidden in the pretty-printed output.
741 # With a header converted to comment in the text source, everything before
742 # the first documentation block (i.e. before the first paragraph using the
743 # matching comment string) will be hidden away (in HTML or PDF output).
745 # This seems a good compromise, the advantages
747 # * line numbers are kept
748 # * the "normal" code_block conversion rules (indent/unindent by `codeindent` apply
749 # * greater flexibility: you can hide a repeating header in a project
750 # consisting of many source files.
752 # set off the disadvantages
754 # - it may come as surprise if a part of the file is not "printed",
755 # - one more syntax element to learn for rst newbies to start with pylit,
756 # (however, starting from the code source, this will be auto-generated)
758 # In the case that there is no matching comment at all, the complete code
759 # source will become a comment -- however, in this case it is not very likely
760 # the source is a literate document anyway.
762 # If needed for the documentation, it is possible to quote the header in (or
763 # after) the first documentation block, e.g. as `parsed literal`.
764 # ::
766 def header_handler(self, lines):
767 """Format leading code block"""
768 # strip header string from first line
769 lines[0] = lines[0].replace(self.header_string, "", 1)
770 # yield remaining lines formatted as code-block
771 for line in self.code_block_handler(lines):
772 yield line
775 # .. _Text2Code.documentation_handler:
777 # documentation_handler
778 # ~~~~~~~~~~~~~~~~~~~~~
780 # The 'documentation' handler processes everything that is not recognised as
781 # "code_block". Documentation is quoted with `self.comment_string`
782 # (or filtered with `--strip=True`).
784 # If end-of-documentation marker is detected,
786 # * set state to 'code_block'
787 # * set `self._textindent` (needed by `Text2Code.set_state`_ to find the
788 # next "documentation" block)
790 # ::
792 def documentation_handler(self, lines):
793 """Convert documentation blocks from text to code format
795 for line in lines:
796 # test lines following the code-block marker for false positives
797 if (self.state == "code_block" and line.rstrip()
798 and not self.directive_option_regexp.search(line)):
799 self.state = "documentation"
800 # test for end of documentation block
801 if self.marker_regexp.search(line):
802 self.state = "code_block"
803 self._textindent = self.get_indent(line)
804 # yield lines
805 if self.strip:
806 continue
807 # do not comment blank lines preceding a code block
808 if line.rstrip():
809 yield self.comment_string + line
810 else:
811 if self.state == "code_block":
812 yield line
813 else:
814 yield self.comment_string.rstrip() + line
818 # .. _Text2Code.code_block_handler:
820 # code_block_handler
821 # ~~~~~~~~~~~~~~~~~~
823 # The "code_block" handler is called with an indented literal block. It
824 # removes leading whitespace up to the indentation of the first code line in
825 # the file (this deviation from Docutils behaviour allows indented blocks of
826 # Python code). ::
828 def code_block_handler(self, block):
829 """Convert indented literal blocks to source code format
832 # If still unset, determine the indentation of code blocks from first non-blank
833 # code line::
835 if self._codeindent == 0:
836 self._codeindent = self.get_indent(block[0])
838 # Yield unindented lines after check whether we can safely unindent. If the
839 # line is less indented then `_codeindent`, something got wrong. ::
841 for line in block:
842 if line.lstrip() and self.get_indent(line) < self._codeindent:
843 raise ValueError("code block contains line less indented "
844 "than %d spaces \n%r"%(self._codeindent, block))
845 yield line.replace(" "*self._codeindent, "", 1)
848 # Code2Text
849 # ---------
851 # The `Code2Text` converter does the opposite of `Text2Code`_ -- it processes
852 # a source in "code format" (i.e. in a programming language), extracts
853 # documentation from comment blocks, and puts program code in literal blocks.
855 # The class inherits the interface and helper functions from
856 # TextCodeConverter_ and adds functions specific to the text-to-code format
857 # conversion::
859 class Code2Text(TextCodeConverter):
860 """Convert code source to text source
863 # set_state
864 # ~~~~~~~~~
866 # Check if block is "header", "documentation", or "code_block":
868 # A paragraph is "documentation", if every non-blank line starts with a
869 # matching comment string (including whitespace except for commented blank
870 # lines) ::
872 def set_state(self, block):
873 """Determine state of `block`."""
874 for line in block:
875 # skip documentation lines (commented, blank or blank comment)
876 if (line.startswith(self.comment_string)
877 or not line.rstrip()
878 or line.rstrip() == self.comment_string.rstrip()
880 continue
881 # non-commented line found:
882 if self.state == "":
883 self.state = "header"
884 else:
885 self.state = "code_block"
886 break
887 else:
888 # no code line found
889 # keep state if the block is just a blank line
890 # if len(block) == 1 and self._is_blank_codeline(line):
891 # return
892 self.state = "documentation"
895 # header_handler
896 # ~~~~~~~~~~~~~~
898 # Handle a leading code block. (See `Text2Code.header_handler`_ for a
899 # discussion of the "header" state.) ::
901 def header_handler(self, lines):
902 """Format leading code block"""
903 if self.strip == True:
904 return
905 # get iterator over the lines that formats them as code-block
906 lines = iter(self.code_block_handler(lines))
907 # prepend header string to first line
908 yield self.header_string + next(lines)
909 # yield remaining lines
910 for line in lines:
911 yield line
913 # .. _Code2Text.documentation_handler:
915 # documentation_handler
916 # ~~~~~~~~~~~~~~~~~~~~~
918 # The *documentation state* handler converts a comment to a documentation
919 # block by stripping the leading `comment string` from every line::
921 def documentation_handler(self, block):
922 """Uncomment documentation blocks in source code
925 # Strip comment strings::
927 lines = [self.uncomment_line(line) for line in block]
929 # If the code block is stripped, the literal marker would lead to an
930 # error when the text is converted with Docutils. Strip it as well. ::
932 if self.strip or self.strip_marker:
933 self.strip_code_block_marker(lines)
935 # Otherwise, check for the `code_block_marker`_ at the end of the
936 # documentation block (skipping directive options that might follow it)::
938 elif self.add_missing_marker:
939 for line in lines[::-1]:
940 if self.marker_regexp.search(line):
941 self._add_code_block_marker = False
942 break
943 if (line.rstrip() and
944 not self.directive_option_regexp.search(line)):
945 self._add_code_block_marker = True
946 break
947 else:
948 self._add_code_block_marker = True
950 # Yield lines::
952 for line in lines:
953 yield line
955 # uncomment_line
956 # ~~~~~~~~~~~~~~
958 # Return documentation line after stripping comment string. Consider the
959 # case that a blank line has a comment string without trailing whitespace::
961 def uncomment_line(self, line):
962 """Return uncommented documentation line"""
963 line = line.replace(self.comment_string, "", 1)
964 if line.rstrip() == self.stripped_comment_string:
965 line = line.replace(self.stripped_comment_string, "", 1)
966 return line
968 # .. _Code2Text.code_block_handler:
970 # code_block_handler
971 # ~~~~~~~~~~~~~~~~~~
973 # The `code_block` handler returns the code block as indented literal
974 # block (or filters it, if ``self.strip == True``). The amount of the code
975 # indentation is controlled by `self.codeindent` (default 2). ::
977 def code_block_handler(self, lines):
978 """Covert code blocks to text format (indent or strip)
980 if self.strip == True:
981 return
982 # eventually insert transition marker
983 if self._add_code_block_marker:
984 self.state = "documentation"
985 yield self.code_block_marker + "\n"
986 yield "\n"
987 self._add_code_block_marker = False
988 self.state = "code_block"
989 for line in lines:
990 yield " "*self.codeindent + line
994 # strip_code_block_marker
995 # ~~~~~~~~~~~~~~~~~~~~~~~
997 # Replace the literal marker with the equivalent of Docutils replace rules
999 # * strip ``::``-line (and preceding blank line) if on a line on its own
1000 # * strip ``::`` if it is preceded by whitespace.
1001 # * convert ``::`` to a single colon if preceded by text
1003 # `lines` is a list of documentation lines (with a trailing blank line).
1004 # It is modified in-place::
1006 def strip_code_block_marker(self, lines):
1007 try:
1008 line = lines[-2]
1009 except IndexError:
1010 return # just one line (no trailing blank line)
1012 # match with regexp: `match` is None or has groups
1013 # \1 leading text, \2 code_block_marker, \3 remainder
1014 match = self.marker_regexp.search(line)
1016 if not match: # no code_block_marker present
1017 return
1018 if not match.group(1): # `code_block_marker` on an extra line
1019 del(lines[-2])
1020 # delete preceding line if it is blank
1021 if len(lines) >= 2 and not lines[-2].lstrip():
1022 del(lines[-2])
1023 elif match.group(1).rstrip() < match.group(1):
1024 # '::' follows whitespace
1025 lines[-2] = match.group(1).rstrip() + match.group(3)
1026 else: # '::' follows text
1027 lines[-2] = match.group(1).rstrip() + ':' + match.group(3)
1029 # Filters
1030 # =======
1032 # Filters allow pre- and post-processing of the data to bring it in a format
1033 # suitable for the "normal" text<->code conversion. An example is conversion
1034 # of `C` ``/*`` ``*/`` comments into C++ ``//`` comments (and back).
1035 # Another example is the conversion of `C` ``/*`` ``*/`` comments into C++
1036 # ``//`` comments (and back).
1038 # Filters are generator functions that return an iterator acting on a
1039 # `data` iterable and yielding processed `data` lines.
1041 # identity_filter
1042 # ---------------
1044 # The most basic filter is the identity filter, that returns its argument as
1045 # iterator::
1047 def identity_filter(data):
1048 """Return data iterator without any processing"""
1049 return iter(data)
1051 # expandtabs_filter
1052 # -----------------
1054 # Expand hard-tabs in every line of `data` (cf. `str.expandtabs`).
1056 # This filter is applied to the input data by `TextCodeConverter.convert`_ as
1057 # hard tabs can lead to errors when the indentation is changed. ::
1059 def expandtabs_filter(data):
1060 """Yield data tokens with hard-tabs expanded"""
1061 for line in data:
1062 yield line.expandtabs()
1065 # collect_blocks
1066 # --------------
1068 # A filter to aggregate "paragraphs" (blocks separated by blank
1069 # lines). Yields lists of lines::
1071 def collect_blocks(lines):
1072 """collect lines in a list
1074 yield list for each paragraph, i.e. block of lines separated by a
1075 blank line (whitespace only).
1077 Trailing blank lines are collected as well.
1079 blank_line_reached = False
1080 block = []
1081 for line in lines:
1082 if blank_line_reached and line.rstrip():
1083 yield block
1084 blank_line_reached = False
1085 block = [line]
1086 continue
1087 if not line.rstrip():
1088 blank_line_reached = True
1089 block.append(line)
1090 yield block
1094 # dumb_c_preprocessor
1095 # -------------------
1097 # This is a basic filter to convert `C` to `C++` comments. Works line-wise and
1098 # only converts lines that
1100 # * start with "/\* " and end with " \*/" (followed by whitespace only)
1102 # A more sophisticated version would also
1104 # * convert multi-line comments
1106 # + Keep indentation or strip 3 leading spaces?
1108 # * account for nested comments
1110 # * only convert comments that are separated from code by a blank line
1112 # ::
1114 def dumb_c_preprocessor(data):
1115 """change `C` ``/* `` `` */`` comments into C++ ``// `` comments"""
1116 comment_string = defaults.comment_strings["c++"]
1117 boc_string = "/* "
1118 eoc_string = " */"
1119 for line in data:
1120 if (line.startswith(boc_string)
1121 and line.rstrip().endswith(eoc_string)
1123 line = line.replace(boc_string, comment_string, 1)
1124 line = "".join(line.rsplit(eoc_string, 1))
1125 yield line
1127 # Unfortunately, the `replace` method of strings does not support negative
1128 # numbers for the `count` argument:
1130 # >>> "foo */ baz */ bar".replace(" */", "", -1) == "foo */ baz bar"
1131 # False
1133 # However, there is the `rsplit` method, that can be used together with `join`:
1135 # >>> "".join("foo */ baz */ bar".rsplit(" */", 1)) == "foo */ baz bar"
1136 # True
1138 # dumb_c_postprocessor
1139 # --------------------
1141 # Undo the preparations by the dumb_c_preprocessor and re-insert valid comment
1142 # delimiters ::
1144 def dumb_c_postprocessor(data):
1145 """change C++ ``// `` comments into `C` ``/* `` `` */`` comments"""
1146 comment_string = defaults.comment_strings["c++"]
1147 boc_string = "/* "
1148 eoc_string = " */"
1149 for line in data:
1150 if line.rstrip() == comment_string.rstrip():
1151 line = line.replace(comment_string, "", 1)
1152 elif line.startswith(comment_string):
1153 line = line.replace(comment_string, boc_string, 1)
1154 line = line.rstrip() + eoc_string + "\n"
1155 yield line
1158 # register filters
1159 # ----------------
1161 # ::
1163 defaults.preprocessors['c2text'] = dumb_c_preprocessor
1164 defaults.preprocessors['css2text'] = dumb_c_preprocessor
1165 defaults.postprocessors['text2c'] = dumb_c_postprocessor
1166 defaults.postprocessors['text2css'] = dumb_c_postprocessor
1169 # Command line use
1170 # ================
1172 # Using this script from the command line will convert a file according to its
1173 # extension. This default can be overridden by a couple of options.
1175 # Dual source handling
1176 # --------------------
1178 # How to determine which source is up-to-date?
1179 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1181 # - set modification date of `outfile` to the one of `infile`
1183 # Points out that the source files are 'synchronised'.
1185 # * Are there problems to expect from "backdating" a file? Which?
1187 # Looking at http://www.unix.com/showthread.php?t=20526, it seems
1188 # perfectly legal to set `mtime` (while leaving `ctime`) as `mtime` is a
1189 # description of the "actuality" of the data in the file.
1191 # * Should this become a default or an option?
1193 # - alternatively move input file to a backup copy (with option: `--replace`)
1195 # - check modification date before overwriting
1196 # (with option: `--overwrite=update`)
1198 # - check modification date before editing (implemented as `Jed editor`_
1199 # function `pylit_check()` in `pylit.sl`_)
1201 # .. _Jed editor: http://www.jedsoft.org/jed/
1202 # .. _pylit.sl: http://jedmodes.sourceforge.net/mode/pylit/
1204 # Recognised Filename Extensions
1205 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1207 # Instead of defining a new extension for "pylit" literate programs,
1208 # by default ``.txt`` will be appended for the text source and stripped by
1209 # the conversion to the code source. I.e. for a Python program foo:
1211 # * the code source is called ``foo.py``
1212 # * the text source is called ``foo.py.txt``
1213 # * the html rendering is called ``foo.py.html``
1216 # OptionValues
1217 # ------------
1219 # The following class adds `as_dict`_, `complete`_ and `__getattr__`_
1220 # methods to `optparse.Values`::
1222 class OptionValues(optparse.Values):
1224 # .. _OptionValues.as_dict:
1226 # as_dict
1227 # ~~~~~~~
1229 # For use as keyword arguments, it is handy to have the options in a
1230 # dictionary. `as_dict` returns a copy of the instances object dictionary::
1232 def as_dict(self):
1233 """Return options as dictionary object"""
1234 return self.__dict__.copy()
1236 # .. _OptionValues.complete:
1238 # complete
1239 # ~~~~~~~~
1241 # ::
1243 def complete(self, **keyw):
1245 Complete the data attributes from keyword arguments.
1247 Do not overwrite existing attributes.
1248 Drop keyword arguments that correspond to data attributes in `self`.
1250 for key, value in keyw.items():
1251 try:
1252 self.__dict__[key]
1253 except KeyError:
1254 setattr(self, key, value)
1256 # .. _OptionValues.__getattr__:
1258 # __getattr__
1259 # ~~~~~~~~~~~
1261 # To replace calls using ``<instance>.ensure_value("OPTION", None)`` with the
1262 # more concise ``<instance>.OPTION``, we define `__getattr__` [#]_ ::
1264 def __getattr__(self, name):
1265 """Return default value for non existing options"""
1266 return None
1269 # .. [#] The special method `__getattr__` is only called when an attribute
1270 # look-up has not found the attribute in the usual places (i.e. it is
1271 # not an instance attribute nor is it found in the class tree for
1272 # self).
1275 # PylitOptions
1276 # ------------
1278 # The `PylitOptions` class comprises an option parser and methods for parsing
1279 # and completion of command line options::
1281 class PylitOptions(object):
1282 """Storage and handling of command line options for pylit"""
1284 # Instantiation
1285 # ~~~~~~~~~~~~~
1287 # ::
1289 def __init__(self):
1290 """Set up an `OptionParser` instance for pylit command line options
1293 p = optparse.OptionParser(usage=main.__doc__, version=__version__)
1295 # Conversion settings
1297 p.add_option("-c", "--code2txt", dest="txt2code", action="store_false",
1298 help="convert code source to text source")
1299 p.add_option("-t", "--txt2code", action="store_true",
1300 help="convert text source to code source")
1301 p.add_option("--language",
1302 choices = list(defaults.comment_strings.keys()),
1303 help="use LANGUAGE native comment style")
1304 p.add_option("--comment-string", dest="comment_string",
1305 help="documentation block marker in code source "
1306 "(including trailing whitespace, "
1307 "default: language dependent)")
1308 p.add_option("-m", "--code-block-marker", dest="code_block_marker",
1309 help="syntax token starting a code block. (default '::')")
1310 p.add_option("--codeindent", type="int",
1311 help="Number of spaces to indent code blocks with "
1312 "code2text (default %d)" % defaults.codeindent)
1314 # Output file handling
1316 p.add_option("--overwrite", action="store",
1317 choices = ["yes", "update", "no"],
1318 help="overwrite output file (default 'update')")
1319 p.add_option("--replace", action="store_true",
1320 help="move infile to a backup copy (appending '~')")
1321 # TODO: do we need this? If yes, make mtime update depend on it!
1322 # p.add_option("--keep-mtime", action="store_true",
1323 # help="do not set the modification time of the outfile "
1324 # "to the corresponding value of the infile")
1325 p.add_option("-s", "--strip", action="store_true",
1326 help='"export" by stripping documentation or code')
1328 # Special actions
1330 p.add_option("-d", "--diff", action="store_true",
1331 help="test for differences to existing file")
1332 p.add_option("--doctest", action="store_true",
1333 help="run doctest.testfile() on the text version")
1334 p.add_option("-e", "--execute", action="store_true",
1335 help="execute code (Python only)")
1337 self.parser = p
1339 # .. _PylitOptions.parse_args:
1341 # parse_args
1342 # ~~~~~~~~~~
1344 # The `parse_args` method calls the `optparse.OptionParser` on command
1345 # line or provided args and returns the result as `PylitOptions.Values`
1346 # instance. Defaults can be provided as keyword arguments::
1348 def parse_args(self, args=sys.argv[1:], **keyw):
1349 """parse command line arguments using `optparse.OptionParser`
1351 parse_args(args, **keyw) -> OptionValues instance
1353 args -- list of command line arguments.
1354 keyw -- keyword arguments or dictionary of option defaults
1356 # parse arguments
1357 (values, args) = self.parser.parse_args(args, OptionValues(keyw))
1358 # Convert FILE and OUTFILE positional args to option values
1359 # (other positional arguments are ignored)
1360 try:
1361 values.infile = args[0]
1362 values.outfile = args[1]
1363 except IndexError:
1364 pass
1366 return values
1368 # .. _PylitOptions.complete_values:
1370 # complete_values
1371 # ~~~~~~~~~~~~~~~
1373 # Complete an OptionValues instance `values`. Use module-level defaults and
1374 # context information to set missing option values to sensible defaults (if
1375 # possible) ::
1377 def complete_values(self, values):
1378 """complete option values with module and context sensible defaults
1380 x.complete_values(values) -> values
1381 values -- OptionValues instance
1384 # Complete with module-level defaults_::
1386 values.complete(**defaults.__dict__)
1388 # Ensure infile is a string::
1390 values.ensure_value("infile", "")
1392 # Guess conversion direction from `infile` filename::
1394 if values.txt2code is None:
1395 in_extension = os.path.splitext(values.infile)[1]
1396 if in_extension in values.text_extensions:
1397 values.txt2code = True
1398 elif in_extension in values.languages.keys():
1399 values.txt2code = False
1401 # Auto-determine the output file name::
1403 values.ensure_value("outfile", self._get_outfile_name(values))
1405 # Second try: Guess conversion direction from outfile filename::
1407 if values.txt2code is None:
1408 out_extension = os.path.splitext(values.outfile)[1]
1409 values.txt2code = not (out_extension in values.text_extensions)
1411 # Set the language of the code::
1413 if values.txt2code is True:
1414 code_extension = os.path.splitext(values.outfile)[1]
1415 elif values.txt2code is False:
1416 code_extension = os.path.splitext(values.infile)[1]
1417 values.ensure_value("language", values.languages[code_extension])
1419 return values
1421 # _get_outfile_name
1422 # ~~~~~~~~~~~~~~~~~
1424 # Construct a matching filename for the output file. The output filename is
1425 # constructed from `infile` by the following rules:
1427 # * '-' (stdin) results in '-' (stdout)
1428 # * strip the `text_extension`_ (txt2code) or
1429 # * add the `text_extension`_ (code2txt)
1430 # * fallback: if no guess can be made, add ".out"
1432 # .. TODO: use values.outfile_extension if it exists?
1434 # ::
1436 def _get_outfile_name(self, values):
1437 """Return a matching output filename for `infile`
1439 # if input is stdin, default output is stdout
1440 if values.infile == '-':
1441 return '-'
1443 # Derive from `infile` name: strip or add text extension
1444 (base, ext) = os.path.splitext(values.infile)
1445 if ext in values.text_extensions:
1446 return base # strip
1447 if ext and ext in values.languages or values.txt2code == False:
1448 return values.infile + values.text_extensions[0] # add
1449 # give up
1450 return values.infile + ".out"
1452 # .. _PylitOptions.__call__:
1454 # __call__
1455 # ~~~~~~~~
1457 # The special `__call__` method allows to use PylitOptions instances as
1458 # *callables*: Calling an instance parses the argument list to extract option
1459 # values and completes them based on "context-sensitive defaults". Keyword
1460 # arguments are used as default values. ::
1462 def __call__(self, args=sys.argv[1:], **keyw):
1463 """parse and complete command line args, return option values
1466 values = self.parse_args(args, **keyw)
1467 return self.complete_values(values)
1470 # Helper functions
1471 # ----------------
1473 # open_streams
1474 # ~~~~~~~~~~~~
1476 # Return file objects for in- and output. If the input path is missing,
1477 # write usage and abort. (An alternative would be to use stdin as default.
1478 # However, this leaves the uninitiated user with a non-responding application
1479 # if (s)he just tries the script without any arguments) ::
1481 def open_streams(infile = '-', outfile = '-', overwrite='update', **keyw):
1482 """Open and return the input and output stream
1484 open_streams(infile, outfile) -> (in_stream, out_stream)
1486 in_stream -- file(infile) or sys.stdin
1487 out_stream -- file(outfile) or sys.stdout
1488 overwrite -- 'yes': overwrite eventually existing `outfile`,
1489 'update': fail if the `outfile` is newer than `infile`,
1490 'no': fail if `outfile` exists.
1492 Irrelevant if `outfile` == '-'.
1494 if overwrite not in ('yes', 'no', 'update'):
1495 raise ValueError('Argument "overwrite" must be "yes", "no",'
1496 ' or update, not "%s".' % overwrite)
1497 if not infile:
1498 strerror = "Missing input file name ('-' for stdin; -h for help)"
1499 raise IOError(2, strerror, infile)
1500 if infile == '-':
1501 in_stream = sys.stdin
1502 else:
1503 in_stream = open(infile, 'r')
1504 if outfile == '-':
1505 out_stream = sys.stdout
1506 elif overwrite == 'no' and os.path.exists(outfile):
1507 raise IOError(17, "Output file exists!", outfile)
1508 elif overwrite == 'update' and is_newer(outfile, infile) is None:
1509 raise IOError(0, "Output file is as old as input file!", outfile)
1510 elif overwrite == 'update' and is_newer(outfile, infile):
1511 raise IOError(1, "Output file is newer than input file!", outfile)
1512 else:
1513 out_stream = open(outfile, 'w')
1514 return (in_stream, out_stream)
1516 # is_newer
1517 # ~~~~~~~~
1519 # ::
1521 def is_newer(path1, path2):
1522 """Check if `path1` is newer than `path2` (using mtime)
1524 Compare modification time of files at path1 and path2.
1526 Non-existing files are considered oldest: Return False if path1 does not
1527 exist and True if path2 does not exist.
1529 Return None if the modification time differs less than 1/10 second.
1530 (This evaluates to False in a Boolean context but allows a test
1531 for equality.)
1533 try:
1534 mtime1 = os.path.getmtime(path1)
1535 except OSError:
1536 mtime1 = -1
1537 try:
1538 mtime2 = os.path.getmtime(path2)
1539 except OSError:
1540 mtime2 = -1
1541 if abs(mtime1 - mtime2) < 0.1:
1542 return None
1543 return mtime1 > mtime2
1546 # get_converter
1547 # ~~~~~~~~~~~~~
1549 # Get an instance of the converter state machine::
1551 def get_converter(data, txt2code=True, **keyw):
1552 if txt2code:
1553 return Text2Code(data, **keyw)
1554 else:
1555 return Code2Text(data, **keyw)
1558 # Use cases
1559 # ---------
1561 # run_doctest
1562 # ~~~~~~~~~~~
1563 # ::
1565 def run_doctest(infile="-", txt2code=True,
1566 globs={}, verbose=False, optionflags=0, **keyw):
1567 """run doctest on the text source
1570 # Allow imports from the current working dir by prepending an empty string to
1571 # sys.path (see doc of sys.path())::
1573 sys.path.insert(0, '')
1575 # Import classes from the doctest module::
1577 from doctest import DocTestParser, DocTestRunner
1579 # Read in source. Make sure it is in text format, as tests in comments are not
1580 # found by doctest::
1582 (data, out_stream) = open_streams(infile, "-")
1583 if txt2code is False:
1584 keyw.update({'add_missing_marker': False})
1585 converter = Code2Text(data, **keyw)
1586 docstring = str(converter)
1587 else:
1588 docstring = data.read()
1590 # decode doc string if there is a "magic comment" in the first or second line
1591 # (http://docs.python.org/reference/lexical_analysis.html#encoding-declarations)
1592 # ::
1594 if sys.version_info < (3,0):
1595 firstlines = ' '.join(docstring.splitlines()[:2])
1596 match = re.search('coding[=:]\s*([-\w.]+)', firstlines)
1597 if match:
1598 docencoding = match.group(1)
1599 docstring = docstring.decode(docencoding)
1601 # Use the doctest Advanced API to run all doctests in the source text::
1603 test = DocTestParser().get_doctest(docstring, globs, name="",
1604 filename=infile, lineno=0)
1605 runner = DocTestRunner(verbose, optionflags)
1606 runner.run(test)
1607 runner.summarize
1608 # give feedback also if no failures occurred
1609 if not runner.failures:
1610 print("%d failures in %d tests"%(runner.failures, runner.tries))
1611 return runner.failures, runner.tries
1614 # diff
1615 # ~~~~
1617 # ::
1619 def diff(infile='-', outfile='-', txt2code=True, **keyw):
1620 """Report differences between converted infile and existing outfile
1622 If outfile does not exist or is '-', do a round-trip conversion and
1623 report differences.
1626 import difflib
1628 instream = open(infile)
1629 # for diffing, we need a copy of the data as list::
1630 data = instream.readlines()
1631 # convert
1632 converter = get_converter(data, txt2code, **keyw)
1633 new = converter()
1635 if outfile != '-' and os.path.exists(outfile):
1636 outstream = open(outfile)
1637 old = outstream.readlines()
1638 oldname = outfile
1639 newname = "<conversion of %s>"%infile
1640 else:
1641 old = data
1642 oldname = infile
1643 # back-convert the output data
1644 converter = get_converter(new, not txt2code)
1645 new = converter()
1646 newname = "<round-conversion of %s>"%infile
1648 # find and print the differences
1649 is_different = False
1650 # print(type(old), old)
1651 # print(type(new), new)
1652 delta = difflib.unified_diff(old, new,
1653 # delta = difflib.unified_diff(["heute\n", "schon\n"], ["heute\n", "noch\n"],
1654 fromfile=oldname, tofile=newname)
1655 for line in delta:
1656 is_different = True
1657 print(line, end=' ') #sys.stdout.write(line + ' ')
1658 if not is_different:
1659 print(oldname)
1660 print(newname)
1661 print("no differences found")
1662 return is_different
1665 # execute
1666 # ~~~~~~~
1668 # Works only for python code.
1670 # Does not work with `eval`, as code is not just one expression. ::
1672 def execute(infile="-", txt2code=True, **keyw):
1673 """Execute the input file. Convert first, if it is a text source.
1676 with open(infile) as f:
1677 data = f.readlines()
1678 if txt2code:
1679 data = str(Text2Code(data, **keyw))
1680 exec(''.join(data))
1683 # main
1684 # ----
1686 # If this script is called from the command line, the `main` function will
1687 # convert the input (file or stdin) between text and code formats.
1689 # Option default values for the conversion can be given as keyword arguments
1690 # to `main`_. The option defaults will be updated by command line options and
1691 # extended with "intelligent guesses" by `PylitOptions`_ and passed on to
1692 # helper functions and the converter instantiation.
1694 # This allows easy customisation for programmatic use -- just call `main`
1695 # with the appropriate keyword options, e.g. ``pylit.main(comment_string="## ")``
1697 # ::
1699 def main(args=sys.argv[1:], **defaults):
1700 """%prog [options] INFILE [OUTFILE]
1702 Convert between (reStructured) text source with embedded code,
1703 and code source with embedded documentation (comment blocks)
1705 The special filename '-' stands for standard in and output.
1708 # Parse and complete the options::
1710 options = PylitOptions()(args, **defaults)
1711 # print("infile", repr(options.infile))
1713 # Special actions with early return::
1715 if options.doctest:
1716 return run_doctest(**vars(options))
1718 if options.diff:
1719 return diff(**vars(options))
1721 if options.execute:
1722 return execute(**vars(options))
1724 # Open in- and output streams::
1726 try:
1727 (data, out_stream) = open_streams(**vars(options))
1728 except IOError as ex:
1729 print("IOError: %s %s" % (ex.filename, ex.strerror))
1730 sys.exit(ex.errno)
1732 # Get a converter instance::
1734 converter = get_converter(data, **vars(options))
1736 # Convert and write to out_stream::
1738 out_stream.write(str(converter))
1740 if out_stream is not sys.stdout:
1741 print("output written to", out_stream.name)
1742 out_stream.close()
1744 # If input and output are from files, set the modification time (`mtime`) of
1745 # the output file to the one of the input file to indicate that the contained
1746 # information is equal. [#]_ ::
1749 # print("fractions?", os.stat_float_times())
1750 try:
1751 os.utime(options.outfile, (os.path.getatime(options.outfile),
1752 os.path.getmtime(options.infile))
1754 except OSError:
1755 pass
1757 ## print("mtime", os.path.getmtime(options.infile), options.infile)
1758 ## print("mtime", os.path.getmtime(options.outfile), options.outfile)
1761 # .. [#] Make sure the corresponding file object (here `out_stream`) is
1762 # closed, as otherwise the change will be overwritten when `close` is
1763 # called afterwards (either explicitly or at program exit).
1766 # Rename the infile to a backup copy if ``--replace`` is set::
1768 if options.replace:
1769 os.rename(options.infile, options.infile + "~")
1772 # Run main, if called from the command line::
1774 if __name__ == '__main__':
1775 main()
1778 # Open questions
1779 # ==============
1781 # Open questions and ideas for further development
1783 # Clean code
1784 # ----------
1786 # * can we gain from using "shutils" over "os.path" and "os"?
1787 # * use pylint or pyChecker to enforce a consistent style?
1789 # Options
1790 # -------
1792 # * Use templates for the "intelligent guesses" (with Python syntax for string
1793 # replacement with dicts: ``"hello %(what)s" % {'what': 'world'}``)
1795 # * Is it sensible to offer the `header_string` option also as command line
1796 # option?
1798 # treatment of blank lines
1799 # ------------------------
1801 # Alternatives: Keep blank lines blank
1803 # - "never" (current setting) -> "visually merges" all documentation
1804 # if there is no interjacent code
1806 # - "always" -> disrupts documentation blocks,
1808 # - "if empty" (no whitespace). Comment if there is whitespace.
1810 # This would allow non-obstructing markup but unfortunately this is (in
1811 # most editors) also non-visible markup.
1813 # + "if double" (if there is more than one consecutive blank line)
1815 # With this handling, the "visual gap" remains in both, text and code
1816 # source.
1819 # Parsing Problems
1820 # ----------------
1822 # * Ignore "matching comments" in literal strings?
1824 # Too complicated: Would need a specific detection algorithm for every
1825 # language that supports multi-line literal strings (C++, PHP, Python)
1827 # * Warn if a comment in code will become documentation after round-trip?
1830 # docstrings in code blocks
1831 # -------------------------
1833 # * How to handle docstrings in code blocks? (it would be nice to convert them
1834 # to rst-text if ``__docformat__ == restructuredtext``)
1836 # TODO: Ask at Docutils users|developers
1838 # Plug-ins
1839 # --------
1841 # Specify a path for user additions and plug-ins. This would require to
1842 # convert Pylit from a pure module to a package...
1844 # 6.4.3 Packages in Multiple Directories
1846 # Packages support one more special attribute, __path__. This is initialized
1847 # to be a list containing the name of the directory holding the package's
1848 # __init__.py before the code in that file is executed. This
1849 # variable can be modified; doing so affects future searches for modules and
1850 # subpackages contained in the package.
1852 # While this feature is not often needed, it can be used to extend the set
1853 # of modules found in a package.
1856 # .. References
1858 # .. _Docutils: http://docutils.sourceforge.net/
1859 # .. _Sphinx: http://sphinx.pocoo.org
1860 # .. _Pygments: http://pygments.org/
1861 # .. _code-block directive:
1862 # http://docutils.sourceforge.net/sandbox/code-block-directive/
1863 # .. _literal block:
1864 # .. _literal blocks:
1865 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#literal-blocks
1866 # .. _indented literal block:
1867 # .. _indented literal blocks:
1868 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#indented-literal-blocks
1869 # .. _quoted literal block:
1870 # .. _quoted literal blocks:
1871 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#quoted-literal-blocks
1872 # .. _parsed-literal blocks:
1873 # http://docutils.sf.net/docs/ref/rst/directives.html#parsed-literal-block
1874 # .. _doctest block:
1875 # .. _doctest blocks:
1876 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#doctest-blocks