-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtmpl.py
More file actions
304 lines (245 loc) · 9.9 KB
/
tmpl.py
File metadata and controls
304 lines (245 loc) · 9.9 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#!/usr/bin/env python3
"""
tmpl -- Template file processor with variable substitution. Zero deps.
Render config files, emails, docs with variables from env files, JSON, or CLI.
Supports {{var}}, ${var}, defaults, conditionals. Cross-platform envsubst.
Usage:
py tmpl.py render config.tmpl -v port=8080 -v env=prod
py tmpl.py render config.tmpl --env vars.env -o config.yml
py tmpl.py render config.tmpl --json vars.json
py tmpl.py render template.html -v name=Alice --env prod.env
py tmpl.py check config.tmpl # List required variables
cat template.txt | py tmpl.py render -v user=Alice # Stdin
py tmpl.py render *.tmpl --env prod.env --outdir ./out/ # Batch process
Template syntax:
{{var}} Variable substitution
${var} Shell-style variable
{{var:default}} Default value if var is not set
{{#if var}}...{{/if}} Conditional block (included if var is truthy)
{{#unless var}}...{{/unless}} Inverse conditional
{{#each items}}...{{/each}} Loop over comma-separated var
{{@index}} Current loop index (inside #each)
{{@value}} Current loop value (inside #each)
{{!comment}} Comment (removed from output)
"""
import argparse
import json
import os
import re
import sys
from pathlib import Path
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
CYAN = "\033[36m"
RED = "\033[31m"
def color_supported() -> bool:
if os.environ.get("NO_COLOR"):
return False
if sys.platform == "win32":
return bool(os.environ.get("TERM") or os.environ.get("WT_SESSION"))
return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
USE_COLOR = color_supported()
def c(code: str, text: str) -> str:
return f"{code}{text}{RESET}" if USE_COLOR else text
def load_env_file(path: str) -> dict:
"""Load variables from .env file."""
variables = {}
p = Path(path)
if not p.exists():
print(c(YELLOW, f" Warning: env file not found: {path}"), file=sys.stderr)
return variables
for line in p.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
key, _, val = line.partition("=")
val = val.strip().strip("'\"")
variables[key.strip()] = val
return variables
def load_json_file(path: str) -> dict:
"""Load variables from JSON file (flat key-value)."""
p = Path(path)
if not p.exists():
print(c(RED, f" Error: JSON file not found: {path}"), file=sys.stderr)
return {}
try:
data = json.loads(p.read_text(encoding="utf-8"))
if isinstance(data, dict):
return {k: str(v) for k, v in data.items()}
except json.JSONDecodeError as e:
print(c(RED, f" Error: invalid JSON in {path}: {e}"), file=sys.stderr)
return {}
def render_template(template: str, variables: dict) -> str:
"""Render a template string with variable substitution."""
result = template
# Remove comments: {{!...}}
result = re.sub(r"\{\{!.*?\}\}", "", result)
# Process {{#each var}}...{{/each}} loops
def process_each(m):
var_name = m.group(1).strip()
body = m.group(2)
items = variables.get(var_name, "")
if isinstance(items, str):
items = [i.strip() for i in items.split(",") if i.strip()]
output = []
for idx, item in enumerate(items):
block = body
block = block.replace("{{@index}}", str(idx))
block = block.replace("{{@value}}", item)
output.append(block)
return "".join(output)
result = re.sub(
r"\{\{#each\s+(\w+)\}\}(.*?)\{\{/each\}\}",
process_each, result, flags=re.DOTALL
)
# Process {{#if var}}...{{/if}} conditionals
def process_if(m):
var_name = m.group(1).strip()
body = m.group(2)
val = variables.get(var_name, "")
if val and val.lower() not in ("false", "0", "no", "null", "none", ""):
return body
return ""
result = re.sub(
r"\{\{#if\s+(\w+)\}\}(.*?)\{\{/if\}\}",
process_if, result, flags=re.DOTALL
)
# Process {{#unless var}}...{{/unless}} inverse conditionals
def process_unless(m):
var_name = m.group(1).strip()
body = m.group(2)
val = variables.get(var_name, "")
if not val or val.lower() in ("false", "0", "no", "null", "none", ""):
return body
return ""
result = re.sub(
r"\{\{#unless\s+(\w+)\}\}(.*?)\{\{/unless\}\}",
process_unless, result, flags=re.DOTALL
)
# Replace {{var:default}} with default value support
def replace_with_default(m):
var_name = m.group(1).strip()
default = m.group(2)
return variables.get(var_name, default)
result = re.sub(r"\{\{\s*(\w+)\s*:\s*([^}]*)\s*\}\}", replace_with_default, result)
# Replace {{var}} mustache-style
def replace_mustache(m):
var_name = m.group(1).strip()
return variables.get(var_name, m.group(0))
result = re.sub(r"\{\{\s*(\w+)\s*\}\}", replace_mustache, result)
# Replace ${var} and $var shell-style
def replace_shell(m):
var_name = m.group(1) or m.group(2)
return variables.get(var_name, m.group(0))
result = re.sub(r"\$\{(\w+)\}|\$(\b[A-Z_][A-Z0-9_]*\b)", replace_shell, result)
return result
def extract_variables(template: str) -> dict:
"""Extract all variable references from a template."""
vars_found = {}
# {{var}} and {{var:default}}
for m in re.finditer(r"\{\{\s*(\w+)\s*(?::\s*([^}]*))?\s*\}\}", template):
name = m.group(1)
default = m.group(2)
if name not in ("if", "unless", "each") and not name.startswith("@"):
vars_found[name] = default
# ${var} and $VAR
for m in re.finditer(r"\$\{(\w+)\}|\$(\b[A-Z_][A-Z0-9_]*\b)", template):
name = m.group(1) or m.group(2)
if name not in vars_found:
vars_found[name] = None
# #if, #unless, #each variable names
for m in re.finditer(r"\{\{#(?:if|unless|each)\s+(\w+)\}\}", template):
name = m.group(1)
if name not in vars_found:
vars_found[name] = None
return vars_found
# --- Commands ---
def cmd_render(args):
# Collect variables
variables = {}
# From env file
if args.env:
variables.update(load_env_file(args.env))
# From JSON file
if args.json:
variables.update(load_json_file(args.json))
# From CLI --var flags
for var_str in args.var:
if "=" in var_str:
k, _, v = var_str.partition("=")
variables[k.strip()] = v.strip()
# Also inherit from environment
if args.use_env:
variables.update(os.environ)
# Read template(s)
if args.files:
for filepath in args.files:
p = Path(filepath)
if not p.exists():
print(c(RED, f" Error: {filepath} not found"), file=sys.stderr)
continue
template = p.read_text(encoding="utf-8", errors="replace")
rendered = render_template(template, variables)
if args.outdir:
out_path = Path(args.outdir) / p.name.replace(".tmpl", "").replace(".template", "")
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(rendered, encoding="utf-8")
print(f" {c(GREEN, 'Rendered')} {filepath} -> {out_path}")
elif args.output:
Path(args.output).write_text(rendered, encoding="utf-8")
print(f" {c(GREEN, 'Rendered')} {filepath} -> {args.output}")
else:
sys.stdout.write(rendered)
else:
# Read from stdin
if sys.stdin.isatty():
print("Error: no template file. Provide files or pipe stdin.", file=sys.stderr)
sys.exit(1)
template = sys.stdin.read()
rendered = render_template(template, variables)
sys.stdout.write(rendered)
def cmd_check(args):
"""List variables required by a template."""
for filepath in args.files:
p = Path(filepath)
if not p.exists():
print(c(RED, f" Error: {filepath} not found"))
continue
template = p.read_text(encoding="utf-8", errors="replace")
vars_found = extract_variables(template)
print(f"\n {c(BOLD, filepath)}: {len(vars_found)} variable(s)\n")
for name, default in sorted(vars_found.items()):
if default is not None:
print(f" {c(CYAN, name):<20} default: {c(DIM, default)}")
else:
print(f" {c(CYAN, name):<20} {c(YELLOW, '(required)')}")
print()
def main():
parser = argparse.ArgumentParser(
description="tmpl -- template file processor with variable substitution",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
sub = parser.add_subparsers(dest="command")
p = sub.add_parser("render", help="Render template(s)")
p.add_argument("files", nargs="*", help="Template file(s)")
p.add_argument("-v", "--var", action="append", default=[], help="Set variable (key=value). Repeatable.")
p.add_argument("--env", help="Load variables from .env file")
p.add_argument("--json", help="Load variables from JSON file")
p.add_argument("--use-env", action="store_true", help="Also use OS environment variables")
p.add_argument("-o", "--output", help="Output file (single template)")
p.add_argument("--outdir", help="Output directory (batch mode)")
p = sub.add_parser("check", help="List variables in template(s)")
p.add_argument("files", nargs="+", help="Template file(s)")
args = parser.parse_args()
if args.command == "render":
cmd_render(args)
elif args.command == "check":
cmd_check(args)
else:
parser.print_help()
if __name__ == "__main__":
main()