Documentation update
[pylit.git] / pylit.py
blobf99dadc424b34d98e358793c31059b143652b632
1 #!/usr/bin/env python3
2 # -*- coding: utf8 -*-
3 from __future__ import print_function
5 # pylit.py
6 # ********
7 # Literate programming with reStructuredText
8 # ++++++++++++++++++++++++++++++++++++++++++
10 # :Copyright: © 2005, 2007, 2015, 2021 Günter Milde.
11 # Released without warranty under the terms of the
12 # GNU General Public License (v. 2 or later)
14 # ::
16 """pylit: bidirectional text <-> code converter
18 Covert between a *text source* with embedded computer code and a *code source*
19 with embedded documentation.
20 """
22 # .. contents::
24 # Frontmatter
25 # ===========
27 # Changelog
28 # ---------
30 # .. class:: borderless
32 # ====== ========== ==========================================================
33 # 0.1 2005-06-29 Initial version.
34 # 0.1.1 2005-06-30 First literate version.
35 # 0.1.2 2005-07-01 Object orientated script using generators.
36 # 0.1.3 2005-07-10 Two state machine (later added 'header' state).
37 # 0.2b 2006-12-04 Start of work on version 0.2 (code restructuring).
38 # 0.2 2007-01-23 Published at http://pylit.berlios.de.
39 # 0.2.1 2007-01-25 Outsourced non-core documentation to the PyLit pages.
40 # 0.2.2 2007-01-26 New behaviour of `diff` function.
41 # 0.2.3 2007-01-29 New `header` methods after suggestion by Riccardo Murri.
42 # 0.2.4 2007-01-31 Raise Error if code indent is too small.
43 # 0.2.5 2007-02-05 New command line option --comment-string.
44 # 0.2.6 2007-02-09 Add section with open questions,
45 # Code2Text: let only blank lines (no comment str)
46 # separate text and code,
47 # fix `Code2Text.header`.
48 # 0.2.7 2007-02-19 Simplify `Code2Text.header`,
49 # new `iter_strip` method replacing a lot of ``if``-s.
50 # 0.2.8 2007-02-22 Set `mtime` of outfile to the one of infile.
51 # 0.3 2007-02-27 New `Code2Text` converter after an idea by Riccardo Murri,
52 # explicit `option_defaults` dict for easier customisation.
53 # 0.3.1 2007-03-02 Expand hard-tabs to prevent errors in indentation,
54 # `Text2Code` now also works on blocks,
55 # removed dependency on SimpleStates module.
56 # 0.3.2 2007-03-06 Bug fix: do not set `language` in `option_defaults`
57 # renamed `code_languages` to `languages`.
58 # 0.3.3 2007-03-16 New language css,
59 # option_defaults -> defaults = optparse.Values(),
60 # simpler PylitOptions: don't store parsed values,
61 # don't parse at initialisation,
62 # OptionValues: return `None` for non-existing attributes,
63 # removed -infile and -outfile, use positional arguments.
64 # 0.3.4 2007-03-19 Documentation update,
65 # separate `execute` function.
66 # 2007-03-21 Code cleanup in `Text2Code.__iter__`.
67 # 0.3.5 2007-03-23 Removed "css" from known languages after learning that
68 # there is no C++ style "// " comment string in CSS2.
69 # 0.3.6 2007-04-24 Documentation update.
70 # 0.4 2007-05-18 Implement Converter.__iter__ as stack of iterator
71 # generators. Iterating over a converter instance now
72 # yields lines instead of blocks.
73 # Provide "hooks" for pre- and postprocessing filters.
74 # Rename states to reduce confusion with formats:
75 # "text" -> "documentation", "code" -> "code_block".
76 # 0.4.1 2007-05-22 Converter.__iter__: cleanup and reorganisation,
77 # rename parent class Converter -> TextCodeConverter.
78 # 0.4.2 2007-05-23 Merged Text2Code.converter and Code2Text.converter into
79 # TextCodeConverter.converter.
80 # 0.4.3 2007-05-30 Replaced use of defaults.code_extensions with
81 # values.languages.keys().
82 # Removed spurious `print` statement in code_block_handler.
83 # Added basic support for 'c' and 'css' languages
84 # with `dumb_c_preprocessor`_ and `dumb_c_postprocessor`_.
85 # 0.5 2007-06-06 Moved `collect_blocks`_ out of `TextCodeConverter`_,
86 # bug fix: collect all trailing blank lines into a block.
87 # Expand tabs with `expandtabs_filter`_.
88 # 0.6 2007-06-20 Configurable code-block marker (default ``::``)
89 # 0.6.1 2007-06-28 Bug fix: reset self.code_block_marker_missing.
90 # 0.7 2007-12-12 prepending an empty string to sys.path in run_doctest()
91 # to allow imports from the current working dir.
92 # 0.7.1 2008-01-07 If outfile does not exist, do a round-trip conversion
93 # and report differences (as with outfile=='-').
94 # 0.7.2 2008-01-28 Do not add missing code-block separators with
95 # `doctest_run` on the code source. Keeps lines consistent.
96 # 0.7.3 2008-04-07 Use value of code_block_marker for insertion of missing
97 # transition marker in Code2Text.code_block_handler
98 # Add "shell" to defaults.languages
99 # 0.7.4 2008-06-23 Add "latex" to defaults.languages
100 # 0.7.5 2009-05-14 Bugfix: ignore blank lines in test for end of code block
101 # 0.7.6 2009-12-15 language-dependent code-block markers (after a
102 # `feature request and patch by jrioux`_),
103 # use DefaultDict for language-dependent defaults,
104 # new defaults setting `add_missing_marker`_.
105 # 0.7.7 2010-06-23 New command line option --codeindent.
106 # 0.7.8 2011-03-30 Do not overwrite custom `add_missing_marker` value,
107 # allow directive options following the 'code' directive.
108 # 0.7.9 2011-04-05 Decode doctest string if 'magic comment' gives encoding.
109 # 0.7.10 2013-06-07 Add "lua" to defaults.languages
110 # 0.7.11 2020-10-10 Return 0, if input and output file are of same age.
111 # 0.8.0 unpublishd Fix tests.
112 # Use collections.defaultdict.
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 from collections import defaultdict
140 import os
141 import re
142 import optparse
143 import sys
146 # Defaults
147 # ========
149 # The `defaults` object provides a central repository for default
150 # values and their customisation. ::
152 defaults = optparse.Values()
154 # It is used for
156 # * the initialisation of data arguments in TextCodeConverter_ and
157 # PylitOptions_
159 # * completion of command line options in `PylitOptions.complete_values`_.
161 # This allows the easy creation of back-ends that customise the
162 # defaults and then call `main`_ e.g.:
164 # >>> import pylit
165 # >>> pylit.defaults.comment_string = "## "
166 # >>> pylit.defaults.codeindent = 4
167 # >>> pylit.main()
169 # The following default values are defined in pylit.py:
171 # languages
172 # ---------
174 # Mapping of code file extensions to code language::
176 defaults.languages = defaultdict(lambda: "python", # fallback language
177 {".c": "c",
178 ".cc": "c++",
179 ".css": "css",
180 ".lua": "lua",
181 ".py": "python",
182 ".sh": "shell",
183 ".sl": "slang",
184 ".sty": "latex",
185 ".tex": "latex"
188 # Will be overridden by the ``--language`` command line option.
190 # The first argument is the fallback language, used if there is no
191 # matching extension (e.g. if pylit is used as filter) and no
192 # ``--language`` is specified. It can be changed programmatically by
193 # assignment to the ``.default`` attribute, e.g.
195 # >>> defaults.languages.default='c++'
198 # .. _text_extension:
200 # text_extensions
201 # ---------------
203 # List of known extensions of (reStructured) text files. The first
204 # extension in this list is used by the `_get_outfile_name`_ method to
205 # generate a text output filename::
207 defaults.text_extensions = [".txt", ".rst"]
210 # comment_strings
211 # ---------------
213 # Comment strings for known languages. Used in Code2Text_ to recognise
214 # text blocks and in Text2Code_ to format text blocks as comments.
215 # Defaults to ``'# '``.
217 # **Comment strings include trailing whitespace.** ::
219 defaults.comment_strings = defaultdict(lambda: '# ',
220 {"css": '// ',
221 "c": '// ',
222 "c++": '// ',
223 "lua": '-- ',
224 "latex": '% ',
225 "python": '# ',
226 "shell": '# ',
227 "slang": '% '
231 # header_string
232 # -------------
234 # Marker string for a header code block in the text source. No trailing
235 # whitespace needed as indented code follows.
236 # Must be a valid rst directive that accepts code on the same line, e.g.
237 # ``'..admonition::'``.
239 # Default is a comment marker::
241 defaults.header_string = '..'
244 # .. _code_block_marker:
246 # code_block_markers
247 # ------------------
249 # Markup at the end of a documentation block.
250 # Default is Docutils' marker for a `literal block`_::
252 defaults.code_block_markers = defaultdict(lambda: '::')
254 # The `code_block_marker` string is `inserted into a regular expression`_.
255 # Language-specific markers can be defined programmatically, e.g. in a
256 # wrapper script.
258 # In a document where code examples are only one of several uses of
259 # literal blocks, it is more appropriate to single out the source code
260 # ,e.g. with the double colon at a separate line ("expanded form")
262 # ``defaults.code_block_marker.default = ':: *'``
264 # or a dedicated ``.. code-block::`` directive [#]_
266 # ``defaults.code_block_marker['c++'] = '.. code-block:: *c++'``
268 # The latter form also allows code in different languages kept together
269 # in one literate source file.
271 # .. [#] The ``.. code-block::`` directive is not (yet) supported by
272 # standard Docutils. It is provided by several add-ons, including
273 # the `code-block directive`_ project in the Docutils Sandbox and
274 # Sphinx_.
277 # strip
278 # -----
280 # Export to the output format stripping documentation or code blocks::
282 defaults.strip = False
284 # strip_marker
285 # ------------
287 # Strip literal marker from the end of documentation blocks when
288 # converting to code format. Makes the code more concise but looses the
289 # synchronisation of line numbers in text and code formats. Can also be used
290 # (together with the auto-completion of the code-text conversion) to change
291 # the `code_block_marker`::
293 defaults.strip_marker = False
295 # add_missing_marker
296 # ------------------
298 # When converting from code format to text format, add a `code_block_marker`
299 # at the end of documentation blocks if it is missing::
301 defaults.add_missing_marker = True
303 # Keep this at ``True``, if you want to re-convert to code format later!
306 # .. _defaults.preprocessors:
308 # preprocessors
309 # -------------
311 # Preprocess the data with language-specific filters_
312 # Set below in Filters_::
314 defaults.preprocessors = {}
316 # .. _defaults.postprocessors:
318 # postprocessors
319 # --------------
321 # Postprocess the data with language-specific filters_::
323 defaults.postprocessors = {}
325 # .. _defaults.codeindent:
327 # codeindent
328 # ----------
330 # Number of spaces to indent code blocks in `Code2Text.code_block_handler`_::
332 defaults.codeindent = 2
334 # In `Text2Code.code_block_handler`_, the codeindent is determined by the
335 # first recognised code line (header or first indented literal block
336 # of the text source).
338 # overwrite
339 # ---------
341 # What to do if the outfile already exists? (ignored if `outfile` == '-')::
343 defaults.overwrite = 'update'
345 # Recognised values:
347 # :'yes': overwrite eventually existing `outfile`,
348 # :'update': fail if the `outfile` is newer than `infile`,
349 # :'no': fail if `outfile` exists.
352 # Extensions
353 # ==========
355 # Try to import optional extensions::
357 try:
358 import pylit_elisp
359 except ImportError:
360 pass
363 # Converter Classes
364 # =================
366 # The converter classes implement a simple state machine to separate and
367 # transform documentation and code blocks. For this task, only a very limited
368 # parsing is needed. PyLit's parser assumes:
370 # * `indented literal blocks`_ in a text source are code blocks.
372 # * comment blocks in a code source where every line starts with a matching
373 # comment string are documentation blocks.
375 # TextCodeConverter
376 # -----------------
377 # ::
379 class TextCodeConverter(object):
380 """Parent class for the converters `Text2Code` and `Code2Text`.
383 # The parent class defines data attributes and functions used in both
384 # `Text2Code`_ converting a text source to executable code source, and
385 # `Code2Text`_ converting commented code to a text source.
387 # Data attributes
388 # ~~~~~~~~~~~~~~~
390 # Class default values are fetched from the `defaults`_ object and can be
391 # overridden by matching keyword arguments during class instantiation. This
392 # also works with keyword arguments to `get_converter`_ and `main`_, as these
393 # functions pass on unused keyword args to the instantiation of a converter
394 # class. ::
396 language = defaults.languages[None]
397 comment_strings = defaults.comment_strings
398 comment_string = "" # set in __init__ (if empty)
399 codeindent = defaults.codeindent
400 header_string = defaults.header_string
401 code_block_markers = defaults.code_block_markers
402 code_block_marker = "" # set in __init__ (if empty)
403 strip = defaults.strip
404 strip_marker = defaults.strip_marker
405 add_missing_marker = defaults.add_missing_marker
406 directive_option_regexp = re.compile(r' +:(\w|[-._+:])+:( |$)')
407 state = "" # type of current block, see `TextCodeConverter.convert`_
409 # Interface methods
410 # ~~~~~~~~~~~~~~~~~
412 # .. _TextCodeConverter.__init__:
414 # __init__
415 # """"""""
417 # Initialising sets the `data` attribute, an iterable object yielding lines of
418 # the source to convert. [#]_
420 # .. [#] The most common choice of data is a `file` object with the text
421 # or code source.
423 # To convert a string into a suitable object, use its splitlines method
424 # like ``"2 lines\nof source".splitlines(True)``.
427 # Additional keyword arguments are stored as instance variables,
428 # overwriting the class defaults::
430 def __init__(self, data, **keyw):
431 """data -- iterable data object
432 (list, file, generator, string, ...)
433 **keyw -- remaining keyword arguments are
434 stored as data-attributes
436 self.data = data
437 self.__dict__.update(keyw)
439 # If empty, `code_block_marker` and `comment_string` are set according
440 # to the `language`::
442 if not self.code_block_marker:
443 self.code_block_marker = self.code_block_markers[self.language]
444 if not self.comment_string:
445 self.comment_string = self.comment_strings[self.language]
446 self.stripped_comment_string = self.comment_string.rstrip()
448 # Pre- and postprocessing filters are set (with
449 # `TextCodeConverter.get_filter`_)::
451 self.preprocessor = self.get_filter("preprocessors", self.language)
452 self.postprocessor = self.get_filter("postprocessors", self.language)
454 # .. _inserted into a regular expression:
456 # Finally, a regular_expression for the `code_block_marker` is compiled
457 # to find valid cases of `code_block_marker` in a given line and return
458 # the groups: ``\1 prefix, \2 code_block_marker, \3 remainder`` ::
460 marker = self.code_block_marker
461 if marker == '::':
462 # the default marker may occur at the end of a text line
463 self.marker_regexp = re.compile('^( *(?!\.\.).*)(::)([ \n]*)$')
464 else:
465 # marker must be on a separate line
466 self.marker_regexp = re.compile('^( *)(%s)(.*\n?)$' % marker)
468 # .. _TextCodeConverter.__iter__:
470 # __iter__
471 # """"""""
473 # Return an iterator for the instance. Iteration yields lines of converted
474 # data.
476 # The iterator is a chain of iterators acting on `self.data` that does
478 # * preprocessing
479 # * text<->code format conversion
480 # * postprocessing
482 # Pre- and postprocessing are only performed, if filters for the current
483 # language are registered in `defaults.preprocessors`_ and|or
484 # `defaults.postprocessors`_. The filters must accept an iterable as first
485 # argument and yield the processed input data line-wise.
486 # ::
488 def __iter__(self):
489 """Iterate over input data source and yield converted lines
491 return self.postprocessor(self.convert(self.preprocessor(self.data)))
494 # .. _TextCodeConverter.__call__:
496 # __call__
497 # """"""""
498 # The special `__call__` method allows the use of class instances as callable
499 # objects. It returns the converted data as list of lines::
501 def __call__(self):
502 """Iterate over state-machine and return results as list of lines"""
503 return [line for line in self]
506 # .. _TextCodeConverter.__str__:
508 # __str__
509 # """""""
510 # Return converted data as string::
512 def __str__(self):
513 return "".join(self())
516 # Helpers and convenience methods
517 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
519 # .. _TextCodeConverter.convert:
521 # convert
522 # """""""
524 # The `convert` method generates an iterator that does the actual code <-->
525 # text format conversion. The converted data is yielded line-wise and the
526 # instance's `status` argument indicates whether the current line is "header",
527 # "documentation", or "code_block"::
529 def convert(self, lines):
530 """Iterate over lines of a program document and convert
531 between "text" and "code" format
534 # Initialise internal data arguments. (Done here, so that every new iteration
535 # re-initialises them.)
537 # `state`
538 # the "type" of the currently processed block of lines. One of
540 # :"": initial state: check for header,
541 # :"header": leading code block: strip `header_string`,
542 # :"documentation": documentation part: comment out,
543 # :"code_block": literal blocks containing source code: unindent.
545 # ::
547 self.state = ""
549 # `_codeindent`
550 # * Do not confuse the internal attribute `_codeindent` with the configurable
551 # `codeindent` (without the leading underscore).
552 # * `_codeindent` is set in `Text2Code.code_block_handler`_ to the indent of
553 # first non-blank "code_block" line and stripped from all "code_block" lines
554 # in the text-to-code conversion,
555 # * `codeindent` is set in `__init__` to `defaults.codeindent`_ and added to
556 # "code_block" lines in the code-to-text conversion.
558 # ::
560 self._codeindent = 0
562 # `_textindent`
563 # * set by `Text2Code.documentation_handler`_ to the minimal indent of a
564 # documentation block,
565 # * used in `Text2Code.set_state`_ to find the end of a code block.
567 # ::
569 self._textindent = 0
571 # `_add_code_block_marker`
572 # If the last paragraph of a documentation block does not end with a
573 # code_block_marker_, it should be added (otherwise, the back-conversion
574 # fails.).
576 # `_add_code_block_marker` is set by `Code2Text.documentation_handler`_
577 # and evaluated by `Code2Text.code_block_handler`_, because the
578 # documentation_handler does not know whether the next block will be
579 # documentation (with no need for a code_block_marker) or a code block.
581 # ::
583 self._add_code_block_marker = False
587 # Determine the state of the block and convert with the matching "handler"::
589 for block in collect_blocks(expandtabs_filter(lines)):
590 try:
591 self.set_state(block)
592 except StopIteration:
593 return
594 for line in getattr(self, self.state+"_handler")(block):
595 yield line
598 # .. _TextCodeConverter.get_filter:
600 # get_filter
601 # """"""""""
602 # ::
604 def get_filter(self, filter_set, language):
605 """Return language specific filter"""
606 if self.__class__ == Text2Code:
607 key = "text2"+language
608 elif self.__class__ == Code2Text:
609 key = language+"2text"
610 else:
611 key = ""
612 try:
613 return getattr(defaults, filter_set)[key]
614 except (AttributeError, KeyError):
615 # print("there is no %r filter in %r"%(key, filter_set))
616 pass
617 return identity_filter
620 # get_indent
621 # """"""""""
622 # Return the number of leading spaces in `line`::
624 def get_indent(self, line):
625 """Return the indentation of `string`.
627 return len(line) - len(line.lstrip())
630 # Text2Code
631 # ---------
633 # The `Text2Code` converter separates *code-blocks* [#]_ from *documentation*.
634 # Code blocks are unindented, documentation is commented (or filtered, if the
635 # ``strip`` option is True).
637 # .. [#] Only `indented literal blocks`_ are considered code-blocks. `quoted
638 # literal blocks`_, `parsed-literal blocks`_, and `doctest blocks`_ are
639 # treated as part of the documentation. This allows the inclusion of
640 # examples:
642 # >>> 23 + 3
643 # 26
645 # Mark that there is no double colon before the doctest block in the
646 # text source.
648 # The class inherits the interface and helper functions from
649 # TextCodeConverter_ and adds functions specific to the text-to-code format
650 # conversion::
652 class Text2Code(TextCodeConverter):
653 """Convert a (reStructured) text source to code source
656 # .. _Text2Code.set_state:
658 # set_state
659 # ~~~~~~~~~
660 # ::
662 def set_state(self, block):
663 """Determine state of `block`. Set `self.state`
666 # `set_state` is used inside an iteration. Hence, if we are out of data, a
667 # StopItertion exception should be raised::
669 if not block:
670 raise StopIteration
672 # The new state depends on the active state (from the last block) and
673 # features of the current block. It is either "header", "documentation", or
674 # "code_block".
676 # If the current state is "" (first block), check for
677 # the `header_string` indicating a leading code block::
679 if self.state == "":
680 # print("set state for %r"%block)
681 if block[0].startswith(self.header_string):
682 self.state = "header"
683 else:
684 self.state = "documentation"
686 # If the current state is "documentation", the next block is also
687 # documentation. The end of a documentation part is detected in the
688 # `Text2Code.documentation_handler`_::
690 # elif self.state == "documentation":
691 # self.state = "documentation"
693 # A "code_block" ends with the first less indented, non-blank line.
694 # `_textindent` is set by the documentation handler to the indent of the
695 # preceding documentation block::
697 elif self.state in ["code_block", "header"]:
698 indents = [self.get_indent(line) for line in block
699 if line.rstrip()]
700 # print("set_state:", indents, self._textindent)
701 if indents and min(indents) <= self._textindent:
702 self.state = 'documentation'
703 else:
704 self.state = 'code_block'
706 # TODO: (or not to do?) insert blank line before the first line with too-small
707 # codeindent using self.ensure_trailing_blank_line(lines, line) (would need
708 # split and push-back of the documentation part)?
710 # .. _Text2Code.header_handler:
712 # header_handler
713 # ~~~~~~~~~~~~~~
715 # Sometimes code needs to remain on the first line(s) of the document to be
716 # valid. The most common example is the "shebang" line that tells a POSIX
717 # shell how to process an executable file::
719 #!/usr/bin/env python
721 # In Python, the special comment to indicate the encoding, e.g.
722 # ``# -*- coding: iso-8859-1 -*-``, must occur before any other comment
723 # or code too.
725 # If we want to keep the line numbers in sync for text and code source, the
726 # reStructured Text markup for these header lines must start at the same line
727 # as the first header line. Therefore, header lines could not be marked as
728 # literal block (this would require the ``::`` and an empty line above the
729 # code_block).
731 # OTOH, a comment may start at the same line as the comment marker and it
732 # includes subsequent indented lines. Comments are visible in the reStructured
733 # Text source but hidden in the pretty-printed output.
735 # With a header converted to comment in the text source, everything before
736 # the first documentation block (i.e. before the first paragraph using the
737 # matching comment string) will be hidden away (in HTML or PDF output).
739 # This seems a good compromise, the advantages
741 # * line numbers are kept
742 # * the "normal" code_block conversion rules (indent/unindent by `codeindent` apply
743 # * greater flexibility: you can hide a repeating header in a project
744 # consisting of many source files.
746 # set off the disadvantages
748 # - it may come as surprise if a part of the file is not "printed",
749 # - one more syntax element to learn for rst newbies to start with pylit,
750 # (however, starting from the code source, this will be auto-generated)
752 # In the case that there is no matching comment at all, the complete code
753 # source will become a comment -- however, in this case it is not very likely
754 # the source is a literate document anyway.
756 # If needed for the documentation, it is possible to quote the header in (or
757 # after) the first documentation block, e.g. as `parsed literal`.
758 # ::
760 def header_handler(self, lines):
761 """Format leading code block"""
762 # strip header string from first line
763 lines[0] = lines[0].replace(self.header_string, "", 1)
764 # yield remaining lines formatted as code-block
765 for line in self.code_block_handler(lines):
766 yield line
769 # .. _Text2Code.documentation_handler:
771 # documentation_handler
772 # ~~~~~~~~~~~~~~~~~~~~~
774 # The 'documentation' handler processes everything that is not recognised as
775 # "code_block". Documentation is quoted with `self.comment_string`
776 # (or filtered with `--strip=True`).
778 # If end-of-documentation marker is detected,
780 # * set state to 'code_block'
781 # * set `self._textindent` (needed by `Text2Code.set_state`_ to find the
782 # next "documentation" block)
784 # ::
786 def documentation_handler(self, lines):
787 """Convert documentation blocks from text to code format
789 for line in lines:
790 # test lines following the code-block marker for false positives
791 if (self.state == "code_block" and line.rstrip()
792 and not self.directive_option_regexp.search(line)):
793 self.state = "documentation"
794 # test for end of documentation block
795 if self.marker_regexp.search(line):
796 self.state = "code_block"
797 self._textindent = self.get_indent(line)
798 # yield lines
799 if self.strip:
800 continue
801 # do not comment blank lines preceding a code block
802 if line.rstrip():
803 yield self.comment_string + line
804 else:
805 if self.state == "code_block":
806 yield line
807 else:
808 yield self.comment_string.rstrip() + line
812 # .. _Text2Code.code_block_handler:
814 # code_block_handler
815 # ~~~~~~~~~~~~~~~~~~
817 # The "code_block" handler is called with an indented literal block. It
818 # removes leading whitespace up to the indentation of the first code line in
819 # the file (this deviation from Docutils behaviour allows indented blocks of
820 # Python code). ::
822 def code_block_handler(self, block):
823 """Convert indented literal blocks to source code format
826 # If still unset, determine the indentation of code blocks from first non-blank
827 # code line::
829 if self._codeindent == 0:
830 self._codeindent = self.get_indent(block[0])
832 # Yield unindented lines after check whether we can safely unindent. If the
833 # line is less indented then `_codeindent`, something got wrong. ::
835 for line in block:
836 if line.lstrip() and self.get_indent(line) < self._codeindent:
837 raise ValueError("code block contains line less indented "
838 "than %d spaces \n%r"%(self._codeindent, block))
839 yield line.replace(" "*self._codeindent, "", 1)
842 # Code2Text
843 # ---------
845 # The `Code2Text` converter does the opposite of `Text2Code`_ -- it processes
846 # a source in "code format" (i.e. in a programming language), extracts
847 # documentation from comment blocks, and puts program code in literal blocks.
849 # The class inherits the interface and helper functions from
850 # TextCodeConverter_ and adds functions specific to the text-to-code format
851 # conversion::
853 class Code2Text(TextCodeConverter):
854 """Convert code source to text source
857 # set_state
858 # ~~~~~~~~~
860 # Check if block is "header", "documentation", or "code_block":
862 # A paragraph is "documentation", if every non-blank line starts with a
863 # matching comment string (including whitespace except for commented blank
864 # lines) ::
866 def set_state(self, block):
867 """Determine state of `block`."""
868 for line in block:
869 # skip documentation lines (commented, blank or blank comment)
870 if (line.startswith(self.comment_string)
871 or not line.rstrip()
872 or line.rstrip() == self.comment_string.rstrip()
874 continue
875 # non-commented line found:
876 if self.state == "":
877 self.state = "header"
878 else:
879 self.state = "code_block"
880 break
881 else:
882 # no code line found
883 # keep state if the block is just a blank line
884 # if len(block) == 1 and self._is_blank_codeline(line):
885 # return
886 self.state = "documentation"
889 # header_handler
890 # ~~~~~~~~~~~~~~
892 # Handle a leading code block. (See `Text2Code.header_handler`_ for a
893 # discussion of the "header" state.) ::
895 def header_handler(self, lines):
896 """Format leading code block"""
897 if self.strip == True:
898 return
899 # get iterator over the lines that formats them as code-block
900 lines = iter(self.code_block_handler(lines))
901 # prepend header string to first line
902 yield self.header_string + next(lines)
903 # yield remaining lines
904 for line in lines:
905 yield line
907 # .. _Code2Text.documentation_handler:
909 # documentation_handler
910 # ~~~~~~~~~~~~~~~~~~~~~
912 # The *documentation state* handler converts a comment to a documentation
913 # block by stripping the leading `comment string` from every line::
915 def documentation_handler(self, block):
916 """Uncomment documentation blocks in source code
919 # Strip comment strings::
921 lines = [self.uncomment_line(line) for line in block]
923 # If the code block is stripped, the literal marker would lead to an
924 # error when the text is converted with Docutils. Strip it as well. ::
926 if self.strip or self.strip_marker:
927 self.strip_code_block_marker(lines)
929 # Otherwise, check for the `code_block_marker`_ at the end of the
930 # documentation block (skipping directive options that might follow it)::
932 elif self.add_missing_marker:
933 for line in lines[::-1]:
934 if self.marker_regexp.search(line):
935 self._add_code_block_marker = False
936 break
937 if (line.rstrip() and
938 not self.directive_option_regexp.search(line)):
939 self._add_code_block_marker = True
940 break
941 else:
942 self._add_code_block_marker = True
944 # Yield lines::
946 for line in lines:
947 yield line
949 # uncomment_line
950 # ~~~~~~~~~~~~~~
952 # Return documentation line after stripping comment string. Consider the
953 # case that a blank line has a comment string without trailing whitespace::
955 def uncomment_line(self, line):
956 """Return uncommented documentation line"""
957 line = line.replace(self.comment_string, "", 1)
958 if line.rstrip() == self.stripped_comment_string:
959 line = line.replace(self.stripped_comment_string, "", 1)
960 return line
962 # .. _Code2Text.code_block_handler:
964 # code_block_handler
965 # ~~~~~~~~~~~~~~~~~~
967 # The `code_block` handler returns the code block as indented literal
968 # block (or filters it, if ``self.strip == True``). The amount of the code
969 # indentation is controlled by `self.codeindent` (default 2). ::
971 def code_block_handler(self, lines):
972 """Covert code blocks to text format (indent or strip)
974 if self.strip == True:
975 return
976 # eventually insert transition marker
977 if self._add_code_block_marker:
978 self.state = "documentation"
979 yield self.code_block_marker + "\n"
980 yield "\n"
981 self._add_code_block_marker = False
982 self.state = "code_block"
983 for line in lines:
984 yield " "*self.codeindent + line
988 # strip_code_block_marker
989 # ~~~~~~~~~~~~~~~~~~~~~~~
991 # Replace the literal marker with the equivalent of Docutils replace rules
993 # * strip ``::``-line (and preceding blank line) if on a line on its own
994 # * strip ``::`` if it is preceded by whitespace.
995 # * convert ``::`` to a single colon if preceded by text
997 # `lines` is a list of documentation lines (with a trailing blank line).
998 # It is modified in-place::
1000 def strip_code_block_marker(self, lines):
1001 try:
1002 line = lines[-2]
1003 except IndexError:
1004 return # just one line (no trailing blank line)
1006 # match with regexp: `match` is None or has groups
1007 # \1 leading text, \2 code_block_marker, \3 remainder
1008 match = self.marker_regexp.search(line)
1010 if not match: # no code_block_marker present
1011 return
1012 if not match.group(1): # `code_block_marker` on an extra line
1013 del(lines[-2])
1014 # delete preceding line if it is blank
1015 if len(lines) >= 2 and not lines[-2].lstrip():
1016 del(lines[-2])
1017 elif match.group(1).rstrip() < match.group(1):
1018 # '::' follows whitespace
1019 lines[-2] = match.group(1).rstrip() + match.group(3)
1020 else: # '::' follows text
1021 lines[-2] = match.group(1).rstrip() + ':' + match.group(3)
1023 # Filters
1024 # =======
1026 # Filters allow pre- and post-processing of the data to bring it in a format
1027 # suitable for the "normal" text<->code conversion. An example is conversion
1028 # of `C` ``/*`` ``*/`` comments into C++ ``//`` comments (and back).
1029 # Another example is the conversion of `C` ``/*`` ``*/`` comments into C++
1030 # ``//`` comments (and back).
1032 # Filters are generator functions that return an iterator acting on a
1033 # `data` iterable and yielding processed `data` lines.
1035 # identity_filter
1036 # ---------------
1038 # The most basic filter is the identity filter, that returns its argument as
1039 # iterator::
1041 def identity_filter(data):
1042 """Return data iterator without any processing"""
1043 return iter(data)
1045 # expandtabs_filter
1046 # -----------------
1048 # Expand hard-tabs in every line of `data` (cf. `str.expandtabs`).
1050 # This filter is applied to the input data by `TextCodeConverter.convert`_ as
1051 # hard tabs can lead to errors when the indentation is changed. ::
1053 def expandtabs_filter(data):
1054 """Yield data tokens with hard-tabs expanded"""
1055 for line in data:
1056 yield line.expandtabs()
1059 # collect_blocks
1060 # --------------
1062 # A filter to aggregate "paragraphs" (blocks separated by blank
1063 # lines). Yields lists of lines::
1065 def collect_blocks(lines):
1066 """collect lines in a list
1068 yield list for each paragraph, i.e. block of lines separated by a
1069 blank line (whitespace only).
1071 Trailing blank lines are collected as well.
1073 blank_line_reached = False
1074 block = []
1075 for line in lines:
1076 if blank_line_reached and line.rstrip():
1077 yield block
1078 blank_line_reached = False
1079 block = [line]
1080 continue
1081 if not line.rstrip():
1082 blank_line_reached = True
1083 block.append(line)
1084 yield block
1088 # dumb_c_preprocessor
1089 # -------------------
1091 # This is a basic filter to convert `C` to `C++` comments. Works line-wise and
1092 # only converts lines that
1094 # * start with "/\* " and end with " \*/" (followed by whitespace only)
1096 # A more sophisticated version would also
1098 # * convert multi-line comments
1100 # + Keep indentation or strip 3 leading spaces?
1102 # * account for nested comments
1104 # * only convert comments that are separated from code by a blank line
1106 # ::
1108 def dumb_c_preprocessor(data):
1109 """change `C` ``/* `` `` */`` comments into C++ ``// `` comments"""
1110 comment_string = defaults.comment_strings["c++"]
1111 boc_string = "/* "
1112 eoc_string = " */"
1113 for line in data:
1114 if (line.startswith(boc_string)
1115 and line.rstrip().endswith(eoc_string)
1117 line = line.replace(boc_string, comment_string, 1)
1118 line = "".join(line.rsplit(eoc_string, 1))
1119 yield line
1121 # Unfortunately, the `replace` method of strings does not support negative
1122 # numbers for the `count` argument:
1124 # >>> "foo */ baz */ bar".replace(" */", "", -1) == "foo */ baz bar"
1125 # False
1127 # However, there is the `rsplit` method, that can be used together with `join`:
1129 # >>> "".join("foo */ baz */ bar".rsplit(" */", 1)) == "foo */ baz bar"
1130 # True
1132 # dumb_c_postprocessor
1133 # --------------------
1135 # Undo the preparations by the dumb_c_preprocessor and re-insert valid comment
1136 # delimiters ::
1138 def dumb_c_postprocessor(data):
1139 """change C++ ``// `` comments into `C` ``/* `` `` */`` comments"""
1140 comment_string = defaults.comment_strings["c++"]
1141 boc_string = "/* "
1142 eoc_string = " */"
1143 for line in data:
1144 if line.rstrip() == comment_string.rstrip():
1145 line = line.replace(comment_string, "", 1)
1146 elif line.startswith(comment_string):
1147 line = line.replace(comment_string, boc_string, 1)
1148 line = line.rstrip() + eoc_string + "\n"
1149 yield line
1152 # register filters
1153 # ----------------
1155 # ::
1157 defaults.preprocessors['c2text'] = dumb_c_preprocessor
1158 defaults.preprocessors['css2text'] = dumb_c_preprocessor
1159 defaults.postprocessors['text2c'] = dumb_c_postprocessor
1160 defaults.postprocessors['text2css'] = dumb_c_postprocessor
1163 # Command line use
1164 # ================
1166 # Using this script from the command line will convert a file according to its
1167 # extension. This default can be overridden by a couple of options.
1169 # Dual source handling
1170 # --------------------
1172 # How to determine which source is up-to-date?
1173 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1175 # - set modification date of `outfile` to the one of `infile`
1177 # Points out that the source files are 'synchronised'.
1179 # * Are there problems to expect from "backdating" a file? Which?
1181 # Looking at http://www.unix.com/showthread.php?t=20526, it seems
1182 # perfectly legal to set `mtime` (while leaving `ctime`) as `mtime` is a
1183 # description of the "actuality" of the data in the file.
1185 # * Should this become a default or an option?
1187 # - alternatively move input file to a backup copy (with option: `--replace`)
1189 # - check modification date before overwriting
1190 # (with option: `--overwrite=update`)
1192 # - check modification date before editing (implemented as `Jed editor`_
1193 # function `pylit_check()` in `pylit.sl`_)
1195 # .. _Jed editor: http://www.jedsoft.org/jed/
1196 # .. _pylit.sl: http://jedmodes.sourceforge.net/mode/pylit/
1198 # Recognised Filename Extensions
1199 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1201 # Instead of defining a new extension for "pylit" literate programs,
1202 # by default ``.txt`` will be appended for the text source and stripped by
1203 # the conversion to the code source. I.e. for a Python program foo:
1205 # * the code source is called ``foo.py``
1206 # * the text source is called ``foo.py.txt``
1207 # * the html rendering is called ``foo.py.html``
1210 # OptionValues
1211 # ------------
1213 # The following class adds `as_dict`_, `complete`_ and `__getattr__`_
1214 # methods to `optparse.Values`::
1216 class OptionValues(optparse.Values):
1218 # .. _OptionValues.as_dict:
1220 # as_dict
1221 # ~~~~~~~
1223 # For use as keyword arguments, it is handy to have the options in a
1224 # dictionary. `as_dict` returns a copy of the instances object dictionary::
1226 def as_dict(self):
1227 """Return options as dictionary object"""
1228 return self.__dict__.copy()
1230 # .. _OptionValues.complete:
1232 # complete
1233 # ~~~~~~~~
1235 # ::
1237 def complete(self, **keyw):
1239 Complete the option values with keyword arguments.
1241 Do not overwrite existing values. Only use arguments that do not
1242 have a corresponding attribute in `self`,
1244 for key in keyw:
1245 try:
1246 self.__dict__[key]
1247 except KeyError:
1248 setattr(self, key, keyw[key])
1250 # .. _OptionValues.__getattr__:
1252 # __getattr__
1253 # ~~~~~~~~~~~
1255 # To replace calls using ``options.ensure_value("OPTION", None)`` with the
1256 # more concise ``options.OPTION``, we define `__getattr__` [#]_ ::
1258 def __getattr__(self, name):
1259 """Return default value for non existing options"""
1260 return None
1263 # .. [#] The special method `__getattr__` is only called when an attribute
1264 # look-up has not found the attribute in the usual places (i.e. it is
1265 # not an instance attribute nor is it found in the class tree for
1266 # self).
1269 # PylitOptions
1270 # ------------
1272 # The `PylitOptions` class comprises an option parser and methods for parsing
1273 # and completion of command line options::
1275 class PylitOptions(object):
1276 """Storage and handling of command line options for pylit"""
1278 # Instantiation
1279 # ~~~~~~~~~~~~~
1281 # ::
1283 def __init__(self):
1284 """Set up an `OptionParser` instance for pylit command line options
1287 p = optparse.OptionParser(usage=main.__doc__, version=_version)
1289 # Conversion settings
1291 p.add_option("-c", "--code2txt", dest="txt2code", action="store_false",
1292 help="convert code source to text source")
1293 p.add_option("-t", "--txt2code", action="store_true",
1294 help="convert text source to code source")
1295 p.add_option("--language",
1296 choices = list(defaults.comment_strings.keys()),
1297 help="use LANGUAGE native comment style")
1298 p.add_option("--comment-string", dest="comment_string",
1299 help="documentation block marker in code source "
1300 "(including trailing whitespace, "
1301 "default: language dependent)")
1302 p.add_option("-m", "--code-block-marker", dest="code_block_marker",
1303 help="syntax token starting a code block. (default '::')")
1304 p.add_option("--codeindent", type="int",
1305 help="Number of spaces to indent code blocks with "
1306 "text2code (default %d)" % defaults.codeindent)
1308 # Output file handling
1310 p.add_option("--overwrite", action="store",
1311 choices = ["yes", "update", "no"],
1312 help="overwrite output file (default 'update')")
1313 p.add_option("--replace", action="store_true",
1314 help="move infile to a backup copy (appending '~')")
1315 # TODO: do we need this? If yes, make mtime update depend on it!
1316 # p.add_option("--keep-mtime", action="store_true",
1317 # help="do not set the modification time of the outfile "
1318 # "to the corresponding value of the infile")
1319 p.add_option("-s", "--strip", action="store_true",
1320 help='"export" by stripping documentation or code')
1322 # Special actions
1324 p.add_option("-d", "--diff", action="store_true",
1325 help="test for differences to existing file")
1326 p.add_option("--doctest", action="store_true",
1327 help="run doctest.testfile() on the text version")
1328 p.add_option("-e", "--execute", action="store_true",
1329 help="execute code (Python only)")
1331 self.parser = p
1333 # .. _PylitOptions.parse_args:
1335 # parse_args
1336 # ~~~~~~~~~~
1338 # The `parse_args` method calls the `optparse.OptionParser` on command
1339 # line or provided args and returns the result as `PylitOptions.Values`
1340 # instance. Defaults can be provided as keyword arguments::
1342 def parse_args(self, args=sys.argv[1:], **keyw):
1343 """parse command line arguments using `optparse.OptionParser`
1345 parse_args(args, **keyw) -> OptionValues instance
1347 args -- list of command line arguments.
1348 keyw -- keyword arguments or dictionary of option defaults
1350 # parse arguments
1351 (values, args) = self.parser.parse_args(args, OptionValues(keyw))
1352 # Convert FILE and OUTFILE positional args to option values
1353 # (other positional arguments are ignored)
1354 try:
1355 values.infile = args[0]
1356 values.outfile = args[1]
1357 except IndexError:
1358 pass
1360 return values
1362 # .. _PylitOptions.complete_values:
1364 # complete_values
1365 # ~~~~~~~~~~~~~~~
1367 # Complete an OptionValues instance `values`. Use module-level defaults and
1368 # context information to set missing option values to sensible defaults (if
1369 # possible) ::
1371 def complete_values(self, values):
1372 """complete option values with module and context sensible defaults
1374 x.complete_values(values) -> values
1375 values -- OptionValues instance
1378 # Complete with module-level defaults_::
1380 values.complete(**defaults.__dict__)
1382 # Ensure infile is a string::
1384 values.ensure_value("infile", "")
1386 # Guess conversion direction from `infile` filename::
1388 if values.txt2code is None:
1389 in_extension = os.path.splitext(values.infile)[1]
1390 if in_extension in values.text_extensions:
1391 values.txt2code = True
1392 elif in_extension in values.languages.keys():
1393 values.txt2code = False
1395 # Auto-determine the output file name::
1397 values.ensure_value("outfile", self._get_outfile_name(values))
1399 # Second try: Guess conversion direction from outfile filename::
1401 if values.txt2code is None:
1402 out_extension = os.path.splitext(values.outfile)[1]
1403 values.txt2code = not (out_extension in values.text_extensions)
1405 # Set the language of the code::
1407 if values.txt2code is True:
1408 code_extension = os.path.splitext(values.outfile)[1]
1409 elif values.txt2code is False:
1410 code_extension = os.path.splitext(values.infile)[1]
1411 values.ensure_value("language", values.languages[code_extension])
1413 return values
1415 # _get_outfile_name
1416 # ~~~~~~~~~~~~~~~~~
1418 # Construct a matching filename for the output file. The output filename is
1419 # constructed from `infile` by the following rules:
1421 # * '-' (stdin) results in '-' (stdout)
1422 # * strip the `text_extension`_ (txt2code) or
1423 # * add the `text_extension`_ (code2txt)
1424 # * fallback: if no guess can be made, add ".out"
1426 # .. TODO: use values.outfile_extension if it exists?
1428 # ::
1430 def _get_outfile_name(self, values):
1431 """Return a matching output filename for `infile`
1433 # if input is stdin, default output is stdout
1434 if values.infile == '-':
1435 return '-'
1437 # Derive from `infile` name: strip or add text extension
1438 (base, ext) = os.path.splitext(values.infile)
1439 if ext in values.text_extensions:
1440 return base # strip
1441 if ext and ext in values.languages or values.txt2code == False:
1442 return values.infile + values.text_extensions[0] # add
1443 # give up
1444 return values.infile + ".out"
1446 # .. _PylitOptions.__call__:
1448 # __call__
1449 # ~~~~~~~~
1451 # The special `__call__` method allows to use PylitOptions instances as
1452 # *callables*: Calling an instance parses the argument list to extract option
1453 # values and completes them based on "context-sensitive defaults". Keyword
1454 # arguments are passed to `PylitOptions.parse_args`_ as default values. ::
1456 def __call__(self, args=sys.argv[1:], **keyw):
1457 """parse and complete command line args return option values
1459 values = self.parse_args(args, **keyw)
1460 return self.complete_values(values)
1464 # Helper functions
1465 # ----------------
1467 # open_streams
1468 # ~~~~~~~~~~~~
1470 # Return file objects for in- and output. If the input path is missing,
1471 # write usage and abort. (An alternative would be to use stdin as default.
1472 # However, this leaves the uninitiated user with a non-responding application
1473 # if (s)he just tries the script without any arguments) ::
1475 def open_streams(infile = '-', outfile = '-', overwrite='update', **keyw):
1476 """Open and return the input and output stream
1478 open_streams(infile, outfile) -> (in_stream, out_stream)
1480 in_stream -- file(infile) or sys.stdin
1481 out_stream -- file(outfile) or sys.stdout
1482 overwrite -- 'yes': overwrite eventually existing `outfile`,
1483 'update': fail if the `outfile` is newer than `infile`,
1484 'no': fail if `outfile` exists.
1486 Irrelevant if `outfile` == '-'.
1488 if overwrite not in ('yes', 'no', 'update'):
1489 raise ValueError('Argument "overwrite" must be yes, no, or update".')
1490 if not infile:
1491 strerror = "Missing input file name ('-' for stdin; -h for help)"
1492 raise IOError(2, strerror, infile)
1493 if infile == '-':
1494 in_stream = sys.stdin
1495 else:
1496 in_stream = open(infile, 'r')
1497 if outfile == '-':
1498 out_stream = sys.stdout
1499 elif overwrite == 'no' and os.path.exists(outfile):
1500 raise IOError(17, "Output file exists!", outfile)
1501 elif overwrite == 'update' and is_newer(outfile, infile) is None:
1502 raise IOError(0, "Output file is as old as input file!", outfile)
1503 elif overwrite == 'update' and is_newer(outfile, infile):
1504 raise IOError(1, "Output file is newer than input file!", outfile)
1505 else:
1506 out_stream = open(outfile, 'w')
1507 return (in_stream, out_stream)
1509 # is_newer
1510 # ~~~~~~~~
1512 # ::
1514 def is_newer(path1, path2):
1515 """Check if `path1` is newer than `path2` (using mtime)
1517 Compare modification time of files at path1 and path2.
1519 Non-existing files are considered oldest: Return False if path1 does not
1520 exist and True if path2 does not exist.
1522 Return None if the modification time differs less than 1/10 second.
1523 (This evaluates to False in a Boolean context but allows a test
1524 for equality.)
1526 try:
1527 mtime1 = os.path.getmtime(path1)
1528 except OSError:
1529 mtime1 = -1
1530 try:
1531 mtime2 = os.path.getmtime(path2)
1532 except OSError:
1533 mtime2 = -1
1534 if abs(mtime1 - mtime2) < 0.1:
1535 return None
1536 return mtime1 > mtime2
1539 # get_converter
1540 # ~~~~~~~~~~~~~
1542 # Get an instance of the converter state machine::
1544 def get_converter(data, txt2code=True, **keyw):
1545 if txt2code:
1546 return Text2Code(data, **keyw)
1547 else:
1548 return Code2Text(data, **keyw)
1551 # Use cases
1552 # ---------
1554 # run_doctest
1555 # ~~~~~~~~~~~
1556 # ::
1558 def run_doctest(infile="-", txt2code=True,
1559 globs={}, verbose=False, optionflags=0, **keyw):
1560 """run doctest on the text source
1563 # Allow imports from the current working dir by prepending an empty string to
1564 # sys.path (see doc of sys.path())::
1566 sys.path.insert(0, '')
1568 # Import classes from the doctest module::
1570 from doctest import DocTestParser, DocTestRunner
1572 # Read in source. Make sure it is in text format, as tests in comments are not
1573 # found by doctest::
1575 (data, out_stream) = open_streams(infile, "-")
1576 if txt2code is False:
1577 keyw.update({'add_missing_marker': False})
1578 converter = Code2Text(data, **keyw)
1579 docstring = str(converter)
1580 else:
1581 docstring = data.read()
1583 # decode doc string if there is a "magic comment" in the first or second line
1584 # (http://docs.python.org/reference/lexical_analysis.html#encoding-declarations)
1585 # ::
1587 if sys.version_info < (3,0):
1588 firstlines = ' '.join(docstring.splitlines()[:2])
1589 match = re.search('coding[=:]\s*([-\w.]+)', firstlines)
1590 if match:
1591 docencoding = match.group(1)
1592 docstring = docstring.decode(docencoding)
1594 # Use the doctest Advanced API to run all doctests in the source text::
1596 test = DocTestParser().get_doctest(docstring, globs, name="",
1597 filename=infile, lineno=0)
1598 runner = DocTestRunner(verbose, optionflags)
1599 runner.run(test)
1600 runner.summarize
1601 # give feedback also if no failures occurred
1602 if not runner.failures:
1603 print("%d failures in %d tests"%(runner.failures, runner.tries))
1604 return runner.failures, runner.tries
1607 # diff
1608 # ~~~~
1610 # ::
1612 def diff(infile='-', outfile='-', txt2code=True, **keyw):
1613 """Report differences between converted infile and existing outfile
1615 If outfile does not exist or is '-', do a round-trip conversion and
1616 report differences.
1619 import difflib
1621 instream = open(infile)
1622 # for diffing, we need a copy of the data as list::
1623 data = instream.readlines()
1624 # convert
1625 converter = get_converter(data, txt2code, **keyw)
1626 new = converter()
1628 if outfile != '-' and os.path.exists(outfile):
1629 outstream = open(outfile)
1630 old = outstream.readlines()
1631 oldname = outfile
1632 newname = "<conversion of %s>"%infile
1633 else:
1634 old = data
1635 oldname = infile
1636 # back-convert the output data
1637 converter = get_converter(new, not txt2code)
1638 new = converter()
1639 newname = "<round-conversion of %s>"%infile
1641 # find and print the differences
1642 is_different = False
1643 # print(type(old), old)
1644 # print(type(new), new)
1645 delta = difflib.unified_diff(old, new,
1646 # delta = difflib.unified_diff(["heute\n", "schon\n"], ["heute\n", "noch\n"],
1647 fromfile=oldname, tofile=newname)
1648 for line in delta:
1649 is_different = True
1650 print(line, end=' ') #sys.stdout.write(line + ' ')
1651 if not is_different:
1652 print(oldname)
1653 print(newname)
1654 print("no differences found")
1655 return is_different
1658 # execute
1659 # ~~~~~~~
1661 # Works only for python code.
1663 # Does not work with `eval`, as code is not just one expression. ::
1665 def execute(infile="-", txt2code=True, **keyw):
1666 """Execute the input file. Convert first, if it is a text source.
1669 data = open(infile)
1670 if txt2code:
1671 data = str(Text2Code(data, **keyw))
1672 # print("executing " + options.infile)
1673 exec(data)
1676 # main
1677 # ----
1679 # If this script is called from the command line, the `main` function will
1680 # convert the input (file or stdin) between text and code formats.
1682 # Option default values for the conversion can be given as keyword arguments
1683 # to `main`_. The option defaults will be updated by command line options and
1684 # extended with "intelligent guesses" by `PylitOptions`_ and passed on to
1685 # helper functions and the converter instantiation.
1687 # This allows easy customisation for programmatic use -- just call `main`
1688 # with the appropriate keyword options, e.g. ``pylit.main(comment_string="## ")``
1690 # ::
1692 def main(args=sys.argv[1:], **defaults):
1693 """%prog [options] INFILE [OUTFILE]
1695 Convert between (reStructured) text source with embedded code,
1696 and code source with embedded documentation (comment blocks)
1698 The special filename '-' stands for standard in and output.
1701 # Parse and complete the options::
1703 options = PylitOptions()(args, **defaults)
1704 # print("infile", repr(options.infile))
1706 # Special actions with early return::
1708 if options.doctest:
1709 return run_doctest(**options.as_dict())
1711 if options.diff:
1712 return diff(**options.as_dict())
1714 if options.execute:
1715 return execute(**options.as_dict())
1717 # Open in- and output streams::
1719 try:
1720 (data, out_stream) = open_streams(**options.as_dict())
1721 except IOError as ex:
1722 print("IOError: %s %s" % (ex.filename, ex.strerror))
1723 sys.exit(ex.errno)
1725 # Get a converter instance::
1727 converter = get_converter(data, **options.as_dict())
1729 # Convert and write to out_stream::
1731 out_stream.write(str(converter))
1733 if out_stream is not sys.stdout:
1734 print("extract written to", out_stream.name)
1735 out_stream.close()
1737 # If input and output are from files, set the modification time (`mtime`) of
1738 # the output file to the one of the input file to indicate that the contained
1739 # information is equal. [#]_ ::
1742 # print("fractions?", os.stat_float_times())
1743 try:
1744 os.utime(options.outfile, (os.path.getatime(options.outfile),
1745 os.path.getmtime(options.infile))
1747 except OSError:
1748 pass
1750 ## print("mtime", os.path.getmtime(options.infile), options.infile)
1751 ## print("mtime", os.path.getmtime(options.outfile), options.outfile)
1754 # .. [#] Make sure the corresponding file object (here `out_stream`) is
1755 # closed, as otherwise the change will be overwritten when `close` is
1756 # called afterwards (either explicitly or at program exit).
1759 # Rename the infile to a backup copy if ``--replace`` is set::
1761 if options.replace:
1762 os.rename(options.infile, options.infile + "~")
1765 # Run main, if called from the command line::
1767 if __name__ == '__main__':
1768 main()
1771 # Open questions
1772 # ==============
1774 # Open questions and ideas for further development
1776 # Clean code
1777 # ----------
1779 # * can we gain from using "shutils" over "os.path" and "os"?
1780 # * use pylint or pyChecker to enforce a consistent style?
1782 # Options
1783 # -------
1785 # * Use templates for the "intelligent guesses" (with Python syntax for string
1786 # replacement with dicts: ``"hello %(what)s" % {'what': 'world'}``)
1788 # * Is it sensible to offer the `header_string` option also as command line
1789 # option?
1791 # treatment of blank lines
1792 # ------------------------
1794 # Alternatives: Keep blank lines blank
1796 # - "never" (current setting) -> "visually merges" all documentation
1797 # if there is no interjacent code
1799 # - "always" -> disrupts documentation blocks,
1801 # - "if empty" (no whitespace). Comment if there is whitespace.
1803 # This would allow non-obstructing markup but unfortunately this is (in
1804 # most editors) also non-visible markup.
1806 # + "if double" (if there is more than one consecutive blank line)
1808 # With this handling, the "visual gap" remains in both, text and code
1809 # source.
1812 # Parsing Problems
1813 # ----------------
1815 # * Ignore "matching comments" in literal strings?
1817 # Too complicated: Would need a specific detection algorithm for every
1818 # language that supports multi-line literal strings (C++, PHP, Python)
1820 # * Warn if a comment in code will become documentation after round-trip?
1823 # docstrings in code blocks
1824 # -------------------------
1826 # * How to handle docstrings in code blocks? (it would be nice to convert them
1827 # to rst-text if ``__docformat__ == restructuredtext``)
1829 # TODO: Ask at Docutils users|developers
1831 # Plug-ins
1832 # --------
1834 # Specify a path for user additions and plug-ins. This would require to
1835 # convert Pylit from a pure module to a package...
1837 # 6.4.3 Packages in Multiple Directories
1839 # Packages support one more special attribute, __path__. This is initialized
1840 # to be a list containing the name of the directory holding the package's
1841 # __init__.py before the code in that file is executed. This
1842 # variable can be modified; doing so affects future searches for modules and
1843 # subpackages contained in the package.
1845 # While this feature is not often needed, it can be used to extend the set
1846 # of modules found in a package.
1849 # .. References
1851 # .. _Docutils: http://docutils.sourceforge.net/
1852 # .. _Sphinx: http://sphinx.pocoo.org
1853 # .. _Pygments: http://pygments.org/
1854 # .. _code-block directive:
1855 # http://docutils.sourceforge.net/sandbox/code-block-directive/
1856 # .. _literal block:
1857 # .. _literal blocks:
1858 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#literal-blocks
1859 # .. _indented literal block:
1860 # .. _indented literal blocks:
1861 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#indented-literal-blocks
1862 # .. _quoted literal block:
1863 # .. _quoted literal blocks:
1864 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#quoted-literal-blocks
1865 # .. _parsed-literal blocks:
1866 # http://docutils.sf.net/docs/ref/rst/directives.html#parsed-literal-block
1867 # .. _doctest block:
1868 # .. _doctest blocks:
1869 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#doctest-blocks
1871 # .. _feature request and patch by jrioux:
1872 # http://developer.berlios.de/feature/?func=detailfeature&feature_id=4890&group_id=7974