|
13 | 13 | from pyfakefs.fake_filesystem import FakeFilesystem |
14 | 14 |
|
15 | 15 |
|
16 | | -def indent(template: templatelib.Template) -> str: |
17 | | - """Template-rendering function to render a t-string while preserving indentation, |
18 | | - processing all the accustomed f-string formatters. |
19 | | - References: https://www.pythonmorsels.com/t-strings-in-python/ |
20 | | - https://github.com/t-strings/pep750-examples/blob/main/pep/fstring.py""" |
| 16 | +def process_template_with_indents(template: templatelib.Template) -> str: |
| 17 | + """Process a template string while preserving indentation. |
| 18 | +
|
| 19 | + The standard f-string formatters in the template are processed. |
| 20 | +
|
| 21 | + This is useful for embedding multi-line code blocks inside other code blocks, |
| 22 | + for example, in Dockerfiles. |
| 23 | +
|
| 24 | + >>> from string import templatelib as t |
| 25 | + >>> import textwrap |
| 26 | + >>> |
| 27 | + >>> cleanup_fragment = ''' |
| 28 | + ... dnf clean all |
| 29 | + ... rm -rf /var/lib/dnf |
| 30 | + ... '''.strip() |
| 31 | + >>> |
| 32 | + >>> # Instead of this, which is hard to read: |
| 33 | + >>> script1 = f'''RUN /bin/bash <<'EOF' |
| 34 | + ... if [ -z "$RUN_CLEANUP" ]; then |
| 35 | + ... {textwrap.indent(cleanup_fragment, prefix=" ")} |
| 36 | + ... EOF |
| 37 | + ... ''' |
| 38 | + >>> |
| 39 | + >>> # You can do this, which is more straightforward to read: |
| 40 | + >>> script2 = process_template_with_indents(t'''RUN /bin/bash <<'EOF' |
| 41 | + ... if [ -z "$RUN_CLEANUP" ]; then |
| 42 | + ... {cleanup_fragment} |
| 43 | + ... EOF |
| 44 | + ... ''') |
| 45 | + >>> |
| 46 | + >>> print(script2) |
| 47 | + RUN /bin/bash <<'EOF' |
| 48 | + if [ -z "$RUN_CLEANUP" ]; then |
| 49 | + dnf clean all |
| 50 | + rm -rf /var/lib/dnf |
| 51 | + EOF |
| 52 | + <BLANKLINE> |
| 53 | + >>> # The results are the same |
| 54 | + >>> script1 == script2 |
| 55 | + True |
| 56 | +
|
| 57 | + References: |
| 58 | + - https://www.pythonmorsels.com/t-strings-in-python/ |
| 59 | + - https://github.com/t-strings/pep750-examples/blob/main/pep/fstring.py |
| 60 | + """ |
21 | 61 | parts = [] |
22 | 62 | indent = 0 |
23 | 63 | for item in template: |
|
0 commit comments