|
1 | 1 | #!/usr/bin/env python3 |
2 | 2 |
|
3 | 3 | import os |
4 | | -import re |
5 | | -import subprocess |
| 4 | +from jinja2 import Template, StrictUndefined |
| 5 | +from j2cli.context import read_context_data |
6 | 6 |
|
7 | | -params = [os.environ['INPUT_TEMPLATE']] |
| 7 | +def guess_format(file_name): |
| 8 | + _, extension = os.path.splitext(file_name) |
| 9 | + print(extension) |
| 10 | + formats = { |
| 11 | + '.yaml': 'yaml', |
| 12 | + '.yml': 'yaml', |
| 13 | + '.json': 'json', |
| 14 | + '.ini': 'ini', |
| 15 | + '.env': 'env', |
| 16 | + } |
| 17 | + return formats.get(extension, 'env') |
8 | 18 |
|
| 19 | +variables = {'env': os.environ} |
9 | 20 | for variable in os.environ.get('INPUT_VARIABLES', '').split('\n'): |
10 | 21 | clean_variable = bytes(variable.strip(), 'utf-8').decode('unicode_escape') |
11 | 22 | if clean_variable != '': |
12 | | - params.extend(['-D', clean_variable]) |
| 23 | + name, value = clean_variable.split('=', 1) |
| 24 | + variables.update({name: value}) |
13 | 25 |
|
14 | | -if os.environ.get('INPUT_STRICT') == 'true': |
15 | | - params.append('--strict') |
| 26 | +data_file = os.environ.get('INPUT_DATA_FILE') |
| 27 | +if data_file: |
| 28 | + format = os.environ.get('INPUT_DATA_FORMAT', guess_format(data_file)) |
| 29 | + with open(data_file, 'r') as file: |
| 30 | + variables.update(read_context_data(format, file, None)) |
16 | 31 |
|
17 | | -params.extend(['-o', os.environ['INPUT_OUTPUT_FILE']]) |
| 32 | +with open(os.environ['INPUT_TEMPLATE'], 'r') as file: |
| 33 | + template_kwargs = {} |
| 34 | + if os.environ.get('INPUT_STRICT') == 'true': |
| 35 | + template_kwargs.update({'undefined': StrictUndefined}) |
| 36 | + template = Template(str(file.read()), **template_kwargs) |
18 | 37 |
|
19 | | -params.extend([os.environ.get('INPUT_DATA_FILE','')]) |
20 | | - |
21 | | -subprocess.run(['jinja2'] + params, check = True) |
| 38 | +with open(os.environ['INPUT_OUTPUT_FILE'], 'w') as file: |
| 39 | + file.write(template.render(**variables) + '\n') |
0 commit comments