scriptengine 0.14.3__py3-none-any.whl → 1.0.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.
Files changed (43) hide show
  1. scriptengine/cli/__init__.py +0 -0
  2. scriptengine/cli/se.py +164 -0
  3. scriptengine/context.py +115 -87
  4. scriptengine/engines/__init__.py +6 -0
  5. scriptengine/engines/simple_script_engine.py +93 -0
  6. scriptengine/exceptions.py +1 -1
  7. scriptengine/helpers/__init__.py +0 -0
  8. scriptengine/helpers/terminal_colors.py +88 -0
  9. scriptengine/jinja.py +13 -6
  10. scriptengine/jobs.py +15 -15
  11. scriptengine/tasks/__init__.py +0 -0
  12. scriptengine/tasks/base/__init__.py +0 -0
  13. scriptengine/tasks/base/chdir.py +21 -0
  14. scriptengine/tasks/base/command.py +158 -0
  15. scriptengine/tasks/base/context.py +95 -0
  16. scriptengine/tasks/base/echo.py +27 -0
  17. scriptengine/tasks/base/envvars.py +57 -0
  18. scriptengine/tasks/base/exit.py +18 -0
  19. scriptengine/tasks/base/file/__init__.py +0 -0
  20. scriptengine/tasks/base/file/copy.py +82 -0
  21. scriptengine/tasks/base/file/link.py +80 -0
  22. scriptengine/tasks/base/file/make_dir.py +43 -0
  23. scriptengine/tasks/base/file/move.py +76 -0
  24. scriptengine/tasks/base/file/remove.py +73 -0
  25. scriptengine/tasks/base/find.py +66 -0
  26. scriptengine/tasks/base/include.py +75 -0
  27. scriptengine/tasks/base/task_timer.py +61 -0
  28. scriptengine/tasks/base/template.py +74 -0
  29. scriptengine/tasks/base/time.py +33 -0
  30. scriptengine/tasks/core/__init__.py +14 -0
  31. scriptengine/tasks/core/loader.py +44 -0
  32. scriptengine/tasks/core/task.py +177 -0
  33. scriptengine/tasks/core/timing.py +63 -0
  34. scriptengine/yaml/__init__.py +0 -0
  35. scriptengine/yaml/noparse_strings.py +11 -0
  36. scriptengine/yaml/parser.py +141 -0
  37. {scriptengine-0.14.3.dist-info → scriptengine-1.0.0.dist-info}/METADATA +11 -3
  38. scriptengine-1.0.0.dist-info/RECORD +44 -0
  39. {scriptengine-0.14.3.dist-info → scriptengine-1.0.0.dist-info}/WHEEL +1 -1
  40. {scriptengine-0.14.3.dist-info → scriptengine-1.0.0.dist-info}/entry_points.txt +1 -19
  41. scriptengine-0.14.3.dist-info/RECORD +0 -12
  42. {scriptengine-0.14.3.dist-info → scriptengine-1.0.0.dist-info}/LICENSE +0 -0
  43. {scriptengine-0.14.3.dist-info → scriptengine-1.0.0.dist-info}/top_level.txt +0 -0
