Don't add indentation to blank lines. Only warn if output has same age.
[pylit.git] / pylit.py
blob312b1bcea2354b9c5f7e22270b09cc9d72e7323b
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 if not line.rstrip():
1067 yield line # don't add indent to blank lines
1068 else:
1069 yield " "*self.codeindent + line
1072 # strip_code_block_marker()
1073 # ~~~~~~~~~~~~~~~~~~~~~~~~~
1075 # Replace the literal marker with the equivalent of Docutils replace rules
1077 # * strip ``::``-line (and preceding blank line) if on a line on its own
1078 # * strip ``::`` if it is preceded by whitespace.
1079 # * convert ``::`` to a single colon if preceded by text
1081 # `lines` is a list of documentation lines (with a trailing blank line).
1082 # It is modified in-place::
1084 def strip_code_block_marker(self, lines):
1085 try:
1086 line = lines[-2]
1087 except IndexError:
1088 return # just one line (no trailing blank line)
1090 # match with regexp: `match` is None or has groups
1091 # \1 leading text, \2 code_block_marker, \3 remainder
1092 match = self.marker_regexp.search(line)
1094 if not match: # no code_block_marker present
1095 return
1096 if not match.group(1): # `code_block_marker` on an extra line
1097 del(lines[-2])
1098 # delete preceding line if it is blank
1099 if len(lines) >= 2 and not lines[-2].lstrip():
1100 del(lines[-2])
1101 elif match.group(1).rstrip() < match.group(1):
1102 # '::' follows whitespace
1103 lines[-2] = match.group(1).rstrip() + match.group(3)
1104 else: # '::' follows text
1105 lines[-2] = match.group(1).rstrip() + ':' + match.group(3)
1108 # Filters
1109 # =======
1111 # Filters allow pre- and post-processing of the data to bring it in a format
1112 # suitable for the "normal" text<->code conversion. An example is conversion
1113 # of `C` ``/*`` ``*/`` comments into C++ ``//`` comments (and back).
1114 # Another example is the conversion of `C` ``/*`` ``*/`` comments into C++
1115 # ``//`` comments (and back).
1117 # Filters are generator functions that return an iterator acting on a
1118 # `data` iterable and yielding processed `data` lines.
1121 # identity_filter()
1122 # -----------------
1124 # The most basic filter is the identity filter, that returns its argument as
1125 # iterator::
1127 def identity_filter(data):
1128 """Return data iterator without any processing"""
1129 return iter(data)
1132 # expandtabs_filter()
1133 # -------------------
1135 # Expand hard-tabs in every line of `data` (cf. `str.expandtabs`).
1137 # This filter is applied to the input data by `TextCodeConverter.convert`_ as
1138 # hard tabs can lead to errors when the indentation is changed. ::
1140 def expandtabs_filter(data):
1141 """Yield data tokens with hard-tabs expanded"""
1142 for line in data:
1143 yield line.expandtabs()
1146 # collect_blocks()
1147 # ----------------
1149 # A filter to aggregate "paragraphs" (blocks separated by blank
1150 # lines). Yields lists of lines::
1152 def collect_blocks(lines):
1153 """collect lines in a list
1155 yield list for each paragraph, i.e. block of lines separated by a
1156 blank line (whitespace only).
1158 Trailing blank lines are collected as well.
1160 blank_line_reached = False
1161 block = []
1162 for line in lines:
1163 if blank_line_reached and line.rstrip():
1164 yield block
1165 blank_line_reached = False
1166 block = [line]
1167 continue
1168 if not line.rstrip():
1169 blank_line_reached = True
1170 block.append(line)
1171 yield block
1175 # dumb_c_preprocessor()
1176 # ---------------------
1178 # This is a basic filter to convert `C` to `C++` comments. Works line-wise and
1179 # only converts lines that
1181 # * start with "/\* " and end with " \*/" (followed by whitespace only)
1183 # A more sophisticated version would also
1185 # * convert multi-line comments
1187 # + Keep indentation or strip 3 leading spaces?
1189 # * account for nested comments
1191 # * only convert comments that are separated from code by a blank line
1193 # ::
1195 def dumb_c_preprocessor(data):
1196 """change `C` ``/* `` `` */`` comments into C++ ``// `` comments"""
1197 comment_string = defaults.comment_strings["c++"]
1198 boc_string = "/* "
1199 eoc_string = " */"
1200 for line in data:
1201 if (line.startswith(boc_string)
1202 and line.rstrip().endswith(eoc_string)
1204 line = line.replace(boc_string, comment_string, 1)
1205 line = "".join(line.rsplit(eoc_string, 1))
1206 yield line
1208 # Unfortunately, the `replace` method of strings does not support negative
1209 # numbers for the `count` argument:
1211 # >>> "foo */ baz */ bar".replace(" */", "", -1) == "foo */ baz bar"
1212 # False
1214 # However, there is the `rsplit` method, that can be used together with `join`:
1216 # >>> "".join("foo */ baz */ bar".rsplit(" */", 1)) == "foo */ baz bar"
1217 # True
1220 # dumb_c_postprocessor()
1221 # ----------------------
1223 # Undo the preparations by the dumb_c_preprocessor and re-insert valid comment
1224 # delimiters ::
1226 def dumb_c_postprocessor(data):
1227 """change C++ ``// `` comments into `C` ``/* `` `` */`` comments"""
1228 comment_string = defaults.comment_strings["c++"]
1229 boc_string = "/* "
1230 eoc_string = " */"
1231 for line in data:
1232 if line.rstrip() == comment_string.rstrip():
1233 line = line.replace(comment_string, "", 1)
1234 elif line.startswith(comment_string):
1235 line = line.replace(comment_string, boc_string, 1)
1236 line = line.rstrip() + eoc_string + "\n"
1237 yield line
1240 # register filters
1241 # ----------------
1243 # ::
1245 defaults.preprocessors['c2text'] = dumb_c_preprocessor
1246 defaults.preprocessors['css2text'] = dumb_c_preprocessor
1247 defaults.postprocessors['text2c'] = dumb_c_postprocessor
1248 defaults.postprocessors['text2css'] = dumb_c_postprocessor
1251 # Command line use
1252 # ================
1254 # Using this script from the command line will convert a file according to its
1255 # extension. This default can be overridden by a couple of options.
1257 # Dual source handling
1258 # --------------------
1260 # How to determine which source is up-to-date?
1261 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1263 # - `Set the modification time`_ of `outfile` to the one of `infile` to
1264 # indicate that the source files are 'synchronised'.
1266 # * Are there problems to expect from "backdating" a file? Which?
1268 # Looking at http://www.unix.com/showthread.php?t=20526, it seems
1269 # perfectly legal to set `mtime` (while leaving `ctime`) as `mtime` is a
1270 # description of the "actuality" of the data in the file.
1272 # - alternatively move input file to a backup copy (with option: `--replace`)
1274 # - check modification date before overwriting
1275 # (with option: `--overwrite=update`)
1277 # - check modification date before editing (implemented as `Jed editor`_
1278 # function `pylit_check()` in `pylit.sl`_)
1280 # .. _Jed editor: http://www.jedsoft.org/jed/
1281 # .. _pylit.sl: http://jedmodes.sourceforge.net/mode/pylit/
1283 # Recognised Filename Extensions
1284 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1286 # Instead of defining a new extension for "pylit" literate programs,
1287 # by default ``.txt`` will be appended for the text source and stripped by
1288 # the conversion to the code source. I.e. for a Python program foo:
1290 # * the code source is called ``foo.py``
1291 # * the text source is called ``foo.py.txt``
1292 # * the html rendering is called ``foo.py.html``
1295 # PylitOptions
1296 # ------------
1298 # The `PylitOptions` class comprises an option parser and methods for
1299 # completion of command line arguments from defaults and context::
1301 class PylitOptions(object):
1302 """Storage and handling of command line arguments for pylit"""
1305 # __init__()
1306 # ~~~~~~~~~~
1308 # ::
1310 def __init__(self):
1311 """Set up an `OptionParser` instance for pylit command line arguments
1313 p = argparse.ArgumentParser(usage=main.__doc__)
1315 # .. _command line arguments:
1317 # Positional arguments (I/O):
1319 # The "infile" argument is required unless there is a value in the
1320 # `namespace` passed to `p.parse_args()`.
1321 # We need to cheat here, because this behaviour is not supported by
1322 # `argparse` (cf. `issue 29670`_).
1324 # The default value is set to `argparse.SUPPRESS` to prevent overwriting an
1325 # existing value in the `namespace` (cf. `issue 28734`_). ::
1327 p.add_argument('infile', metavar='INFILE',
1328 nargs='?', default=argparse.SUPPRESS,
1329 help='input file ("-" for stdin)')
1330 p.add_argument('outfile', metavar='OUTFILE',
1331 nargs='?', default=argparse.SUPPRESS,
1332 help=u'output file, default: auto-determined')
1334 # Conversion settings::
1336 p.add_argument("-c", "--code2txt", action="store_false",
1337 dest="txt2code",
1338 help='convert code source to text')
1339 p.add_argument("-t", "--txt2code", action="store_true",
1340 help='convert text source to code'
1341 ' (default determined from input file name)')
1342 p.add_argument("--language",
1343 choices = list(defaults.comment_strings.keys()),
1344 help="use LANGUAGE's native comment style"
1345 ' (default: determined from input file extension)')
1346 p.add_argument("--comment-string", dest="comment_string",
1347 help="documentation block marker in code source "
1348 "(including trailing whitespace, "
1349 "default: language dependent)")
1350 p.add_argument("-m", "--code-block-marker", dest="code_block_marker",
1351 help='syntax token starting a code block. (default "%s")'
1352 % defaults.code_block_markers.default)
1353 p.add_argument("--codeindent", type=int,
1354 help='Number of spaces to indent code blocks with code2text'
1355 ' (default %d)' % defaults.codeindent)
1357 # Output file handling::
1359 p.add_argument("--overwrite", action="store",
1360 choices = ['yes', 'no', 'update'],
1361 help='overwrite output file (default "%s")'
1362 % defaults.overwrite)
1363 p.add_argument("--replace", action="store_true",
1364 help="move infile to a backup copy (appending '~')")
1365 # TODO: do we need this? If yes, make mtime update depend on it!
1366 # p.add_argument("--keep-mtime", action="store_true",
1367 # help="do not set the modification time of the outfile "
1368 # "to the corresponding value of the infile")
1369 p.add_argument("-s", "--strip", action="store_true",
1370 help='"export" by stripping documentation or code')
1372 # Actions::
1374 p.add_argument("-d", "--diff", action="store_true",
1375 help="test for differences to existing file")
1376 p.add_argument("--doctest", action="store_true",
1377 help="run doctest.testfile() on the text version")
1378 p.add_argument("-e", "--execute", action="store_true",
1379 help="execute code (Python only)")
1380 p.add_argument('-v', '--version', action='version',
1381 version=__version__)
1383 self.parser = p
1386 # .. _PylitOptions.complete_values():
1388 # complete_values()
1389 # ~~~~~~~~~~~~~~~~~
1391 # Complete an OptionValues instance `values`. Use module-level defaults and
1392 # context information to set missing option values to sensible defaults (if
1393 # possible) ::
1395 def complete_values(self, values):
1396 """complete option values with module and context sensible defaults
1398 x.complete_values(values) -> values
1399 values -- OptionValues instance
1402 # The "infile" argument is required but may be pre-set in the `namespace`
1403 # passed to `p.parse_args()` (cf. `issue 29670`_::
1405 try:
1406 values.infile
1407 except AttributeError:
1408 self.parser.error('the following argument is required: infile')
1410 # Guess conversion direction from `infile` filename::
1412 if getattr(values, 'txt2code', None) is None:
1413 in_extension = os.path.splitext(values.infile)[1]
1414 if in_extension in defaults.text_extensions:
1415 values.txt2code = True
1416 elif in_extension in defaults.languages.keys():
1417 values.txt2code = False
1418 else:
1419 values.txt2code = None
1421 # Auto-determine the output file name::
1423 if not values.outfile:
1424 values.outfile = self._get_outfile_name(values)
1426 # Second try: Guess conversion direction from outfile filename::
1428 if values.txt2code is None:
1429 out_extension = os.path.splitext(values.outfile)[1]
1430 values.txt2code = not (out_extension in defaults.text_extensions)
1432 # Set the language of the code::
1434 if values.language is None:
1435 if values.txt2code is True:
1436 code_extension = os.path.splitext(values.outfile)[1]
1437 elif values.txt2code is False:
1438 code_extension = os.path.splitext(values.infile)[1]
1439 values.language = defaults.languages[code_extension]
1441 return values
1444 # _get_outfile_name()
1445 # ~~~~~~~~~~~~~~~~~~~
1447 # Construct a matching filename for the output file. The output filename is
1448 # constructed from `infile` by the following rules:
1450 # * '-' (stdin) results in '-' (stdout)
1451 # * strip the `text_extension`_ (txt2code) or
1452 # * add the `text_extension`_ (code2txt)
1453 # * fallback: if no guess can be made, add ".out"
1455 # .. TODO: use values.outfile_extension if it exists?
1457 # ::
1459 def _get_outfile_name(self, values):
1460 """Return a matching output filename for `infile`
1462 # if input is stdin, default output is stdout
1463 if values.infile == '-':
1464 return '-'
1466 # Derive from `infile` name: strip or add text extension
1467 (base, ext) = os.path.splitext(values.infile)
1468 if ext in defaults.text_extensions:
1469 return base # strip
1470 if ext and ext in defaults.languages or values.txt2code == False:
1471 return values.infile + defaults.text_extensions[0] # add
1472 # give up
1473 return values.infile + ".out"
1476 # .. _PylitOptions.__call__():
1478 # __call__()
1479 # ~~~~~~~~~~
1481 # Use PylitOptions instances as *callables*: Calling a `PylitOptions` instance
1482 # parses the argument list to extract option values and completes them based
1483 # on "context-sensitive defaults".
1484 # Keyword arguments overwrite the `defaults`_
1485 # and are overwritten by command line arguments.
1487 # Attention: passing a `namespace` to `ArgumentParser.parse_args()` has a
1488 # side-effect:
1490 # […] if you give an existing object, the option defaults will not be
1491 # initialized on it
1493 # -- https://docs.python.org/dev/library/optparse.html#parsing-arguments
1495 # .. The argument is renamed from `values` to `namespace` in Python 3.
1496 # Positional argument defaults are initialized unless the default value
1497 # `argparse.SUPPRESS` is specified.
1499 # ::
1501 def __call__(self, args=sys.argv[1:], **kwargs):
1502 """parse and complete command line args, return option values
1504 settings = vars(defaults).copy() # don't change global settings
1505 settings.update(kwargs)
1506 settings = argparse.Namespace(**settings)
1508 settings = self.parser.parse_args(args, settings)
1509 settings = self.complete_values(settings)
1510 # print(f'{settings.outfile=}')
1511 # for k,v in vars(settings).items():
1512 # print(k,v)
1513 return settings
1515 # Helper functions
1516 # ----------------
1518 # open_streams()
1519 # ~~~~~~~~~~~~~~
1521 # Return file objects for in- and output. If the input path is missing,
1522 # write usage and abort. (An alternative would be to use stdin as default.
1523 # However, this leaves the uninitiated user with a non-responding application
1524 # if (s)he just tries the script without any arguments) ::
1526 def open_streams(infile = '-', outfile = '-', overwrite='update', **keyw):
1527 """Open and return the input and output stream
1529 open_streams(infile, outfile) -> (in_stream, out_stream)
1531 in_stream -- file(infile) or sys.stdin
1532 out_stream -- file(outfile) or sys.stdout
1533 overwrite -- 'yes': overwrite eventually existing `outfile`,
1534 'update': fail if the `outfile` is newer than `infile`,
1535 'no': fail if `outfile` exists.
1537 Irrelevant if `outfile` == '-'.
1539 if overwrite not in ('yes', 'no', 'update'):
1540 raise ValueError('Argument "overwrite" must be "yes", "no",'
1541 ' or update, not "%s".' % overwrite)
1542 if not infile:
1543 strerror = "Missing input file name ('-' for stdin; -h for help)"
1544 raise IOError(2, strerror, infile)
1545 if infile == '-':
1546 in_stream = sys.stdin
1547 else:
1548 in_stream = open(infile, 'r')
1549 if outfile == '-':
1550 out_stream = sys.stdout
1551 elif overwrite == 'no' and os.path.exists(outfile):
1552 raise IOError(17, "Output file exists!", outfile)
1553 elif overwrite == 'update' and is_newer(outfile, infile) is None:
1554 print('Output file "%s" is as old as input file!\n'
1555 'Use "--overwrite=yes", if you want to overwrite it.' % outfile,
1556 file=sys.stderr)
1557 sys.exit()
1558 elif overwrite == 'update' and is_newer(outfile, infile):
1559 raise IOError(1, "Output file is newer than input file!", outfile)
1560 else:
1561 out_stream = open(outfile, 'w')
1562 return (in_stream, out_stream)
1565 # is_newer()
1566 # ~~~~~~~~~~
1567 # ::
1569 def is_newer(path1, path2):
1570 """Check if `path1` is newer than `path2` (using mtime)
1572 Compare modification time of files at path1 and path2.
1574 Non-existing files are considered oldest: Return False if path1 does not
1575 exist and True if path2 does not exist.
1577 Return None if the modification time differs less than 1/10 second.
1578 (This evaluates to False in a Boolean context but allows a test
1579 for equality.)
1581 try:
1582 mtime1 = os.path.getmtime(path1)
1583 except OSError:
1584 mtime1 = -1
1585 try:
1586 mtime2 = os.path.getmtime(path2)
1587 except OSError:
1588 mtime2 = -1
1589 if abs(mtime1 - mtime2) < 0.1:
1590 return None
1591 return mtime1 > mtime2
1594 # get_converter()
1595 # ~~~~~~~~~~~~~~~
1597 # Get an instance of the converter state machine::
1599 def get_converter(data, txt2code=True, **keyw):
1600 if txt2code:
1601 return Text2Code(data, **keyw)
1602 else:
1603 return Code2Text(data, **keyw)
1606 # Actions
1607 # -------
1609 # run_doctest()
1610 # ~~~~~~~~~~~~~
1611 # ::
1613 def run_doctest(infile="-", txt2code=True,
1614 globs={}, verbose=False, optionflags=0, **keyw):
1615 """run doctest on the text source
1618 # Allow imports from the current working dir by prepending an empty string to
1619 # sys.path (see doc of sys.path())::
1621 sys.path.insert(0, '')
1623 # Import classes from the doctest module::
1625 from doctest import DocTestParser, DocTestRunner
1627 # Read in source. Make sure it is in text format, as tests in comments are not
1628 # found by doctest::
1630 (data, out_stream) = open_streams(infile, "-")
1631 if txt2code is False:
1632 keyw.update({'add_missing_marker': False})
1633 converter = Code2Text(data, **keyw)
1634 docstring = str(converter)
1635 else:
1636 docstring = data.read()
1638 # decode doc string if there is a "magic comment" in the first or second line
1639 # (http://docs.python.org/reference/lexical_analysis.html#encoding-declarations)
1640 # ::
1642 if sys.version_info < (3,0):
1643 firstlines = ' '.join(docstring.splitlines()[:2])
1644 match = re.search('coding[=:]\s*([-\w.]+)', firstlines)
1645 if match:
1646 docencoding = match.group(1)
1647 docstring = docstring.decode(docencoding)
1649 # Use the doctest Advanced API to run all doctests in the source text::
1651 test = DocTestParser().get_doctest(docstring, globs, name="",
1652 filename=infile, lineno=0)
1653 runner = DocTestRunner(verbose, optionflags)
1654 runner.run(test)
1655 runner.summarize()
1656 # give feedback also if no failures occurred
1657 if not runner.failures:
1658 print("%d failures in %d tests"%(runner.failures, runner.tries))
1659 return runner.failures, runner.tries
1662 # diff()
1663 # ~~~~~~
1665 # ::
1667 def diff(infile='-', outfile='-', txt2code=True, **keyw):
1668 """Report differences between converted infile and existing outfile
1670 If outfile does not exist or is '-', do a round-trip conversion and
1671 report differences.
1674 import difflib
1676 instream = open(infile)
1677 # for diffing, we need a copy of the data as list::
1678 data = instream.readlines()
1679 # convert
1680 converter = get_converter(data, txt2code, **keyw)
1681 new = converter()
1683 if outfile != '-' and os.path.exists(outfile):
1684 outstream = open(outfile)
1685 old = outstream.readlines()
1686 oldname = outfile
1687 newname = "<conversion of %s>"%infile
1688 else:
1689 old = data
1690 oldname = infile
1691 # back-convert the output data
1692 converter = get_converter(new, not txt2code)
1693 new = converter()
1694 newname = "<round-conversion of %s>"%infile
1696 # find and print the differences
1697 is_different = False
1698 # print(type(old), old)
1699 # print(type(new), new)
1700 delta = difflib.unified_diff(old, new,
1701 # delta = difflib.unified_diff(["heute\n", "schon\n"], ["heute\n", "noch\n"],
1702 fromfile=oldname, tofile=newname)
1703 for line in delta:
1704 is_different = True
1705 print(line, end=' ')
1706 if not is_different:
1707 print(oldname)
1708 print(newname)
1709 print("no differences found")
1710 return is_different
1713 # execute()
1714 # ~~~~~~~~~
1716 # Works only for python code.
1718 # Does not work with `eval`, as code is not just one expression. ::
1720 def execute(infile="-", txt2code=True, **keyw):
1721 """Execute the input file. Convert first, if it is a text source.
1724 with open(infile) as f:
1725 data = f.readlines()
1726 if txt2code:
1727 data = str(Text2Code(data, **keyw))
1728 exec(''.join(data))
1731 # main()
1732 # ------
1734 # If this script is called from the command line, the `main` function will
1735 # convert the input (file or stdin) between text and code formats.
1737 # Setting values for the conversion can be given as keyword arguments
1738 # to `main()`_. The option defaults will be updated by command line arguments and
1739 # extended with "intelligent guesses" by `PylitOptions`_ and passed on to
1740 # helper functions and the converter instantiation.
1742 # This allows easy customisation for programmatic use -- just call `main`
1743 # with the appropriate keyword options, e.g. ``pylit.main(comment_string="## ")``
1745 # ::
1747 def main(args=sys.argv[1:], **settings):
1748 """%(prog)s [options] INFILE [OUTFILE]
1750 Convert between (reStructured) text source with embedded code,
1751 and code source with embedded documentation (comment blocks)
1753 The special filename '-' stands for standard in- and output.
1756 # Parse and complete the options::
1758 settings = PylitOptions()(args, **settings)
1760 # Special actions with early return::
1762 if settings.doctest:
1763 return run_doctest(**vars(settings).copy())
1765 if settings.diff:
1766 return diff(**vars(settings).copy())
1768 if settings.execute:
1769 return execute(**vars(settings).copy())
1771 # Open in- and output streams::
1773 try:
1774 (data, out_stream) = open_streams(**vars(settings).copy())
1775 except IOError as ex:
1776 print("IOError: %s %s" % (ex.filename, ex.strerror))
1777 sys.exit(ex.errno)
1779 # Get a converter instance::
1781 converter = get_converter(data, **vars(settings).copy())
1783 # Convert and write to out_stream::
1785 out_stream.write(str(converter))
1787 if out_stream is not sys.stdout:
1788 print('Output written to %r' % out_stream.name)
1789 out_stream.close()
1791 # If input and output are from files, _`set the modification time` (`mtime`) of
1792 # the output file to the one of the input file to indicate that the contained
1793 # information is equal. [#]_ ::
1796 # print("fractions?", os.stat_float_times())
1797 try:
1798 os.utime(settings.outfile, (os.path.getatime(settings.outfile),
1799 os.path.getmtime(settings.infile))
1801 except OSError:
1802 pass
1804 ## print("mtime", os.path.getmtime(settings.infile), settings.infile)
1805 ## print("mtime", os.path.getmtime(settings.outfile), settings.outfile)
1808 # .. [#] Make sure the corresponding file object (here `out_stream`) is
1809 # closed, as otherwise the change will be overwritten when `close` is
1810 # called afterwards (either explicitly or at program exit).
1813 # Rename the infile to a backup copy if ``--replace`` is set::
1815 if settings.replace:
1816 os.rename(settings.infile, settings.infile + "~")
1819 # Run main, if called from the command line::
1821 if __name__ == '__main__':
1822 main()
1825 # Open questions
1826 # ==============
1828 # Open questions and ideas for further development
1830 # Clean code
1831 # ----------
1833 # * can we gain from using "shutils" over "os.path" and "os"?
1834 # * use pylint or pyChecker to enforce a consistent style?
1836 # Options
1837 # -------
1839 # * Use templates for the "intelligent guesses" (with Python syntax for string
1840 # replacement with dicts: ``"hello %(what)s" % {'what': 'world'}``)
1842 # * Is it sensible to offer the `header_string` option also as command line
1843 # option?
1845 # treatment of blank lines
1846 # ------------------------
1848 # Alternatives: Keep blank lines blank
1850 # - "never" (current setting) -> "visually merges" all documentation
1851 # if there is no interjacent code
1853 # - "always" -> disrupts documentation blocks,
1855 # - "if empty" (no whitespace). Comment if there is whitespace.
1857 # This would allow non-obstructing markup but unfortunately this is (in
1858 # most editors) also non-visible markup.
1860 # + "if double" (if there is more than one consecutive blank line)
1862 # With this handling, the "visual gap" remains in both, text and code
1863 # source.
1866 # Parsing Problems
1867 # ----------------
1869 # * Ignore "matching comments" in literal strings?
1871 # Too complicated: Would need a specific detection algorithm for every
1872 # language that supports multi-line literal strings (C++, PHP, Python)
1874 # * Warn if a comment in code will become documentation after round-trip?
1877 # docstrings in code blocks
1878 # -------------------------
1880 # * How to handle docstrings in code blocks? (it would be nice to convert them
1881 # to rst-text if ``__docformat__ == restructuredtext``)
1883 # TODO: Ask at Docutils users|developers
1885 # Plug-ins
1886 # --------
1888 # Specify a path for user additions and plug-ins. This would require to
1889 # convert Pylit from a pure module to a package...
1891 # 6.4.3 Packages in Multiple Directories
1893 # Packages support one more special attribute, __path__. This is initialized
1894 # to be a list containing the name of the directory holding the package's
1895 # __init__.py before the code in that file is executed. This
1896 # variable can be modified; doing so affects future searches for modules and
1897 # subpackages contained in the package.
1899 # While this feature is not often needed, it can be used to extend the set
1900 # of modules found in a package.
1903 # .. References
1905 # .. _Docutils: http://docutils.sourceforge.net/
1906 # .. _Sphinx: http://sphinx.pocoo.org
1907 # .. _Pygments: http://pygments.org/
1908 # .. _code-block directive:
1909 # http://docutils.sourceforge.net/sandbox/code-block-directive/
1910 # .. _literal block:
1911 # .. _literal blocks:
1912 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#literal-blocks
1913 # .. _indented literal block:
1914 # .. _indented literal blocks:
1915 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#indented-literal-blocks
1916 # .. _quoted literal block:
1917 # .. _quoted literal blocks:
1918 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#quoted-literal-blocks
1919 # .. _parsed-literal blocks:
1920 # http://docutils.sf.net/docs/ref/rst/directives.html#parsed-literal-block
1921 # .. _doctest block:
1922 # .. _doctest blocks:
1923 # http://docutils.sf.net/docs/ref/rst/restructuredtext.html#doctest-blocks
1924 # .. _issue 28734: https://bugs.python.org/issue28734
1925 # .. _issue 29670: https://bugs.python.org/issue29670
1926 # .. _argparse: https://docs.python.org/dev/library/argparse.html
1927 # .. _ArgumentParser.parse_args():
1928 # https://docs.python.org/dev/library/argparse.html#the-parse-args-method