scriptengine 0.14.4__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 (59) hide show
  1. {scriptengine-0.14.4/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-0.14.4 → scriptengine-1.0.0/src}/scriptengine/cli/se.py +7 -11
  5. scriptengine-1.0.0/src/scriptengine/context.py +124 -0
  6. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/engines/simple_script_engine.py +9 -6
  7. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/exceptions.py +1 -1
  8. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/helpers/terminal_colors.py +1 -1
  9. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/jinja.py +13 -6
  10. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/jobs.py +15 -15
  11. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/command.py +30 -7
  12. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/context.py +11 -12
  13. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/envvars.py +3 -3
  14. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/find.py +2 -2
  15. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/include.py +4 -5
  16. scriptengine-1.0.0/src/scriptengine/tasks/base/task_timer.py +61 -0
  17. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/template.py +11 -4
  18. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/time.py +5 -7
  19. scriptengine-1.0.0/src/scriptengine/tasks/core/loader.py +44 -0
  20. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/core/task.py +56 -62
  21. scriptengine-1.0.0/src/scriptengine/tasks/core/timing.py +63 -0
  22. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/yaml/parser.py +1 -1
  23. {scriptengine-0.14.4 → scriptengine-1.0.0/src/scriptengine.egg-info}/PKG-INFO +15 -2
  24. scriptengine-1.0.0/src/scriptengine.egg-info/SOURCES.txt +49 -0
  25. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine.egg-info/entry_points.txt +1 -19
  26. scriptengine-1.0.0/src/scriptengine.egg-info/requires.txt +16 -0
  27. scriptengine-1.0.0/tests/test_logging.py +88 -0
  28. scriptengine-0.14.4/pyproject.toml +0 -71
  29. scriptengine-0.14.4/scriptengine/context.py +0 -96
  30. scriptengine-0.14.4/scriptengine/tasks/base/task_timer.py +0 -56
  31. scriptengine-0.14.4/scriptengine/tasks/core/loader.py +0 -40
  32. scriptengine-0.14.4/scriptengine/tasks/core/timing.py +0 -58
  33. scriptengine-0.14.4/scriptengine.egg-info/SOURCES.txt +0 -48
  34. scriptengine-0.14.4/scriptengine.egg-info/requires.txt +0 -5
  35. scriptengine-0.14.4/setup.py +0 -62
  36. {scriptengine-0.14.4 → scriptengine-1.0.0}/LICENSE +0 -0
  37. {scriptengine-0.14.4 → scriptengine-1.0.0}/README.md +0 -0
  38. {scriptengine-0.14.4 → scriptengine-1.0.0}/setup.cfg +0 -0
  39. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/__init__.py +0 -0
  40. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/cli/__init__.py +0 -0
  41. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/engines/__init__.py +0 -0
  42. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/helpers/__init__.py +0 -0
  43. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/logging.py +0 -0
  44. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/__init__.py +0 -0
  45. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/__init__.py +0 -0
  46. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/chdir.py +0 -0
  47. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/echo.py +0 -0
  48. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/exit.py +0 -0
  49. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/file/__init__.py +0 -0
  50. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/file/copy.py +0 -0
  51. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/file/link.py +0 -0
  52. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/file/make_dir.py +0 -0
  53. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/file/move.py +0 -0
  54. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/base/file/remove.py +0 -0
  55. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/tasks/core/__init__.py +0 -0
  56. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/yaml/__init__.py +0 -0
  57. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine/yaml/noparse_strings.py +0 -0
  58. {scriptengine-0.14.4 → scriptengine-1.0.0/src}/scriptengine.egg-info/dependency_links.txt +0 -0
  59. {scriptengine-0.14.4 → 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.4
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()
@@ -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})
@@ -10,8 +10,9 @@ import os
10
10
  import subprocess
11
11
  import threading
12
12
  from contextlib import contextmanager
13
+ from pathlib import Path
13
14
 
14
- from scriptengine.context import ContextUpdate
15
+ from scriptengine.context import Context
15
16
  from scriptengine.exceptions import (
16
17
  ScriptEngineTaskArgumentInvalidError,
17
18
  ScriptEngineTaskRunError,
@@ -110,8 +111,21 @@ class Command(Task):
110
111
  "stderr mode: "
111
112
  f'{stderr_mode if stderr_mode in (True, False) else "context"}'
112
113
  )
