scriptengine 0.14.4__tar.gz → 1.0.0rc2__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 (57) hide show
  1. {scriptengine-0.14.4/scriptengine.egg-info → scriptengine-1.0.0rc2}/PKG-INFO +15 -2
  2. scriptengine-1.0.0rc2/pyproject.toml +56 -0
  3. scriptengine-1.0.0rc2/setup.py +3 -0
  4. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/cli/se.py +7 -11
  5. scriptengine-1.0.0rc2/src/scriptengine/context.py +124 -0
  6. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/engines/simple_script_engine.py +9 -6
  7. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/exceptions.py +1 -1
  8. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/helpers/terminal_colors.py +1 -1
  9. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/jinja.py +13 -6
  10. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/jobs.py +15 -15
  11. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/command.py +15 -7
  12. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/context.py +5 -4
  13. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/envvars.py +3 -3
  14. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/find.py +2 -2
  15. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/include.py +4 -5
  16. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/template.py +11 -4
  17. scriptengine-1.0.0rc2/src/scriptengine/tasks/core/loader.py +44 -0
  18. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/core/task.py +56 -62
  19. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/yaml/parser.py +1 -1
  20. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src/scriptengine.egg-info}/PKG-INFO +15 -2
  21. scriptengine-1.0.0rc2/src/scriptengine.egg-info/SOURCES.txt +49 -0
  22. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine.egg-info/entry_points.txt +0 -18
  23. scriptengine-1.0.0rc2/src/scriptengine.egg-info/requires.txt +16 -0
  24. scriptengine-1.0.0rc2/tests/test_logging.py +88 -0
  25. scriptengine-0.14.4/pyproject.toml +0 -71
  26. scriptengine-0.14.4/scriptengine/context.py +0 -96
  27. scriptengine-0.14.4/scriptengine/tasks/core/loader.py +0 -40
  28. scriptengine-0.14.4/scriptengine.egg-info/SOURCES.txt +0 -48
  29. scriptengine-0.14.4/scriptengine.egg-info/requires.txt +0 -5
  30. scriptengine-0.14.4/setup.py +0 -62
  31. {scriptengine-0.14.4 → scriptengine-1.0.0rc2}/LICENSE +0 -0
  32. {scriptengine-0.14.4 → scriptengine-1.0.0rc2}/README.md +0 -0
  33. {scriptengine-0.14.4 → scriptengine-1.0.0rc2}/setup.cfg +0 -0
  34. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/__init__.py +0 -0
  35. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/cli/__init__.py +0 -0
  36. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/engines/__init__.py +0 -0
  37. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/helpers/__init__.py +0 -0
  38. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/logging.py +0 -0
  39. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/__init__.py +0 -0
  40. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/__init__.py +0 -0
  41. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/chdir.py +0 -0
  42. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/echo.py +0 -0
  43. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/exit.py +0 -0
  44. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/file/__init__.py +0 -0
  45. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/file/copy.py +0 -0
  46. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/file/link.py +0 -0
  47. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/file/make_dir.py +0 -0
  48. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/file/move.py +0 -0
  49. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/file/remove.py +0 -0
  50. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/task_timer.py +0 -0
  51. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/base/time.py +0 -0
  52. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/core/__init__.py +0 -0
  53. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/tasks/core/timing.py +0 -0
  54. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/yaml/__init__.py +0 -0
  55. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine/yaml/noparse_strings.py +0 -0
  56. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/src}/scriptengine.egg-info/dependency_links.txt +0 -0
  57. {scriptengine-0.14.4 → scriptengine-1.0.0rc2/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.4
3
+ Version: 1.0.0rc2
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.0rc2"
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.from" = "scriptengine.tasks.base.context:ContextFrom"
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()
@@ -1,7 +1,7 @@
1
1
  """ScriptEngine command line interface (cli).
2
2
 
3
3
  The se command provides a command line interface to ScriptEngine, allowing for
4
- the creation of scripts from YAML files and runnig the scripts via the
4
+ the creation of scripts from YAML files and running the scripts via the
5
5
  SimpleScriptEngine.
6
6
  """
7
7
 
@@ -26,21 +26,19 @@ along with ScriptEngine. If not, see <https://www.gnu.org/licenses/>.
26
26
  __license__ = "GPLv3+"
27
27
 
28
28
 
29
- import os
30
29
  import argparse
30
+ import importlib.metadata
31
31
  import logging
32
- import pkg_resources
32
+ import os
33
33
 
34
34
  import scriptengine.helpers.terminal_colors
35
35
  import scriptengine.logging
36
-
37
- from scriptengine.tasks.core.loader import load as load_tasks
38
- from scriptengine.yaml.parser import parse_file as parse_yaml_file
39
-
40
36
  from scriptengine.engines import SimpleScriptEngine
41
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
42
40
 
43
- __version__ = pkg_resources.get_distribution("scriptengine").version
41
+ __version__ = importlib.metadata.version("scriptengine")
44
42
 
45
43
 
46
44
  def parse_cmd_line_args():
@@ -138,9 +136,7 @@ def main():
138
136
  logger.critical("Could not parse all script files")
139
137
  return os.EX_DATAERR
140
138
 
141
- # Note that the following removal of duplicates does not guarantee the
142
- # order of entries before Python 3.7! We'll accept this in favour of the
143
- # easier implementation.
139
+ # Collect paths (and remove duplicates)
144
140
  script_path = tuple(
145
141
  dict.fromkeys((os.path.dirname(file) for file in parsed_args.files))
146
142
  )
@@ -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)
@@ -5,11 +5,12 @@ on the local machine, without consideration of job contexts. The
5
5
  SimpleScriptEngine relies on the Job class to run the actual tasks/jobs.
