scriptengine 0.14.3__tar.gz → 1.0.0__tar.gz

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 (56) hide show
  1. {scriptengine-0.14.3/scriptengine.egg-info → scriptengine-1.0.0}/PKG-INFO +15 -2
  2. scriptengine-1.0.0/pyproject.toml +56 -0
  3. scriptengine-1.0.0/setup.py +3 -0
  4. scriptengine-1.0.0/src/scriptengine/cli/__init__.py +0 -0
  5. scriptengine-1.0.0/src/scriptengine/cli/se.py +164 -0
  6. scriptengine-1.0.0/src/scriptengine/context.py +124 -0
  7. scriptengine-1.0.0/src/scriptengine/engines/__init__.py +6 -0
  8. scriptengine-1.0.0/src/scriptengine/engines/simple_script_engine.py +93 -0
  9. {scriptengine-0.14.3 → scriptengine-1.0.0/src}/scriptengine/exceptions.py +1 -1
  10. scriptengine-1.0.0/src/scriptengine/helpers/__init__.py +0 -0
  11. scriptengine-1.0.0/src/scriptengine/helpers/terminal_colors.py +88 -0
  12. {scriptengine-0.14.3 → scriptengine-1.0.0/src}/scriptengine/jinja.py +13 -6
  13. {scriptengine-0.14.3 → scriptengine-1.0.0/src}/scriptengine/jobs.py +15 -15
  14. scriptengine-1.0.0/src/scriptengine/tasks/__init__.py +0 -0
  15. scriptengine-1.0.0/src/scriptengine/tasks/base/__init__.py +0 -0
  16. scriptengine-1.0.0/src/scriptengine/tasks/base/chdir.py +21 -0
  17. scriptengine-1.0.0/src/scriptengine/tasks/base/command.py +158 -0
  18. scriptengine-1.0.0/src/scriptengine/tasks/base/context.py +95 -0
  19. scriptengine-1.0.0/src/scriptengine/tasks/base/echo.py +27 -0
  20. scriptengine-1.0.0/src/scriptengine/tasks/base/envvars.py +57 -0
  21. scriptengine-1.0.0/src/scriptengine/tasks/base/exit.py +18 -0
  22. scriptengine-1.0.0/src/scriptengine/tasks/base/file/__init__.py +0 -0
  23. scriptengine-1.0.0/src/scriptengine/tasks/base/file/copy.py +82 -0
  24. scriptengine-1.0.0/src/scriptengine/tasks/base/file/link.py +80 -0
  25. scriptengine-1.0.0/src/scriptengine/tasks/base/file/make_dir.py +43 -0
  26. scriptengine-1.0.0/src/scriptengine/tasks/base/file/move.py +76 -0
  27. scriptengine-1.0.0/src/scriptengine/tasks/base/file/remove.py +73 -0
  28. scriptengine-1.0.0/src/scriptengine/tasks/base/find.py +66 -0
  29. scriptengine-1.0.0/src/scriptengine/tasks/base/include.py +75 -0
  30. scriptengine-1.0.0/src/scriptengine/tasks/base/task_timer.py +61 -0
  31. scriptengine-1.0.0/src/scriptengine/tasks/base/template.py +74 -0
  32. scriptengine-1.0.0/src/scriptengine/tasks/base/time.py +33 -0
  33. scriptengine-1.0.0/src/scriptengine/tasks/core/__init__.py +14 -0
  34. scriptengine-1.0.0/src/scriptengine/tasks/core/loader.py +44 -0
  35. scriptengine-1.0.0/src/scriptengine/tasks/core/task.py +177 -0
  36. scriptengine-1.0.0/src/scriptengine/tasks/core/timing.py +63 -0
  37. scriptengine-1.0.0/src/scriptengine/yaml/__init__.py +0 -0
  38. scriptengine-1.0.0/src/scriptengine/yaml/noparse_strings.py +11 -0
  39. scriptengine-1.0.0/src/scriptengine/yaml/parser.py +141 -0
  40. {scriptengine-0.14.3 → scriptengine-1.0.0/src/scriptengine.egg-info}/PKG-INFO +15 -2
  41. scriptengine-1.0.0/src/scriptengine.egg-info/SOURCES.txt +49 -0
  42. {scriptengine-0.14.3 → scriptengine-1.0.0/src}/scriptengine.egg-info/entry_points.txt +1 -19
  43. scriptengine-1.0.0/src/scriptengine.egg-info/requires.txt +16 -0
  44. scriptengine-1.0.0/tests/test_logging.py +88 -0
  45. scriptengine-0.14.3/pyproject.toml +0 -71
  46. scriptengine-0.14.3/scriptengine/context.py +0 -96
  47. scriptengine-0.14.3/scriptengine.egg-info/SOURCES.txt +0 -16
  48. scriptengine-0.14.3/scriptengine.egg-info/requires.txt +0 -5
  49. scriptengine-0.14.3/setup.py +0 -63
  50. {scriptengine-0.14.3 → scriptengine-1.0.0}/LICENSE +0 -0
  51. {scriptengine-0.14.3 → scriptengine-1.0.0}/README.md +0 -0
  52. {scriptengine-0.14.3 → scriptengine-1.0.0}/setup.cfg +0 -0
  53. {scriptengine-0.14.3 → scriptengine-1.0.0/src}/scriptengine/__init__.py +0 -0
  54. {scriptengine-0.14.3 → scriptengine-1.0.0/src}/scriptengine/logging.py +0 -0
  55. {scriptengine-0.14.3 → scriptengine-1.0.0/src}/scriptengine.egg-info/dependency_links.txt +0 -0
  56. {scriptengine-0.14.3 → scriptengine-1.0.0/src}/scriptengine.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: scriptengine
