| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 1 | from collections import defaultdict |
| 2 | from io import StringIO |
| 3 | from textwrap import indent |
| 4 | |
| 5 | |
| 6 | class CodeWriter(StringIO): |
| 7 | """ |
| 8 | Blob of text that, when used in the context of facade.py, ends up |
| 9 | holding the source code for a Python class and associated methods. |
| 10 | |
| 11 | """ |
| 12 | INDENT = " " |
| 13 | |
| 14 | CLASS = 0 |
| 15 | METHOD = 1 |
| 16 | |
| 17 | def write(self, msg, depth=0): |
| 18 | if depth: |
| 19 | prefix = self.INDENT * depth |
| 20 | msg = indent(msg, prefix) |
| 21 | |
| 22 | return super(CodeWriter, self).write(msg) |
| 23 | |
| 24 | def __str__(self): |
| 25 | return super(CodeWriter, self).getvalue() |
| 26 | |
| 27 | |
| 28 | class Capture(defaultdict): |
| 29 | """ |
| 30 | A collection of CodeWriter objects, together representing a Python |
| 31 | module. |
| 32 | |
| 33 | """ |
| 34 | |
| 35 | def __init__(self, default_factory=CodeWriter, *args, **kwargs): |
| 36 | super(Capture, self).__init__(default_factory, *args, **kwargs) |
| 37 | |
| 38 | def clear(self, name): |
| 39 | """ |
| 40 | Reset one of the keys in this class, if it exists. |
| 41 | |
| 42 | This is necessary, because we don't worry about de-duplicating |
| 43 | the schemas for each version of juju up front, and this gives |
| 44 | us a way to sort of de-duplicate on the fly, by resetting a |
| 45 | specific CodeWriter instance before we start to write a class |
| 46 | into it. |
| 47 | |
| 48 | """ |
| 49 | try: |
| 50 | del self[name] |
| 51 | except KeyError: |
| 52 | pass |