blob: 285858fcb78d3428e0b3dc57f7d0c66895bce574 [file] [log] [blame]
Dennis Dmitrievf260d152017-08-15 00:59:24 +03001# Copyright 2013 - 2017 Mirantis, Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
15import sys
16import yaml
17
18from cookiecutter.exceptions import UndefinedVariableInTemplate
19from cookiecutter import generate
20
21from reclass_tools import helpers
22
23
24def render_dir(template_dir, output_dir, contexts, env_name=None):
25 """Coockiecutter echancement to use several source JSON files
26
27 :param template_dir: directory with templates to render
28 :param output_dir: directory that should be created from templates
29 :param context_files: list of strings, paths to YAML or JSON files
30 that provide the context variables for rendering.
31 Merge of the files usind update() into a single
32 dict is in the same order as files in the list.
33 :param env_name: name for new environment that will be created
34 """
35 def toyaml(value, width=0, indentfirst=False):
36 string = yaml.dump(value, default_flow_style=False)
37 if string.splitlines():
38 return (
39 ' ' * width * indentfirst +
40 ('\n' + ' ' * width).join(string.splitlines()) + '\n')
41 else:
42 return ''
43
44 overwrite_if_exists = True
45
46 merged_context = {}
47
48 for fcon in contexts:
49 if fcon.endswith('.yaml'):
50 context = helpers.yaml_read(fcon)
51 elif fcon.endswith('.json'):
52 context = helpers.json_read(fcon)
53 else:
54 sys.exit("Error: Please use YAML or JSON files for contexts")
55
56 merged_context = helpers.merge_nested_objects(merged_context, context)
57
58 merged_context['toyaml'] = toyaml
59 if env_name:
60 if 'cookiecutter' not in merged_context:
61 merged_context['cookiecutter'] = {}
62 merged_context['cookiecutter']['_env_name'] = env_name
63
64 try:
65 generate.generate_files(
66 repo_dir=template_dir,
67 context=merged_context,
68 overwrite_if_exists=overwrite_if_exists,
69 output_dir=output_dir
70 )
71
72 except UndefinedVariableInTemplate as undefined_err:
73 context_str = yaml.dump(
74 undefined_err.context,
75 default_flow_style=False
76 )
77 print('=' * 15 + ' Context: ' + '=' * 15 +
78 '\n{}'.format(context_str) + '='*40)
79 print('>>> {}'.format(undefined_err.message))
80 sys.exit('>>> Error message: {}'.format(undefined_err.error.message))