File without changes
scriptengine/cli/se.py ADDED
@@ -0,0 +1,164 @@
1
+ """ScriptEngine command line interface (cli).
2
+
3
+ The se command provides a command line interface to ScriptEngine, allowing for
4
+ the creation of scripts from YAML files and running the scripts via the
5
+ SimpleScriptEngine.
6
+ """
7
+
8
+ __copyright__ = """
9
+ Copyright 2019, 2020 Uwe Fladrich
10
+
11
+ This file is part of ScriptEngine.
12
+
13
+ ScriptEngine is free software: you can redistribute it and/or modify
14
+ it under the terms of the GNU General Public License as published by
15
+ the Free Software Foundation, either version 3 of the License, or
16
+ (at your option) any later version.
17
+
18
+ ScriptEngine is distributed in the hope that it will be useful,
19
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
20
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
+ GNU General Public License for more details.
22
+
23
+ You should have received a copy of the GNU General Public License
24
+ along with ScriptEngine. If not, see <https://www.gnu.org/licenses/>.
25
+ """
26
+ __license__ = "GPLv3+"
27
+
28
+
29
+ import argparse
30
+ import importlib.metadata
31
+ import logging
32
+ import os
33
+
34
+ import scriptengine.helpers.terminal_colors
35
+ import scriptengine.logging
36
+ from scriptengine.engines import SimpleScriptEngine
37
+ from scriptengine.exceptions import ScriptEngineParseError, ScriptEngineParseFileError
38
+ from scriptengine.tasks.core.loader import load as load_tasks
39
+ from scriptengine.yaml.parser import parse_file as parse_yaml_file
40
+
41
+ __version__ = importlib.metadata.version("scriptengine")
42
+
43
+
44
+ def parse_cmd_line_args():
45
+ """Parses the command line arguments with argparse"""
46
+ arg_parser = argparse.ArgumentParser(
47
+ description="ScriptEngine command line tool",
48
+ epilog="Available ScriptEngine tasks: " + ", ".join(load_tasks().keys()),
49
+ )
50
+ arg_parser.add_argument(
51
+ "-V",
52
+ "--version",
53
+ help="show ScriptEngine version and exit",
54
+ action="version",
55
+ version=__version__,
56
+ )
57
+ arg_parser.add_argument(
58
+ "--loglevel",
59
+ help="The minimum level of log messages that is "
60
+ "displayed. For verbose output, use "
61
+ '"debug". For minimal output, use "error" '
62
+ 'or "critical".',
63
+ choices=["debug", "info", "warning", "error", "critical"],
64
+ )
65
+ arg_parser.add_argument(
66
+ "--nocolor", help="do not use colored terminal output", action="store_true"
67
+ )
68
+ arg_parser.add_argument("files", help="YAML file(s) to read", nargs="+")
69
+
70
+ return arg_parser.parse_args()
71
+
72
+
73
+ def parse_files(logger, files):
74
+ """Parses files and returns a script (list of tasks/jobs)."""
75
+ script = []
76
+ for fname in files:
77
+ # next_script is a Task or Job or list of either
78
+ next_script = parse_yaml_file(fname)
79
+ if isinstance(next_script, list):
80
+ script.extend(next_script)
81
+ else:
82
+ script.append(next_script)
83
+
84
+ return script
85
+
86
+
87
+ def main():
88
+ """ScriptEngine command line tool
89
+
90
+ The context is passed to the ScriptEngine instance and, later, to all
91
+ tasks. Some context information is already set here in the se command
92
+ line tool:
93
+ context['se']['cli']['cwd'] - the original working directory
94
+ context['se']['cli']['script_path'] - list of paths for all scripts
95
+ given at the command line (used
96
+ as search path for includes, for
97
+ example)
98
+ context['se']['instance'] - a reference to the ScriptEngine
99
+ instance that executes the task
100
+ context['se']['tasks']['timing'] - task timing information
101
+ (defaults to no timing)
102
+ """
103
+
104
+ # Parse command line arguments
105
+ parsed_args = parse_cmd_line_args()
106
+
107
+ # Choose colored output unless --nocolor
108
+ scriptengine.helpers.terminal_colors.set_theme(
109
+ "none" if parsed_args.nocolor else "standard"
110
+ )
111
+
112
+ # Configure logging with level given by --loglevel
113
+ # or by default with logging.INFO
114
+ scriptengine.logging.configure(
115
+ logging.getLevelName(parsed_args.loglevel.upper())
116
+ if parsed_args.loglevel
117
+ else logging.INFO
118
+ )
119
+ logger = logging.getLogger("se.cli")
120
+ logger.info("Logging configured and started")
121
+
122
+ # Log all loaded tasks if debugging
123
+ if logger.level <= logging.DEBUG:
124
+ for name, task in load_tasks().items():
125
+ logger.debug(
126
+ f"Loaded task {name}: {task.__name__} " f"from {task.__module__}"
127
+ )
128
+
129
+ # Create script by parsing the files given on the command line
130
+ try:
131
+ script = parse_files(logger, parsed_args.files)
132
+ except ScriptEngineParseFileError:
133
+ logger.critical("Could not read all script files")
134
+ return os.EX_NOINPUT
135
+ except ScriptEngineParseError:
136
+ logger.critical("Could not parse all script files")
137
+ return os.EX_DATAERR
138
+
139
+ # Collect paths (and remove duplicates)
140
+ script_path = tuple(
141
+ dict.fromkeys((os.path.dirname(file) for file in parsed_args.files))
142
+ )
143
+
144
+ context = {
145
+ "se": {
146
+ "cli": {
147
+ "cwd": os.getcwd(),
148
+ "script_path": script_path,
149
+ },
150
+ "tasks": {
151
+ "timing": {
152
+ "mode": None,
153
+ "logging": None,
154
+ "timers": {},
155
+ },
156
+ },
157
+ "instance": SimpleScriptEngine(),
158
+ }
159
+ }
160
+
161
+ # Call ScriptEngine instance to run the script
162
+ context["se"]["instance"].run(script, context)
163
+
164
+ return os.EX_OK
scriptengine/context.py CHANGED
@@ -1,96 +1,124 @@
1
- import sys
2
- from copy import deepcopy
1
+ from collections import UserDict
2
+ from collections.abc import Mapping
3
+ from typing import Any
3
4
 