6
6
  """
7
7
 
8
+ import copy
8
9
  import logging
9
10
  import sys
10
11
  from pprint import pprint
11
12
 
12
- from scriptengine.context import Context, ContextUpdate, save_copy
13
+ from scriptengine.context import Context
13
14
  from scriptengine.exceptions import (
14
15
  ScriptEngineJobError,
15
16
  ScriptEngineStopException,
@@ -64,12 +65,14 @@ class SimpleScriptEngine:
64
65
  sys.exit()
65
66
 
66
67
  def run(self, script, context):
67
- local_context = Context(save_copy(context))
68
+ local_context = Context(context)
69
+ context_update = Context()
68
70
  for todo in script if isinstance(script, list) else [script]:
69
- context_update = self._guarded_run(todo, local_context)
70
- if context_update:
71
- local_context += context_update
72
- return ContextUpdate(context, local_context)
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
73
76
 
74
77
  def _log(self, level, msg):
75
78
  self.logger.log(level, 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):
@@ -1,4 +1,4 @@
1
- """ScripteEngine helpers: Colored terminal output
1
+ """ScriptEngine helpers: Colored terminal output
2
2
 
3
3
  Terminal markup and colors by using ANSI escape sequences. To print colored
4
4
  text, use, for example:
@@ -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
@@ -6,10 +6,11 @@ be given to a ScriptEngine, for execution.
6
6
  """
7
7
 
8
8
  import ast
9
+ import copy
9
10
  import logging
10
11
  import uuid
11
12
 
