Skip to content

Commit

Permalink
[Added] Support for json file loader
Browse files Browse the repository at this point in the history
Signed-off-by: amannocci <[email protected]>
  • Loading branch information
amannocci committed May 3, 2021
1 parent 1ac80eb commit 108b5ad
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 6 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,36 @@ temply --dotenv /path/to/dotenv /path/to/template.yml.tpl
foobar = foobar
```

### How to render a configuration with a json file.

* Create a file where you want `/path/to/template.yml.tpl` with the following content.

```text
foo="{{ FOO }}"
bar="{{ BAR }}"
```

* Then create a json file named `file.json` with the following content.
```json
[
{"key": "FOO", "value": "foo"},
{"key": "BAR", "value": "bar"}
]
```

* Then launch the command below to render.

```bash
temply --json-file /path/to/file.json /path/to/template.yml.tpl
```

* It will output on stdout the following content.

```yaml
foo="foo"
bar="bar"
```

### How to render a configuration and keep template after rendering.

* By default, temply will remove template file.
Expand Down
27 changes: 27 additions & 0 deletions temply/loaders.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import os
from abc import ABC, abstractmethod
from typing import Dict, Optional
Expand Down Expand Up @@ -72,3 +73,29 @@ def load(self, ref: Optional[Dict] = None) -> Dict:
raise click.FileError(dotfile_path.abspath(), err.__str__())

return ctx


class JsonFileLoader(Loader):
"""Environment json file loader implementation"""

def __init__(self, path: str):
self.__path = path

def load(self, ref: Optional[Dict] = None) -> Dict:
ctx = ref if ref else dict()

# Check json file is a regular file
json_file_path = Path(self.__path)
if not json_file_path.isfile():
raise click.FileError(json_file_path.abspath(), 'Must be a regular file')

# Process
try:
values = json.loads(json_file_path.read_text())
for val in values:
if val.get('key'):
ctx[val.get('key')] = val.get('value')
except OSError as err:
raise click.FileError(json_file_path.abspath(), err.__str__())

return ctx
12 changes: 6 additions & 6 deletions temply/temply.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,19 @@
from path import Path

from . import __version__
from .loaders import EnvLoader, EnvdirLoader, DotenvLoader
from .loaders import EnvLoader, EnvdirLoader, DotenvLoader, JsonFileLoader


@click.command('temply')
@click.option('--allow-missing', help='Allow missing variables.', is_flag=True)
@click.option('--keep-template', help='Keep original template file.', is_flag=True)
@click.option('--envdir', help='Load environment variables from directory', type=click.Path())
@click.option('--dotenv', help='Load environment variables from dotenv file', type=click.Path())
@click.option('--json-file', help='Load environment variables from json file', type=click.Path())
@click.option('-o', '--output-file', help='Output file path.', type=click.Path())
@click.version_option(f'{__version__}')
@click.argument('input_file', required=False)
def main(allow_missing, keep_template, envdir, dotenv, output_file, input_file):
def main(allow_missing, keep_template, envdir, dotenv, json_file, output_file, input_file):
"""Render jinja2 templates on the command line with environment variables."""

# Define undefine behaviour
Expand Down Expand Up @@ -58,10 +59,9 @@ def main(allow_missing, keep_template, envdir, dotenv, output_file, input_file):

# Compute env
envs = EnvLoader().load()
if envdir:
envs = EnvdirLoader(envdir).load(envs)
if dotenv:
envs = DotenvLoader(dotenv).load(envs)
envs = EnvdirLoader(envdir).load(envs) if envdir else envs
envs = DotenvLoader(dotenv).load(envs) if dotenv else envs
envs = JsonFileLoader(json_file).load(envs) if json_file else envs
try:
rendering = template.render(**envs)
except jinja2.UndefinedError as e:
Expand Down
7 changes: 7 additions & 0 deletions tests/e2e/temply_file_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ def test_dotenv_template():
assert result.exit_code == 0


def test_json_file_template():
runner = CliRunner()
result = runner.invoke(main, args=['--keep-template', '--json-file', 'tests/fixtures/envs.json', 'tests/fixtures/envs.tpl'])
assert result.output == "key.secret = value-of-secret\n\n"
assert result.exit_code == 0


def test_wrong_dotenv_template():
runner = CliRunner()
result = runner.invoke(main, args=['--keep-template', '--dotenv', 'tests/fixtures/wrong_dotenv', 'tests/fixtures/envs.tpl'],
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures/envs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[{
"key": "MY_key.secret",
"value": "value-of-secret"
}]

0 comments on commit 108b5ad

Please sign in to comment.