4
- from deepdiff import DeepDiff, Delta
5
+ import yaml
5
6
  from deepmerge import always_merger
6
7
 
7
- _python_version = (sys.version_info.major, sys.version_info.minor)
8
+ KEY_SEP = "."
8
9
 
9
10
 
10
- def save_copy(context):
11
- """For versions other than 3.6, this is just copy.deepcopy.
12
- For 3.6, we have to remove ["se"]["instance"] before deepcopying and restore
13
- afterwards, because this constitutes some recursive reference that 3.6 has a
14
- problem with.
11
+ class Context(UserDict):
15
12
  """
16
- if _python_version != (3, 6):
17
- return deepcopy(context)
18
- singleton = object()
19
- try:
20
- se_instance = context["se"]["instance"]
21
- context["se"]["instance"] = None
22
- except KeyError:
23
- se_instance = singleton
24
- copied_context = deepcopy(context)
25
- if se_instance is not singleton:
26
- copied_context["se"]["instance"] = context["se"]["instance"] = se_instance
27
- return copied_context
28
-
29
-
30
- def context_delta(first, second):
31
- """The deepdiff.Delta's __init__ and __add__ functions use copy.deepcopy
32
- internally, which does not work with the SE context (see above).
33
- Therefore, we ignore context["se"]["instance"] before creating Delta. This
34
- means, that for Python 3.6 this item in the context is not part of the Delta,
35
- even if it was changed between first and second!
36
- Also, we have to create the Delta with mutate=True to avoid another deepcopy.
13
+ The ScriptEngine Context provides context information for Tasks
14
+
15
+ https://scriptengine.readthedocs.io/en/latest/concepts.html#task-context
16
+ The Context is a special dict that allows
17
+ * dotted keys, i.e. c["foo.bar"] is equivalent to c["foo"]["bar"]
18
+ * deep merges of other Mappings (via deepmerge.always_merger)
19
+ * save and load the data to/from a file-like object
20
+
21
+ Methods
22
+ -------
23
+ merge(other)
24
+ Deep merges other into the context
25
+
26
+ reset(keep=None)
27
+ Deletes all data from the context, except for the keys listed in 'keep'
28
+
29
+ save(stream)
30
+ ...
31
+
32
+ load(stream)
33
+ ...
37
34
  """
