-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.py
More file actions
144 lines (111 loc) · 4.44 KB
/
generator.py
File metadata and controls
144 lines (111 loc) · 4.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python3
"""
Configuration Generator using Jinja2 Templates
"""
import os
import sys
import yaml
from jinja2 import Environment, FileSystemLoader, TemplateNotFound
from pathlib import Path
class ConfigGenerator:
"""Generate configurations from Jinja2 templates and YAML data."""
def __init__(self, template_dir='templates', output_dir='configs'):
"""
Initialize the configuration generator.
Args:
template_dir: Directory containing Jinja2 templates
output_dir: Directory for generated configurations
"""
self.template_dir = template_dir
self.output_dir = output_dir
self.env = Environment(
loader=FileSystemLoader(self.template_dir),
trim_blocks=True,
lstrip_blocks=True
)
# Create output directory if it doesn't exist
Path(self.output_dir).mkdir(parents=True, exist_ok=True)
def load_data(self, data_file):
"""
Load configuration data from YAML file.
Args:
data_file: Path to YAML data file
Returns:
Dictionary containing configuration data
"""
try:
with open(data_file, 'r', encoding='utf-8') as f:
data = yaml.safe_load(f)
if data is None:
return {}
if not isinstance(data, dict):
raise ValueError(f"YAML data in '{data_file}' must be a dictionary/object at the top level.")
return data
except FileNotFoundError:
raise FileNotFoundError(f"Data file not found: {data_file}")
except yaml.YAMLError as e:
raise ValueError(f"Failed to parse YAML file '{data_file}': {e}")
def generate_config(self, template_name, data, output_file=None):
"""
Generate configuration from template and data.
Args:
template_name: Name of the template file
data: Dictionary containing template variables
output_file: Optional output filename (defaults to template name without .j2)
Returns:
Generated configuration as string
"""
try:
template = self.env.get_template(template_name)
except TemplateNotFound:
raise FileNotFoundError(f"Template not found: {template_name}")
rendered = template.render(**data)
if output_file is None:
if template_name.endswith('.j2'):
output_file = template_name[:-3]
else:
output_file = template_name
output_path = Path(self.output_dir) / output_file
with open(output_path, 'w', encoding='utf-8') as f:
f.write(rendered)
if not rendered.endswith('\n'):
f.write('\n')
return rendered
def generate_all(self, data_file, template_list=None):
"""
Generate multiple configurations from a data file.
Args:
data_file: Path to YAML data file
template_list: List of template names (None = all templates)
"""
data = self.load_data(data_file)
if template_list is None:
template_list = sorted(
[f for f in os.listdir(self.template_dir) if f.endswith('.j2')]
)
generated_files = []
for template_name in template_list:
try:
output_file = template_name[:-3] if template_name.endswith('.j2') else template_name
self.generate_config(template_name, data, output_file=output_file)
generated_files.append(str(Path(self.output_dir) / output_file))
print(f"Generated: {Path(self.output_dir) / output_file}")
except Exception as e:
print(f"Error generating '{template_name}': {e}", file=sys.stderr)
print(f"\nSummary: generated {len(generated_files)} file(s) from {data_file}")
def main():
"""Main execution function."""
if len(sys.argv) < 2:
print("Usage: python3 generator.py <data_file> [template1 template2 ...]")
print("Example: python3 generator.py data/dev_config.yaml")
sys.exit(1)
data_file = sys.argv[1]
templates = sys.argv[2:] if len(sys.argv) > 2 else None
generator = ConfigGenerator()
try:
generator.generate_all(data_file, templates)
except Exception as e:
print(f"Generator error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()