3
- Version: 0.14.3
3
+ Version: 1.0.0
4
4
  Summary: A lightweight and extensible framework for executing scripts written in YAML
5
5
  Author-email: Uwe Fladrich <uwe.fladrich@protonmail.com>
6
6
  Project-URL: Homepage, https://github.com/uwefladrich/scriptengine
@@ -8,9 +8,22 @@ Project-URL: Bug Tracker, https://github.com/uwefladrich/scriptengine/issues
8
8
  Classifier: Programming Language :: Python :: 3
9
9
  Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
10
10
  Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.6
11
+ Requires-Python: >=3.8
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
+ Requires-Dist: python-dateutil
15
+ Requires-Dist: deepmerge
16
+ Requires-Dist: PyYAML
17
+ Requires-Dist: jinja2
18
+ Provides-Extra: tests
19
+ Requires-Dist: coverage; extra == "tests"
20
+ Requires-Dist: coveralls; extra == "tests"
21
+ Requires-Dist: pytest; extra == "tests"
22
+ Provides-Extra: docs
23
+ Requires-Dist: sphinx; extra == "docs"
24
+ Requires-Dist: sphinx-rtd-theme; extra == "docs"
25
+ Provides-Extra: all
26
+ Requires-Dist: scriptengine[docs,tests]; extra == "all"
14
27
 
15
28
  # ScriptEngine
16
29
 
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["setuptools>=60", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scriptengine"
7
+ version = "1.0.0"
8
+ authors = [{ name = "Uwe Fladrich", email = "uwe.fladrich@protonmail.com" }]
9
+ description = "A lightweight and extensible framework for executing scripts written in YAML"
10
+ readme = "README.md"
11
+ requires-python = ">=3.8"
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
15
+ "Operating System :: OS Independent",
16
+ ]
17
+ dependencies = [
18
+ "python-dateutil",
19
+ "deepmerge",
20
+ "PyYAML",
21
+ "jinja2",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ tests = ["coverage", "coveralls", "pytest"]
26
+
27
+ docs = ["sphinx", "sphinx-rtd-theme"]
28
+
29
+ all = ["scriptengine[tests,docs]"]
30
+
31
+ [project.urls]
32
+ "Homepage" = "https://github.com/uwefladrich/scriptengine"
33
+ "Bug Tracker" = "https://github.com/uwefladrich/scriptengine/issues"
34
+
35
+ [project.scripts]
36
+ se = "scriptengine.cli.se:main"
37
+
38
+ [project.entry-points."scriptengine.tasks"]
39
+ "base.chdir" = "scriptengine.tasks.base.chdir:Chdir"
40
+ "base.command" = "scriptengine.tasks.base.command:Command"
41
+ "base.context" = "scriptengine.tasks.base.context:Context"
42
+ "base.context.load" = "scriptengine.tasks.base.context:ContextLoad"
43
+ "base.copy" = "scriptengine.tasks.base.file.copy:Copy"
44
+ "base.echo" = "scriptengine.tasks.base.echo:Echo"
45
+ "base.exit" = "scriptengine.tasks.base.exit:Exit"
46
+ "base.find" = "scriptengine.tasks.base.find:Find"
47
+ "base.getenv" = "scriptengine.tasks.base.envvars:Getenv"
48
+ "base.include" = "scriptengine.tasks.base.include:Include"
49
+ "base.link" = "scriptengine.tasks.base.file.link:Link"
50
+ "base.make_dir" = "scriptengine.tasks.base.file.make_dir:MakeDir"
51
+ "base.move" = "scriptengine.tasks.base.file.move:Move"
52
+ "base.remove" = "scriptengine.tasks.base.file.remove:Remove"
53
+ "base.setenv" = "scriptengine.tasks.base.envvars:Setenv"
54
+ "base.task_timer" = "scriptengine.tasks.base.task_timer:TaskTimer"
55
+ "base.template" = "scriptengine.tasks.base.template:Template"
56
+ "base.time" = "scriptengine.tasks.base.time:Time"
@@ -0,0 +1,3 @@
1
+ import setuptools
2
+
3
+ setuptools.setup()
File without changes
@@ -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
@@ -0,0 +1,124 @@
1
+ from collections import UserDict
2
+ from collections.abc import Mapping
3
+ from typing import Any
4
+
5
+ import yaml
6
+ from deepmerge import always_merger
7
+
8
+ KEY_SEP = "."
9
+
10
+
11
+ class Context(UserDict):
12
+ """
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
+ ...
34
+ """
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
64
+ else:
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)
102
+ else:
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):
@@ -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)
@@ -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