38
- if _python_version != (3, 6):
39
- return Delta(DeepDiff(first, second))
40
-
41
- singleton = object()
42
- try:
43
- first_se_instance = first["se"]["instance"]
44
- first["se"]["instance"] = None
45
- except KeyError:
46
- first_se_instance = singleton
47
- try:
48
- second_se_instance = second["se"]["instance"]
49
- second["se"]["instance"] = None
50
- except KeyError:
51
- second_se_instance = singleton
52
- delta = Delta(DeepDiff(first, second), mutate=True)
53
- if first_se_instance is not singleton:
54
- first["se"]["instance"] = first_se_instance
55
- if second_se_instance is not singleton:
56
- second["se"]["instance"] = second_se_instance
57
- return delta
58
-
59
-
60
- class Context(dict):
61
- pass
62
-
63
-
64
- class ContextUpdate:
65
- def __init__(self, base=None, second=None):
66
- if base is None:
67
- self.merge = self.delta = None
68
- elif second is None:
69
- if not isinstance(base, dict):
70
- raise TypeError(
71
- "First argument of ContextUpdate() must be None or a dict"
72
- )
73
- self.merge = base
74
- self.delta = None
35
+
36
+ def __getitem__(self, key: Any) -> Any:
37
+ """Return x[key] where key is possibly a dotted key"""
38
+ def iter_getitem(data, subkey):
39
+ try:
40
+ return data[subkey]
41
+ except TypeError: # dotted key with too many components
42
+ raise KeyError(subkey)
43
+ except KeyError:
44
+ pass
45
+ try:
46
+ first, _, remain = subkey.partition(KEY_SEP)
47
+ except AttributeError:
48
+ raise KeyError(subkey)
49
+ return iter_getitem(data[first], remain)
50
+
51
+ try:
52
+ return iter_getitem(self.data, key)
53
+ except KeyError as e:
54
+ raise KeyError(
55
+ f"{key} (subkey {e} not found)" if str(key) != str(e) else key
56
+ ) from None
57
+
58
+ def __setitem__(self, key: Any, item: Any) -> None:
59
+ """Set x[key]=item where key is possibly a dotted key"""
60
+ try:
61
+ keys = key.split(KEY_SEP)
62
+ except AttributeError:
63
+ self.data[key] = item
75
64
  else:
76
- self.merge = None
77
- self.delta = context_delta(base, second)
78
-
79
- def __radd__(self, other):
80
- if isinstance(other, dict):
81
- if self.merge:
82
- return always_merger.merge(other, self.merge)
83
- elif self.delta:
84
- return other + self.delta
85
- return other
86
- raise TypeError(
87
- f"Unsupported operand types for +: '{type(other)}' and 'ContextUpdate'"
88
- )
89
-
90
- def __repr__(self):
91
- if self.merge:
92
- return f"<ContextUpdate: merge {self.merge}>"
93
- elif self.delta:
94
- return f"<ContextUpdate: {self.delta}>"
65
+ d = self.data
66
+ for k in keys[:-1]:
67
+ # allow overwriting of non-mapping keys
68
+ if k not in d or not isinstance(d[k], Mapping):
69
+ d[k] = {}
70
+ d = d[k]
71
+ # Make sure that nested dotted keys are resolved!
72
+ d[keys[-1]] = Context(item).data if isinstance(item, Mapping) else item
73
+
74
+ def __contains__(self, key: object) -> bool:
75
+ def iter_contains(data, subkey):
76
+ if subkey in data:
77
+ return True
78
+ try:
79
+ first, _, remain = subkey.partition(KEY_SEP)
80
+ except AttributeError:
81
+ return False
82
+ if first in data:
83
+ return iter_contains(data[first], remain)
84
+ return False
85
+
86
+ return iter_contains(self.data, key)
87
+
88
+ def __str__(self) -> str:
89
+ return f"Context({self.data})"
90
+
91
+ def __add__(self, other):
92
+ if isinstance(other, Mapping):
93
+ self.merge(other)
94
+ return self
95
+ return NotImplemented
96
+
97
+ def merge(self, other):
98
+ if isinstance(other, Context):
99
+ always_merger.merge(self.data, other.data)
100
+ elif isinstance(other, Mapping):
101
+ always_merger.merge(self.data, other)
95
102
  else:
