Documentation update.
[pylit.git] / pylit.py
blob698519727a3007068e6a5f77129530644550e07c
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 # .. Change default `codeindent`_ to 2.
112 # .. Switch to `argparse`_. Remove class `OptionValues`.
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 import os
141 import re
142 import sys
145 # DefaultDict
146 # ~~~~~~~~~~~
148 # As `collections.defaultdict` adds key/value pairs when the default
149 # constructor is called, we define an alternative that does not mutate the
150 # dict as side-effect. ::
152 class DefaultDict(dict):
153 """Dictionary with default value."""
155 default = 'python'
157 def __missing__(self, key):
158 # cf. file:///usr/share/doc/python3/html/library/stdtypes.html#dict
159 return self.default
162 # defaults
163 # ========
165 # The `defaults` object provides a central repository for default
166 # values and their customisation. ::
168 defaults = argparse.Namespace()
170 # It is used for
172 # * the initialisation of data arguments in TextCodeConverter_ and
173 # PylitOptions_
175 # * completion of `command line arguments`_ in `PylitOptions.complete_values()`_.
177 # This allows the easy creation of _`back-ends` that customise the
178 # defaults and then call `main()`_ e.g.
180 # .. code:: python
182 # #!/usr/bin/env python
183 # import pylit
185 # pylit.defaults.code_block_marker['c++'] = '.. code-block:: c++'
186 # pylit.defaults.languages['.def'] = 'latex'
187 # pylit.defaults.languages['.dfu'] = 'latex'
189 # pylit.main()
191 # .. note:: Defaults for the `command line arguments`_ can also be specified as keyword
192 # arguments to ``main()``
194 # .. code:: python
196 # #!/usr/bin/env python
197 # import pylit
198 # pylit.main(language='c++')
200 # The following default values are defined in pylit.py:
202 # language
203 # --------
205 # Code language. Determined from languages_ if ``None``::
207 defaults.language = None
209 # languages
210 # ---------
212 # Mapping of code file extensions to code language::
214 defaults.languages = DefaultDict({".c": "c",
215 ".cc": "c++",
216 ".css": "css",
217 ".lua": "lua",
218 ".py": "python",
219 ".sh": "shell",
220 ".sl": "slang",
221 ".sty": "latex",
222 ".tex": "latex"
225 # The result can be overridden by the ``--language`` command line option.
227 # The fallback language, used if there is no matching extension (e.g. if pylit
228 # is used as filter) and no ``--language`` is specified is ``"python"``::
230 defaults.languages.default = 'python'
232 # It can be changed programmatically by changing the ``.default``
233 # attribute, e.g.
235 # >>> import pylit
236 # >>> pylit.defaults.languages.default = 'c++'
237 # >>> pylit.defaults.languages['.camel']
238 # 'c++'
240 # .. _text_extension:
242 # text_extensions
243 # ---------------
245 # List of known extensions of (reStructured) text files. The first
246 # extension in this list is used by the `_get_outfile_name()`_ method to
247 # generate a text output filename::
249 defaults.text_extensions = [".txt", ".rst"]
251 # comment_string
252 # --------------
254 # Used in Code2Text_ to recognise text blocks and in Text2Code_ to format
255 # text blocks as comments.
256 # Determined from comment_strings_ if ``None``::
258 defaults.comment_string = None
261 # comment_strings
262 # ---------------
264 # Comment strings for known languages.
265 # The fallback value is ``'# '``.
267 # **Comment strings include trailing whitespace.** ::
269 defaults.comment_strings = DefaultDict({"css": '// ',
270 "c": '// ',
271 "c++": '// ',
272 "lua": '-- ',
273 "latex": '% ',
274 "python": '# ',
275 "shell": '# ',
276 "slang": '% '
278 defaults.comment_strings.default = '# '
280 # header_string
281 # -------------
283 # Marker string for a header code block in the text source. No trailing
284 # whitespace needed as indented code follows.
285 # Must be a valid rst directive that accepts code on the same line, e.g.
286 # ``'..admonition::'``.
288 # Default is a comment marker::
290 defaults.header_string = '..'
293 # code_block_marker
294 # -----------------
296 # Markup at the end of a documentation block.
298 # The `code_block_marker` string is determined based on the code language_
299 # and `inserted into a regular expression`_.
301 # defaults.code_block_marker = None # get from `code_block_markers`
303 # code_block_markers
304 # ------------------
306 # Language-specific code-block markers can be defined programmatically in
307 # back-ends_.
309 # The fallback value is Docutils' marker for a `literal block`_::
311 defaults.code_block_markers = DefaultDict()
312 defaults.code_block_markers.default = '::'
314 # In a document where code examples are only one of several uses of
315 # literal blocks, it is more appropriate to single out the source code,
316 # e.g., with the double colon at a separate line ("expanded form")
318 # ``defaults.code_block_marker.default = ':: *'``
320 # or a dedicated ``.. code-block::`` directive
322 # ``defaults.code_block_marker['c++'] = '.. code-block:: *c++'``
324 # The latter form also allows mixing code in different languages in one
325 # literate source file.
328 # strip
329 # -----
331 # Strip documentation (or code) blocks from the output::
333 defaults.strip = False
336 # strip_marker
337 # ------------
339 # Strip `code_block_marker`_ from the end of documentation blocks when
340 # converting to code format. Makes the code more concise but looses the
341 # synchronisation of line numbers in text and code formats.
343 # Can be used together with `add_missing_marker`_ to change
344 # the `code_block_marker`_ in a round trip::
346 defaults.strip_marker = False
349 # add_missing_marker
350 # ------------------
352 # When converting from code format to text format, add a `code_block_marker`_
353 # at the end of documentation blocks if it is missing::
355 defaults.add_missing_marker = True
357 # Keep this at ``True``, if you want to re-convert to code format later!
360 # .. _defaults.preprocessors:
362 # preprocessors
363 # -------------
365 # Preprocess the data with language-specific Filters_
366 # (cf. `register filters`_)::
368 defaults.preprocessors = {}
370 # .. _defaults.postprocessors:
372 # postprocessors
373 # --------------
375 # Postprocess the data with language-specific Filters_
376 # (cf. `register filters`_)::
378 defaults.postprocessors = {}
380 # .. _defaults.codeindent:
382 # codeindent
383 # ----------
385 # Number of spaces to indent code blocks in `Code2Text.code_block_handler()`_::
387 defaults.codeindent = 2
389 # In `Text2Code.code_block_handler()`_, the codeindent is determined by the
390 # first recognised code line (header or first indented literal block
391 # of the text source).
393 # overwrite
394 # ---------
396 # What to do if the outfile already exists? (ignored if `outfile` == '-')::
398 defaults.overwrite = 'update'
400 # Recognised values:
402 # :'yes': overwrite eventually existing `outfile`,
403 # :'update': fail if the `outfile` is newer than `infile`,
404 # TODO: fix behaviour if both are of same age
405 # :'no': fail if `outfile` exists.
408 # Actions: execute, doctest, diff
409 # -------------------------------
410 # If true, these actions replace or follow the txt<->code conversion.
411 # See `command line arguments`_. ::
413 defaults.execute = False
414 defaults.doctest = False
415 defaults.diff = False
417 # Initial values
418 # --------------
420 # The following settings are auto-determined if None
421 # (see `PylitOptions.complete_values()`_).
422 # Initialize them here as they will not be set by
423 # `ArgumentParser.parse_args()`_::
425 # defaults.infile = '' # required
426 defaults.outfile = None
427 defaults.replace = None
428 defaults.txt2code = None
431 # Extensions
432 # ==========
434 # Try to import optional extensions::
436 try:
437 import pylit_elisp # noqa
438 except ImportError:
439 pass
442 # Converter Classes
443 # =================
445 # The converter classes implement a simple state machine to separate and
446 # transform documentation and code blocks. For this task, only a very limited
447 # parsing is needed. PyLit's parser assumes:
449 # * `indented literal blocks`_ in a text source are code blocks.
451 # * comment blocks in a code source where every line starts with a matching
452 # `comment_string`_ are documentation blocks.
454 # TextCodeConverter
455 # -----------------
456 # ::
458 class TextCodeConverter(object):
459 """Parent class for the converters `Text2Code` and `Code2Text`.
462 # The parent class defines data attributes and functions used in both
463 # `Text2Code`_ converting a text source to executable code source, and
464 # `Code2Text`_ converting commented code to a text source.
466 # Data attributes
467 # ~~~~~~~~~~~~~~~
469 # Class default values are fetched from the `defaults`_ object and can be
470 # overridden by matching keyword arguments during class instantiation. This
471 # also works with keyword arguments to `get_converter()`_ and `main()`_, as these
472 # functions pass on unused keyword args to the instantiation of a converter
473 # class. ::
475 language = defaults.languages[None]
476 comment_strings = defaults.comment_strings
477 comment_string = "" # set in __init__ (if empty)
478 codeindent = defaults.codeindent
479 header_string = defaults.header_string
480 code_block_markers = defaults.code_block_markers
481 code_block_marker = "" # set in __init__ (if empty)
482 strip = defaults.strip
483 strip_marker = defaults.strip_marker
484 add_missing_marker = defaults.add_missing_marker
485 directive_option_regexp = re.compile(r' +:(\w|[-._+:])+:( |$)')
486 state = "" # type of current block, see `TextCodeConverter.convert`_
488 # Interface methods
489 # ~~~~~~~~~~~~~~~~~
491 # .. _TextCodeConverter.__init__:
493 # __init__()
494 # """"""""""
496 # Initialising sets the `data` attribute, an iterable object yielding lines of
497 # the source to convert. [#]_
499 # .. [#] The most common choice of data is a `file` object with the text
500 # or code source.
502 # To convert a string into a suitable object, use its splitlines()
503 # method like ``"2 lines\nof source".splitlines(True)``.
506 # Additional keyword arguments are stored as instance variables,
507 # overwriting the class defaults::
509 def __init__(self, data, **keyw):
510 """data -- iterable data object
511 (list, file, generator, string, ...)
512 **keyw -- remaining keyword arguments are
513 stored as data-attributes
515 self.data = data
516 self.__dict__.update(keyw)
518 # If empty, `code_block_marker` and `comment_string` are set according
519 # to the `language`::
521 if not self.code_block_marker:
522 self.code_block_marker = self.code_block_markers[self.language]
523 if not self.comment_string:
524 self.comment_string = self.comment_strings[self.language]
525 self.stripped_comment_string = self.comment_string.rstrip()
527 # Pre- and postprocessing filters are set (with
528 # `TextCodeConverter.get_filter`_)::
530 self.preprocessor = self.get_filter("preprocessors", self.language)
531 self.postprocessor = self.get_filter("postprocessors", self.language)
533 # .. _inserted into a regular expression:
535 # Finally, a regular_expression for the `code_block_marker` is compiled
536 # to find valid cases of `code_block_marker` in a given line and return
537 # the groups: ``\1 prefix, \2 code_block_marker, \3 remainder`` ::
539 marker = self.code_block_marker
540 if marker == '::':
541 # the default marker may occur at the end of a text line
542 self.marker_regexp = re.compile('^( *(?!\.\.).*)(::)([ \n]*)$')
543 else:
544 # marker must be on a separate line
545 self.marker_regexp = re.compile('^( *)(%s)(.*\n?)$' % marker)
547 # .. _TextCodeConverter.__iter__:
549 # __iter__()
550 # """"""""""
552 # Return an iterator for the instance. Iteration yields lines of converted
553 # data.
555 # The iterator is a chain of iterators acting on `self.data` that does
557 # * preprocessing
558 # * text<->code format conversion
559 # * postprocessing
561 # Pre- and postprocessing are only performed, if filters for the current
562 # language are registered in `defaults.preprocessors`_ and|or
563 # `defaults.postprocessors`_. The filters must accept an iterable as first
564 # argument and yield the processed input data line-wise.
565 # ::
567 def __iter__(self):
568 """Iterate over input data source and yield converted lines
570 return self.postprocessor(self.convert(self.preprocessor(self.data)))
573 # .. _TextCodeConverter.__call__:
575 # __call__()
576 # """"""""""
577 # The special `__call__` method allows the use of class instances as callable
578 # objects. It returns the converted data as list of lines::
580 def __call__(self):
581 """Iterate over state-machine and return results as list of lines"""
582 return [line for line in self]
585 # .. _TextCodeConverter.__str__:
587 # __str__()
588 # """""""""
589 # Return converted data as string::
591 def __str__(self):
592 return "".join(self())
595 # Helpers and convenience methods
596 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
598 # .. _TextCodeConverter.convert:
600 # convert()
601 # """""""""
603 # The `convert` method generates an iterator that does the actual code <-->
604 # text format conversion. The converted data is yielded line-wise and the
605 # instance's `status` argument indicates whether the current line is "header",
606 # "documentation", or "code_block"::
608 def convert(self, lines):
609 """Iterate over lines of a program document and convert
610 between "text" and "code" format
613 # Initialise internal data arguments. (Done here, so that every new iteration
614 # re-initialises them.)
616 # `state`
617 # the "type" of the currently processed block of lines. One of
619 # :"": initial state: check for header,
620 # :"header": leading code block: strip `header_string`,
621 # :"documentation": documentation part: comment out,
622 # :"code_block": literal blocks containing source code: unindent.
624 # ::
626 self.state = ""
628 # `_codeindent`
629 # * Do not confuse the internal attribute `_codeindent` with the configurable
630 # `codeindent` (without the leading underscore).
631 # * `_codeindent` is set in `Text2Code.code_block_handler()`_ to the indent of
632 # first non-blank "code_block" line and stripped from all "code_block" lines
633 # in the text-to-code conversion,
634 # * `codeindent` is set in `__init__` to `defaults.codeindent`_ and added to
635 # "code_block" lines in the code-to-text conversion.
637 # ::
639 self._codeindent = 0
641 # `_textindent`
642 # * set by `Text2Code.documentation_handler()`_ to the minimal indent of a
643 # documentation block,
644 # * used in `Text2Code.set_state`_ to find the end of a code block.
646 # ::
648 self._textindent = 0
650 # `_add_code_block_marker`
651 # If the last paragraph of a documentation block does not end with a
652 # code_block_marker_, it should be added (otherwise, the back-conversion
653 # fails.).
655 # `_add_code_block_marker` is set by `Code2Text.documentation_handler()`_
656 # and evaluated by `Code2Text.code_block_handler()`_, because the
657 # documentation_handler does not know whether the next block will be
658 # documentation (with no need for a code_block_marker) or a code block.
660 # ::
662 self._add_code_block_marker = False
666 # Determine the state of the block and convert with the matching "handler"::
668 for block in collect_blocks(expandtabs_filter(lines)):
669 try:
670 self.set_state(block)
671 except StopIteration:
672 return
673 for line in getattr(self, self.state+"_handler")(block):
674 yield line
677 # .. _TextCodeConverter.get_filter:
679 # get_filter()
680 # """"""""""""
681 # ::
683 def get_filter(self, filter_set, language):
684 """Return language specific filter"""
685 if self.__class__ == Text2Code:
686 key = "text2"+language
687 elif self.__class__ == Code2Text:
688 key = language+"2text"
689 else:
690 key = ""
691 try:
692 return getattr(defaults, filter_set)[key]
693 except (AttributeError, KeyError, TypeError):
694 # print("there is no %r filter in %r"%(key, filter_set))
695 pass
696 return identity_filter
699 # get_indent()
700 # """"""""""""
701 # Return the number of leading spaces in `line`::
703 def get_indent(self, line):
704 """Return the indentation of `string`.
706 return len(line) - len(line.lstrip())
709 # Text2Code
710 # ---------
712 # The `Text2Code` converter separates *code-blocks* [#]_ from *documentation*.
713 # Code blocks are unindented, documentation is commented (or filtered, if the
714 # ``strip`` option is True).
716 # .. [#] Only `indented literal blocks`_ are considered code-blocks. `quoted
717 # literal blocks`_, `parsed-literal blocks`_, and `doctest blocks`_ are
718 # treated as part of the documentation. This allows the inclusion of
719 # examples:
721 # >>> 23 + 3
722 # 26
724 # Mark that there is no double colon before the doctest block in the
725 # text source.
727 # The class inherits the interface and helper functions from
728 # TextCodeConverter_ and adds functions specific to the text-to-code format
729 # conversion::
731 class Text2Code(TextCodeConverter):
732 """Convert a (reStructured) text source to code source
735 # .. _Text2Code.set_state:
737 # set_state()
738 # ~~~~~~~~~~~
739 # ::
741 def set_state(self, block):
742 """Determine state of `block`. Set `self.state`
745 # `set_state` is used inside an iteration. Hence, if we are out of data, a
746 # StopItertion exception should be raised::
748 if not block:
749 raise StopIteration
751 # The new state depends on the active state (from the last block) and
752 # features of the current block. It is either "header", "documentation", or
753 # "code_block".
755 # If the current state is "" (first block), check for
756 # the `header_string` indicating a leading code block::
758 if self.state == "":
759 # print("set state for %r"%block)
760 if block[0].startswith(self.header_string):
761 self.state = "header"
762 else:
763 self.state = "documentation"
765 # If the current state is "documentation", the next block is also
766 # documentation. The end of a documentation part is detected in the
767 # `Text2Code.documentation_handler()`_::
769 # elif self.state == "documentation":
770 # self.state = "documentation"
772 # A "code_block" ends with the first less indented, non-blank line.
773 # `_textindent` is set by the documentation handler to the indent of the
774 # preceding documentation block::
776 elif self.state in ["code_block", "header"]:
777 indents = [self.get_indent(line) for line in block
778 if line.rstrip()]
779 # print("set_state:", indents, self._textindent)
780 if indents and min(indents) <= self._textindent:
781 self.state = 'documentation'
782 else:
783 self.state = 'code_block'
785 # TODO: (or not to do?) insert blank line before the first line with too-small
786 # codeindent using self.ensure_trailing_blank_line(lines, line) (would need
787 # split and push-back of the documentation part)?
790 # .. _Text2Code.header_handler():
792 # header_handler()
793 # ~~~~~~~~~~~~~~~~
795 # Sometimes code needs to remain on the first line(s) of the document to be
796 # valid. The most common example is the "shebang" line that tells a POSIX
797 # shell how to process an executable file::
799 #!/usr/bin/env python
801 # In Python, the special comment to indicate the encoding, e.g.
802 # ``# -*- coding: iso-8859-1 -*-``, must occur before any other comment
803 # or code too.
805 # If we want to keep the line numbers in sync for text and code source, the
806 # reStructured Text markup for these header lines must start at the same line
807 # as the first header line. Therefore, header lines could not be marked as
808 # literal block (this would require the ``::`` and an empty line above the
809 # code_block).
811 # OTOH, a comment may start at the same line as the comment marker and it
812 # includes subsequent indented lines. Comments are visible in the reStructured
813 # Text source but hidden in the pretty-printed output.
815 # With a header converted to comment in the text source, everything before
816 # the first documentation block (i.e. before the first paragraph using the
817 # matching comment string) will be hidden away (in HTML or PDF output).
819 # This seems a good compromise, the advantages
821 # * line numbers are kept
822 # * the "normal" code_block conversion rules (indent/unindent by `codeindent` apply
823 # * greater flexibility: you can hide a repeating header in a project
824 # consisting of many source files.
826 # set off the disadvantages
828 # - it may come as surprise if a part of the file is not "printed",
829 # - one more syntax element to learn for rst newbies to start with pylit,
830 # (however, starting from the code source, this will be auto-generated)
832 # In the case that there is no matching comment at all, the complete code
833 # source will become a comment -- however, in this case it is not very likely
834 # the source is a literate document anyway.
836 # If needed for the documentation, it is possible to quote the header in (or
837 # after) the first documentation block, e.g. as `parsed literal`.
838 # ::
840 def header_handler(self, lines):
841 """Format leading code block"""
842 # strip header string from first line
843 lines[0] = lines[0].replace(self.header_string, "", 1)
844 # yield remaining lines formatted as code-block
845 for line in self.code_block_handler(lines):
846 yield line
849 # .. _Text2Code.documentation_handler():
851 # documentation_handler()
852 # ~~~~~~~~~~~~~~~~~~~~~~~
854 # The 'documentation' handler processes everything that is not recognised as
855 # "code_block". Documentation is quoted with `self.comment_string`
856 # (or filtered with `--strip=True`).
858 # If end-of-documentation marker is detected,
860 # * set state to 'code_block'
861 # * set `self._textindent` (needed by `Text2Code.set_state`_ to find the
862 # next "documentation" block)
864 # ::
866 def documentation_handler(self, lines):
867 """Convert documentation blocks from text to code format
869 for line in lines:
870 # test lines following the code-block marker for false positives
871 if (self.state == "code_block" and line.rstrip()
872 and not self.directive_option_regexp.search(line)):
873 self.state = "documentation"
874 # test for end of documentation block
875 if self.marker_regexp.search(line):
876 self.state = "code_block"
877 self._textindent = self.get_indent(line)
878 # yield lines
879 if self.strip:
880 continue
881 # do not comment blank lines preceding a code block
882 if line.rstrip():
883 yield self.comment_string + line
884 else:
885 if self.state == "code_block":
886 yield line
887 else:
888 yield self.comment_string.rstrip() + line
892 # .. _Text2Code.code_block_handler():
894 # code_block_handler()
895 # ~~~~~~~~~~~~~~~~~~~~
897 # The "code_block" handler is called with an indented literal block. It
898 # removes leading whitespace up to the indentation of the first code line in
899 # the file (this deviation from Docutils behaviour allows indented blocks of
900 # Python code). ::
902 def code_block_handler(self, block):
903 """Convert indented literal blocks to source code format
906 # If still unset, determine the indentation of code blocks from first non-blank
907 # code line::
909 if self._codeindent == 0:
910 self._codeindent = self.get_indent(block[0])
912 # Yield unindented lines after check whether we can safely unindent. If the
913 # line is less indented then `_codeindent`, something got wrong. ::
915 for line in block:
916 if line.lstrip() and self.get_indent(line) < self._codeindent:
917 raise ValueError("code block contains line less indented "
918 "than %d spaces \n%r"%(self._codeindent, block))
919 yield line.replace(" "*self._codeindent, "", 1)
922 # Code2Text
923 # ---------
925 # The `Code2Text` converter does the opposite of `Text2Code`_ -- it processes
926 # a source in "code format" (i.e. in a programming language), extracts
927 # documentation from comment blocks, and puts program code in literal blocks.
929 # The class inherits the interface and helper functions from
930 # TextCodeConverter_ and adds functions specific to the text-to-code format
931 # conversion::
933 class Code2Text(TextCodeConverter):
934 """Convert code source to text source
937 # set_state()
938 # ~~~~~~~~~~~
940 # Check if block is "header", "documentation", or "code_block":
942 # A paragraph is "documentation", if every non-blank line starts with a
943 # matching comment string (including whitespace except for commented blank
944 # lines) ::
946 def set_state(self, block):
947 """Determine state of `block`."""
948 for line in block:
949 # skip documentation lines (commented, blank or blank comment)
950 if (line.startswith(self.comment_string)
951 or not line.rstrip()
952 or line.rstrip() == self.comment_string.rstrip()
954 continue
955 # non-commented line found:
956 if self.state == "":
957 self.state = "header"
958 else:
959 self.state = "code_block"
960 break
961 else:
962 # no code line found
963 # keep state if the block is just a blank line
964 # if len(block) == 1 and self._is_blank_codeline(line):
965 # return
966 self.state = "documentation"
969 # header_handler()
970 # ~~~~~~~~~~~~~~~~
972 # Handle a leading code block. (See `Text2Code.header_handler()`_ for a
973 # discussion of the "header" state.) ::
975 def header_handler(self, lines):
976 """Format leading code block"""
977 if self.strip == True:
978 return
979 # get iterator over the lines that formats them as code-block
980 lines = iter(self.code_block_handler(lines))
981 # prepend header string to first line
982 yield self.header_string + next(lines)
983 # yield remaining lines
984 for line in lines:
985 yield line
987 # .. _Code2Text.documentation_handler():
989 # documentation_handler()
990 # ~~~~~~~~~~~~~~~~~~~~~~~
992 # The *documentation state* handler converts a comment to a documentation
993 # block by stripping the leading `comment string` from every line::
995 def documentation_handler(self, block):
996 """Uncomment documentation blocks in source code
999 # Strip comment strings::
1001 lines = [self.uncomment_line(line) for line in block]
1003 # If the code block is stripped, the literal marker would lead to an
1004 # error when the text is converted with Docutils. Strip it as well. ::
1006 if self.strip or self.strip_marker:
1007 self.strip_code_block_marker(lines)
1009 # Otherwise, check for the `code_block_marker`_ at the end of the
1010 # documentation block (skipping directive options that might follow it)::
1012 elif self.add_missing_marker:
1013 for line in lines[::-1]:
1014 if self.marker_regexp.search(line):
1015 self._add_code_block_marker = False
1016 break
1017 if (line.rstrip() and
1018 not self.directive_option_regexp.search(line)):
1019 self._add_code_block_marker = True
1020 break
1021 else:
1022 self._add_code_block_marker = True
1024 # Yield lines::
1026 for line in lines:
1027 yield line
1030 # uncomment_line()
1031 # ~~~~~~~~~~~~~~~~
1033 # Return documentation line after stripping comment string. Consider the
1034 # case that a blank line has a comment string without trailing whitespace::
1036 def uncomment_line(self, line):
1037 """Return uncommented documentation line"""
1038 line = line.replace(self.comment_string, "", 1)
1039 if line.rstrip() == self.stripped_comment_string:
1040 line = line.replace(self.stripped_comment_string, "", 1)
1041 return line
1044 # .. _Code2Text.code_block_handler():
1046 # code_block_handler()
1047 # ~~~~~~~~~~~~~~~~~~~~
1049 # The `code_block` handler returns the code block as indented literal
1050 # block (or filters it, if ``self.strip == True``). The amount of the code
1051 # indentation is controlled by `self.codeindent` (default 2). ::
1053 def code_block_handler(self, lines):
1054 """Covert code blocks to text format (indent or strip)
1056 if self.strip == True:
1057 return
1058 # eventually insert transition marker
1059 if self._add_code_block_marker:
1060 self.state = "documentation"
1061 yield self.code_block_marker + "\n"
1062 yield "\n"
1063 self._add_code_block_marker = False
1064 self.state = "code_block"
1065 for line in lines:
1066 yield " "*self.codeindent + line
1070 # strip_code_block_marker()
1071 # ~~~~~~~~~~~~~~~~~~~~~~~~~
1073 # Replace the literal marker with the equivalent of Docutils replace rules
1075 # * strip ``::``-line (and preceding blank line) if on a line on its own
1076 # * strip ``::`` if it is preceded by whitespace.
1077 # * convert ``::`` to a single colon if preceded by text
1079 # `lines` is a list of documentation lines (with a trailing blank line).
1080 # It is modified in-place::
1082 def strip_code_block_marker(self, lines):
1083 try:
1084 line = lines[-2]
1085 except IndexError:
1086 return # just one line (no trailing blank line)
1088 # match with regexp: `match` is None or has groups
1089 # \1 leading text, \2 code_block_marker, \3 remainder
1090 match = self.marker_regexp.search(line)
1092 if not match: # no code_block_marker present
1093 return
1094 if not match.group(1): # `code_block_marker` on an extra line
1095 del(lines[-2])
1096 # delete preceding line if it is blank
1097 if len(lines) >= 2 and not lines[-2].lstrip():
1098 del(lines[-2])
1099 elif match.group(1).rstrip() < match.group(1):
1100 # '::' follows whitespace
1101 lines[-2] = match.group(1).rstrip() + match.group(3)
1102 else: # '::' follows text
1103 lines[-2] = match.group(1).rstrip() + ':' + match.group(3)
1106 # Filters
1107 # =======
1109 # Filters allow pre- and post-processing of the data to bring it in a format
1110 # suitable for the "normal" text<->code conversion. An example is conversion
1111 # of `C` ``/*`` ``*/`` comments into C++ ``//`` comments (and back).
1112 # Another example is the conversion of `C` ``/*`` ``*/`` comments into C++
1113 # ``//`` comments (and back).
1115 # Filters are generator functions that return an iterator acting on a
1116 # `data` iterable and yielding processed `data` lines.
1119 # identity_filter()
1120 # -----------------
1122 # The most basic filter is the identity filter, that returns its argument as
1123 # iterator::
1125 def identity_filter(data):
1126 """Return data iterator without any processing"""
1127 return iter(data)
1130 # expandtabs_filter()
1131 # -------------------
1133 # Expand hard-tabs in every line of `data` (cf. `str.expandtabs`).
1135 # This filter is applied to the input data by `TextCodeConverter.convert`_ as
1136 # hard tabs can lead to errors when the indentation is changed. ::
1138 def expandtabs_filter(data):
1139 """Yield data tokens with hard-tabs expanded"""
1140 for line in data:
1141 yield line.expandtabs()
1144 # collect_blocks()
1145 # ----------------
1147 # A filter to aggregate "paragraphs" (blocks separated by blank
1148 # lines). Yields lists of lines::
1150 def collect_blocks(lines):
1151 """collect lines in a list
1153 yield list for each paragraph, i.e. block of lines separated by a
1154 blank line (whitespace only).
1156 Trailing blank lines are collected as well.
1158 blank_line_reached = False
1159 block = []
1160 for line in lines:
1161 if blank_line_reached and line.rstrip():
1162 yield block
1163 blank_line_reached = False
1164 block = [line]
1165 continue
1166 if not line.rstrip():
1167 blank_line_reached = True
1168 block.append(line)
1169 yield block
1173 # dumb_c_preprocessor()
1174 # ---------------------
1176 # This is a basic filter to convert `C` to `C++` comments. Works line-wise and
1177 # only converts lines that
1179 # * start with "/\* " and end with " \*/" (followed by whitespace only)
1181 # A more sophisticated version would also
1183 # * convert multi-line comments
1185 # + Keep indentation or strip 3 leading spaces?
1187 # * account for nested comments
1189 # * only convert comments that are separated from code by a blank line
1191 # ::
1193 def dumb_c_preprocessor(data):
1194 """change `C` ``/* `` `` */`` comments into C++ ``// `` comments"""
1195 comment_string = defaults.comment_strings["c++"]
1196 boc_string = "/* "
1197 eoc_string = " */"
1198 for line in data:
1199 if (line.startswith(boc_string)
1200 and line.rstrip().endswith(eoc_string)
1202 line = line.replace(boc_string, comment_string, 1)
1203 line = "".join(line.rsplit(eoc_string, 1))
1204 yield line
1206 # Unfortunately, the `replace` method of strings does not support negative
1207 # numbers for the `count` argument:
1209 # >>> "foo */ baz */ bar".replace(" */", "", -1) == "foo */ baz bar"
1210 # False
1212 # However, there is the `rsplit` method, that can be used together with `join`:
1214 # >>> "".join("foo */ baz */ bar".rsplit(" */", 1)) == "foo */ baz bar"
1215 # True
1218 # dumb_c_postprocessor()
1219 # ----------------------
1221 # Undo the preparations by the dumb_c_preprocessor and re-insert valid comment
1222 # delimiters ::
1224 def dumb_c_postprocessor(data):
1225 """change C++ ``// `` comments into `C` ``/* `` `` */`` comments"""
1226 comment_string = defaults.comment_strings["c++"]
1227 boc_string = "/* "
1228 eoc_string = " */"
1229 for line in data:
1230 if line.rstrip() == comment_string.rstrip():
1231 line = line.replace(comment_string, "", 1)
1232 elif line.startswith(comment_string):
1233 line = line.replace(comment_string, boc_string, 1)
1234 line = line.rstrip() + eoc_string + "\n"
1235 yield line
1238 # register filters
1239 # ----------------
1241 # ::
1243 defaults.preprocessors['c2text'] = dumb_c_preprocessor
1244 defaults.preprocessors['css2text'] = dumb_c_preprocessor
1245 defaults.postprocessors['text2c'] = dumb_c_postprocessor
1246 defaults.postprocessors['text2css'] = dumb_c_postprocessor
1249 # Command line use
1250 # ================
1252 # Using this script from the command line will convert a file according to its
1253 # extension. This default can be overridden by a couple of options.
1255 # Dual source handling
1256 # --------------------
1258 # How to determine which source is up-to-date?
1259 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1261 # - `Set the modification time`_ of `outfile` to the one of `infile` to
1262 # indicate that the source files are 'synchronised'.
1264 # * Are there problems to expect from "backdating" a file? Which?
1266 # Looking at http://www.unix.com/showthread.php?t=20526, it seems
1267 # perfectly legal to set `mtime` (while leaving `ctime`) as `mtime` is a
1268 # description of the "actuality" of the data in the file.
1270 # - alternatively move input file to a backup copy (with option: `--replace`)
1272 # - check modification date before overwriting
1273 # (with option: `--overwrite=update`)
1275 # - check modification date before editing (implemented as `Jed editor`_
1276 # function `pylit_check()` in `pylit.sl`_)
1278 # .. _Jed editor: http://www.jedsoft.org/jed/
1279 # .. _pylit.sl: http://jedmodes.sourceforge.net/mode/pylit/
1281 # Recognised Filename Extensions
1282 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1284 # Instead of defining a new extension for "pylit" literate programs,
1285 # by default ``.txt`` will be appended for the text source and stripped by
1286 # the conversion to the code source. I.e. for a Python program foo:
1288 # * the code source is called ``foo.py``
1289 # * the text source is called ``foo.py.txt``
1290 # * the html rendering is called ``foo.py.html``
1293 # PylitOptions
1294 # ------------
1296 # The `PylitOptions` class comprises an option parser and methods for
1297 # completion of command line arguments from defaults and context::
1299 class PylitOptions(object):
1300 """Storage and handling of command line arguments for pylit"""
1303 # __init__()
1304 # ~~~~~~~~~~
1306 # ::
1308 def __init__(self):
1309 """Set up an `OptionParser` instance for pylit command line arguments
1311 p = argparse.ArgumentParser(usage=main.__doc__)
1313 # .. _command line arguments:
1315 # Positional arguments (I/O):
1317 # The "infile" argument is required unless there is a value in the
1318 # `namespace` passed to `p.parse_args()`.
1319 # We need to cheat here, because this behaviour is not supported by
1320 # `argparse` (cf. `issue 29670`_).
1322 # The default value is set to `argparse.SUPPRESS` to prevent overwriting an
1323 # existing value in the `namespace` (cf. `issue 28734`_). ::
1325 p.add_argument('infile', metavar='INFILE',
1326 nargs='?', default=argparse.SUPPRESS,
1327 help='input file ("-" for stdin)')
1328 p.add_argument('outfile', metavar='OUTFILE',
1329 nargs='?', default=argparse.SUPPRESS,
1330 help=u'output file, default: auto-determined')
1332 # Conversion settings::
1334 p.add_argument("-c", "--code2txt", action="store_false",
1335 dest="txt2code",
1336 help='convert code source to text')
1337 p.add_argument("-t", "--txt2code", action="store_true",
1338 help='convert text source to code'
1339 ' (default determined from input file name)')
1340 p.add_argument("--language",
1341 choices = list(defaults.comment_strings.keys()),
1342 help="use LANGUAGE's native comment style"
1343 ' (default: determined from input file extension)')
1344 p.add_argument("--comment-string", dest="comment_string",
1345 help="documentation block marker in code source "
1346 "(including trailing whitespace, "
1347 "default: language dependent)")
1348 p.add_argument("-m", "--code-block-marker", dest="code_block_marker",
1349 help='syntax token starting a code block. (default "%s")'
1350 % defaults.code_block_markers.default)
1351 p.add_argument("--codeindent", type=int,
1352 help='Number of spaces to indent code blocks with code2text'
1353 ' (default %d)' % defaults.codeindent)
1355 # Output file handling::
1357 p.add_argument("--overwrite", action="store",
1358 choices = ['yes', 'no', 'update'],
1359 help='overwrite output file (default "%s")'
1360 % defaults.overwrite)
1361 p.add_argument("--replace", action="store_true",
1362 help="move infile to a backup copy (appending '~')")
1363 # TODO: do we need this? If yes, make mtime update depend on it!
1364 # p.add_argument("--keep-mtime", action="store_true",
1365 # help="do not set the modification time of the outfile "
1366 # "to the corresponding value of the infile")
1367 p.add_argument("-s", "--strip", action="store_true",
1368 help='"export" by stripping documentation or code')
1370 # Actions::
1372 p.add_argument("-d", "--diff", action="store_true",
1373 help="test for differences to existing file")
1374 p.add_argument("--doctest", action="store_true",
1375 help="run doctest.testfile() on the text version")
1376 p.add_argument("-e", "--execute", action="store_true",
1377 help="execute code (Python only)")
1378 p.add_argument('-v', '--version', action='version',
1379 version=__version__)
1381 self.parser = p
1384 # .. _PylitOptions.complete_values():
1386 # complete_values()
1387 # ~~~~~~~~~~~~~~~~~
1389 # Complete an OptionValues instance `values`. Use module-level defaults and
1390 # context information to set missing option values to sensible defaults (if
1391 # possible) ::
1393 def complete_values(self, values):
1394 """complete option values with module and context sensible defaults
1396 x.complete_values(values) -> values
1397 values -- OptionValues instance
1400 # The "infile" argument is required but may be pre-set in the `namespace`
1401 # passed to `p.parse_args()` (cf. `issue 29670`_::
1403 try:
1404 values.infile
1405 except AttributeError:
1406 self.parser.error('the following argument is required: infile')
1408 # Guess conversion direction from `infile` filename::
1410 if getattr(values, 'txt2code', None) is None:
1411 in_extension = os.path.splitext(values.infile)[1]
1412 if in_extension in defaults.text_extensions:
1413 values.txt2code = True
1414 elif in_extension in defaults.languages.keys():
1415 values.txt2code = False
1416 else:
1417 values.txt2code = None
1419 # Auto-determine the output file name::
1421 if not values.outfile:
1422 values.outfile = self._get_outfile_name(values)
1424 # Second try: Guess conversion direction from outfile filename::
1426 if values.txt2code is None:
1427 out_extension = os.path.splitext(values.outfile)[1]
1428 values.txt2code = not (out_extension in defaults.text_extensions)
1430 # Set the language of the code::
1432 if values.language is None:
1433 if values.txt2code is True:
1434 code_extension = os.path.splitext(values.outfile)[1]
1435 elif values.txt2code is False:
1436 code_extension = os.path.splitext(values.infile)[1]
1437 values.language = defaults.languages[code_extension]
1439 return values
1442 # _get_outfile_name()
1443 # ~~~~~~~~~~~~~~~~~~~
1445 # Construct a matching filename for the output file. The output filename is
1446 # constructed from `infile` by the following rules:
1448 # * '-' (stdin) results in '-' (stdout)
1449 # * strip the `text_extension`_ (txt2code) or
1450 # * add the `text_extension`_ (code2txt)
1451 # * fallback: if no guess can be made, add ".out"
1453 # .. TODO: use values.outfile_extension if it exists?
1455 # ::
1457 def _get_outfile_name(self, values):
1458 """Return a matching output filename for `infile`
1460 # if input is stdin, default output is stdout
1461 if values.infile == '-':
1462 return '-'
1464 # Derive from `infile` name: strip or add text extension
1465 (base, ext) = os.path.splitext(values.infile)
1466 if ext in defaults.text_extensions:
1467 return base # strip
1468 if ext and ext in defaults.languages or values.txt2code == False:
1469 return values.infile + defaults.text_extensions[0] # add
1470 # give up
1471 return values.infile + ".out"
1474 # .. _PylitOptions.__call__():
1476 # __call__()
1477 # ~~~~~~~~~~
1479 # Use PylitOptions instances as *callables*: Calling a `PylitOptions` instance
1480 # parses the argument list to extract option values and completes them based
1481 # on "context-sensitive defaults".
1482 # Keyword arguments overwrite the `defaults`_
1483 # and are overwritten by command line arguments.
1485 # Attention: passing a `namespace` to `ArgumentParser.parse_args()` has a
1486 # side-effect:
1488 # […] if you give an existing object, the option defaults will not be
1489 # initialized on it
1491 # -- https://docs.python.org/dev/library/optparse.html#parsing-arguments
1493 # .. The argument is renamed from `values` to `namespace` in Python 3.
1494 # Positional argument defaults are initialized unless the default value
1495 # `argparse.SUPPRESS` is specified.
1497 # ::
1499 def __call__(self, args=sys.argv[1:], **kwargs):
1500 """parse and complete command line args, return option values
1502 settings = vars(defaults).copy() # don't change global settings
1503 settings.update(kwargs)
1504 settings = argparse.Namespace(**settings)
1506 settings = self.parser.parse_args(args, settings)
1507 settings = self.complete_values(settings)
1508 # print(f'{settings.outfile=}')
1509 # for k,v in vars(settings).items():
1510 # print(k,v)
1511 return settings
1513 # Helper functions
1514 # ----------------
1516 # open_streams()
1517 # ~~~~~~~~~~~~~~
1519 # Return file objects for in- and output. If the input path is missing,
1520 # write usage and abort. (An alternative would be to use stdin as default.
1521 # However, this leaves the uninitiated user with a non-responding application
1522 # if (s)he just tries the script without any arguments) ::
1524 def open_streams(infile = '-', outfile = '-', overwrite='update', **keyw):
1525 """Open and return the input and output stream
1527 open_streams(infile, outfile) -> (in_stream, out_stream)
1529 in_stream -- file(infile) or sys.stdin
1530 out_stream -- file(outfile) or sys.stdout
1531 overwrite -- 'yes': overwrite eventually existing `outfile`,
1532 'update': fail if the `outfile` is newer than `infile`,
1533 'no': fail if `outfile` exists.
1535 Irrelevant if `outfile` == '-'.
1537 if overwrite not in ('yes', 'no', 'update'):
1538 raise ValueError('Argument "overwrite" must be "yes", "no",'
1539 ' or update, not "%s".' % overwrite)
1540 if not infile:
1541 strerror = "Missing input file name ('-' for stdin; -h for help)"
1542 raise IOError(2, strerror, infile)
1543 if infile == '-':
1544 in_stream = sys.stdin
1545 else:
1546 in_stream = open(infile, 'r')
1547 if outfile == '-':
1548 out_stream = sys.stdout
1549 elif overwrite == 'no' and os.path.exists(outfile):
1550 raise IOError(17, "Output file exists!", outfile)
1551 elif overwrite == 'update' and is_newer(outfile, infile) is None:
1552 raise IOError(0, "Output file is as old as input file!", outfile)
1553 elif overwrite == 'update' and is_newer(outfile, infile):
1554 raise IOError(1, "Output file is newer than input file!", outfile)
1555 else:
1556 out_stream = open(outfile, 'w')
1557 return (in_stream, out_stream)
1560 # is_newer()
1561 # ~~~~~~~~~~
1563 # ::
1565 def is_newer(path1, path2):
1566 """Check if `path1` is newer than `path2` (using mtime)
1568 Compare modification time of files at path1 and path2.
1570 Non-existing files are considered oldest: Return False if path1 does not
1571 exist and True if path2 does not exist.
1573 Return None if the modification time differs less than 1/10 second.
1574 (This evaluates to False in a Boolean context but allows a test
1575 for equality.)
1577 try:
1578 mtime1 = os.path.getmtime(path1)
1579 except OSError:
1580 mtime1 = -1
1581 try:
1582 mtime2 = os.path.getmtime(path2)
1583 except OSError:
1584 mtime2 = -1
1585 if abs(mtime1 - mtime2) < 0.1:
1586 return None
1587 return mtime1 > mtime2
1590 # get_converter()
1591 # ~~~~~~~~~~~~~~~
1593 # Get an instance of the converter state machine::
1595 def get_converter(data, txt2code=True, **keyw):
1596 if txt2code:
1597 return Text2Code(data, **keyw)
1598 else:
1599 return Code2Text(data, **keyw)
1602 # Actions
1603 # -------
1605 # run_doctest()
1606 # ~~~~~~~~~~~~~
1607 # ::
1609 def run_doctest(infile="-", txt2code=True,
1610 globs={}, verbose=False, optionflags=0, **keyw):
1611 """run doctest on the text source
1614 # Allow imports from the current working dir by prepending an empty string to
1615 # sys.path (see doc of sys.path())::
1617 sys.path.insert(0, '')
1619 # Import classes from the doctest module::
1621 from doctest import DocTestParser, DocTestRunner
1623 # Read in source. Make sure it is in text format, as tests in comments are not
1624 # found by doctest::
1626 (data, out_stream) = open_streams(infile, "-")
1627 if txt2code is False:
1628 keyw.update({'add_missing_marker': False})
1629 converter = Code2Text(data, **keyw)
1630 docstring = str(converter)
1631 else:
1632 docstring = data.read()
1634 # decode doc string if there is a "magic comment" in the first or second line
1635 # (http://docs.python.org/reference/lexical_analysis.html#encoding-declarations)
1636 # ::
1638 if sys.version_info < (3,0):
1639 firstlines = ' '.join(docstring.splitlines()[:2])
1640 match = re.search('coding[=:]\s*([-\w.]+)', firstlines)
1641 if match:
1642 docencoding = match.group(1)
1643 docstring = docstring.decode(docencoding)
1645 # Use the doctest Advanced API to run all doctests in the source text::
1647 test = DocTestParser().get_doctest(docstring, globs, name="",
1648 filename=infile, lineno=0)
1649 runner = DocTestRunner(verbose, optionflags)
1650 runner.run(test)
1651 runner.summarize()
1652 # give feedback also if no failures occurred
1653 if not runner.failures:
1654 print("%d failures in %d tests"%(runner.failures, runner.tries))
1655 return runner.failures, runner.tries
1658 # diff()
1659 # ~~~~~~
1661 # ::
1663 def diff(infile='-', outfile='-', txt2code=True, **keyw):
1664 """Report differences between converted infile and existing outfile
1666 If outfile does not exist or is '-', do a round-trip conversion and
1667 report differences.
1670 import difflib
1672 instream = open(infile)
1673 # for diffing, we need a copy of the data as list::
1674 data = instream.readlines()
1675 # convert
1676 converter = get_converter(data, txt2code, **keyw)
1677 new = converter()
1679 if outfile != '-' and os.path.exists(outfile):
1680 outstream = open(outfile)
1681 old = outstream.readlines()
1682 oldname = outfile
1683 newname = "<conversion of %s>"%infile
1684 else:
1685 old = data
1686 oldname = infile
1687 # back-convert the output data
1688 converter = get_converter(new, not txt2code)
1689 new = converter()
1690 newname = "<round-conversion of %s>"%infile
1692 # find and print the differences
1693 is_different = False
1694 # print(type(old), old)
1695 # print(type(new), new)
1696 delta = difflib.unified_diff(old, new,
1697 # delta = difflib.unified_diff(["heute\n", "schon\n"], ["heute\n", "noch\n"],
1698 fromfile=oldname, tofile=newname)
1699 for line in delta:
1700 is_different = True
1701 print(line, end=' ')
1702 if not is_different:
1703 print(oldname)
1704 print(newname)
1705 print("no differences found")
1706 return is_different
1709 # execute()
1710 # ~~~~~~~~~
1712 # Works only for python code.
1714 # Does not work with `eval`, as code is not just one expression. ::
1716 def execute(infile="-", txt2code=True, **keyw):
1717 """Execute the input file. Convert first, if it is a text source.
1720 with open(infile) as f:
1721 data = f.readlines()
1722 if txt2code:
1723 data = str(Text2Code(data, **keyw))
1724 exec(''.join(data))
1727 # main()
1728 # ------
1730 # If this script is called from the command line, the `main` function will
1731 # convert the input (file or stdin) between text and code formats.
1733 # Setting values for the conversion can be given as keyword arguments
1734 # to `main()`_. The option defaults will be updated by command line arguments and
1735 # extended with "intelligent guesses" by `PylitOptions`_ and passed on to
1736 # helper functions and the converter instantiation.
1738 # This allows easy customisation for programmatic use -- just call `main`
1739 # with the appropriate keyword options, e.g. ``pylit.main(comment_string="## ")``
1741 # ::
1743 def main(args=sys.argv[1:], **settings):
1744 """%(prog)s [options] INFILE [OUTFILE]
1746 Convert between (reStructured) text source with embedded code,
1747 and code source with embedded documentation (comment blocks)
1749 The special filename '-' stands for standard in- and output.
1752 # Parse and complete the options::
1754 settings = PylitOptions()(args, **settings)
1756 # Special actions with early return::
1758 if settings.doctest:
1759 return run_doctest(**vars(settings).copy())
1761 if settings.diff:
1762 return diff(**vars(settings).copy())
1764 if settings.execute:
1765 return execute(**vars(settings).copy())
1767 # Open in- and output streams::
1769 try:
1770 (data, out_stream) = open_streams(**vars(settings).copy())
1771 except IOError as ex:
1772 print("IOError: %s %s" % (ex.filename, ex.strerror))
1773 sys.exit(ex.errno)
1775 # Get a converter instance::
1777 converter = get_converter(data, **vars(settings).copy())
1779 # Convert and write to out_stream::
1781 out_stream.write(str(converter))
1783 if out_stream is not sys.stdout:
1784 print('output written to %r' % out_stream.name)
1785 out_stream.close()
1787 # If input and output are from files, _`set the modification time` (`mtime`) of
1788 # the output file to the one of the input file to indicate that the contained
1789 # information is equal. [#]_ ::
1792 # print("fractions?", os.stat_float_times())
1793 try:
1794 os.utime(settings.outfile, (os.path.getatime(settings.outfile),
1795 os.path.getmtime(settings.infile))
1797 except OSError:
1798 pass
1800 ## print("mtime", os.path.getmtime(settings.infile), settings.infile)
1801 ## print("mtime", os.path.getmtime(settings.outfile), settings.outfile)
1804 # .. [#] Make sure the corresponding file object (here `out_stream`) is
1805 # closed, as otherwise the change will be overwritten when `close` is
1806 # called afterwards (either explicitly or at program exit).
1809 # Rename the infile to a backup copy if ``--replace`` is set::
1811 if settings.replace:
1812 os.rename(settings.infile, settings.infile + "~")
1815 # Run main, if called from the command line::
1817 if __name__ == '__main__':
1818 main()
1821 # Open questions
1822 # ==============
1824 # Open questions and ideas for further development
1826 # Clean code
1827 # ----------
1829 # * can we gain from using "shutils" over "os.path" and "os"?
1830 # * use pylint or pyChecker to enforce a consistent style?
1832 # Options
1833 # -------
1835 # * Use templates for the "intelligent guesses" (with Python syntax for string
1836 # replacement with dicts: ``"hello %(what)s" % {'what': 'world'}``)
1838 # * Is it sensible to offer the `header_string` option also as command line
1839 # option?
1841 # treatment of blank lines
1842 # ------------------------
1844 # Alternatives: Keep blank lines blank
1846 # - "never" (current setting) -> "visually merges" all documentation
1847 # if there is no interjacent code
1849 # - "always" -> disrupts documentation blocks,
1851 # - "if empty" (no whitespace). Comment if there is whitespace.
1853 # This would allow non-obstructing markup but unfortunately this is (in
1854 # most editors) also non-visible markup.
1856 # + "if double" (if there is more than one consecutive blank line)
1858 # With this handling, the "visual gap" remains in both, text and code
1859 # source.
1862 # Parsing Problems
1863 # ----------------
1865 # * Ignore "matching comments" in literal strings?
1867 # Too complicated: Would need a specific detection algorithm for every
1868 # language that supports multi-line literal strings (C++, PHP, Python)
1870 # * Warn if a comment in code will become documentation after round-trip?
1873 # docstrings in code blocks
1874 # -------------------------
1876 # * How to handle docstrings in code blocks? (it would be nice to convert them
1877 # to rst-text if ``__docformat__ == restructuredtext``)
1879 # TODO: Ask at Docutils users|developers
1881 # Plug-ins
1882 # --------
1884 # Specify a path for user additions and plug-ins. This would require to
1885 # convert Pylit from a pure module to a package...
1887 # 6.4.3 Packages in Multiple Directories
1889 # Packages support one more special attribute, __path__. This is initialized
1890 # to be a list containing the name of the directory holding the package's
1891 # __init__.py before the code in that file is executed. This
1892 # variable can be modified; doing so affects future searches for modules and
1893 # subpackages contained in the package.
1895 # While this feature is not often needed, it can be used to extend the set
1896 # of modules found in a package.
1899 # .. References
1901 # .. _Docutils: http://docutils.sourceforge.net/
1902 # .. _Sphinx: http://sphinx.pocoo.org
1903 # .. _Pygments: http://pygments.org/
1904 # .. _code-block directive:
1905 # http://docutils.sourceforge.net/sandbox/code-block-directive/
1906 # .. _literal block:
1907 # .. _literal blocks:
1908 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#literal-blocks
1909 # .. _indented literal block:
1910 # .. _indented literal blocks:
1911 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#indented-literal-blocks
1912 # .. _quoted literal block:
1913 # .. _quoted literal blocks:
1914 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#quoted-literal-blocks
1915 # .. _parsed-literal blocks:
1916 # http://docutils.sf.net/docs/ref/rst/directives.html#parsed-literal-block
1917 # .. _doctest block:
1918 # .. _doctest blocks:
1919 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#doctest-blocks
1920 # .. _issue 28734: https://bugs.python.org/issue28734
1921 # .. _issue 29670: https://bugs.python.org/issue29670
1922 # .. _argparse: https://docs.python.org/dev/library/argparse.html
1923 # .. _ArgumentParser.parse_args():
1924 # https://docs.python.org/dev/library/argparse.html#the-parse-args-method