jj2 0.7.0b1__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 +11 -0
- jj2/__main__.py +8 -0
- jj2/cli.py +154 -0
- jj2/context.py +43 -0
- jj2/customize.py +33 -0
- jj2/defaults.py +31 -0
- jj2/errors.py +56 -0
- jj2/filters.py +160 -0
- jj2/parsers.py +197 -0
- jj2/render.py +108 -0
- jj2-0.7.0b1.dist-info/METADATA +257 -0
- jj2-0.7.0b1.dist-info/RECORD +15 -0
- jj2-0.7.0b1.dist-info/WHEEL +4 -0
- jj2-0.7.0b1.dist-info/entry_points.txt +3 -0
- jj2-0.7.0b1.dist-info/licenses/LICENSE +26 -0
jj2/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
""" j2cli main file """
|
|
2
|
+
import importlib.metadata
|
|
3
|
+
|
|
4
|
+
__author__ = "Manolis Stamatogiannakis"
|
|
5
|
+
__email__ = "mstamat@gmail.com"
|
|
6
|
+
__version__ = importlib.metadata.version('jj2')
|
|
7
|
+
|
|
8
|
+
from jj2.cli import render
|
|
9
|
+
|
|
10
|
+
# The entry point of the jj2 command (jj2:render) and of python -m jj2.
|
|
11
|
+
__all__ = ['render']
|
jj2/__main__.py
ADDED
jj2/cli.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import io
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import traceback
|
|
7
|
+
from functools import reduce
|
|
8
|
+
|
|
9
|
+
import jinja2
|
|
10
|
+
import jinja2.loaders
|
|
11
|
+
import jinja2.meta
|
|
12
|
+
|
|
13
|
+
from . import __version__, filters, parsers
|
|
14
|
+
from .context import dict_squash
|
|
15
|
+
from .customize import CustomizationModule
|
|
16
|
+
from .defaults import CONTEXT_FORMATS
|
|
17
|
+
from .errors import error_message
|
|
18
|
+
from .render import Jinja2TemplateRenderer, load_python_file
|
|
19
|
+
|
|
20
|
+
# available log levels, adjusted with -v at command line
|
|
21
|
+
LOGLEVELS = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
|
|
22
|
+
|
|
23
|
+
# format to use for logging
|
|
24
|
+
LOGFORMAT = '%(levelname)s: %(message)s'
|
|
25
|
+
|
|
26
|
+
# Printed after the traceback of an exception that jj2 does not know.
|
|
27
|
+
UNEXPECTED_ERROR = (
|
|
28
|
+
'jj2: unexpected error. If the traceback above does not point to your own code '
|
|
29
|
+
'(--filters, --tests, --customize), this is a bug in jj2: please report it, with '
|
|
30
|
+
'the traceback, at https://github.com/m000/jj2/issues'
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def render_command(argv):
|
|
35
|
+
""" Pure render command
|
|
36
|
+
:param argv: Command-line arguments
|
|
37
|
+
:type argv: list
|
|
38
|
+
:return: Rendered template
|
|
39
|
+
:rtype: basestring
|
|
40
|
+
"""
|
|
41
|
+
version_info = (__version__, jinja2.__version__)
|
|
42
|
+
parser = argparse.ArgumentParser(
|
|
43
|
+
prog='jj2',
|
|
44
|
+
description='Renders Jinja2 templates from the command line.',
|
|
45
|
+
epilog='',
|
|
46
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter
|
|
47
|
+
)
|
|
48
|
+
p_input = parser.add_argument_group('input options')
|
|
49
|
+
p_output = parser.add_argument_group('output options')
|
|
50
|
+
p_custom = parser.add_argument_group('customization options')
|
|
51
|
+
|
|
52
|
+
### optional arguments ##########################################
|
|
53
|
+
parser.add_argument('-V', '--version', action='version',
|
|
54
|
+
version='jj2 {0}, Jinja2 {1}'.format(*version_info))
|
|
55
|
+
parser.add_argument('-v', '--verbose', action='count', default=0,
|
|
56
|
+
help='Increase verbosity.')
|
|
57
|
+
### input options ###############################################
|
|
58
|
+
p_input.add_argument('template', help='Template file to process.')
|
|
59
|
+
p_input.add_argument('data', nargs='+', default=[], type=parsers.InputDataType(),
|
|
60
|
+
help='Input data specification: [<dest>=]<source>[:<format>]. '
|
|
61
|
+
'Multiple sources in different formats can be specified. '
|
|
62
|
+
'They are squashed into one context, from left to right. '
|
|
63
|
+
'<source> is a file, or - or nothing for stdin. '
|
|
64
|
+
'<format> overrides the format given by the file extension. '
|
|
65
|
+
'<dest> puts the data under a key, or a dotted key path (app.host=host.yaml).')
|
|
66
|
+
p_input.add_argument('-U', '--undefined', default='strict',
|
|
67
|
+
dest='undefined', choices=Jinja2TemplateRenderer.UNDEFINED,
|
|
68
|
+
help='Set the Jinja2 beahaviour for undefined variables.)')
|
|
69
|
+
p_input.add_argument('-I', '--ignore-missing', action='store_true',
|
|
70
|
+
help='Ignore any missing data files.')
|
|
71
|
+
p_input.add_argument('-f', '--fallback-format',
|
|
72
|
+
default='ini', choices=CONTEXT_FORMATS,
|
|
73
|
+
help='Specify fallback data format. '
|
|
74
|
+
'Used for data with no specified format and no appropriate extension.')
|
|
75
|
+
### output options ##############################################
|
|
76
|
+
p_output.add_argument('-o', metavar='outfile', dest='output_file',
|
|
77
|
+
help="Output to a file instead of stdout.")
|
|
78
|
+
p_output.add_argument('--no-compact', action='store_true', dest='no_compact',
|
|
79
|
+
help='Do not compact space around Jinja2 blocks.')
|
|
80
|
+
### customization ###############################################
|
|
81
|
+
p_custom.add_argument('--filters', nargs='+', default=[],
|
|
82
|
+
metavar='python-file', dest='filters',
|
|
83
|
+
help='Load the top-level functions from the specified file(s) as Jinja2 filters.')
|
|
84
|
+
p_custom.add_argument('--tests', nargs='+', default=[],
|
|
85
|
+
metavar='python-file', dest='tests',
|
|
86
|
+
help='Load the top-level functions from the specified file(s) as Jinja2 tests.')
|
|
87
|
+
p_custom.add_argument('--customize', default=None,
|
|
88
|
+
metavar='python-file', dest='customize',
|
|
89
|
+
help='Load custom jj2 behavior from a Python file.')
|
|
90
|
+
|
|
91
|
+
args = parser.parse_args(argv[1:])
|
|
92
|
+
logging.basicConfig(format=LOGFORMAT, level=LOGLEVELS[min(args.verbose, len(LOGLEVELS)-1)])
|
|
93
|
+
logging.debug("PARSED_ARGS render_command: %s", args)
|
|
94
|
+
|
|
95
|
+
# Customization
|
|
96
|
+
if args.customize is not None:
|
|
97
|
+
customize = CustomizationModule(
|
|
98
|
+
load_python_file(args.customize, 'customize-module')
|
|
99
|
+
)
|
|
100
|
+
else:
|
|
101
|
+
customize = CustomizationModule(None)
|
|
102
|
+
|
|
103
|
+
# Read data based on specs.
|
|
104
|
+
data = [d.parse(ignore_missing=args.ignore_missing, fallback_format=args.fallback_format) for d in args.data]
|
|
105
|
+
|
|
106
|
+
# Squash data into a single context.
|
|
107
|
+
context = reduce(dict_squash, data, {})
|
|
108
|
+
|
|
109
|
+
# Apply final customizations.
|
|
110
|
+
context = customize.alter_context(context)
|
|
111
|
+
|
|
112
|
+
# Renderer
|
|
113
|
+
renderer = Jinja2TemplateRenderer(os.getcwd(), args.undefined, args.no_compact, j2_env_params=customize.j2_environment_params())
|
|
114
|
+
customize.j2_environment(renderer._env) # pylint: disable=protected-access
|
|
115
|
+
|
|
116
|
+
# Filters, Tests
|
|
117
|
+
renderer.register_filters(filters.EXTRA_FILTERS)
|
|
118
|
+
for fname in args.filters:
|
|
119
|
+
renderer.import_filters(fname)
|
|
120
|
+
for fname in args.tests:
|
|
121
|
+
renderer.import_tests(fname)
|
|
122
|
+
|
|
123
|
+
renderer.register_filters(customize.extra_filters())
|
|
124
|
+
renderer.register_tests(customize.extra_tests())
|
|
125
|
+
result = renderer.render(args.template, context)
|
|
126
|
+
|
|
127
|
+
# -o
|
|
128
|
+
if args.output_file:
|
|
129
|
+
with io.open(args.output_file, 'wt', encoding='utf-8') as f:
|
|
130
|
+
f.write(result.decode('utf-8'))
|
|
131
|
+
f.close()
|
|
132
|
+
return b''
|
|
133
|
+
|
|
134
|
+
# Finish
|
|
135
|
+
return result
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def render():
|
|
139
|
+
""" CLI entry point for rendering templates. """
|
|
140
|
+
# NB: argparse ends the run with SystemExit for -h, --version (code 0) and
|
|
141
|
+
# usage errors (code 2). It is not caught, so the code reaches the shell.
|
|
142
|
+
try:
|
|
143
|
+
output = render_command(sys.argv)
|
|
144
|
+
except Exception as e:
|
|
145
|
+
if (message := error_message(e)) is None:
|
|
146
|
+
traceback.print_exc()
|
|
147
|
+
print(UNEXPECTED_ERROR, file=sys.stderr)
|
|
148
|
+
return 1
|
|
149
|
+
logging.debug('Traceback of the error:', exc_info=True)
|
|
150
|
+
print(f'jj2: error: {message}', file=sys.stderr)
|
|
151
|
+
return 1
|
|
152
|
+
outstream = getattr(sys.stdout, 'buffer', sys.stdout)
|
|
153
|
+
outstream.write(output)
|
|
154
|
+
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,33 @@
|
|
|
1
|
+
|
|
2
|
+
class CustomizationModule:
|
|
3
|
+
""" The interface for customization functions, defined as module-level functions """
|
|
4
|
+
|
|
5
|
+
def __init__(self, module=None):
|
|
6
|
+
if module is not None:
|
|
7
|
+
# Import every module function as a method on ourselves
|
|
8
|
+
for name in self._IMPORTED_METHOD_NAMES:
|
|
9
|
+
try:
|
|
10
|
+
setattr(self, name, getattr(module, name))
|
|
11
|
+
except AttributeError:
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
# stubs
|
|
15
|
+
|
|
16
|
+
def j2_environment_params(self):
|
|
17
|
+
return {}
|
|
18
|
+
|
|
19
|
+
def j2_environment(self, env):
|
|
20
|
+
return env
|
|
21
|
+
|
|
22
|
+
def alter_context(self, context):
|
|
23
|
+
return context
|
|
24
|
+
|
|
25
|
+
def extra_filters(self):
|
|
26
|
+
return {}
|
|
27
|
+
|
|
28
|
+
def extra_tests(self):
|
|
29
|
+
return {}
|
|
30
|
+
|
|
31
|
+
_IMPORTED_METHOD_NAMES = [
|
|
32
|
+
f.__name__
|
|
33
|
+
for f in (j2_environment_params, j2_environment, alter_context, extra_filters, extra_tests)]
|
jj2/defaults.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
|
|
3
|
+
# Jinja2 extensions loaded by jj2.
|
|
4
|
+
JINJA2_ENABLED_EXTENSIONS = (
|
|
5
|
+
'jinja2.ext.i18n',
|
|
6
|
+
'jinja2.ext.do',
|
|
7
|
+
'jinja2.ext.loopcontrols',
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
# Set yaml_loader for parsers.
|
|
11
|
+
try:
|
|
12
|
+
import yaml
|
|
13
|
+
try:
|
|
14
|
+
_yaml_loader = yaml.FullLoader
|
|
15
|
+
except AttributeError:
|
|
16
|
+
_yaml_loader = yaml.SafeLoader
|
|
17
|
+
yaml_load = lambda iostr: yaml.load(iostr, Loader=_yaml_loader)
|
|
18
|
+
except ImportError:
|
|
19
|
+
yaml_load = None
|
|
20
|
+
|
|
21
|
+
# Supported context formats.
|
|
22
|
+
CONTEXT_FORMATS = ['env', 'ENV', 'ini', 'json', 'yaml']
|
|
23
|
+
if yaml_load is None:
|
|
24
|
+
CONTEXT_FORMATS.remove('yaml')
|
|
25
|
+
|
|
26
|
+
# Format aliases dictionary.
|
|
27
|
+
# COMPAT: Chaining used instead of unpacking (*) for backwards compatibility.
|
|
28
|
+
CONTEXT_FORMATS_ALIASES = dict(itertools.chain(
|
|
29
|
+
zip(CONTEXT_FORMATS, CONTEXT_FORMATS),
|
|
30
|
+
filter(lambda t: t[1] in CONTEXT_FORMATS, [('yml', 'yaml')])
|
|
31
|
+
))
|
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,160 @@
|
|
|
1
|
+
""" Additional Jinja2 filters """
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
from shlex import quote as sh_quote
|
|
5
|
+
from shutil import which
|
|
6
|
+
|
|
7
|
+
from jinja2 import is_undefined, pass_context
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def docker_link(value, fmt='{addr}:{port}'):
|
|
11
|
+
""" Given a Docker Link environment variable value, format it into something else.
|
|
12
|
+
XXX: The name of the filter is not very informative. This is actually a partial URI parser.
|
|
13
|
+
|
|
14
|
+
This first parses a Docker Link value like this:
|
|
15
|
+
|
|
16
|
+
DB_PORT=tcp://172.17.0.5:5432
|
|
17
|
+
|
|
18
|
+
Into a dict:
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
{
|
|
22
|
+
'proto': 'tcp',
|
|
23
|
+
'addr': '172.17.0.5',
|
|
24
|
+
'port': '5432'
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
And then uses `fmt` to format it, where the default format is '{addr}:{port}'.
|
|
29
|
+
|
|
30
|
+
More info here: [Docker Links](https://docs.docker.com/userguide/dockerlinks/)
|
|
31
|
+
|
|
32
|
+
:param value: Docker link (from an environment variable)
|
|
33
|
+
:param fmt: The format to apply. Supported placeholders: `{proto}`, `{addr}`, `{port}`
|
|
34
|
+
:return: Formatted string
|
|
35
|
+
"""
|
|
36
|
+
# pass undefined values on down the pipeline
|
|
37
|
+
if is_undefined(value):
|
|
38
|
+
return value
|
|
39
|
+
|
|
40
|
+
# Parse the value
|
|
41
|
+
m = re.match(r'(?P<proto>.+)://' r'(?P<addr>.+):' r'(?P<port>.+)$', value)
|
|
42
|
+
if not m:
|
|
43
|
+
raise ValueError('The provided value does not seems to be a Docker link: {0}'.format(value))
|
|
44
|
+
d = m.groupdict()
|
|
45
|
+
|
|
46
|
+
# Format
|
|
47
|
+
return fmt.format(**d)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def env(varname, default=None):
|
|
51
|
+
""" Use an environment variable's value inside your template.
|
|
52
|
+
|
|
53
|
+
This filter is available even when your data source is something other that the environment.
|
|
54
|
+
|
|
55
|
+
Example:
|
|
56
|
+
|
|
57
|
+
```jinja2
|
|
58
|
+
User: {{ user_login }}
|
|
59
|
+
Pass: {{ "USER_PASSWORD"|env }}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
You can provide the default value:
|
|
63
|
+
|
|
64
|
+
```jinja2
|
|
65
|
+
Pass: {{ "USER_PASSWORD"|env("-none-") }}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
For your convenience, it's also available as a function:
|
|
69
|
+
|
|
70
|
+
```jinja2
|
|
71
|
+
User: {{ user_login }}
|
|
72
|
+
Pass: {{ env("USER_PASSWORD") }}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Notice that there must be quotes around the environment variable name
|
|
76
|
+
"""
|
|
77
|
+
if default is None:
|
|
78
|
+
# Raise KeyError when not provided
|
|
79
|
+
return os.environ[varname]
|
|
80
|
+
|
|
81
|
+
# With the default, there's never an error
|
|
82
|
+
return os.getenv(varname, default)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def align_suffix(text, delim, column=None, spaces_after_delim=1):
|
|
86
|
+
""" Align the suffixes of lines in text, starting from the specified delim.
|
|
87
|
+
|
|
88
|
+
Example: XXX
|
|
89
|
+
"""
|
|
90
|
+
s=''
|
|
91
|
+
|
|
92
|
+
if column is None or column == 'auto':
|
|
93
|
+
column = max(map(lambda ln: ln.find(delim), text.splitlines()))
|
|
94
|
+
elif column == 'previous':
|
|
95
|
+
column = align_suffix.column_previous
|
|
96
|
+
|
|
97
|
+
for ln in map(lambda s: s.split(delim, 1), text.splitlines()):
|
|
98
|
+
if len(ln) < 2:
|
|
99
|
+
# no delimiter occurs
|
|
100
|
+
s += ln[0].rstrip() + os.linesep
|
|
101
|
+
elif ln[0].strip() == '':
|
|
102
|
+
# no content before delimiter - leave as-is
|
|
103
|
+
s += ln[0] + delim + ln[1] + os.linesep
|
|
104
|
+
else:
|
|
105
|
+
# align
|
|
106
|
+
s += ln[0].rstrip().ljust(column) + delim + spaces_after_delim*' ' + ln[1].strip() + os.linesep
|
|
107
|
+
|
|
108
|
+
align_suffix.column_previous = column
|
|
109
|
+
return s
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
align_suffix.column_previous = None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@pass_context
|
|
116
|
+
def ctxlookup(context, key):
|
|
117
|
+
""" Lookup the value of a key in the template context.
|
|
118
|
+
"""
|
|
119
|
+
v = context
|
|
120
|
+
try:
|
|
121
|
+
for k in key.split('.'):
|
|
122
|
+
v = v[k]
|
|
123
|
+
return v
|
|
124
|
+
except KeyError:
|
|
125
|
+
return context.environment.undefined(name=key)
|
|
126
|
+
|
|
127
|
+
def sh_opt(text, name, delim=" ", quote=False):
|
|
128
|
+
""" Format text as a command line option.
|
|
129
|
+
"""
|
|
130
|
+
if not text:
|
|
131
|
+
return ''
|
|
132
|
+
if quote:
|
|
133
|
+
text = sh_quote(text)
|
|
134
|
+
return '%s%s%s' % (name, delim, text)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def sh_optq(text, name, delim=" "):
|
|
138
|
+
""" Quote text and format as a command line option.
|
|
139
|
+
"""
|
|
140
|
+
return sh_opt(text, name, delim, quote=True)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# Filters to be loaded
|
|
144
|
+
EXTRA_FILTERS = {
|
|
145
|
+
'sh_quote': sh_quote,
|
|
146
|
+
'sh_which': which,
|
|
147
|
+
'sh_expand': lambda s: os.path.expandvars(os.path.expanduser(s)),
|
|
148
|
+
'sh_expanduser': os.path.expanduser,
|
|
149
|
+
'sh_expandvars': os.path.expandvars,
|
|
150
|
+
'sh_realpath': os.path.realpath,
|
|
151
|
+
'sh_opt': sh_opt,
|
|
152
|
+
'sh_optq': sh_optq,
|
|
153
|
+
'ifelse': lambda t, truev, falsev: truev if t else falsev,
|
|
154
|
+
'onoff': lambda t: 'on' if t else 'off',
|
|
155
|
+
'yesno': lambda t: 'yes' if t else 'no',
|
|
156
|
+
'docker_link': docker_link,
|
|
157
|
+
'env': env,
|
|
158
|
+
'align_suffix': align_suffix,
|
|
159
|
+
'ctxlookup': ctxlookup,
|
|
160
|
+
}
|
jj2/parsers.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
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 .errors import JJ2Error
|
|
17
|
+
from .defaults import CONTEXT_FORMATS_ALIASES, yaml_load
|
|
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_ALIASES.get(path.suffix[1:].lower()) if path else None
|
|
52
|
+
case known if known in CONTEXT_FORMATS_ALIASES:
|
|
53
|
+
fmt = CONTEXT_FORMATS_ALIASES[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
|
+
"""
|
|
162
|
+
return os.environ.copy()
|
|
163
|
+
|
|
164
|
+
def _parse_env(self, text):
|
|
165
|
+
"""Parses a .env file with python-dotenv: quotes, export, comments.
|
|
166
|
+
Variables in values (${VAR}) are not expanded.
|
|
167
|
+
"""
|
|
168
|
+
# NB: Imported here, so that only runs that read env data pay for the
|
|
169
|
+
# import (about 30 ms).
|
|
170
|
+
from dotenv import dotenv_values # noqa: PLC0415
|
|
171
|
+
|
|
172
|
+
return dotenv_values(stream=io.StringIO(text), interpolate=False)
|
|
173
|
+
|
|
174
|
+
def _parse_ini(self, text):
|
|
175
|
+
"""Parses windows-style ini files.
|
|
176
|
+
"""
|
|
177
|
+
class MyConfigParser(configparser.ConfigParser):
|
|
178
|
+
def as_dict(self):
|
|
179
|
+
""" Export as dict
|
|
180
|
+
:rtype: dict
|
|
181
|
+
"""
|
|
182
|
+
d = dict(self._sections)
|
|
183
|
+
for k in d:
|
|
184
|
+
d[k] = dict(self._defaults, **d[k])
|
|
185
|
+
d[k].pop('__name__', None)
|
|
186
|
+
return d
|
|
187
|
+
ini = MyConfigParser()
|
|
188
|
+
ini.read_string(text, source=self.source)
|
|
189
|
+
return ini.as_dict()
|
|
190
|
+
|
|
191
|
+
def _parse_json(self, text):
|
|
192
|
+
return json.loads(text)
|
|
193
|
+
|
|
194
|
+
def _parse_yaml(self, text):
|
|
195
|
+
if yaml_load is None:
|
|
196
|
+
raise RuntimeError("YAML data parser invoked, but no YAML support is present.")
|
|
197
|
+
return yaml_load(text)
|
jj2/render.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import inspect
|
|
3
|
+
import io
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
import jinja2
|
|
9
|
+
import jinja2.loaders
|
|
10
|
+
import jinja2.meta
|
|
11
|
+
|
|
12
|
+
from . import filters
|
|
13
|
+
from .defaults import JINJA2_ENABLED_EXTENSIONS
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def load_python_file(path, name):
|
|
17
|
+
""" Load a Python file as a new module, and return the module.
|
|
18
|
+
|
|
19
|
+
The module is executed again on each call, also when a module with the
|
|
20
|
+
same name has been loaded before.
|
|
21
|
+
"""
|
|
22
|
+
spec = importlib.util.spec_from_file_location(name, path)
|
|
23
|
+
if spec is None or spec.loader is None:
|
|
24
|
+
raise ImportError("Cannot load Python file: %s" % path)
|
|
25
|
+
module = importlib.util.module_from_spec(spec)
|
|
26
|
+
sys.modules[name] = module
|
|
27
|
+
spec.loader.exec_module(module)
|
|
28
|
+
return module
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class FilePathLoader(jinja2.BaseLoader):
|
|
32
|
+
""" Custom Jinja2 template loader which just loads a single template file """
|
|
33
|
+
|
|
34
|
+
def __init__(self, cwd, encoding='utf-8'):
|
|
35
|
+
self.cwd = cwd
|
|
36
|
+
self.encoding = encoding
|
|
37
|
+
|
|
38
|
+
def get_source(self, environment, template):
|
|
39
|
+
# Path
|
|
40
|
+
filename = os.path.join(self.cwd, template)
|
|
41
|
+
logging.debug("TEMPLATE_PATH %s", filename)
|
|
42
|
+
|
|
43
|
+
# Read
|
|
44
|
+
try:
|
|
45
|
+
with io.open(template, 'rt', encoding=self.encoding) as f:
|
|
46
|
+
contents = f.read()
|
|
47
|
+
except IOError:
|
|
48
|
+
raise jinja2.TemplateNotFound(template)
|
|
49
|
+
|
|
50
|
+
# Finish
|
|
51
|
+
uptodate = lambda: False
|
|
52
|
+
return contents, filename, uptodate
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Jinja2TemplateRenderer:
|
|
56
|
+
""" Template renderer """
|
|
57
|
+
|
|
58
|
+
UNDEFINED = {
|
|
59
|
+
'strict': jinja2.StrictUndefined, # raises errors for undefined variables
|
|
60
|
+
'normal': jinja2.Undefined, # can be printed/iterated - error on other operations
|
|
61
|
+
'debug': jinja2.DebugUndefined, # return the debug info when printed
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
def __init__(self, cwd, undefined='strict', no_compact=False, j2_env_params=None):
|
|
65
|
+
# Custom env params
|
|
66
|
+
j2_env_params = j2_env_params if j2_env_params is not None else {}
|
|
67
|
+
j2_env_params.setdefault('keep_trailing_newline', True)
|
|
68
|
+
j2_env_params.setdefault('undefined', self.UNDEFINED[undefined])
|
|
69
|
+
j2_env_params.setdefault('trim_blocks', not no_compact)
|
|
70
|
+
j2_env_params.setdefault('lstrip_blocks', not no_compact)
|
|
71
|
+
j2_env_params.setdefault('extensions', JINJA2_ENABLED_EXTENSIONS)
|
|
72
|
+
j2_env_params.setdefault('loader', FilePathLoader(cwd))
|
|
73
|
+
|
|
74
|
+
# Environment
|
|
75
|
+
self._env = jinja2.Environment(**j2_env_params)
|
|
76
|
+
self._env.globals.update(dict(
|
|
77
|
+
env=filters.env
|
|
78
|
+
))
|
|
79
|
+
|
|
80
|
+
def register_filters(self, filters):
|
|
81
|
+
self._env.filters.update(filters)
|
|
82
|
+
|
|
83
|
+
def register_tests(self, tests):
|
|
84
|
+
self._env.tests.update(tests)
|
|
85
|
+
|
|
86
|
+
def import_filters(self, filename):
|
|
87
|
+
self.register_filters(self._import_functions(filename))
|
|
88
|
+
|
|
89
|
+
def import_tests(self, filename):
|
|
90
|
+
self.register_tests(self._import_functions(filename))
|
|
91
|
+
|
|
92
|
+
def _import_functions(self, filename):
|
|
93
|
+
m = load_python_file(filename, 'imported-funcs')
|
|
94
|
+
return dict((name, func) for name, func in inspect.getmembers(m) if inspect.isfunction(func))
|
|
95
|
+
|
|
96
|
+
def render(self, template_path, context):
|
|
97
|
+
""" Render a template
|
|
98
|
+
:param template_path: Path to the template file
|
|
99
|
+
:type template_path: basestring
|
|
100
|
+
:param context: Template data
|
|
101
|
+
:type context: dict
|
|
102
|
+
:return: Rendered template
|
|
103
|
+
:rtype: basestring
|
|
104
|
+
"""
|
|
105
|
+
return self._env \
|
|
106
|
+
.get_template(template_path) \
|
|
107
|
+
.render(context) \
|
|
108
|
+
.encode('utf-8')
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jj2
|
|
3
|
+
Version: 0.7.0b1
|
|
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
|
+
[](https://github.com/m000/jj2/actions/workflows/ci.yaml)
|
|
35
|
+
[](https://pypi.org/project/jj2/)
|
|
36
|
+
[](https://pypi.org/project/jj2/)
|
|
37
|
+
# jj2 - Juiced Jinja2 command-line tool
|
|
38
|
+
|
|
39
|
+
jj2 (previously `j2cli`) is a command-line tool for templating in
|
|
40
|
+
shell-scripts, leveraging the [Jinja2](http://jinja.pocoo.org/docs/)
|
|
41
|
+
library.
|
|
42
|
+
It supports [several formats](#supported-formats) for loading the context
|
|
43
|
+
used for rendering the Jinja2 templates. Loading environment variables as
|
|
44
|
+
rendering context is also supported.
|
|
45
|
+
|
|
46
|
+
> **Warning**
|
|
47
|
+
> jj2 is in beta, on the way to a full spin-off from the
|
|
48
|
+
> [upstream][j2cli]. The aim is to keep each release usable. However,
|
|
49
|
+
> until the spin-off is complete you should expect:
|
|
50
|
+
> - cli option changes
|
|
51
|
+
> - history rewrites on the development branches
|
|
52
|
+
> - no support for Python <3.12
|
|
53
|
+
>
|
|
54
|
+
> Having said that, you are welcome to use this branch and start an
|
|
55
|
+
> issue if you encounter any problems or have feedback.
|
|
56
|
+
|
|
57
|
+
## jj2 features and roadmap
|
|
58
|
+
|
|
59
|
+
The following planned/implemented features differentiate jj2 from
|
|
60
|
+
its upstreams.
|
|
61
|
+
|
|
62
|
+
- [x] Focus on modern Python (≥3.12). This allows modernizing the codebase.
|
|
63
|
+
- [x] Switch to more modern tooling.
|
|
64
|
+
* [x] [pytest][pytest] (to replace [nose][nose])
|
|
65
|
+
* [x] [ruff][ruff] (to replace [prospector][prospector])
|
|
66
|
+
* [x] [uv][uv] (to replace poetry and tox)
|
|
67
|
+
- [ ] Rendering of multiple templates using the same context in one go.
|
|
68
|
+
Rendering a couple of dozens template one-by-one is fairly slow.
|
|
69
|
+
This should make the tool snappier to use, but also means that
|
|
70
|
+
the command line interface will need to change.
|
|
71
|
+
- [ ] Template dependency analysis to allow better integration with tools
|
|
72
|
+
like [make][make]. Such tools are otherwise oblivious to Jinja2 template
|
|
73
|
+
inheritance/inclusion.
|
|
74
|
+
- [ ] Extended library of Jinja2 filters. This should allow using jj2
|
|
75
|
+
out of the box in a wider range of use cases.
|
|
76
|
+
- [x] Support of *context squashing* (see [below](#context-squashing)),
|
|
77
|
+
to eliminate the need to preprocess context data with external tools.
|
|
78
|
+
|
|
79
|
+
## Getting started
|
|
80
|
+
|
|
81
|
+
### Installation
|
|
82
|
+
```sh
|
|
83
|
+
# as a standalone tool, with uv
|
|
84
|
+
$ uv tool install jj2
|
|
85
|
+
# or with pip
|
|
86
|
+
$ pip install jj2
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
To run jj2 once, without installing it:
|
|
90
|
+
```sh
|
|
91
|
+
$ uvx jj2 config.j2 config.json
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
To try the development branch:
|
|
95
|
+
```sh
|
|
96
|
+
$ uv tool install git+https://github.com/m000/jj2@master-next
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
In a checkout of the repository, run jj2 from the project environment:
|
|
100
|
+
```sh
|
|
101
|
+
$ uv run jj2 config.j2 config.json
|
|
102
|
+
$ uv run python -m jj2 config.j2 config.json
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### Basic usage
|
|
106
|
+
```sh
|
|
107
|
+
# render config from template config.j2
|
|
108
|
+
$ jj2 config.j2 config.json -o config
|
|
109
|
+
|
|
110
|
+
# render using yaml data from stdin
|
|
111
|
+
$ wget -O - http://example.com/config.yml | jj2 config.j2 -:yaml
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
For an extensive list of examples, see [docs/examples.md](https://github.com/m000/jj2/blob/master/docs/examples.md).
|
|
115
|
+
|
|
116
|
+
## Context data
|
|
117
|
+
|
|
118
|
+
### Supported formats
|
|
119
|
+
jj2 supports importing context from several different sources:
|
|
120
|
+
|
|
121
|
+
* [JSON][json]: A language-independent data-serialization format, originally derived
|
|
122
|
+
from JavaScript.
|
|
123
|
+
* [YAML][yaml]: A data-serialization language, designed to be human-readable.
|
|
124
|
+
* [INI][ini]: Windows-style configuration files.
|
|
125
|
+
* env: Simple [unix-style][ini] environment variable assignments.
|
|
126
|
+
|
|
127
|
+
For examples with each supported format, see [docs/formats.md](https://github.com/m000/jj2/blob/master/docs/formats.md).
|
|
128
|
+
|
|
129
|
+
### Context squashing
|
|
130
|
+
One of the main strengths of jj2 is that it is not limited to using a single
|
|
131
|
+
data file as context. Several data files—perhaps in different formats—can be
|
|
132
|
+
used to construct the rendering context.
|
|
133
|
+
As the contents of the data files may "overlap", jj2 *recursively squashes*
|
|
134
|
+
their contents to produce the context that will be used for rendering.
|
|
135
|
+
The order of squashing is *from left to right*. I.e. the contents of a data file
|
|
136
|
+
may be overriden by any data files specified *after it* on the command line.
|
|
137
|
+
|
|
138
|
+
Here is a simple example illustrating how context squashing works:
|
|
139
|
+
|
|
140
|
+
* `a.json` contents:
|
|
141
|
+
```json
|
|
142
|
+
{"a": 1, "c": {"x": 2, "y": 3}}
|
|
143
|
+
```
|
|
144
|
+
* `b.json` contents:
|
|
145
|
+
```json
|
|
146
|
+
{"b": 2, "c": {"y": 4}}
|
|
147
|
+
```
|
|
148
|
+
* effective context when rendering with `a.json` and `b.json` (in that order):
|
|
149
|
+
```json
|
|
150
|
+
{"a": 1, "b": 2, "c": {"x": 2, "y": 4}}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Loading data as a context subtree
|
|
154
|
+
By default, the data from each source is squashed into the top level of the
|
|
155
|
+
context. Sources with overlapping keys, or with many keys, such as the
|
|
156
|
+
environment variables, can instead be put under a key. Each data source is
|
|
157
|
+
given as a *data spec*:
|
|
158
|
+
|
|
159
|
+
[dest=]path[:format]
|
|
160
|
+
|
|
161
|
+
* `path`: a data file, or `-` (or nothing) for stdin.
|
|
162
|
+
* `format`: overrides the format given by the file extension, e.g. `settings.cfg:ini`.
|
|
163
|
+
* `dest`: the *context destination*, a key or a dotted key path to put the data
|
|
164
|
+
under, e.g. `web=nginx.json` or `app.host=host.yaml`. The part before the first
|
|
165
|
+
`=` is a destination only if it is a dotted name, so a path like `./a=b.json`
|
|
166
|
+
still works.
|
|
167
|
+
|
|
168
|
+
A source whose top level is a list or a single value, such as a JSON array,
|
|
169
|
+
needs a destination: `items=list.json`. An empty YAML file gives no data.
|
|
170
|
+
|
|
171
|
+
jj2 expands a leading `~` in the path itself, because shells do not always do
|
|
172
|
+
it after `dest=`: zsh never does by default, and bash does not after a dotted
|
|
173
|
+
key path.
|
|
174
|
+
|
|
175
|
+
| Data spec | Where the data goes |
|
|
176
|
+
|---|---|
|
|
177
|
+
| `nginx.json` | the top level |
|
|
178
|
+
| `web=nginx.json` | under `web`: `{{ web.hostname }}` |
|
|
179
|
+
| `app.host=host.yaml` | under `app.host`, squashed with the other data under `app` |
|
|
180
|
+
| `settings.cfg:ini` | the top level, read as INI |
|
|
181
|
+
| `web=-:json` | under `web`, read as JSON from stdin |
|
|
182
|
+
| `env=:ENV` | under `env`, from the environment variables |
|
|
183
|
+
|
|
184
|
+
> [!TIP]
|
|
185
|
+
> In zsh, pressing <kbd>Tab</kbd> after `dest=` does not complete the path by
|
|
186
|
+
> default, because zsh treats `web=ngi` as a single word. Add
|
|
187
|
+
> `setopt magic_equal_subst` to your `~/.zshrc` to complete after `=`, or
|
|
188
|
+
> complete the path first and then add `dest=` in front of it. bash completes
|
|
189
|
+
> after `=` without any setup.
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
## Reference
|
|
193
|
+
`jj2` accepts the following arguments:
|
|
194
|
+
|
|
195
|
+
* `template`: Jinja2 template file to render
|
|
196
|
+
* `data`: one or more data specs, `[dest=]path[:format]`.
|
|
197
|
+
See [Loading data as a context subtree](#loading-data-as-a-context-subtree).
|
|
198
|
+
|
|
199
|
+
Options:
|
|
200
|
+
|
|
201
|
+
* `--format, -f`: format for the data file. The default is `?`: guess from file extension.
|
|
202
|
+
* `--import-env VAR, -e EVAR`: import all environment variables into the template as `VAR`.
|
|
203
|
+
To import environment variables into the global scope, give it an empty string: `--import-env=`.
|
|
204
|
+
(This will overwrite any existing variables!)
|
|
205
|
+
* `-o outfile`: Write rendered template to a file
|
|
206
|
+
* `--undefined={strict, normal, debug}`: Specify the behaviour of jj2 for undefined
|
|
207
|
+
variables. Refer to [Jinja2 docs][jinja2-undefined] for details.
|
|
208
|
+
* `--filters filters.py`: Load custom Jinja2 filters and tests from a Python file.
|
|
209
|
+
Will load all top-level functions and register them as filters.
|
|
210
|
+
This option can be used multiple times to import several files.
|
|
211
|
+
* `--tests tests.py`: Load custom Jinja2 filters and tests from a Python file.
|
|
212
|
+
* `--customize custom.py`: A Python file that implements hooks to fine-tune the jj2 behavior.
|
|
213
|
+
This is fairly advanced stuff, use it only if you really need to customize the way Jinja2 is initialized.
|
|
214
|
+
See [Customization](#customization) for more info.
|
|
215
|
+
|
|
216
|
+
There is some special behavior with environment variables:
|
|
217
|
+
|
|
218
|
+
* When `data` is not provided (data is `-`), `--format` defaults to `env` and thus reads environment variables
|
|
219
|
+
* When `--format=env`, it can read a special "environment variables" file made like this: `env > /tmp/file.env`
|
|
220
|
+
|
|
221
|
+
## Extras
|
|
222
|
+
|
|
223
|
+
### Filters
|
|
224
|
+
For convenience, jj2 offers several additional Jinja2 filters that can be used
|
|
225
|
+
in your templates. These filters should help you avoid having to implement an
|
|
226
|
+
[advanced customization module](#advanced-customization) for many use cases.
|
|
227
|
+
|
|
228
|
+
See [docs/filters.md](https://github.com/m000/jj2/blob/master/docs/filters.md) for details on the available filters.
|
|
229
|
+
|
|
230
|
+
### Advanced customization
|
|
231
|
+
jj2 offers several *hooks* that allow for more advanced customization of its
|
|
232
|
+
operation. This includes:
|
|
233
|
+
|
|
234
|
+
* passing additional keywords to Jinja2 environment
|
|
235
|
+
* modifying the context before it's used for rendering
|
|
236
|
+
* registering custom filters and tests
|
|
237
|
+
|
|
238
|
+
See [docs/advanced.md](https://github.com/m000/jj2/blob/master/docs/advanced.md) for details on advanced customization.
|
|
239
|
+
|
|
240
|
+
## Credits
|
|
241
|
+
jj2 is inspired by and builds on [kolypto/j2cli][j2cli] and
|
|
242
|
+
[mattrobenolt/jinja2-cli][jinja2-cli] tools.
|
|
243
|
+
|
|
244
|
+
[docker]: http://www.docker.com/
|
|
245
|
+
[env]: https://en.wikipedia.org/wiki/Environment_variable#Unix
|
|
246
|
+
[ini]: https://en.wikipedia.org/wiki/INI_file
|
|
247
|
+
[j2cli]: https://github.com/kolypto/j2cli
|
|
248
|
+
[jinja2-cli]: https://github.com/mattrobenolt/jinja2-cli
|
|
249
|
+
[jinja2-undefined]: https://jinja.palletsprojects.com/en/2.10.x/api/#undefined-types
|
|
250
|
+
[json]: https://en.wikipedia.org/wiki/JSON
|
|
251
|
+
[make]: https://www.gnu.org/software/make/
|
|
252
|
+
[nose]: https://nose.readthedocs.io/
|
|
253
|
+
[prospector]: https://prospector.landscape.io/en/master/
|
|
254
|
+
[pytest]: https://docs.pytest.org/
|
|
255
|
+
[ruff]: https://docs.astral.sh/ruff/
|
|
256
|
+
[uv]: https://docs.astral.sh/uv/
|
|
257
|
+
[yaml]: https://en.wikipedia.org/wiki/YAML
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
jj2/__init__.py,sha256=fOiFG-GGbfiL20PMWX3BAdCMXsGc4DxCNOjVRnJmmac,297
|
|
2
|
+
jj2/__main__.py,sha256=Rbdwx_p7diFqOHFWwbiyy_gMgk7M8qjVG4lXbCN4vQM,121
|
|
3
|
+
jj2/cli.py,sha256=NVoJU08Zpih_449t67RJ6WqjiAUeXRudzKgUI2vYwJ0,6382
|
|
4
|
+
jj2/context.py,sha256=fGTxdtc80vCPFDCCHKZAbSbPLr4QbxwIYS460JDrBa8,1620
|
|
5
|
+
jj2/customize.py,sha256=u-8J74ygvfWuhdyTMRQItWxn2UTQOfFQAN12k1HzKrk,887
|
|
6
|
+
jj2/defaults.py,sha256=-mF_TUlWJEX2_FtY-QTdGPA-7qbjZyH-HWboW3XToTA,866
|
|
7
|
+
jj2/errors.py,sha256=arOpvo4ZFRYrz7hvyZHgVVmNtIRlQft_GDArbUv41v0,2293
|
|
8
|
+
jj2/filters.py,sha256=xFRG72si8l1aXnj4c4JusrzDlyr9RHpkmC8Kui874fw,4422
|
|
9
|
+
jj2/parsers.py,sha256=8pXAZJsIQrhmPw8T0na8ZzMErtdu0p8tZFIe9rH6kcY,7476
|
|
10
|
+
jj2/render.py,sha256=gor8SviTpDyM0V5OVcBBBzKeF1wcMaDXWH2C0XS2Zt4,3555
|
|
11
|
+
jj2-0.7.0b1.dist-info/licenses/LICENSE,sha256=QXCZ27GyG6rSYRRtbp3rX2WfjTh5MM0uOzuzyRjCfBk,1416
|
|
12
|
+
jj2-0.7.0b1.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
|
|
13
|
+
jj2-0.7.0b1.dist-info/entry_points.txt,sha256=RHcoF_zQve0W9YeKjgFKdrV8ViXq9bek397GzVaj8bc,36
|
|
14
|
+
jj2-0.7.0b1.dist-info/METADATA,sha256=3DQQLRZYYTN7O2MRemJyTtKDT-kbU1yCl3D8WPJc4rw,10743
|
|
15
|
+
jj2-0.7.0b1.dist-info/RECORD,,
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Copyright (c) 2019-2023, 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.
|