96
- return "<ContextUpdate: None>"
103
+ raise TypeError(f"can not merge Context and {type(other).__name__}")
104
+
105
+ def reset(self, keep=None):
106
+ save_copy = Context()
107
+ for k in keep or []:
108
+ if k in self:
109
+ save_copy[k] = self[k]
110
+ self.data.clear()
111
+ for k in save_copy:
112
+ self[k] = save_copy[k]
113
+
114
+ def load(self, stream):
115
+ self.data = yaml.safe_load(stream)
116
+
117
+ def save(self, stream):
118
+ yaml.dump(self.data, stream, sort_keys=False)
119
+
120
+
121
+ # from dotty_dict import Dotty
122
+ # class Context(Dotty):
123
+ # def __init__(self, dictionary=None):
124
+ # super().__init__(dictionary or {}, no_list=True)
@@ -0,0 +1,6 @@
1
+ """ ScriptEngine scripts.
2
+
3
+ This module provides script engines, which can run lists of jobs.
4
+ """
5
+
6
+ from .simple_script_engine import SimpleScriptEngine
@@ -0,0 +1,93 @@
1
+ """ SimpleScriptEngine for ScriptEngine.
2
+
3
+ SimpleScriptEngine is a simplistic script engine. It runs all jobs sequentially
4
+ on the local machine, without consideration of job contexts. The
5
+ SimpleScriptEngine relies on the Job class to run the actual tasks/jobs.
6
+ """
7
+
8
+ import copy
9
+ import logging
10
+ import sys
11
+ from pprint import pprint
12
+
13
+ from scriptengine.context import Context
14
+ from scriptengine.exceptions import (
15
+ ScriptEngineJobError,
16
+ ScriptEngineStopException,
17
+ ScriptEngineTaskError,
18
+ )
19
+ from scriptengine.tasks.core import Task
20
+
21
+
22
+ class SimpleScriptEngine:
23
+ def __init__(self):
24
+ self.logger = logging.getLogger(
25
+ "se.instance." + self.__class__.__name__.lower()
26
+ )
27
+
28
+ def _guarded_run(self, runner, context):
29
+ try:
30
+ return runner.run(context)
31
+ except AttributeError as e:
32
+ self.log_error(
33
+ "STOPPING SimpleScriptEngine due to internal error: "
34
+ f"Cannot run type {type(runner).__name__}"
35
+ )
36
+ error = e
37
+ except ScriptEngineStopException:
38
+ self.log_info("STOPPING SimpleScriptEngine instance upon request")
39
+ error = None
40
+ except ScriptEngineTaskError as e:
41
+ if isinstance(runner, Task):
42
+ self.log_error(
43
+ "STOPPING SimpleScriptEngine due to task error in "
44
+ f"{runner.reg_name} <{runner.shortid}>"
45
+ )
46
+ else:
47
+ self.log_error(
48
+ "STOPPING SimpleScriptEngine due to task error in job "
49
+ f"<{runner.shortid}>"
50
+ )
51
+ error = e
52
+ except ScriptEngineJobError as e:
53
+ self.log_error(
54
+ f"STOPPING SimpleScriptEngine due to job error in <{runner.shortid}>"
55
+ )
56
+ error = e
57
+ if error:
58
+ if self.logger.getEffectiveLevel() <= logging.DEBUG:
59
+ self.log_error("Last context before error:")
60
+ pprint(context)
61
+ self.log_error("Traceback from error:")
62
+ raise error
63
+ else:
64
+ self.log_error("For more debugging info, re-run with loglevel DEBUG")
65
+ sys.exit()
66
+
67
+ def run(self, script, context):
68
+ local_context = Context(context)
69
+ context_update = Context()
70
+ for todo in script if isinstance(script, list) else [script]:
71
+ c = self._guarded_run(todo, local_context)
72
+ if c:
73
+ local_context += c
74
+ context_update += copy.deepcopy(c)
75
+ return context_update or None
76
+
77
+ def _log(self, level, msg):
78
+ self.logger.log(level, msg)
79
+
80
+ def log_debug(self, msg):
81
+ self._log(logging.DEBUG, msg)
82
+
83
+ def log_info(self, msg):
84
+ self._log(logging.INFO, msg)
85
+
86
+ def log_warning(self, msg):
87
+ self._log(logging.WARNING, msg)
88
+
89
+ def log_error(self, msg):
90
+ self._log(logging.ERROR, msg)
91
+
92
+ def log_critical(self, msg):
93
+ self._log(logging.CRITICAL, msg)
@@ -15,7 +15,7 @@ class ScriptEngineParseError(ScriptEngineError):
15
15
 
