jj2 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jj2/__init__.py +12 -0
- jj2/__main__.py +8 -0
- jj2/cli.py +219 -0
- jj2/context.py +43 -0
- jj2/customize.py +31 -0
- jj2/defaults.py +15 -0
- jj2/errors.py +56 -0
- jj2/filters.py +139 -0
- jj2/parsers.py +193 -0
- jj2/render.py +106 -0
- jj2-0.7.0.dist-info/METADATA +345 -0
- jj2-0.7.0.dist-info/RECORD +15 -0
- jj2-0.7.0.dist-info/WHEEL +4 -0
- jj2-0.7.0.dist-info/entry_points.txt +3 -0
- jj2-0.7.0.dist-info/licenses/LICENSE +26 -0
jj2/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""j2cli main file"""
|
|
2
|
+
|
|
3
|
+
import importlib.metadata
|
|
4
|
+
|
|
5
|
+
__author__ = 'Manolis Stamatogiannakis'
|
|
6
|
+
__email__ = 'mstamat@gmail.com'
|
|
7
|
+
__version__ = importlib.metadata.version('jj2')
|
|
8
|
+
|
|
9
|
+
from jj2.cli import render
|
|
10
|
+
|
|
11
|
+
# The entry point of the jj2 command (jj2:render) and of python -m jj2.
|
|
12
|
+
__all__ = ['render']
|
jj2/__main__.py
ADDED
jj2/cli.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import logging
|
|
3
|
+
import sys
|
|
4
|
+
import traceback
|
|
5
|
+
from functools import reduce
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import jinja2
|
|
9
|
+
import jinja2.loaders
|
|
10
|
+
import jinja2.meta
|
|
11
|
+
|
|
12
|
+
from . import __version__, filters, parsers
|
|
13
|
+
from .context import dict_squash
|
|
14
|
+
from .customize import CustomizationModule
|
|
15
|
+
from .defaults import CONTEXT_FORMATS
|
|
16
|
+
from .errors import error_message
|
|
17
|
+
from .render import Jinja2TemplateRenderer, load_python_file
|
|
18
|
+
|
|
19
|
+
# available log levels, adjusted with -v at command line
|
|
20
|
+
LOGLEVELS = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
|
|
21
|
+
|
|
22
|
+
# format to use for logging
|
|
23
|
+
LOGFORMAT = '%(levelname)s: %(message)s'
|
|
24
|
+
|
|
25
|
+
# Printed after the traceback of an exception that jj2 does not know.
|
|
26
|
+
UNEXPECTED_ERROR = (
|
|
27
|
+
'jj2: unexpected error. If the traceback above does not point to your own code '
|
|
28
|
+
'(--filters, --tests, --customize), this is a bug in jj2: please report it, with '
|
|
29
|
+
'the traceback, at https://github.com/m000/jj2/issues'
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def comma_list(value):
|
|
34
|
+
"""Splits an option value at commas: 'a.py,b.py' -> ['a.py', 'b.py']."""
|
|
35
|
+
return [item for item in value.split(',') if item]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def render_command(argv):
|
|
39
|
+
"""Pure render command
|
|
40
|
+
:param argv: Command-line arguments
|
|
41
|
+
:type argv: list
|
|
42
|
+
:return: Rendered template
|
|
43
|
+
:rtype: basestring
|
|
44
|
+
"""
|
|
45
|
+
parser = argparse.ArgumentParser(
|
|
46
|
+
prog='jj2',
|
|
47
|
+
description='Renders Jinja2 templates from the command line.',
|
|
48
|
+
epilog='',
|
|
49
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
50
|
+
)
|
|
51
|
+
p_input = parser.add_argument_group('input options')
|
|
52
|
+
p_output = parser.add_argument_group('output options')
|
|
53
|
+
p_custom = parser.add_argument_group('customization options')
|
|
54
|
+
|
|
55
|
+
### optional arguments ##########################################
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
'-V',
|
|
58
|
+
'--version',
|
|
59
|
+
action='version',
|
|
60
|
+
version=f'jj2 {__version__}, Jinja2 {jinja2.__version__}',
|
|
61
|
+
)
|
|
62
|
+
parser.add_argument('-v', '--verbose', action='count', default=0, help='Increase verbosity.')
|
|
63
|
+
### input options ###############################################
|
|
64
|
+
p_input.add_argument('template', help='Template file to process.')
|
|
65
|
+
p_input.add_argument(
|
|
66
|
+
'-T',
|
|
67
|
+
'--template-dir',
|
|
68
|
+
action='append',
|
|
69
|
+
default=[],
|
|
70
|
+
metavar='DIR',
|
|
71
|
+
dest='template_dirs',
|
|
72
|
+
help='Look for included templates in DIR, before the directory of the template. '
|
|
73
|
+
'Repeat the option for more directories, in order.',
|
|
74
|
+
)
|
|
75
|
+
p_input.add_argument(
|
|
76
|
+
'data',
|
|
77
|
+
nargs='+',
|
|
78
|
+
default=[],
|
|
79
|
+
type=parsers.InputDataType(),
|
|
80
|
+
help='Input data specification: [<dest>=]<source>[:<format>]. '
|
|
81
|
+
'Multiple sources in different formats can be specified. '
|
|
82
|
+
'They are squashed into one context, from left to right. '
|
|
83
|
+
'<source> is a file, or - or nothing for stdin. '
|
|
84
|
+
'<format> overrides the format given by the file extension. '
|
|
85
|
+
'<dest> puts the data under a key, or a dotted key path (app.host=host.yaml).',
|
|
86
|
+
)
|
|
87
|
+
p_input.add_argument(
|
|
88
|
+
'-U',
|
|
89
|
+
'--undefined',
|
|
90
|
+
default='strict',
|
|
91
|
+
dest='undefined',
|
|
92
|
+
choices=Jinja2TemplateRenderer.UNDEFINED,
|
|
93
|
+
help='What Jinja2 does with undefined variables.',
|
|
94
|
+
)
|
|
95
|
+
p_input.add_argument(
|
|
96
|
+
'-I', '--ignore-missing', action='store_true', help='Ignore any missing data files.'
|
|
97
|
+
)
|
|
98
|
+
p_input.add_argument(
|
|
99
|
+
'-f',
|
|
100
|
+
'--fallback-format',
|
|
101
|
+
default='ini',
|
|
102
|
+
choices=CONTEXT_FORMATS,
|
|
103
|
+
help='Specify fallback data format. '
|
|
104
|
+
'Used for data with no specified format and no appropriate extension.',
|
|
105
|
+
)
|
|
106
|
+
### output options ##############################################
|
|
107
|
+
p_output.add_argument(
|
|
108
|
+
'-o', metavar='outfile', dest='output_file', help='Output to a file instead of stdout.'
|
|
109
|
+
)
|
|
110
|
+
p_output.add_argument(
|
|
111
|
+
'--no-compact',
|
|
112
|
+
action='store_true',
|
|
113
|
+
dest='no_compact',
|
|
114
|
+
help='Do not compact space around Jinja2 blocks.',
|
|
115
|
+
)
|
|
116
|
+
### customization ###############################################
|
|
117
|
+
# NB: Each option takes one argument, a comma-separated list, so that it never
|
|
118
|
+
# takes the template and data that follow it. action='extend' collects the
|
|
119
|
+
# lists of repeated options into one list.
|
|
120
|
+
p_custom.add_argument(
|
|
121
|
+
'--filters',
|
|
122
|
+
type=comma_list,
|
|
123
|
+
action='extend',
|
|
124
|
+
default=[],
|
|
125
|
+
metavar='python-file[,...]',
|
|
126
|
+
dest='filters',
|
|
127
|
+
help='Load the top-level functions of Python files as Jinja2 filters. '
|
|
128
|
+
'Give a comma-separated list, or repeat the option.',
|
|
129
|
+
)
|
|
130
|
+
p_custom.add_argument(
|
|
131
|
+
'--tests',
|
|
132
|
+
type=comma_list,
|
|
133
|
+
action='extend',
|
|
134
|
+
default=[],
|
|
135
|
+
metavar='python-file[,...]',
|
|
136
|
+
dest='tests',
|
|
137
|
+
help='Load the top-level functions of Python files as Jinja2 tests. '
|
|
138
|
+
'Give a comma-separated list, or repeat the option.',
|
|
139
|
+
)
|
|
140
|
+
p_custom.add_argument(
|
|
141
|
+
'--customize',
|
|
142
|
+
default=None,
|
|
143
|
+
metavar='python-file',
|
|
144
|
+
dest='customize',
|
|
145
|
+
help='Load custom jj2 behavior from a Python file.',
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
args = parser.parse_args(argv[1:])
|
|
149
|
+
logging.basicConfig(format=LOGFORMAT, level=LOGLEVELS[min(args.verbose, len(LOGLEVELS) - 1)])
|
|
150
|
+
logging.debug('PARSED_ARGS render_command: %s', args)
|
|
151
|
+
|
|
152
|
+
# Customization
|
|
153
|
+
if args.customize is not None:
|
|
154
|
+
customize = CustomizationModule(load_python_file(args.customize, 'customize-module'))
|
|
155
|
+
else:
|
|
156
|
+
customize = CustomizationModule(None)
|
|
157
|
+
|
|
158
|
+
# Read data based on specs.
|
|
159
|
+
data = [
|
|
160
|
+
d.parse(
|
|
161
|
+
ignore_missing=args.ignore_missing,
|
|
162
|
+
fallback_format=CONTEXT_FORMATS[args.fallback_format],
|
|
163
|
+
)
|
|
164
|
+
for d in args.data
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
# Squash data into a single context.
|
|
168
|
+
context = reduce(dict_squash, data, {})
|
|
169
|
+
|
|
170
|
+
# Apply final customizations.
|
|
171
|
+
context = customize.alter_context(context)
|
|
172
|
+
|
|
173
|
+
# Renderer
|
|
174
|
+
renderer = Jinja2TemplateRenderer(
|
|
175
|
+
args.template,
|
|
176
|
+
args.template_dirs,
|
|
177
|
+
args.undefined,
|
|
178
|
+
args.no_compact,
|
|
179
|
+
j2_env_params=customize.j2_environment_params(),
|
|
180
|
+
)
|
|
181
|
+
customize.j2_environment(renderer._env) # pylint: disable=protected-access
|
|
182
|
+
|
|
183
|
+
# Filters, Tests
|
|
184
|
+
renderer.register_filters(filters.EXTRA_FILTERS)
|
|
185
|
+
for fname in args.filters:
|
|
186
|
+
renderer.import_filters(fname)
|
|
187
|
+
for fname in args.tests:
|
|
188
|
+
renderer.import_tests(fname)
|
|
189
|
+
|
|
190
|
+
renderer.register_filters(customize.extra_filters())
|
|
191
|
+
renderer.register_tests(customize.extra_tests())
|
|
192
|
+
result = renderer.render(args.template, context)
|
|
193
|
+
|
|
194
|
+
# -o
|
|
195
|
+
if args.output_file:
|
|
196
|
+
Path(args.output_file).write_text(result.decode('utf-8'), encoding='utf-8')
|
|
197
|
+
return b''
|
|
198
|
+
|
|
199
|
+
# Finish
|
|
200
|
+
return result
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def render():
|
|
204
|
+
"""CLI entry point for rendering templates."""
|
|
205
|
+
# NB: argparse ends the run with SystemExit for -h, --version (code 0) and
|
|
206
|
+
# usage errors (code 2). It is not caught, so the code reaches the shell.
|
|
207
|
+
try:
|
|
208
|
+
output = render_command(sys.argv)
|
|
209
|
+
except Exception as e:
|
|
210
|
+
if (message := error_message(e)) is None:
|
|
211
|
+
traceback.print_exc()
|
|
212
|
+
print(UNEXPECTED_ERROR, file=sys.stderr)
|
|
213
|
+
return 1
|
|
214
|
+
logging.debug('Traceback of the error:', exc_info=True)
|
|
215
|
+
print(f'jj2: error: {message}', file=sys.stderr)
|
|
216
|
+
return 1
|
|
217
|
+
outstream = getattr(sys.stdout, 'buffer', sys.stdout)
|
|
218
|
+
outstream.write(output)
|
|
219
|
+
return 0
|
jj2/context.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Building the template context from the parsed data sources."""
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def dict_squash(base: Mapping, update: Mapping, *, _path: tuple = ()) -> dict:
|
|
9
|
+
"""Merge `update` into a copy of `base`, and return the copy.
|
|
10
|
+
|
|
11
|
+
Later values win, and dicts are merged recursively. A `None` value removes
|
|
12
|
+
the key, so that templates see it as undefined. When a dict and a non-dict
|
|
13
|
+
meet under the same key, the later one wins, with a warning that names the
|
|
14
|
+
key path. Neither argument is changed: dicts from `update` are copied,
|
|
15
|
+
lists and scalars are not. `_path` is only for the recursion.
|
|
16
|
+
"""
|
|
17
|
+
merged = dict(base)
|
|
18
|
+
for key, value in update.items():
|
|
19
|
+
path = (*_path, str(key))
|
|
20
|
+
old = merged.get(key)
|
|
21
|
+
if (
|
|
22
|
+
key in merged
|
|
23
|
+
and value is not None
|
|
24
|
+
and isinstance(old, Mapping) != isinstance(value, Mapping)
|
|
25
|
+
):
|
|
26
|
+
logging.warning(
|
|
27
|
+
'%s: a %s replaces a %s',
|
|
28
|
+
'.'.join(path),
|
|
29
|
+
type(value).__name__,
|
|
30
|
+
type(old).__name__,
|
|
31
|
+
)
|
|
32
|
+
if isinstance(value, Mapping):
|
|
33
|
+
merged[key] = dict_squash(old if isinstance(old, Mapping) else {}, value, _path=path)
|
|
34
|
+
elif value is None:
|
|
35
|
+
merged.pop(key, None)
|
|
36
|
+
else:
|
|
37
|
+
merged[key] = value
|
|
38
|
+
return merged
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def nest(dest: str, value):
|
|
42
|
+
"""Put `value` at the dotted key path `dest`: nest('a.b', 1) gives {'a': {'b': 1}}."""
|
|
43
|
+
return functools.reduce(lambda inner, key: {key: inner}, reversed(dest.split('.')), value)
|
jj2/customize.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
class CustomizationModule:
|
|
2
|
+
"""The interface for customization functions, defined as module-level functions"""
|
|
3
|
+
|
|
4
|
+
def __init__(self, module=None):
|
|
5
|
+
if module is not None:
|
|
6
|
+
# Import every module function as a method on ourselves
|
|
7
|
+
for name in self._IMPORTED_METHOD_NAMES:
|
|
8
|
+
if (func := getattr(module, name, None)) is not None:
|
|
9
|
+
setattr(self, name, func)
|
|
10
|
+
|
|
11
|
+
# stubs
|
|
12
|
+
|
|
13
|
+
def j2_environment_params(self):
|
|
14
|
+
return {}
|
|
15
|
+
|
|
16
|
+
def j2_environment(self, env):
|
|
17
|
+
return env
|
|
18
|
+
|
|
19
|
+
def alter_context(self, context):
|
|
20
|
+
return context
|
|
21
|
+
|
|
22
|
+
def extra_filters(self):
|
|
23
|
+
return {}
|
|
24
|
+
|
|
25
|
+
def extra_tests(self):
|
|
26
|
+
return {}
|
|
27
|
+
|
|
28
|
+
_IMPORTED_METHOD_NAMES = [
|
|
29
|
+
f.__name__
|
|
30
|
+
for f in (j2_environment_params, j2_environment, alter_context, extra_filters, extra_tests)
|
|
31
|
+
]
|
jj2/defaults.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Jinja2 extensions loaded by jj2.
|
|
2
|
+
JINJA2_ENABLED_EXTENSIONS = (
|
|
3
|
+
'jinja2.ext.do',
|
|
4
|
+
'jinja2.ext.loopcontrols',
|
|
5
|
+
)
|
|
6
|
+
|
|
7
|
+
# Data formats, by the names a data spec, a file extension or -f can give.
|
|
8
|
+
CONTEXT_FORMATS = {
|
|
9
|
+
'env': 'env',
|
|
10
|
+
'ENV': 'ENV',
|
|
11
|
+
'ini': 'ini',
|
|
12
|
+
'json': 'json',
|
|
13
|
+
'yaml': 'yaml',
|
|
14
|
+
'yml': 'yaml',
|
|
15
|
+
}
|
jj2/errors.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Errors that jj2 reports as one line, without a traceback."""
|
|
2
|
+
|
|
3
|
+
import traceback
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import jinja2
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class JJ2Error(Exception):
|
|
10
|
+
"""An error in the user's input, with a message that says where and what."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def template_line(exc: BaseException) -> str | None:
|
|
14
|
+
"""`file:line` of the innermost template code in the traceback of `exc`, or None."""
|
|
15
|
+
# NB: Jinja rewrites the tracebacks of errors while rendering, so that template
|
|
16
|
+
# code shows up as frames of the template file, at the template line. Their
|
|
17
|
+
# globals hold __jinja_exception__. The docs do not describe this; see
|
|
18
|
+
# rewrite_traceback_stack() and fake_traceback() in the source:
|
|
19
|
+
# https://github.com/pallets/jinja/blob/main/src/jinja2/debug.py
|
|
20
|
+
frames = [
|
|
21
|
+
(frame.f_code.co_filename, line)
|
|
22
|
+
for frame, line in traceback.walk_tb(exc.__traceback__)
|
|
23
|
+
if '__jinja_exception__' in frame.f_globals
|
|
24
|
+
]
|
|
25
|
+
if not frames:
|
|
26
|
+
return None
|
|
27
|
+
path, line = Path(frames[-1][0]), frames[-1][1]
|
|
28
|
+
if path.is_relative_to(Path.cwd()):
|
|
29
|
+
path = path.relative_to(Path.cwd())
|
|
30
|
+
return f'{path}:{line}'
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def error_message(exc: BaseException) -> str | None:
|
|
34
|
+
"""The one-line message for an error in the user's input, or None for others."""
|
|
35
|
+
match exc:
|
|
36
|
+
case JJ2Error():
|
|
37
|
+
message = str(exc)
|
|
38
|
+
case jinja2.TemplateSyntaxError():
|
|
39
|
+
message = f'{exc.name or exc.filename}:{exc.lineno}: {exc.message}'
|
|
40
|
+
# NB: TemplateNotFound is also an OSError, so it must come before OSError.
|
|
41
|
+
case jinja2.TemplateNotFound():
|
|
42
|
+
message = f'{exc.name}: template not found'
|
|
43
|
+
case _ if (where := template_line(exc)) is not None:
|
|
44
|
+
# Undefined variables and other template errors speak for themselves;
|
|
45
|
+
# Python errors from template code get their type.
|
|
46
|
+
kind = '' if isinstance(exc, jinja2.TemplateError) else f'{type(exc).__name__}: '
|
|
47
|
+
message = f'{where}: {kind}{exc}'
|
|
48
|
+
case jinja2.TemplateError():
|
|
49
|
+
message = str(exc)
|
|
50
|
+
case OSError() if exc.filename is not None:
|
|
51
|
+
message = f'{exc.filename}: {exc.strerror}'
|
|
52
|
+
case OSError():
|
|
53
|
+
message = str(exc)
|
|
54
|
+
case _:
|
|
55
|
+
message = None
|
|
56
|
+
return message
|
jj2/filters.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Additional Jinja2 filters"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from shlex import quote as sh_quote
|
|
5
|
+
from shutil import which
|
|
6
|
+
|
|
7
|
+
from jinja2 import pass_context
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def env(varname, default=None):
|
|
11
|
+
"""Use an environment variable's value inside your template.
|
|
12
|
+
|
|
13
|
+
This filter is available even when your data source is something other that the environment.
|
|
14
|
+
|
|
15
|
+
Example:
|
|
16
|
+
|
|
17
|
+
```jinja2
|
|
18
|
+
User: {{ user_login }}
|
|
19
|
+
Pass: {{ "USER_PASSWORD"|env }}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
You can provide the default value:
|
|
23
|
+
|
|
24
|
+
```jinja2
|
|
25
|
+
Pass: {{ "USER_PASSWORD"|env("-none-") }}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
For your convenience, it's also available as a function:
|
|
29
|
+
|
|
30
|
+
```jinja2
|
|
31
|
+
User: {{ user_login }}
|
|
32
|
+
Pass: {{ env("USER_PASSWORD") }}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Notice that there must be quotes around the environment variable name
|
|
36
|
+
"""
|
|
37
|
+
if default is None:
|
|
38
|
+
# Raise KeyError when not provided
|
|
39
|
+
return os.environ[varname]
|
|
40
|
+
|
|
41
|
+
# With the default, there's never an error
|
|
42
|
+
return os.getenv(varname, default)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def ternary(value, true_value='true', false_value='false', none_value=None):
|
|
46
|
+
"""Choose a value by the truth of the input, as Ansible's ternary filter does.
|
|
47
|
+
|
|
48
|
+
```jinja2
|
|
49
|
+
gzip {{ compress|ternary("on", "off") }};
|
|
50
|
+
enabled = {{ feature|ternary }}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Without arguments, gives `true` or `false`. With `none_value`, a `None` input gives
|
|
54
|
+
`none_value` instead of `false_value`.
|
|
55
|
+
"""
|
|
56
|
+
if value is None and none_value is not None:
|
|
57
|
+
return none_value
|
|
58
|
+
return true_value if value else false_value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def align_suffix(text, delim, column=None, spaces_after_delim=1):
|
|
62
|
+
"""Align the suffixes of lines in text, starting from the specified delim.
|
|
63
|
+
|
|
64
|
+
Example: XXX
|
|
65
|
+
"""
|
|
66
|
+
s = ''
|
|
67
|
+
|
|
68
|
+
if column is None or column == 'auto':
|
|
69
|
+
column = max(line.find(delim) for line in text.splitlines())
|
|
70
|
+
elif column == 'previous':
|
|
71
|
+
column = align_suffix.column_previous
|
|
72
|
+
|
|
73
|
+
for line in text.splitlines():
|
|
74
|
+
before, found, after = line.partition(delim)
|
|
75
|
+
if not found:
|
|
76
|
+
# no delimiter occurs
|
|
77
|
+
s += before.rstrip() + os.linesep
|
|
78
|
+
elif before.strip() == '':
|
|
79
|
+
# no content before delimiter - leave as-is
|
|
80
|
+
s += before + delim + after + os.linesep
|
|
81
|
+
else:
|
|
82
|
+
# align
|
|
83
|
+
s += (
|
|
84
|
+
before.rstrip().ljust(column)
|
|
85
|
+
+ delim
|
|
86
|
+
+ spaces_after_delim * ' '
|
|
87
|
+
+ after.strip()
|
|
88
|
+
+ os.linesep
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
align_suffix.column_previous = column
|
|
92
|
+
return s
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
align_suffix.column_previous = None
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@pass_context
|
|
99
|
+
def ctxlookup(context, key):
|
|
100
|
+
"""Lookup the value of a key in the template context."""
|
|
101
|
+
v = context
|
|
102
|
+
try:
|
|
103
|
+
for k in key.split('.'):
|
|
104
|
+
v = v[k]
|
|
105
|
+
return v
|
|
106
|
+
except KeyError:
|
|
107
|
+
return context.environment.undefined(name=key)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def sh_opt(text, name, delim=' ', quote=False):
|
|
111
|
+
"""Format text as a command line option."""
|
|
112
|
+
if not text:
|
|
113
|
+
return ''
|
|
114
|
+
if quote:
|
|
115
|
+
text = sh_quote(text)
|
|
116
|
+
return f'{name}{delim}{text}'
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def sh_optq(text, name, delim=' '):
|
|
120
|
+
"""Quote text and format as a command line option."""
|
|
121
|
+
return sh_opt(text, name, delim, quote=True)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# Filters to be loaded
|
|
125
|
+
EXTRA_FILTERS = {
|
|
126
|
+
'sh_quote': sh_quote,
|
|
127
|
+
'sh_which': which,
|
|
128
|
+
# NB: These filters work on strings. Path would change some values: 'a/' -> 'a'.
|
|
129
|
+
'sh_expand': lambda s: os.path.expandvars(os.path.expanduser(s)), # noqa: PTH111
|
|
130
|
+
'sh_expanduser': os.path.expanduser,
|
|
131
|
+
'sh_expandvars': os.path.expandvars,
|
|
132
|
+
'sh_realpath': os.path.realpath,
|
|
133
|
+
'sh_opt': sh_opt,
|
|
134
|
+
'sh_optq': sh_optq,
|
|
135
|
+
'ternary': ternary,
|
|
136
|
+
'env': env,
|
|
137
|
+
'align_suffix': align_suffix,
|
|
138
|
+
'ctxlookup': ctxlookup,
|
|
139
|
+
}
|
jj2/parsers.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import configparser
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import sys
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import yaml
|
|
14
|
+
|
|
15
|
+
from .context import nest
|
|
16
|
+
from .defaults import CONTEXT_FORMATS
|
|
17
|
+
from .errors import JJ2Error
|
|
18
|
+
|
|
19
|
+
# A context destination: Python-style names, separated by dots (app.host).
|
|
20
|
+
DEST_PATTERN = re.compile(r'[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class DataSpec:
|
|
25
|
+
"""The parts of a data spec, `[dest=]path[:format]`."""
|
|
26
|
+
|
|
27
|
+
path: Path | None # None for stdin, and for the ENV format.
|
|
28
|
+
fmt: str | None # None when neither the spec nor the extension gives a format.
|
|
29
|
+
dest: str | None # None for the top level of the context.
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_dataspec(spec: str) -> DataSpec:
|
|
33
|
+
"""Split a data spec of the form `[dest=]path[:format]` into its parts.
|
|
34
|
+
|
|
35
|
+
The part before the first `=` is a destination only when it is a dotted
|
|
36
|
+
name, so `./a=b.json` is a path. An empty path or `-` is stdin. A leading
|
|
37
|
+
`~` in the path is expanded, because shells do not always expand it after
|
|
38
|
+
`dest=`. Without a format, the format comes from the file extension.
|
|
39
|
+
"""
|
|
40
|
+
dest, sep, rest = spec.partition('=')
|
|
41
|
+
if not (sep and DEST_PATTERN.fullmatch(dest)):
|
|
42
|
+
dest, rest = None, spec
|
|
43
|
+
# NB: Split at the last `:` only when the part after it cannot belong to a
|
|
44
|
+
# path. This keeps Windows drive letters in the path: C:\data.json.
|
|
45
|
+
path, sep, fmt = rest.rpartition(':')
|
|
46
|
+
if not sep or '/' in fmt or '\\' in fmt:
|
|
47
|
+
path, fmt = rest, ''
|
|
48
|
+
path = Path(path).expanduser() if path not in ('', '-') else None
|
|
49
|
+
match fmt:
|
|
50
|
+
case '' | '?':
|
|
51
|
+
fmt = CONTEXT_FORMATS.get(path.suffix[1:].lower()) if path else None
|
|
52
|
+
case known if known in CONTEXT_FORMATS:
|
|
53
|
+
fmt = CONTEXT_FORMATS[known]
|
|
54
|
+
case _:
|
|
55
|
+
raise ValueError(f'unknown format {fmt!r} in data spec {spec!r}')
|
|
56
|
+
return DataSpec(path, fmt, dest)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class InputDataType:
|
|
60
|
+
"""Argparse type for data specs: turns a spec into an InputData.
|
|
61
|
+
|
|
62
|
+
Pass an instance as type= to ArgumentParser.add_argument(). It parses the
|
|
63
|
+
spec, but does not open the file: InputData.parse() does that.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __call__(self, dspec):
|
|
67
|
+
try:
|
|
68
|
+
spec = parse_dataspec(dspec)
|
|
69
|
+
except ValueError as e:
|
|
70
|
+
raise argparse.ArgumentTypeError(str(e)) from e
|
|
71
|
+
path, fmt = spec.path, spec.fmt
|
|
72
|
+
|
|
73
|
+
# check for formats that don't use file input
|
|
74
|
+
if fmt == 'ENV' and path is not None:
|
|
75
|
+
logging.warning('Ignoring source for %s format: %s', fmt, path)
|
|
76
|
+
path = None
|
|
77
|
+
|
|
78
|
+
# NB: The file is not opened here. argparse calls this while it parses the
|
|
79
|
+
# command line, and nothing would close the file. InputData.parse() reads
|
|
80
|
+
# it with Path.read_text(), which closes it.
|
|
81
|
+
match fmt, path:
|
|
82
|
+
case 'ENV', _:
|
|
83
|
+
iostr = None
|
|
84
|
+
case _, None:
|
|
85
|
+
iostr = sys.stdin
|
|
86
|
+
case _, _:
|
|
87
|
+
iostr = path
|
|
88
|
+
return InputData(iostr, fmt, spec.dest, source=str(path) if path else '-')
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class InputData:
|
|
92
|
+
def __init__(self, iostr, fmt=None, ctx_dst=None, source='-'):
|
|
93
|
+
# iostr: a Path that parse() reads, an open stream (stdin), or None
|
|
94
|
+
# for the ENV format.
|
|
95
|
+
self._iostr = iostr
|
|
96
|
+
self._fmt = fmt
|
|
97
|
+
self._ctx_dst = ctx_dst
|
|
98
|
+
self.source = source # The path, or - for stdin, for messages.
|
|
99
|
+
|
|
100
|
+
def __repr__(self):
|
|
101
|
+
return f'{type(self).__name__}({self.source}, {self._fmt}, {self._ctx_dst})'
|
|
102
|
+
|
|
103
|
+
def parse(self, ignore_missing=False, fallback_format='ini'):
|
|
104
|
+
"""Reads and parses the data of the object.
|
|
105
|
+
If ignore_missing is set, missing files will produce and empty dict.
|
|
106
|
+
If no format is set for the object, fallback_format is used.
|
|
107
|
+
With a context destination, the data is put under that key path.
|
|
108
|
+
Without one, the data must be a mapping. An empty YAML file gives {}.
|
|
109
|
+
"""
|
|
110
|
+
fmt = self._fmt if self._fmt is not None else fallback_format
|
|
111
|
+
try:
|
|
112
|
+
text = self._read()
|
|
113
|
+
except FileNotFoundError:
|
|
114
|
+
if ignore_missing:
|
|
115
|
+
return {}
|
|
116
|
+
raise
|
|
117
|
+
data = self._load(fmt, text)
|
|
118
|
+
if data is None: # An empty YAML file.
|
|
119
|
+
data = {}
|
|
120
|
+
if self._ctx_dst:
|
|
121
|
+
return nest(self._ctx_dst, data)
|
|
122
|
+
match data:
|
|
123
|
+
case Mapping():
|
|
124
|
+
return data
|
|
125
|
+
case _:
|
|
126
|
+
raise JJ2Error(
|
|
127
|
+
f'{self.source}: the top level is a {type(data).__name__}, not a mapping. '
|
|
128
|
+
f'Give it a key with a context destination: name={self.source}'
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
def _read(self):
|
|
132
|
+
"""The text of the data: from the file, from stdin, or none for ENV."""
|
|
133
|
+
match self._iostr:
|
|
134
|
+
case Path() as path:
|
|
135
|
+
try:
|
|
136
|
+
return path.read_text()
|
|
137
|
+
except UnicodeDecodeError as e:
|
|
138
|
+
message = f'{self.source}: not valid {e.encoding} text ({e.reason})'
|
|
139
|
+
raise JJ2Error(message) from e
|
|
140
|
+
case None: # The ENV format reads no input.
|
|
141
|
+
return ''
|
|
142
|
+
case stream:
|
|
143
|
+
return stream.read()
|
|
144
|
+
|
|
145
|
+
def _load(self, fmt, text):
|
|
146
|
+
"""Parses the text in the given format. Errors name the source."""
|
|
147
|
+
try:
|
|
148
|
+
return getattr(self, f'_parse_{fmt}')(text)
|
|
149
|
+
except yaml.MarkedYAMLError as e:
|
|
150
|
+
# NB: PyYAML's message spans several lines, with the faulty line and a
|
|
151
|
+
# ^ under the error. Its fields give the same in one line.
|
|
152
|
+
where = self.source
|
|
153
|
+
if (mark := e.problem_mark) is not None:
|
|
154
|
+
where += f':{mark.line + 1}:{mark.column + 1}'
|
|
155
|
+
raise JJ2Error(f'{where}: {e.problem}') from e
|
|
156
|
+
except (ValueError, configparser.Error, yaml.YAMLError) as e:
|
|
157
|
+
raise JJ2Error(f'{self.source}: {" ".join(str(e).split())}') from e
|
|
158
|
+
|
|
159
|
+
def _parse_ENV(self, _text):
|
|
160
|
+
"""Loads data from shell environment."""
|
|
161
|
+
return os.environ.copy()
|
|
162
|
+
|
|
163
|
+
def _parse_env(self, text):
|
|
164
|
+
"""Parses a .env file with python-dotenv: quotes, export, comments.
|
|
165
|
+
Variables in values (${VAR}) are not expanded.
|
|
166
|
+
"""
|
|
167
|
+
# NB: Imported here, so that only runs that read env data pay for the
|
|
168
|
+
# import (about 30 ms).
|
|
169
|
+
from dotenv import dotenv_values # noqa: PLC0415
|
|
170
|
+
|
|
171
|
+
return dotenv_values(stream=io.StringIO(text), interpolate=False)
|
|
172
|
+
|
|
173
|
+
def _parse_ini(self, text):
|
|
174
|
+
"""Parses windows-style ini files."""
|
|
175
|
+
|
|
176
|
+
class MyConfigParser(configparser.ConfigParser):
|
|
177
|
+
def as_dict(self):
|
|
178
|
+
"""Export as dict
|
|
179
|
+
:rtype: dict
|
|
180
|
+
"""
|
|
181
|
+
return {
|
|
182
|
+
name: {**self._defaults, **section} for name, section in self._sections.items()
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
ini = MyConfigParser()
|
|
186
|
+
ini.read_string(text, source=self.source)
|
|
187
|
+
return ini.as_dict()
|
|
188
|
+
|
|
189
|
+
def _parse_json(self, text):
|
|
190
|
+
return json.loads(text)
|
|
191
|
+
|
|
192
|
+
def _parse_yaml(self, text):
|
|
193
|
+
return yaml.safe_load(text)
|
jj2/render.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import inspect
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import jinja2
|
|
7
|
+
import jinja2.loaders
|
|
8
|
+
import jinja2.meta
|
|
9
|
+
|
|
10
|
+
from . import filters
|
|
11
|
+
from .defaults import JINJA2_ENABLED_EXTENSIONS
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def load_python_file(path, name):
|
|
15
|
+
"""Load a Python file as a new module, and return the module.
|
|
16
|
+
|
|
17
|
+
The module is executed again on each call, also when a module with the
|
|
18
|
+
same name has been loaded before.
|
|
19
|
+
"""
|
|
20
|
+
spec = importlib.util.spec_from_file_location(name, path)
|
|
21
|
+
if spec is None or spec.loader is None:
|
|
22
|
+
raise ImportError(f'Cannot load Python file: {path}')
|
|
23
|
+
module = importlib.util.module_from_spec(spec)
|
|
24
|
+
sys.modules[name] = module
|
|
25
|
+
spec.loader.exec_module(module)
|
|
26
|
+
return module
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class TemplateLoader(jinja2.BaseLoader):
|
|
30
|
+
"""Loads the main template from its path, and the templates it includes, imports or
|
|
31
|
+
extends from the search path: the template directories, then the directory of the
|
|
32
|
+
main template.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(self, main, template_dirs=(), encoding='utf-8'):
|
|
36
|
+
self.main = main
|
|
37
|
+
self.encoding = encoding
|
|
38
|
+
# NB: FileSystemLoader looks up a name in each directory of its search path, in
|
|
39
|
+
# order, and rejects names that leave the directory (../).
|
|
40
|
+
self.search = jinja2.FileSystemLoader(
|
|
41
|
+
[*template_dirs, Path(main).parent], encoding=encoding
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
def get_source(self, environment, template):
|
|
45
|
+
# The main template is the file given, even if a template directory has a file
|
|
46
|
+
# with the same name.
|
|
47
|
+
if template == self.main:
|
|
48
|
+
try:
|
|
49
|
+
contents = Path(template).read_text(encoding=self.encoding)
|
|
50
|
+
except OSError as e:
|
|
51
|
+
raise jinja2.TemplateNotFound(template) from e
|
|
52
|
+
return contents, template, lambda: False
|
|
53
|
+
return self.search.get_source(environment, template)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Jinja2TemplateRenderer:
|
|
57
|
+
"""Template renderer"""
|
|
58
|
+
|
|
59
|
+
UNDEFINED = {
|
|
60
|
+
'strict': jinja2.StrictUndefined, # raises errors for undefined variables
|
|
61
|
+
'normal': jinja2.Undefined, # can be printed/iterated - error on other operations
|
|
62
|
+
'debug': jinja2.DebugUndefined, # return the debug info when printed
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self, template, template_dirs=(), undefined='strict', no_compact=False, j2_env_params=None
|
|
67
|
+
):
|
|
68
|
+
# Custom env params
|
|
69
|
+
j2_env_params = j2_env_params if j2_env_params is not None else {}
|
|
70
|
+
j2_env_params.setdefault('keep_trailing_newline', True)
|
|
71
|
+
j2_env_params.setdefault('undefined', self.UNDEFINED[undefined])
|
|
72
|
+
j2_env_params.setdefault('trim_blocks', not no_compact)
|
|
73
|
+
j2_env_params.setdefault('lstrip_blocks', not no_compact)
|
|
74
|
+
j2_env_params.setdefault('extensions', JINJA2_ENABLED_EXTENSIONS)
|
|
75
|
+
j2_env_params.setdefault('loader', TemplateLoader(template, template_dirs))
|
|
76
|
+
|
|
77
|
+
# Environment
|
|
78
|
+
self._env = jinja2.Environment(**j2_env_params)
|
|
79
|
+
self._env.globals.update({'env': filters.env})
|
|
80
|
+
|
|
81
|
+
def register_filters(self, filters):
|
|
82
|
+
self._env.filters.update(filters)
|
|
83
|
+
|
|
84
|
+
def register_tests(self, tests):
|
|
85
|
+
self._env.tests.update(tests)
|
|
86
|
+
|
|
87
|
+
def import_filters(self, filename):
|
|
88
|
+
self.register_filters(self._import_functions(filename))
|
|
89
|
+
|
|
90
|
+
def import_tests(self, filename):
|
|
91
|
+
self.register_tests(self._import_functions(filename))
|
|
92
|
+
|
|
93
|
+
def _import_functions(self, filename):
|
|
94
|
+
m = load_python_file(filename, 'imported-funcs')
|
|
95
|
+
return {name: func for name, func in inspect.getmembers(m) if inspect.isfunction(func)}
|
|
96
|
+
|
|
97
|
+
def render(self, template_path, context):
|
|
98
|
+
"""Render a template
|
|
99
|
+
:param template_path: Path to the template file
|
|
100
|
+
:type template_path: basestring
|
|
101
|
+
:param context: Template data
|
|
102
|
+
:type context: dict
|
|
103
|
+
:return: Rendered template
|
|
104
|
+
:rtype: basestring
|
|
105
|
+
"""
|
|
106
|
+
return self._env.get_template(template_path).render(context).encode('utf-8')
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jj2
|
|
3
|
+
Version: 0.7.0
|
|
4
|
+
Summary: Juiced Jinja2 command-line tool
|
|
5
|
+
Keywords: Jinja2,templating,command-line,CLI
|
|
6
|
+
Author: Manolis Stamatogiannakis
|
|
7
|
+
Author-email: Manolis Stamatogiannakis <mstamat@gmail.com>
|
|
8
|
+
License-Expression: BSD-2-Clause
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: System Administrators
|
|
14
|
+
Classifier: Natural Language :: English
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
22
|
+
Classifier: Topic :: Software Development
|
|
23
|
+
Classifier: Topic :: Text Processing :: General
|
|
24
|
+
Requires-Dist: jinja2>=3.1
|
|
25
|
+
Requires-Dist: python-dotenv>=1.0
|
|
26
|
+
Requires-Dist: pyyaml>=6.0
|
|
27
|
+
Requires-Python: >=3.12
|
|
28
|
+
Project-URL: Homepage, https://github.com/m000/jj2
|
|
29
|
+
Project-URL: Repository, https://github.com/m000/jj2
|
|
30
|
+
Project-URL: Issues, https://github.com/m000/jj2/issues
|
|
31
|
+
Project-URL: Changelog, https://github.com/m000/jj2/blob/master/CHANGELOG.md
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
[![CI][]][1] [![PyPI][]][2] [![Python]][2]
|
|
35
|
+
|
|
36
|
+
[CI]: https://github.com/m000/jj2/actions/workflows/ci.yaml/badge.svg?branch=master
|
|
37
|
+
[1]: https://github.com/m000/jj2/actions/workflows/ci.yaml
|
|
38
|
+
[PyPI]: https://img.shields.io/pypi/v/jj2.svg
|
|
39
|
+
[2]: https://pypi.org/project/jj2/
|
|
40
|
+
[Python]: https://img.shields.io/badge/python-3.12%2B-blue.svg
|
|
41
|
+
|
|
42
|
+
# jj2 - Juiced Jinja2 command-line tool
|
|
43
|
+
|
|
44
|
+
jj2 (previously `jj2cli`, a fork of [j2cli]) is a command-line tool for
|
|
45
|
+
templating in shell-scripts, leveraging the [Jinja2] library. It supports
|
|
46
|
+
[several formats] for loading the context used for rendering the Jinja2
|
|
47
|
+
templates. Loading environment variables as rendering context is also supported.
|
|
48
|
+
|
|
49
|
+
> [!WARNING]
|
|
50
|
+
> jj2 is in beta. This means that you can expect each release to be usable, but
|
|
51
|
+
> before 1.0 you should expect occasional:
|
|
52
|
+
>
|
|
53
|
+
> - command-line option changes
|
|
54
|
+
> - history rewrites on the development branch (`master-next`)
|
|
55
|
+
|
|
56
|
+
If you find jj2 useful, we would love to hear from you! Please [open an issue]
|
|
57
|
+
for bugs, questions, ideas, or use cases that jj2 does not cover yet. Feedback
|
|
58
|
+
from users shapes what comes next.
|
|
59
|
+
|
|
60
|
+
[j2cli]: https://github.com/kolypto/j2cli
|
|
61
|
+
[Jinja2]: https://jinja.palletsprojects.com/
|
|
62
|
+
[several formats]: #supported-formats
|
|
63
|
+
[open an issue]: https://github.com/m000/jj2/issues
|
|
64
|
+
|
|
65
|
+
## Getting started
|
|
66
|
+
|
|
67
|
+
### Installation
|
|
68
|
+
|
|
69
|
+
``` sh
|
|
70
|
+
# Install jj2 as a standalone tool with uv:
|
|
71
|
+
$ uv tool install jj2
|
|
72
|
+
# Or install jj2 with pip:
|
|
73
|
+
$ pip install jj2
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
To run jj2 one time without installation, use `uvx`:
|
|
77
|
+
|
|
78
|
+
``` sh
|
|
79
|
+
$ uvx jj2 config.j2 config.json
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
To install the development branch, use its Git URL:
|
|
83
|
+
|
|
84
|
+
``` sh
|
|
85
|
+
$ uv tool install git+https://github.com/m000/jj2@master-next
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
In a clone of the repository, run jj2 in the project environment:
|
|
89
|
+
|
|
90
|
+
``` sh
|
|
91
|
+
$ uv run jj2 config.j2 config.json
|
|
92
|
+
$ uv run python -m jj2 config.j2 config.json
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Basic usage
|
|
96
|
+
|
|
97
|
+
``` sh
|
|
98
|
+
# Render the template config.j2 with the data in config.json.
|
|
99
|
+
# Write the result to the file config.
|
|
100
|
+
$ jj2 config.j2 config.json -o config
|
|
101
|
+
|
|
102
|
+
# Render the template with YAML data from stdin.
|
|
103
|
+
$ wget -O - http://example.com/config.yml | jj2 config.j2 :yaml
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
For more examples, see [docs/examples.md]. For recipes for common tasks, see
|
|
107
|
+
[docs/howto.md].
|
|
108
|
+
|
|
109
|
+
[docs/examples.md]: https://github.com/m000/jj2/blob/master/docs/examples.md
|
|
110
|
+
[docs/howto.md]: https://github.com/m000/jj2/blob/master/docs/howto.md
|
|
111
|
+
|
|
112
|
+
## Context data
|
|
113
|
+
|
|
114
|
+
### Supported formats
|
|
115
|
+
|
|
116
|
+
jj2 reads the context in these formats:
|
|
117
|
+
|
|
118
|
+
- [JSON][]: a data format that many programming languages use. It comes from
|
|
119
|
+
JavaScript.
|
|
120
|
+
- [YAML][]: a data format that is easy for persons to read.
|
|
121
|
+
- [INI][]: the configuration file format of Windows.
|
|
122
|
+
- env: a file with [Unix-style] environment variable assignments, as in `.env`
|
|
123
|
+
files.
|
|
124
|
+
- ENV: the environment variables of the jj2 process. This format does not read a
|
|
125
|
+
file.
|
|
126
|
+
|
|
127
|
+
For an example of each format, see [docs/formats.md].
|
|
128
|
+
|
|
129
|
+
[JSON]: https://en.wikipedia.org/wiki/JSON
|
|
130
|
+
[YAML]: https://en.wikipedia.org/wiki/YAML
|
|
131
|
+
[INI]: https://en.wikipedia.org/wiki/INI_file
|
|
132
|
+
[Unix-style]: https://en.wikipedia.org/wiki/Environment_variable#Unix
|
|
133
|
+
[docs/formats.md]: https://github.com/m000/jj2/blob/master/docs/formats.md
|
|
134
|
+
|
|
135
|
+
### Context squashing
|
|
136
|
+
|
|
137
|
+
One of the main strengths of jj2 is that it is not limited to using a single
|
|
138
|
+
data file as context. Several data files—perhaps in different formats—can be
|
|
139
|
+
used to construct the rendering context. As the contents of the data files may
|
|
140
|
+
"overlap", jj2 *recursively squashes* their contents to produce the context that
|
|
141
|
+
will be used for rendering. The order of squashing is *from left to right*. That
|
|
142
|
+
is, the contents of a data file may be overridden by any data files specified
|
|
143
|
+
*after it* on the command line.
|
|
144
|
+
|
|
145
|
+
This example shows how jj2 squashes two files:
|
|
146
|
+
|
|
147
|
+
- The data in `a.json`:
|
|
148
|
+
|
|
149
|
+
``` json
|
|
150
|
+
{"a": 1, "c": {"x": 2, "y": 3}}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
- The data in `b.json`:
|
|
154
|
+
|
|
155
|
+
``` json
|
|
156
|
+
{"b": 2, "c": {"y": 4}}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
- The context for `jj2 template.j2 a.json b.json`:
|
|
160
|
+
|
|
161
|
+
``` json
|
|
162
|
+
{"a": 1, "b": 2, "c": {"x": 2, "y": 4}}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
A key with the value `null` is removed from the context. A YAML key with no
|
|
166
|
+
value is also removed.
|
|
167
|
+
|
|
168
|
+
### Loading data as a context subtree
|
|
169
|
+
|
|
170
|
+
By default, the data from each source is squashed into the top level of the
|
|
171
|
+
context. Sources with overlapping keys, or with many keys, such as the
|
|
172
|
+
environment variables, can instead be put under a key. Each data source is given
|
|
173
|
+
as a *data spec*:
|
|
174
|
+
|
|
175
|
+
[dest=]path[:format]
|
|
176
|
+
|
|
177
|
+
- `path`: the data file. For stdin, use `-` or no path.
|
|
178
|
+
- `format`: the format of the data. It replaces the format of the file
|
|
179
|
+
extension. For example: `settings.cfg:ini`.
|
|
180
|
+
- `dest`: the *context destination*. This is a key or a dotted key path. jj2
|
|
181
|
+
puts the data under it. For example: `web=nginx.json` or `app.host=host.yaml`.
|
|
182
|
+
jj2 uses the part before the first `=` as a destination only if it is a dotted
|
|
183
|
+
name. Thus, a path such as `./a=b.json` also works.
|
|
184
|
+
|
|
185
|
+
If the top level of a source is a list or a single value, the source must have a
|
|
186
|
+
destination. For example: `items=list.json`. An empty YAML file gives no data.
|
|
187
|
+
|
|
188
|
+
jj2 expands a `~` at the start of the path. The shell does not always do this
|
|
189
|
+
after `dest=`: zsh does not do it by default, and bash does not do it after a
|
|
190
|
+
dotted key path.
|
|
191
|
+
|
|
192
|
+
| Data spec | Where jj2 puts the data |
|
|
193
|
+
|----------------------|----------------------------------------------------------|
|
|
194
|
+
| `nginx.json` | at the top level |
|
|
195
|
+
| `web=nginx.json` | under `web`: `{{ web.hostname }}` |
|
|
196
|
+
| `app.host=host.yaml` | under `app.host`, merged with the other data under `app` |
|
|
197
|
+
| `settings.cfg:ini` | at the top level, read as INI |
|
|
198
|
+
| `web=-:json` | under `web`, read as JSON from stdin |
|
|
199
|
+
| `env=:ENV` | under `env`, from the environment variables |
|
|
200
|
+
|
|
201
|
+
> [!NOTE]
|
|
202
|
+
> The argument parser reads a data spec that starts with `-` as an option. For
|
|
203
|
+
> example: `-:json`. Write `:json` in its place, or put `--` before it:
|
|
204
|
+
> `jj2 config.j2 -- -:json`.
|
|
205
|
+
|
|
206
|
+
> [!TIP]
|
|
207
|
+
> By default, zsh does not complete a path after `dest=` when you push
|
|
208
|
+
> <kbd>Tab</kbd>. zsh reads `web=ngi` as one word. To complete after `=`, add
|
|
209
|
+
> `setopt magic_equal_subst` to your `~/.zshrc`. Or complete the path first, and
|
|
210
|
+
> then type `dest=` in front of it. bash completes after `=` without changes.
|
|
211
|
+
|
|
212
|
+
## Reference
|
|
213
|
+
|
|
214
|
+
`jj2` uses these arguments:
|
|
215
|
+
|
|
216
|
+
- `template`: the Jinja2 template file to render.
|
|
217
|
+
- `data`: one or more data specs, `[dest=]path[:format]`. Refer to [Loading data
|
|
218
|
+
as a context subtree].
|
|
219
|
+
|
|
220
|
+
Options:
|
|
221
|
+
|
|
222
|
+
- `-f FORMAT`, `--fallback-format FORMAT`: the format of data that has no format
|
|
223
|
+
in its data spec and no known file extension. The default is `ini`.
|
|
224
|
+
- `-T DIR`, `--template-dir DIR`: look for the templates that a template
|
|
225
|
+
includes, imports or extends in `DIR`. Give the option more times for more
|
|
226
|
+
directories. Refer to [Template search].
|
|
227
|
+
- `-I`, `--ignore-missing`: ignore data files that do not exist. Without this
|
|
228
|
+
option, jj2 stops with an error.
|
|
229
|
+
- `-o outfile`: write the result to a file. Without this option, jj2 writes to
|
|
230
|
+
stdout.
|
|
231
|
+
- `-U MODE`, `--undefined MODE`: what jj2 does with undefined variables:
|
|
232
|
+
`strict` (the default), `normal` or `debug`. Refer to the [Jinja2 docs].
|
|
233
|
+
- `--no-compact`: keep the whitespace around Jinja2 blocks.
|
|
234
|
+
- `--filters a.py,b.py`: load the top-level functions of Python files as Jinja2
|
|
235
|
+
filters. Give a comma-separated list, or give the option more times.
|
|
236
|
+
- `--tests a.py,b.py`: load the top-level functions of Python files as Jinja2
|
|
237
|
+
tests. Give a comma-separated list, or give the option more times.
|
|
238
|
+
- `--customize custom.py`: load hooks from a Python file. The hooks change how
|
|
239
|
+
jj2 sets up Jinja2. Use this option only if the other options are not
|
|
240
|
+
sufficient. Refer to [Advanced customization].
|
|
241
|
+
- `-v`, `--verbose`: show more messages. Give the option more times for more
|
|
242
|
+
messages.
|
|
243
|
+
- `-V`, `--version`: show the versions of jj2 and Jinja2.
|
|
244
|
+
|
|
245
|
+
[Loading data as a context subtree]: #loading-data-as-a-context-subtree
|
|
246
|
+
[Template search]: #template-search
|
|
247
|
+
[Jinja2 docs]: https://jinja.palletsprojects.com/en/stable/api/#undefined-types
|
|
248
|
+
[Advanced customization]: #advanced-customization
|
|
249
|
+
|
|
250
|
+
### Template search
|
|
251
|
+
|
|
252
|
+
jj2 looks for the templates that a template includes, imports or extends in this
|
|
253
|
+
order:
|
|
254
|
+
|
|
255
|
+
1. The `-T` directories, in the order of the options.
|
|
256
|
+
2. The directory of the main template.
|
|
257
|
+
|
|
258
|
+
A file in a `-T` directory thus replaces the file with the same name next to the
|
|
259
|
+
template. To prevent this by accident, put libraries of templates in
|
|
260
|
+
subdirectories, for example `{% include "tools/vim.j2" %}`. jj2 does not look in
|
|
261
|
+
the current directory; to add it, use `-T .`.
|
|
262
|
+
|
|
263
|
+
The main template is always the file on the command line.
|
|
264
|
+
|
|
265
|
+
### Environment variables
|
|
266
|
+
|
|
267
|
+
To use the environment variables as data, use the `ENV` format. `:ENV` puts them
|
|
268
|
+
at the top level, and `env=:ENV` puts them under `env`.
|
|
269
|
+
|
|
270
|
+
To read a file with variable assignments, use the `env` format. For example,
|
|
271
|
+
make the file with `env > /tmp/file.env`.
|
|
272
|
+
|
|
273
|
+
## Extras
|
|
274
|
+
|
|
275
|
+
### Filters
|
|
276
|
+
|
|
277
|
+
For convenience, jj2 offers several additional Jinja2 filters that can be used
|
|
278
|
+
in your templates. These filters should help you avoid having to implement an
|
|
279
|
+
[advanced customization module] for many use cases.
|
|
280
|
+
|
|
281
|
+
For a list of the filters, see [docs/filters.md].
|
|
282
|
+
|
|
283
|
+
[advanced customization module]: #advanced-customization
|
|
284
|
+
[docs/filters.md]: https://github.com/m000/jj2/blob/master/docs/filters.md
|
|
285
|
+
|
|
286
|
+
### Advanced customization
|
|
287
|
+
|
|
288
|
+
jj2 offers several *hooks* that allow for more advanced customization of its
|
|
289
|
+
operation. With these hooks, you can:
|
|
290
|
+
|
|
291
|
+
- give more parameters to the Jinja2 environment.
|
|
292
|
+
- change the context before jj2 renders the template.
|
|
293
|
+
- add filters and tests.
|
|
294
|
+
|
|
295
|
+
For more information, see [docs/advanced.md].
|
|
296
|
+
|
|
297
|
+
[docs/advanced.md]: https://github.com/m000/jj2/blob/master/docs/advanced.md
|
|
298
|
+
|
|
299
|
+
## Features and roadmap
|
|
300
|
+
|
|
301
|
+
How jj2 compares with other Jinja2 command-line tools, as of December 2026:
|
|
302
|
+
|
|
303
|
+
| | jj2 | [jinja2-cli] | [jinjanator] | [j2cli] |
|
|
304
|
+
|----|----|----|----|----|
|
|
305
|
+
| Latest release | [![jj2 on PyPI]][3] | [![jinja2-cli on PyPI]][4] | [![jinjanator on PyPI]][5] | 0.3.10 (2019) |
|
|
306
|
+
| Status | beta, active | stable; no release since 2026-04 | stable, active | archived (2024) |
|
|
307
|
+
| Made for | shell scripts and makefiles: config and dotfile builds | general use, also in Docker images | shell scripts | shell scripts, Docker containers |
|
|
308
|
+
| Python | 3.12 and later | 3.8 and later | 3.11 and later | 2 and 3 |
|
|
309
|
+
| Data files | many, [squashed] | many, deep merge | one | one |
|
|
310
|
+
| Data formats | JSON, YAML, INI, env, ENV | JSON, INI, env, querystring, TOML; YAML, XML, HJSON, JSON5 as extras | JSON, YAML, INI, dotenv; TOML, XML as plugins | JSON, YAML, INI, env |
|
|
311
|
+
| Format override | for each file: `data.cfg:ini` | one `-f` for all files | `-f` | `-f` |
|
|
312
|
+
| Data under a key | `web=nginx.json` | — | — | — |
|
|
313
|
+
| Environment variables | as data: `:ENV`, `env=:ENV`; `env()` | `environ()` | `env()`, `--import-env` | `env()`, `--import-env` |
|
|
314
|
+
| Values on the command line | planned: [\#9] | `-D key=value` | — | — |
|
|
315
|
+
| Template search paths | `-T DIR` | `-I DIR` | — | — |
|
|
316
|
+
| Custom filters and tests | Python files | Python modules (`-F`), extensions (`-e`) | Python files, plugins | Python files |
|
|
317
|
+
| Customization | `--customize` hooks | Jinja2 options as flags | `--customize` hooks, plugins | `--customize` hooks |
|
|
318
|
+
| Dependency file for make | planned: [\#10] | — | — | — |
|
|
319
|
+
| Render a directory | planned: [\#18] | — | — | — |
|
|
320
|
+
|
|
321
|
+
The planned features are GitHub issues, grouped in [milestones]. If jj2 does not
|
|
322
|
+
do something that you need, [open an issue].
|
|
323
|
+
|
|
324
|
+
[jinja2-cli]: https://github.com/mattrobenolt/jinja2-cli
|
|
325
|
+
[jinjanator]: https://github.com/kpfleming/jinjanator
|
|
326
|
+
[j2cli]: https://github.com/kolypto/j2cli
|
|
327
|
+
[jj2 on PyPI]: https://img.shields.io/pypi/v/jj2
|
|
328
|
+
[3]: https://pypi.org/project/jj2/
|
|
329
|
+
[jinja2-cli on PyPI]: https://img.shields.io/pypi/v/jinja2-cli
|
|
330
|
+
[4]: https://pypi.org/project/jinja2-cli/
|
|
331
|
+
[jinjanator on PyPI]: https://img.shields.io/pypi/v/jinjanator
|
|
332
|
+
[5]: https://pypi.org/project/jinjanator/
|
|
333
|
+
[squashed]: #context-squashing
|
|
334
|
+
[\#9]: https://github.com/m000/jj2/issues/9
|
|
335
|
+
[\#10]: https://github.com/m000/jj2/issues/10
|
|
336
|
+
[\#18]: https://github.com/m000/jj2/issues/18
|
|
337
|
+
[milestones]: https://github.com/m000/jj2/milestones
|
|
338
|
+
[open an issue]: https://github.com/m000/jj2/issues
|
|
339
|
+
|
|
340
|
+
## Credits
|
|
341
|
+
|
|
342
|
+
jj2 is inspired by and builds on [kolypto/j2cli] and [mattrobenolt/jinja2-cli].
|
|
343
|
+
|
|
344
|
+
[kolypto/j2cli]: https://github.com/kolypto/j2cli
|
|
345
|
+
[mattrobenolt/jinja2-cli]: https://github.com/mattrobenolt/jinja2-cli
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
jj2/__init__.py,sha256=Pn-SUjFZvg_VvT_aiPo5vYFXoxog-q9neksWVnfPhC0,292
|
|
2
|
+
jj2/__main__.py,sha256=Rbdwx_p7diFqOHFWwbiyy_gMgk7M8qjVG4lXbCN4vQM,121
|
|
3
|
+
jj2/cli.py,sha256=sUwXw58qwkGvIX0efdBxZaaumjy9TFPbT32MTWIbyYg,7465
|
|
4
|
+
jj2/context.py,sha256=fGTxdtc80vCPFDCCHKZAbSbPLr4QbxwIYS460JDrBa8,1620
|
|
5
|
+
jj2/customize.py,sha256=w6EHQdAi2XlWeCgz1poXWrDyh6Yz-YcXgnjASWe06N8,857
|
|
6
|
+
jj2/defaults.py,sha256=V1AzuAVN7qVn9o87c2XeasHFb6eracmuOtSxjlfWJ1M,330
|
|
7
|
+
jj2/errors.py,sha256=arOpvo4ZFRYrz7hvyZHgVVmNtIRlQft_GDArbUv41v0,2293
|
|
8
|
+
jj2/filters.py,sha256=f3EeCyzCCS-F7ZO1RMHVLwBs6TMIT4XMhgY1_W6wYd4,3704
|
|
9
|
+
jj2/parsers.py,sha256=Tubrjt34iLGOv3PXFYSHPvemlRnTxUy0ucsOEBt0M3s,7245
|
|
10
|
+
jj2/render.py,sha256=eHjPe8jspfdYEksZoYa5j2ajpyCd09et5O-G--uuDlw,3966
|
|
11
|
+
jj2-0.7.0.dist-info/licenses/LICENSE,sha256=I9O7vCdeSedZT0uraGSAZnw-UJbhvZwQhahEQQr0FIY,1416
|
|
12
|
+
jj2-0.7.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
|
|
13
|
+
jj2-0.7.0.dist-info/entry_points.txt,sha256=RHcoF_zQve0W9YeKjgFKdrV8ViXq9bek397GzVaj8bc,36
|
|
14
|
+
jj2-0.7.0.dist-info/METADATA,sha256=qr5Ddzt1y8GQj_lZtJFGe3dsHSZ9xUaki9dYZuNNV98,13926
|
|
15
|
+
jj2-0.7.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Copyright (c) 2019-2026, Manolis Stamatogiannakis
|
|
2
|
+
Copyright (c) 2014-2019, Mark Vartanyan
|
|
3
|
+
Copyright (c) 2012-2013, Matt Robenolt
|
|
4
|
+
|
|
5
|
+
All rights reserved.
|
|
6
|
+
|
|
7
|
+
Redistribution and use in source and binary forms, with or without modification,
|
|
8
|
+
are permitted provided that the following conditions are met:
|
|
9
|
+
|
|
10
|
+
* Redistributions of source code must retain the above copyright notice,
|
|
11
|
+
this list of conditions and the following disclaimer.
|
|
12
|
+
* Redistributions in binary form must reproduce the above copyright notice,
|
|
13
|
+
this list of conditions and the following disclaimer in the documentation
|
|
14
|
+
and/or other materials provided with the distribution.
|
|
15
|
+
|
|
16
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
17
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
18
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
19
|
+
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
20
|
+
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
21
|
+
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
22
|
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
23
|
+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
24
|
+
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
25
|
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
26
|
+
POSSIBILITY OF SUCH DAMAGE.
|