114
+
115
+ # Update $PWD in the environment of the command
116
+ # Once support for Python<=3.8 is dropped, this can be done directly in the
117
+ # call to subprocess.run() below:
118
+ # subprocess.run(
119
+ # ...
120
+ # env=os.environ | {"PWD": Path(cwd).resolve()} if cwd else {},
121
+ # ...
122
+ # )
123
+ cmd_env = os.environ.copy()
124
+ if cwd:
125
+ cmd_env["PWD"] = Path(cwd).resolve()
126
+
113
127
  with log_pipe(stdout_mode) as stdout, log_pipe(stderr_mode) as stderr:
114
- context_update = {}
128
+ context_update = Context()
115
129
  try:
116
130
  cmd_proc = subprocess.run(
117
131
  map(str, (command, *args)),
@@ -119,17 +133,26 @@ class Command(Task):
119
133
  stderr=stderr,
120
134
  cwd=cwd,
121
135
  check=True,
136
+ env=cmd_env,
122
137
  errors="replace",
123
138
  )
124
139
  except subprocess.CalledProcessError as e:
125
140
  if ignore_error:
126
141
  self.log_warning(f"Command returned error code {e.returncode}")
142
+ stdout = e.stdout
143
+ stderr = e.stderr
127
144
  else:
128
145
  self.log_error(f"Command returned error code {e.returncode}")
129
146
  raise ScriptEngineTaskRunError
130
147
  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)
148
+ stdout = cmd_proc.stdout
149
+ stderr = cmd_proc.stderr
150
+
151
+ if isinstance(stdout_mode, str):
152
+ self.log_debug(f"Store stdout in context under {stdout_mode}")
153
+ context_update[stdout_mode] = stdout.split("\n")
154
+ if isinstance(stderr_mode, str):
155
+ self.log_debug(f"Store stderr in context under {stderr_mode}")
156
+ context_update[stderr_mode] = stderr.split("\n")
157
+
158
+ 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,14 +20,14 @@ 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}")
25
27
  return context_update
26
28
 
27
29
 
28
- class ContextFrom(Task):
30
+ class ContextLoad(Task):
29
31
  """
30
32
  This task updates the context, just as the Context task, but from sources
31
33
  other than direct arguments.
@@ -36,19 +38,18 @@ class ContextFrom(Task):
36
38
  - base.context:
37
39
  upd:
38
40
  foo: 1
39
- - base.context.from:
41
+ - base.context.load:
40
42
  dict: "{{upd}}"
41
43
 
42
44
  If the 'file' argument is given, the argument value must be a file name and
43
45
  the context is updated from the file context. The file format must be YAML:
44
46
 
45
- - base.context.from:
47
+ - base.context.load:
46
48
  file: update.yml
47
49
  """
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
 
@@ -57,7 +58,7 @@ class ContextFrom(Task):
57
58
  raise ScriptEngineTaskError
58
59
 
59
60
  if dict_arg:
60
- self.log_info(f"Context update from dict: {dict_arg}")
61
+ self.log_info(f"Load context update from dict: {dict_arg}")
61
62
  if not isinstance(dict_arg, dict):
62
63
  self.log_error(
63
64
  "The 'dict' argument must be a dictionary "
@@ -67,7 +68,7 @@ class ContextFrom(Task):
67
68
  context_update_d = dict_arg
68
69
 
69
70
  elif file_arg:
70
- self.log_info(f"Context update from file: {file_arg}")
71
+ self.log_info(f"Load context update from file: {file_arg}")
71
72
  try:
72
73
  with open(file_arg) as f:
73
74
  dict_from_file = yaml.load(f, Loader=yaml.SafeLoader)
@@ -77,9 +78,7 @@ class ContextFrom(Task):
77
78
  except yaml.scanner.ScannerError as e:
78
79
  self.log_error("Error reading the file as YAML, error message follows:")
79
80
  self.log_error(f" {''.join(str(e).splitlines())}")
80
- self.log_error(
81
- "Note that only YAML file are supported by base.context.from"
82
- )
81
+ self.log_error("Note: base.context.load supports only YAML files")
83
82
  raise ScriptEngineTaskRunError
84
83
  if not isinstance(dict_from_file, dict):
85
84
  self.log_error(
@@ -93,4 +92,4 @@ class ContextFrom(Task):
93
92
  self.log_error("Missing argument: either 'dict' or 'file' is needed")
94
93
  raise ScriptEngineTaskError
95
94
 
96
- return ContextUpdate(context_update_d)
95
+ 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