16
16
 
17
17
  class ScriptEngineParseFileError(ScriptEngineParseError):
18
- """An file error while acessing an SE script"""
18
+ """An file error while accessing an SE script"""
19
19
 
20
20
 
21
21
  class ScriptEngineParseJinjaError(ScriptEngineParseError):
File without changes
@@ -0,0 +1,88 @@
1
+ """ScriptEngine helpers: Colored terminal output
2
+
3
+ Terminal markup and colors by using ANSI escape sequences. To print colored
4
+ text, use, for example:
5
+
6
+ import terminal_colors as TC
7
+
8
+ print(f'{TC.RED}Hello!{TC.RESET}')
9
+
10
+ For background colors, use BG_ prefix, i.e. TC.BG_GREEN.
11
+
12
+ The module supports color themes. To set another theme, use, for example
13
+
14
+ TC.set_theme('none')
15
+
16
+ Further output will then be without colors.
17
+ """
18
+
19
+ import sys
20
+
21
+ from scriptengine.exceptions import ScriptEngineError
22
+
23
+ # The default color theme
24
+ ACTIVE_THEME = 'standard'
25
+
26
+ # All themes with all colors.
27
+ # It is not necessary that all themes define the same colors. But if you are
28
+ # using a color that is not defined in the active theme, there will be an
29
+ # AttributeError.
30
+ COLORTABLE = {
31
+ 'standard': {
32
+ 'RESET': '\033[0m',
33
+
34
+ 'BOLD': '\033[01m', 'DIM': '\033[02m', 'UNDERLINE': '\033[04m',
35
+ 'REVERSE': '\033[07m', 'STRIKETHROUGH': '\033[09m',
36
+ 'INVISIBLE': '\033[08m',
37
+
38
+ 'BLACK': '\033[30m', 'RED': '\033[31m', 'GREEN': '\033[32m',
39
+ 'ORANGE': '\033[33m', 'BLUE': '\033[34m', 'PURPLE': '\033[35m',
40
+ 'CYAN': '\033[36m', 'LIGHTGREY': '\033[37m', 'DARKGREY': '\033[90m',
41
+ 'LIGHTRED': '\033[91m', 'LIGHTGREEN': '\033[92m',
42
+ 'YELLOW': '\033[93m', 'LIGHTBLUE': '\033[94m', 'PINK': '\033[95m',
43
+ 'LIGHTCYAN': '\033[96m',
44
+
45
+ 'BG_BLACK': '\033[40m', 'BG_RED': '\033[41m', 'BG_GREEN': '\033[42m',
46
+ 'BG_ORANGE': '\033[43m', 'BG_BLUE': '\033[44m',
47
+ 'BG_PURPLE': '\033[45m', 'BG_CYAN': '\033[46m',
48
+ 'BG_LIGHTGREY': '\033[47m'},
49
+
50
+ 'none': {
51
+ 'RESET': '',
52
+
53
+ 'BOLD': '', 'DIM': '', 'UNDERLINE': '', 'REVERSE': '',
54
+ 'STRIKETHROUGH': '', 'INVISIBLE': '',
55
+
56
+ 'BLACK': '', 'RED': '', 'GREEN': '', 'ORANGE': '',
57
+ 'BLUE': '', 'PURPLE': '', 'CYAN': '', 'LIGHTGREY': '',
58
+ 'DARKGREY': '', 'LIGHTRED': '', 'LIGHTGREEN': '',
59
+ 'YELLOW': '', 'LIGHTBLUE': '', 'PINK': '',
60
+ 'LIGHTCYAN': '',
61
+
62
+ 'BG_BLACK': '', 'BG_RED': '', 'BG_GREEN': '',
63
+ 'BG_ORANGE': '', 'BG_BLUE': '', 'BG_PURPLE': '',
64
+ 'BG_CYAN': '', 'BG_LIGHTGREY': ''}
65
+ }
66
+
67
+
68
+ def set_theme(theme):
69
+ """ Changes the active color theme
70
+ """
71
+ global ACTIVE_THEME
72
+ if theme not in COLORTABLE.keys():
73
+ raise ScriptEngineError(f'Invalid terminal color scheme: "{theme}"')
74
+ ACTIVE_THEME = theme
75
+
76
+ # Clean all present color settings
77
+ for color in {c for t in COLORTABLE for c in COLORTABLE[t]}:
78
+ if hasattr(sys.modules[__name__], color):
79
+ delattr(sys.modules[__name__], color)
80
+
81
+ # Set colors for new theme
82
+ for color, value in COLORTABLE[theme].items():
83
+ setattr(sys.modules[__name__], color, value)
84
+
85
+
86
+ # Set default colors
87
+ for _color, _value in COLORTABLE[ACTIVE_THEME].items():
88
+ setattr(sys.modules[__name__], _color, _value)
scriptengine/jinja.py CHANGED
@@ -1,7 +1,6 @@
1
1
  """ScriptEngine helpers: Jinja2 rendering"""