12
- from scriptengine.context import Context, ContextUpdate, save_copy
13
+ from scriptengine.context import Context
13
14
  from scriptengine.exceptions import (
14
15
  ScriptEngineJobParseError,
15
16
  ScriptEngineParseJinjaError,
@@ -74,29 +75,26 @@ class Job:
74
75
  def when(self, context):
75
76
  try:
76
77
  return self._when is None or j2render(self._when, context, boolean=True)
77
- except ScriptEngineParseJinjaError:
78
+ except ScriptEngineParseJinjaError as e:
78
79
  self.log_error(
79
- "Error while parsing (Jinja2) invalid when clause "
80
- f'"{self._when}" with context "{context}"'
80
+ f"Jinja2 error in *when* clause '{self._when}' (full error: {e})"
81
81
  )
82
82
  raise ScriptEngineJobParseError
83
83
 
84
84
  def loop_spec(self, context):
85
85
  try:
86
86
  iter = j2render(self._loop, context)
87
- except ScriptEngineParseJinjaError:
87
+ except ScriptEngineParseJinjaError as e:
88
88
  self.log_error(
89
- "Error while parsing (Jinja2) invalid loop expression "
90
- f'"{self._loop}" with context "{context}"'
89
+ f"Jinja2 error in *loop* spec '{self._loop}' (full error: {e})"
91
90
  )
92
91
  raise ScriptEngineJobParseError
93
92
  if isinstance(iter, str):
94
93
  try:
95
94
  iter = ast.literal_eval(iter or "None")
96
- except (SyntaxError, ValueError):
95
+ except (SyntaxError, ValueError) as e:
97
96
  self.log_error(
98
- "Error while evaluating (AST) invalid loop expression "
99
- f'"{iter}" with context "{context}"'
97
+ f"AST evaluation error in *loop* spec '{iter}' (full error: {e})"
100
98
  )
101
99
  raise ScriptEngineJobParseError
102
100
  if isinstance(iter, dict):
@@ -138,7 +136,8 @@ class Job:
138
136
 
139
137
  def run(self, context):
140
138
  if self.when(context):
141
- local_context = Context(save_copy(context))
139
+ local_context = Context(copy.deepcopy(context))
140
+ context_update = Context()
142
141
  for items in self.loop(local_context):
143
142
  if set(items) & set(local_context):
144
143
  self.log_warning(
@@ -146,10 +145,11 @@ class Job:
146
145
  f"context: {set(items) & set(local_context)}"
147
146
  )
148
147
  for t in self.todo:
149
- context_update = t.run(Context({**local_context, **items}))
150
- if context_update:
151
- local_context += context_update
152
- return ContextUpdate(context, local_context)
148
+ c = t.run(Context({**local_context, **items}))
149
+ if c:
150
+ local_context += c
151
+ context_update += c
152
+ return context_update or None
153
153
 
154
154
  def _log(self, level, msg):
155
155
  logging.getLogger("se.job").log(level, msg, extra={"id": self.shortid})
@@ -11,7 +11,7 @@ import subprocess
11
11
  import threading
12
12
  from contextlib import contextmanager
13
13
 
14
- from scriptengine.context import ContextUpdate
14
+ from scriptengine.context import Context
15
15
  from scriptengine.exceptions import (
16
16
  ScriptEngineTaskArgumentInvalidError,
17
17
  ScriptEngineTaskRunError,
@@ -111,7 +111,7 @@ class Command(Task):
111
111
  f'{stderr_mode if stderr_mode in (True, False) else "context"}'
112
112
  )
113
113
  with log_pipe(stdout_mode) as stdout, log_pipe(stderr_mode) as stderr:
114
- context_update = {}
114
+ context_update = Context()
115
115
  try:
116
116
  cmd_proc = subprocess.run(
117
117
  map(str, (command, *args)),
@@ -124,12 +124,20 @@ class Command(Task):
124
124
  except subprocess.CalledProcessError as e:
125
125
  if ignore_error:
126
126
  self.log_warning(f"Command returned error code {e.returncode}")
127
+ stdout = e.stdout
128
+ stderr = e.stderr
127
129
  else:
128
130
  self.log_error(f"Command returned error code {e.returncode}")
129
131
  raise ScriptEngineTaskRunError
130
132
  else:
131
- if isinstance(stdout_mode, str):
132
- context_update[stdout_mode] = cmd_proc.stdout.split("\n")
133
- if isinstance(stderr_mode, str):
134
- context_update[stderr_mode] = cmd_proc.stderr.split("\n")
135
- return ContextUpdate(context_update)
133
+ stdout = cmd_proc.stdout
134
+ stderr = cmd_proc.stderr
135
+
136
+ if isinstance(stdout_mode, str):
137
+ self.log_debug(f"Store stdout in context under {stdout_mode}")
138
+ context_update[stdout_mode] = stdout.split("\n")
139
+ if isinstance(stderr_mode, str):
140
+ self.log_debug(f"Store stderr in context under {stderr_mode}")
141
+ context_update[stderr_mode] = stderr.split("\n")
142
+
143
+ return context_update or None
@@ -2,7 +2,9 @@
2
2
 
3
3
  import yaml
4
4
 
5
- from scriptengine.context import ContextUpdate
5
+ from scriptengine.context import (
6
+ Context as SEContext,
7
+ ) # avoid name clashes between se.context.Context and se.tasks.base.Context
6
8
  from scriptengine.exceptions import ScriptEngineTaskError, ScriptEngineTaskRunError
7
9
  from scriptengine.tasks.core import Task, timed_runner
8
10
 
@@ -18,7 +20,7 @@ class Context(Task):
18
20
 
19
21
  @timed_runner
20
22
  def run(self, context):
21
- context_update = ContextUpdate(
23
+ context_update = SEContext(
22
24
  {n: self.getarg(n, context) for n in vars(self) if not n.startswith("_")}
23
25
  )
24
26
  self.log_info(f"Context update: {context_update}")
@@ -48,7 +50,6 @@ class ContextFrom(Task):
48
50
 
49
51
  @timed_runner
50
52
  def run(self, context):
51
-
52
53
  dict_arg = self.getarg("dict", context, default=False)
53
54
  file_arg = self.getarg("file", context, default=False)
54
55
 
@@ -93,4 +94,4 @@ class ContextFrom(Task):
93
94
  self.log_error("Missing argument: either 'dict' or 'file' is needed")
94
95
  raise ScriptEngineTaskError
95
96
 
96
- return ContextUpdate(context_update_d)
97
+ return SEContext(context_update_d)
@@ -2,7 +2,7 @@
2
2
 
3
3
  import os
4
4
 
5
- from scriptengine.context import ContextUpdate
5
+ from scriptengine.context import Context
6
6
  from scriptengine.tasks.core import Task, timed_runner
7
7
 
8
8
 
@@ -33,13 +33,13 @@ class Getenv(Task):
33
33
  valid[n] = os.environ[v]
34
34
  except KeyError:
35
35
  self.log_warning(f"Environment variable {v} does not exist")
36
- return ContextUpdate(valid)
36
+ return Context(valid)
37
37
 
38
38
 
39
39
  class Setenv(Task):
40
40
  """Setenv task, sets environment variables from context.
41
41
  Setenv.run() takes the list of argument name, value pairs, and sets the
42
- environemt variables given by the argument names to the values given by the
42
+ environment variables given by the argument names to the values given by the
43
43
  argument values. For example,
44
44
  base.setenv:
45
45
  foo: one
@@ -3,7 +3,7 @@
3
3
  import fnmatch
4
4
  import os
5
5
 
6
- from scriptengine.context import ContextUpdate
6
+ from scriptengine.context import Context
7
7
  from scriptengine.exceptions import ScriptEngineTaskArgumentInvalidError
8
8
  from scriptengine.tasks.core import Task, timed_runner
9
9
 
@@ -63,4 +63,4 @@ class Find(Task):
63
63
  result_key = self.getarg("set", context, default="result")
64
64
  self.log_debug(f'Store result under context key "{result_key}"')
65
65
 
66
- return ContextUpdate({result_key: result})
66
+ return Context({result_key: result})
@@ -4,9 +4,10 @@
4
4
  ScriptEngine script and lets the active ScriptEngine instance execute it.
5
5
  """
6
6
 
7
+ import copy
7
8
  from pathlib import Path
8
9
 
9
- from scriptengine.context import Context, ContextUpdate, save_copy
10
+ from scriptengine.context import Context
10
11
  from scriptengine.exceptions import ScriptEngineTaskRunError
11
12
  from scriptengine.tasks.core import Task, timed_runner
12
13
  from scriptengine.yaml.parser import parse_file
@@ -67,10 +68,8 @@ class Include(Task):
67
68
  script = parse_file(inc_file)
68
69
 
69
70
  self.log_debug(f"Execute include script: {inc_file}")
70
- local_context = Context(save_copy(context))
71
+ local_context = Context(copy.deepcopy(context))
71
72
  context_update = local_context["se"]["instance"].run(script, local_context)
72
- if context_update:
73
- local_context += context_update
74
73
  self.log_debug(f"Finished executing include script: {inc_file}")
75
74
 
76
- return ContextUpdate(context, local_context)
75
+ return context_update or None
@@ -1,13 +1,15 @@
1
1
  """Template task for ScriptEngine."""
2
2
 
3
- from pathlib import Path
4
3
  import os
5
4
  import stat
5
+ from pathlib import Path
6
+
6
7
  import jinja2
7
8
 
8
- from scriptengine.tasks.core import Task, timed_runner
9
- from scriptengine.jinja import render as j2render
9
+ from scriptengine.exceptions import ScriptEngineTaskRunError
10
10
  from scriptengine.jinja import filters as j2filters
11
+ from scriptengine.jinja import render as j2render
12
+ from scriptengine.tasks.core import Task, timed_runner
11
13
 
12
14
 
13
15
  class Template(Task):
@@ -54,7 +56,12 @@ class Template(Task):
54
56
  for name, function in j2filters().items():
55
57
  j2env.filters[name] = function
56
58
 
57
- output = j2render(j2env.get_template(src).render(context), context)
59
+ try:
60
+ output = j2render(j2env.get_template(src).render(context), context)
61
+ except jinja2.TemplateError as e:
62
+ self.log_error(f"Jinja2 error {type(e).__name__}: {e}")
63
+ raise ScriptEngineTaskRunError
64
+
58
65
  with dst.open(mode="w") as f:
59
66
  f.write(output + "\n")
60
67
 
@@ -0,0 +1,44 @@
1
+ import functools
2
+ import logging
3
+
4
+ try:
5
+ from importlib.metadata import entry_points
6
+ except ModuleNotFoundError: # Python prior to 3.8
7
+ from importlib_metadata import entry_points
8
+
9
+ from scriptengine.exceptions import ScriptEngineTaskLoaderError
10
+
11
+
12
+ # The load function goes through entry points, searching for ScriptEngine
13
+ # tasks. Since the function can be called quite frequently and modules are
14
+ # *usually* not loaded while SE is run, the result is cached.
15
+ # Note that this means that dynamic module is *not supported* by the loading
16
+ # mechanism!
17
+ @functools.lru_cache(maxsize=None)
18
+ def load():
19
+ loaded_tasks = dict()
20
+ try:
21
+ eps = entry_points(group="scriptengine.tasks")
22
+ except TypeError: # importlib.metadata prior to Python 3.10
23
+ eps = set(entry_points().get("scriptengine.tasks", []))
24
+ for ep in eps:
25
+ if ep.name not in loaded_tasks:
26
+ loaded_tasks[ep.name] = ep.load()
27
+ else:
28
+ existing_ep = next(cep for cep in eps if cep.name == ep.name)
29
+ existing_mod = existing_ep.value.partition(":")[0]
30
+ clashing_mod = ep.value.partition(":")[0]
31
+ logging.getLogger("se.task.loader").error(
32
+ f'Same task name "{ep.name}" defined in modules '
33
+ f'"{existing_mod}" and "{clashing_mod}"'
34
+ )
35
+ raise ScriptEngineTaskLoaderError
36
+
37
+ return loaded_tasks
38
+
39
+
40
+ def load_and_register():
41
+ loaded_tasks = load()
42
+ for name, task in loaded_tasks.items():
43
+ task.register_name(name)
44
+ return loaded_tasks