|
| 1 | +""" |
| 2 | +Representer for Python. |
| 3 | +""" |
| 4 | +from typing import Dict |
| 5 | + |
| 6 | +from . import utils |
| 7 | +from .normalizer import Normalizer |
| 8 | + |
| 9 | + |
| 10 | +class Representer: |
| 11 | + """ |
| 12 | + Represent Python code in normalized form. |
| 13 | + """ |
| 14 | + |
| 15 | + def __init__(self, source: str) -> None: |
| 16 | + self._tree = utils.parse(source) |
| 17 | + self._normalizer = Normalizer() |
| 18 | + |
| 19 | + def normalize(self) -> None: |
| 20 | + """ |
| 21 | + Normalize the tree. |
| 22 | + """ |
| 23 | + self._tree = self._normalizer.visit(self._tree) |
| 24 | + |
| 25 | + def dump_tree(self) -> str: |
| 26 | + """ |
| 27 | + Dump the current state of the tree for printing. |
| 28 | + """ |
| 29 | + return utils.dump_tree(self._tree) |
| 30 | + |
| 31 | + def dump_code(self, reformat=True) -> str: |
| 32 | + """ |
| 33 | + Dump the current tree as generate code. |
| 34 | + """ |
| 35 | + code = utils.to_source(self._tree) |
| 36 | + if reformat: |
| 37 | + return utils.reformat(code) |
| 38 | + return code |
| 39 | + |
| 40 | + @property |
| 41 | + def mapping(self) -> Dict[str, str]: |
| 42 | + """ |
| 43 | + Get the placeholder assignments after normalize. |
| 44 | + """ |
| 45 | + return self._normalizer.get_placeholders() |
| 46 | + |
| 47 | + def dump_map(self) -> str: |
| 48 | + """ |
| 49 | + Dump the tree's mapping of placeholders. |
| 50 | + """ |
| 51 | + return utils.to_json(self.mapping) |
| 52 | + |
| 53 | + |
| 54 | +def represent(slug: utils.Slug, directory: utils.Directory) -> None: |
| 55 | + """ |
| 56 | + Normalize the `directory/slug.py` file representation. |
| 57 | + """ |
| 58 | + src = directory.joinpath(slug.replace("-", "_") + ".py") |
| 59 | + out_dst = directory.joinpath("representation.out") |
| 60 | + txt_dst = directory.joinpath("representation.txt") |
| 61 | + map_dst = directory.joinpath("mapping.json") |
| 62 | + |
| 63 | + # parse the tree from the file contents |
| 64 | + representation = Representer(src.read_text()) |
| 65 | + |
| 66 | + # save dump of the initial tree for debug |
| 67 | + out = ["# BEGIN TREE BEFORE", representation.dump_tree(), ""] |
| 68 | + |
| 69 | + # normalize the tree |
| 70 | + representation.normalize() |
| 71 | + |
| 72 | + # save dump of the normalized tree for debug |
| 73 | + out.extend(["# BEGIN TREE AFTER", representation.dump_tree()]) |
| 74 | + |
| 75 | + # dump the representation files |
| 76 | + out_dst.write_text("\n".join(out)) |
| 77 | + txt_dst.write_text(representation.dump_code()) |
| 78 | + map_dst.write_text(representation.dump_map()) |
0 commit comments