2
2
 
3
3
  import datetime
4
- import distutils.util
5
4
  import os
6
5
 
7
6
  import jinja2
@@ -57,6 +56,14 @@ for name, function in filters().items():
57
56
  _param_env.filters[name] = function
58
57
 
59
58
 
59
+ def _strtobool(value):
60
+ if value in ("y", "yes", "t", "true", "on", "1"):
61
+ return True
62
+ elif value in ("n", "no", "f", "false", "off", "0"):
63
+ return False
64
+ raise ValueError(f"Cannot convert '{value}' to a boolean value")
65
+
66
+
60
67
  def render(arg, context, recursive=True, boolean=False):
61
68
  """Renders a string with Jinja2.
62
69
 
@@ -87,11 +94,11 @@ def render(arg, context, recursive=True, boolean=False):
87
94
  try:
88
95
  # Render string in parameter environment using context
89
96
  return _param_env.from_string(string_arg).render(context)
90
- except jinja2.TemplateSyntaxError:
97
+ except jinja2.TemplateError as e:
91
98
  raise ScriptEngineParseJinjaError(
92
- "Syntax error while rendering template string "
93
- f'"{string_arg}"'
94
- f'{" in boolean context" if boolean else ""}'
99
+ f"Jinja2 {type(e).__name__} while parsing '{string_arg}'"
100
+ f"{' (in boolean context): ' if boolean else ': '}"
101
+ f"{e}"
95
102
  )
96
103
 
97
104
  if isinstance(arg, str):
@@ -103,7 +110,7 @@ def render(arg, context, recursive=True, boolean=False):
103
110
  next_rendered_string = render_with_context(rendered_string)
104
111
  if boolean:
105
112
  expr = f"{{% if {rendered_string} %}}1{{% else %}}0{{% endif %}}"
106
- return bool(distutils.util.strtobool(render_with_context(expr)))
113
+ return _strtobool(render_with_context(expr))
107
114
  return rendered_string
108
115
  else:
109
116
  return arg