Skip to content

Commit

Permalink
Support for including file contents as an array (#154)
Browse files Browse the repository at this point in the history
  • Loading branch information
besbes committed May 27, 2020
1 parent 8e6d502 commit 9f65bb8
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
11 changes: 11 additions & 0 deletions docs/template-files.md
Expand Up @@ -207,6 +207,17 @@ Resources:
Runtime: "python3.7"
```

### code_array

Sometimes you might want to take the contents of a file as input for an array (line-by-line). Combine `code()` with `code_array` to make that happen:

```yaml
Resources:
...
ListOfItems: {{ code('my-list') | code_array }}
```



### file

Expand Down
13 changes: 10 additions & 3 deletions formica/loader.py
Expand Up @@ -41,6 +41,9 @@
def code_escape(source):
return source.replace("\n", "\\n").replace('"', '\\"')

def code_array(source):
lines = source.split("\\n")
return '[' + ','.join(['"%s"' % line for line in lines]) + ']'

def mandatory(a):
from jinja2.runtime import Undefined
Expand Down Expand Up @@ -69,9 +72,13 @@ def __init__(self, path=".", filename="*", variables=None, main_account_paramete
self.path = path
self.filename = filename
self.env = Environment(loader=FileSystemLoader("./", followlinks=True))
self.env.filters.update(
{"code_escape": code_escape, "mandatory": mandatory, "resource": resource, "novalue": novalue}
)
self.env.filters.update({
"code_escape": code_escape,
"code_array": code_array,
"mandatory": mandatory,
"resource": resource,
"novalue": novalue,
})
self.variables = variables
self.main_account_parameter = main_account_parameter

Expand Down
13 changes: 13 additions & 0 deletions tests/unit/test_loader.py
Expand Up @@ -333,6 +333,19 @@ def test_code_includes_and_escapes_code(load, tmpdir):
assert actual == {"Description": "test\n\"something\""}


def test_code_with_code_array(load, tmpdir):
example = '{"Resources": {"Test": {{ code("test.py") | code_array }} }}'
pycode = "test\n\"something\"\nanother line"
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with open('test.py', 'w') as f:
f.write(pycode)
load.load()
actual = json.loads(load.template())
assert actual == {"Resources": {"Test": ["test", "\"something\"", "another line"]}}


def test_code_allows_to_include_files_from_parent(load, tmpdir):
parent = '{"Resources": {"Test": {"From": "Moduledir"}}}'
module = '{"Description": "{{ code("../test.txt") }}"}'
Expand Down

0 comments on commit 9f65bb8

Please sign in to comment.