scriptengine 1.0.0rc3__tar.gz → 1.1.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 (55) hide show
  1. {scriptengine-1.0.0rc3/src/scriptengine.egg-info → scriptengine-1.1.0}/PKG-INFO +2 -2
  2. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/pyproject.toml +3 -3
  3. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/context.py +1 -0
  4. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/engines/__init__.py +1 -1
  5. scriptengine-1.1.0/src/scriptengine/helpers/terminal_colors.py +117 -0
  6. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/jinja.py +14 -0
  7. scriptengine-1.1.0/src/scriptengine/logging.py +132 -0
  8. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/chdir.py +4 -4
  9. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/command.py +15 -0
  10. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/context.py +6 -8
  11. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/echo.py +6 -7
  12. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/exit.py +4 -8
  13. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/core/__init__.py +2 -2
  14. scriptengine-1.1.0/src/scriptengine/tasks/core/timing.py +63 -0
  15. {scriptengine-1.0.0rc3 → scriptengine-1.1.0/src/scriptengine.egg-info}/PKG-INFO +2 -2
  16. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine.egg-info/SOURCES.txt +1 -0
  17. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine.egg-info/entry_points.txt +1 -1
  18. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine.egg-info/requires.txt +1 -1
  19. scriptengine-1.1.0/tests/test_jinja_filters.py +143 -0
  20. scriptengine-1.0.0rc3/src/scriptengine/helpers/terminal_colors.py +0 -88
  21. scriptengine-1.0.0rc3/src/scriptengine/logging.py +0 -140
  22. scriptengine-1.0.0rc3/src/scriptengine/tasks/core/timing.py +0 -58
  23. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/LICENSE +0 -0
  24. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/README.md +0 -0
  25. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/setup.cfg +0 -0
  26. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/setup.py +0 -0
  27. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/__init__.py +0 -0
  28. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/cli/__init__.py +0 -0
  29. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/cli/se.py +0 -0
  30. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/engines/simple_script_engine.py +0 -0
  31. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/exceptions.py +0 -0
  32. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/helpers/__init__.py +0 -0
  33. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/jobs.py +0 -0
  34. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/__init__.py +0 -0
  35. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/__init__.py +0 -0
  36. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/envvars.py +0 -0
  37. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/file/__init__.py +0 -0
  38. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/file/copy.py +0 -0
  39. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/file/link.py +0 -0
  40. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/file/make_dir.py +0 -0
  41. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/file/move.py +0 -0
  42. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/file/remove.py +0 -0
  43. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/find.py +0 -0
  44. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/include.py +0 -0
  45. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/task_timer.py +0 -0
  46. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/template.py +0 -0
  47. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/base/time.py +1 -1
  48. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/core/loader.py +0 -0
  49. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/tasks/core/task.py +0 -0
  50. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/yaml/__init__.py +0 -0
  51. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/yaml/noparse_strings.py +0 -0
  52. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine/yaml/parser.py +0 -0
  53. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine.egg-info/dependency_links.txt +0 -0
  54. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/src/scriptengine.egg-info/top_level.txt +0 -0
  55. {scriptengine-1.0.0rc3 → scriptengine-1.1.0}/tests/test_logging.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: scriptengine
3
- Version: 1.0.0rc3
3
+ Version: 1.1.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
@@ -14,7 +14,7 @@ License-File: LICENSE
14
14
  Requires-Dist: python-dateutil
15
15
  Requires-Dist: deepmerge
16
16
  Requires-Dist: PyYAML
17
- Requires-Dist: jinja2
17
+ Requires-Dist: jinja2>=3.0.0
18
18
  Provides-Extra: tests
19
19
  Requires-Dist: coverage; extra == "tests"
20
20
  Requires-Dist: coveralls; extra == "tests"
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scriptengine"
7
- version = "1.0.0rc3"
7
+ version = "1.1.0"
8
8
  authors = [{ name = "Uwe Fladrich", email = "uwe.fladrich@protonmail.com" }]
9
9
  description = "A lightweight and extensible framework for executing scripts written in YAML"
10
10
  readme = "README.md"
@@ -18,7 +18,7 @@ dependencies = [
18
18
  "python-dateutil",
19
19
  "deepmerge",
20
20
  "PyYAML",
21
- "jinja2",
21
+ "jinja2>=3.0.0",
22
22
  ]
23
23
 
24
24
  [project.optional-dependencies]
@@ -39,7 +39,7 @@ se = "scriptengine.cli.se:main"
39
39
  "base.chdir" = "scriptengine.tasks.base.chdir:Chdir"
40
40
  "base.command" = "scriptengine.tasks.base.command:Command"
41
41
  "base.context" = "scriptengine.tasks.base.context:Context"
42
- "base.context.from" = "scriptengine.tasks.base.context:ContextFrom"
42
+ "base.context.load" = "scriptengine.tasks.base.context:ContextLoad"
43
43
  "base.copy" = "scriptengine.tasks.base.file.copy:Copy"
44
44
  "base.echo" = "scriptengine.tasks.base.echo:Echo"
45
45
  "base.exit" = "scriptengine.tasks.base.exit:Exit"
@@ -35,6 +35,7 @@ class Context(UserDict):
35
35
 
36
36
  def __getitem__(self, key: Any) -> Any:
37
37
  """Return x[key] where key is possibly a dotted key"""
38
+
38
39
  def iter_getitem(data, subkey):
39
40
  try:
40
41
  return data[subkey]
@@ -3,4 +3,4 @@
3
3
  This module provides script engines, which can run lists of jobs.
4
4
  """
5
5
 
6
- from .simple_script_engine import SimpleScriptEngine
6
+ from .simple_script_engine import SimpleScriptEngine as SimpleScriptEngine
@@ -0,0 +1,117 @@
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
+ "BOLD": "\033[01m",
34
+ "DIM": "\033[02m",
35
+ "UNDERLINE": "\033[04m",
36
+ "REVERSE": "\033[07m",
37
+ "STRIKETHROUGH": "\033[09m",
38
+ "INVISIBLE": "\033[08m",
39
+ "BLACK": "\033[30m",
40
+ "RED": "\033[31m",
41
+ "GREEN": "\033[32m",
42
+ "ORANGE": "\033[33m",
43
+ "BLUE": "\033[34m",
44
+ "PURPLE": "\033[35m",
45
+ "CYAN": "\033[36m",
46
+ "LIGHTGREY": "\033[37m",
47
+ "DARKGREY": "\033[90m",
48
+ "LIGHTRED": "\033[91m",
49
+ "LIGHTGREEN": "\033[92m",
50
+ "YELLOW": "\033[93m",
51
+ "LIGHTBLUE": "\033[94m",
52
+ "PINK": "\033[95m",
53
+ "LIGHTCYAN": "\033[96m",
54
+ "BG_BLACK": "\033[40m",
55
+ "BG_RED": "\033[41m",
56
+ "BG_GREEN": "\033[42m",
57
+ "BG_ORANGE": "\033[43m",
58
+ "BG_BLUE": "\033[44m",
59
+ "BG_PURPLE": "\033[45m",
60
+ "BG_CYAN": "\033[46m",
61
+ "BG_LIGHTGREY": "\033[47m",
62
+ },
63
+ "none": {
64
+ "RESET": "",
65
+ "BOLD": "",
66
+ "DIM": "",
67
+ "UNDERLINE": "",
68
+ "REVERSE": "",
69
+ "STRIKETHROUGH": "",
70
+ "INVISIBLE": "",
71
+ "BLACK": "",
72
+ "RED": "",
73
+ "GREEN": "",
74
+ "ORANGE": "",
75
+ "BLUE": "",
76
+ "PURPLE": "",
77
+ "CYAN": "",
78
+ "LIGHTGREY": "",
79
+ "DARKGREY": "",
80
+ "LIGHTRED": "",
81
+ "LIGHTGREEN": "",
82
+ "YELLOW": "",
83
+ "LIGHTBLUE": "",
84
+ "PINK": "",
85
+ "LIGHTCYAN": "",
86
+ "BG_BLACK": "",
87
+ "BG_RED": "",
88
+ "BG_GREEN": "",
89
+ "BG_ORANGE": "",
90
+ "BG_BLUE": "",
91
+ "BG_PURPLE": "",
92
+ "BG_CYAN": "",
93
+ "BG_LIGHTGREY": "",
94
+ },
95
+ }
96
+
97
+
98
+ def set_theme(theme):
99
+ """Changes the active color theme"""
100
+ global ACTIVE_THEME
101
+ if theme not in COLORTABLE.keys():
102
+ raise ScriptEngineError(f'Invalid terminal color scheme: "{theme}"')
103
+ ACTIVE_THEME = theme
104
+
105
+ # Clean all present color settings
106
+ for color in {c for t in COLORTABLE for c in COLORTABLE[t]}:
107
+ if hasattr(sys.modules[__name__], color):
108
+ delattr(sys.modules[__name__], color)
109
+
110
+ # Set colors for new theme
111
+ for color, value in COLORTABLE[theme].items():
112
+ setattr(sys.modules[__name__], color, value)
113
+
114
+
115
+ # Set default colors
116
+ for _color, _value in COLORTABLE[ACTIVE_THEME].items():
117
+ setattr(sys.modules[__name__], _color, _value)
@@ -18,6 +18,13 @@ def string_to_date(string, format="%Y-%m-%d %H:%M:%S"):
18
18
  return datetime.datetime.strptime(string, format).date()
19
19
 
20
20
 
21
+ def increment_datetime(dt, days=0, hours=0, minutes=0, seconds=0):
22
+ """Jinja2 filter to increment datetime by a number of days/hours/minutes/seconds"""
23
+ return dt + datetime.timedelta(
24
+ days=days, hours=hours, minutes=minutes, seconds=seconds
25
+ )
26
+
27
+
21
28
  def basename(path):
22
29
  """Jinja2 filter that returns a path's base name"""
23
30
  return os.path.basename(path)
@@ -38,15 +45,22 @@ def path_join(pathlist):
38
45
  return os.path.join(*pathlist)
39
46
 
40
47
 
48
+ @jinja2.pass_context
49
+ def render_filter(context, expression):
50
+ return render(expression, context)
51
+
52
+
41
53
  def filters():
42
54
  """Return all defined Jinja2 filters by their name and corresponding function"""
43
55
  return {
44
56
  "datetime": string_to_datetime,
45
57
  "date": string_to_date,
58
+ "increment_datetime": increment_datetime,
46
59
  "basename": basename,
47
60
  "dirname": dirname,
48
61
  "exists": exists,
49
62
  "path_join": path_join,
63
+ "render": render_filter,
50
64
  }
51
65
 
52
66
 
@@ -0,0 +1,132 @@
1
+ """ ScriptEngine logging.
2
+ """
3
+
4
+ import logging
5
+ import logging.config
6
+
7
+ from scriptengine.helpers import terminal_colors as tc
8
+
9
+
10
+ class LogLevelFormatter:
11
+
12
+ def __init__(self, formatters):
13
+ self._formatters = formatters
14
+
15
+ def format(self, record):
16
+ return self._formatters[record.levelno].format(record)
17
+
18
+
19
+ def configure(log_level=logging.INFO):
20
+
21
+ levels = [
22
+ logging.DEBUG,
23
+ logging.INFO,
24
+ logging.WARNING,
25
+ logging.ERROR,
26
+ logging.CRITICAL,
27
+ ]
28
+
29
+ colors = {
30
+ logging.DEBUG: tc.CYAN,
31
+ logging.INFO: tc.GREEN,
32
+ logging.WARNING: tc.ORANGE,
33
+ logging.ERROR: tc.RED,
34
+ logging.CRITICAL: tc.RED,
35
+ }
36
+
37
+ formats = {
38
+ "basic": {
39
+ lvl: f"{colors[lvl]}{{asctime}} "
40
+ f"{tc.BOLD}{{levelname}}{tc.RESET}{colors[lvl]} "
41
+ f"[{{name}}] {{message}}"
42
+ f"{tc.RESET}"
43
+ for lvl in levels
44
+ },
45
+ "with_id": {
46
+ lvl: f"{colors[lvl]}{{asctime}} "
47
+ f"{tc.BOLD}{{levelname}}{tc.RESET}{colors[lvl]} "
48
+ f"[{{name}} <{{id}}>] {{message}}"
49
+ f"{tc.RESET}"
50
+ for lvl in levels
51
+ },
52
+ "with_id_and_type": {
53
+ lvl: f"{colors[lvl]}{{asctime}} "
54
+ f"{tc.BOLD}{{levelname}}{tc.RESET}{colors[lvl]} "
55
+ f"[{{name}}:{{type}} <{{id}}>] {{message}}"
56
+ f"{tc.RESET}"
57
+ for lvl in levels
58
+ },
59
+ }
60
+
61
+ date_format = "%Y-%m-%d %H:%M:%S"
62
+
63
+ configuration = dict(
64
+ version=1,
65
+ formatters={
66
+ "basic": {
67
+ "()": "scriptengine.logging.LogLevelFormatter",
68
+ "formatters": {
69
+ lvl: logging.Formatter(
70
+ fmt=formats["basic"][lvl], style="{", datefmt=date_format
71
+ )
72
+ for lvl in levels
73
+ },
74
+ },
75
+ "job": {
76
+ "()": "scriptengine.logging.LogLevelFormatter",
77
+ "formatters": {
78
+ lvl: logging.Formatter(
79
+ fmt=formats["with_id"][lvl], style="{", datefmt=date_format
80
+ )
81
+ for lvl in levels
82
+ },
83
+ },
84
+ "task": {
85
+ "()": "scriptengine.logging.LogLevelFormatter",
86
+ "formatters": {
87
+ lvl: logging.Formatter(
88
+ fmt=formats["with_id_and_type"][lvl],
89
+ style="{",
90
+ datefmt=date_format,
91
+ )
92
+ for lvl in levels
93
+ },
94
+ },
95
+ },
96
+ handlers={
97
+ "default": {
98
+ "class": "logging.StreamHandler",
99
+ "formatter": "basic",
100
+ },
101
+ "job": {
102
+ "class": "logging.StreamHandler",
103
+ "formatter": "job",
104
+ },
105
+ "task": {
106
+ "class": "logging.StreamHandler",
107
+ "formatter": "task",
108
+ },
109
+ },
110
+ loggers={
111
+ "se": {
112
+ "handlers": ["default"],
113
+ "level": log_level,
114
+ },
115
+ "se.job": {
116
+ "handlers": ["job"],
117
+ "level": log_level,
118
+ "propagate": False,
119
+ },
120
+ "se.task": {
121
+ "handlers": ["task"],
122
+ "level": log_level,
123
+ "propagate": False,
124
+ },
125
+ "se.task.loader": {
126
+ "handlers": ["default"],
127
+ "level": log_level,
128
+ "propagate": False,
129
+ },
130
+ },
131
+ )
132
+ logging.config.dictConfig(configuration)
@@ -6,9 +6,9 @@ from scriptengine.tasks.core import Task, timed_runner
6
6
 
7
7
 
8
8
  class Chdir(Task):
9
- """Chdir task, changes the current working directory
10
- """
11
- _required_arguments = ('path', )
9
+ """Chdir task, changes the current working directory"""
10
+
11
+ _required_arguments = ("path",)
12
12
 
13
13
  def __init__(self, arguments):
14
14
  Chdir.check_arguments(arguments)
@@ -16,6 +16,6 @@ class Chdir(Task):
16
16
 
17
17
  @timed_runner
18
18
  def run(self, context):
19
- path = self.getarg('path', context)
19
+ path = self.getarg("path", context)
20
20
  self.log_info(f"Change path to {path}")
21
21
  os.chdir(path)
@@ -10,6 +10,7 @@ import os
10
10
  import subprocess
11
11
  import threading
12
12
  from contextlib import contextmanager
13
+ from pathlib import Path
13
14
 
14
15
  from scriptengine.context import Context
15
16
  from scriptengine.exceptions import (
@@ -110,6 +111,19 @@ 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
128
  context_update = Context()
115
129
  try:
@@ -119,6 +133,7 @@ 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:
@@ -27,7 +27,7 @@ class Context(Task):
27
27
  return context_update
28
28
 
29
29
 
30
- class ContextFrom(Task):
30
+ class ContextLoad(Task):
31
31
  """
32
32
  This task updates the context, just as the Context task, but from sources
33
33
  other than direct arguments.
@@ -38,13 +38,13 @@ class ContextFrom(Task):
38
38
  - base.context:
39
39
  upd:
40
40
  foo: 1
41
- - base.context.from:
41
+ - base.context.load:
42
42
  dict: "{{upd}}"
43
43
 
44
44
  If the 'file' argument is given, the argument value must be a file name and
45
45
  the context is updated from the file context. The file format must be YAML:
46
46
 
47
- - base.context.from:
47
+ - base.context.load:
48
48
  file: update.yml
49
49
  """
50
50
 
@@ -58,7 +58,7 @@ class ContextFrom(Task):
58
58
  raise ScriptEngineTaskError
59
59
 
60
60
  if dict_arg:
61
- self.log_info(f"Context update from dict: {dict_arg}")
61
+ self.log_info(f"Load context update from dict: {dict_arg}")
62
62
  if not isinstance(dict_arg, dict):
63
63
  self.log_error(
64
64
  "The 'dict' argument must be a dictionary "
@@ -68,7 +68,7 @@ class ContextFrom(Task):
68
68
  context_update_d = dict_arg
69
69
 
70
70
  elif file_arg:
71
- self.log_info(f"Context update from file: {file_arg}")
71
+ self.log_info(f"Load context update from file: {file_arg}")
72
72
  try:
73
73
  with open(file_arg) as f:
74
74
  dict_from_file = yaml.load(f, Loader=yaml.SafeLoader)
@@ -78,9 +78,7 @@ class ContextFrom(Task):
78
78
  except yaml.scanner.ScannerError as e:
79
79
  self.log_error("Error reading the file as YAML, error message follows:")
80
80
  self.log_error(f" {''.join(str(e).splitlines())}")
81
- self.log_error(
82
- "Note that only YAML file are supported by base.context.from"
83
- )
81
+ self.log_error("Note: base.context.load supports only YAML files")
84
82
  raise ScriptEngineTaskRunError
85
83
  if not isinstance(dict_from_file, dict):
86
84
  self.log_error(
@@ -1,14 +1,13 @@
1
1
  """Echo task for ScriptEngine."""
2
2
 
3
- from scriptengine.tasks.core import Task, timed_runner
4
3
  from scriptengine.helpers import terminal_colors as tc
4
+ from scriptengine.tasks.core import Task, timed_runner
5
5
 
6
6
 
7
7
  class Echo(Task):
8
- """Echo task, writes a (coloured) message to stdout
9
- """
8
+ """Echo task, writes a (coloured) message to stdout"""
10
9
 
11
- _required_arguments = ('msg', )
10
+ _required_arguments = ("msg",)
12
11
 
13
12
  def __init__(self, arguments):
14
13
  Echo.check_arguments(arguments)
@@ -20,8 +19,8 @@ class Echo(Task):
20
19
  @timed_runner
21
20
  def run(self, context):
22
21
 
23
- log_msg = self.msg.replace('\n', '')
24
- self.log_info(log_msg[:15]+'...' if len(log_msg) > 18 else log_msg)
22
+ log_msg = self.msg.replace("\n", "")
23
+ self.log_info(log_msg[:15] + "..." if len(log_msg) > 18 else log_msg)
25
24
 
26
- msg = self.getarg('msg', context)
25
+ msg = self.getarg("msg", context)
27
26
  print(tc.LIGHTBLUE + str(msg) + tc.RESET)
@@ -1,18 +1,14 @@
1
1
  """Exit task for ScriptEngine."""
2
2
 
3
- from scriptengine.tasks.core import Task
4
3
  from scriptengine.exceptions import ScriptEngineStopException
4
+ from scriptengine.tasks.core import Task
5
5
 
6
6
 
7
7
  class Exit(Task):
8
- """Exit task, run method throws ScriptEngineStopException
9
- """
8
+ """Exit task, run method throws ScriptEngineStopException"""
9
+
10
10
  def run(self, context):
11
11
  self.log_info(
12
- self.getarg(
13
- 'msg',
14
- context,
15
- default='Requesting ScriptEngine to STOP'
16
- )
12
+ self.getarg("msg", context, default="Requesting ScriptEngine to STOP")
17
13
  )
18
14
  raise ScriptEngineStopException
@@ -10,5 +10,5 @@ This module provides
10
10
  - a timing wrapper for Task.run() functions
11
11
  """
12
12
 
13
- from .task import Task
14
- from .timing import timed_runner
13
+ from .task import Task as Task
14
+ from .timing import timed_runner as timed_runner
@@ -0,0 +1,63 @@
1
+ """ScriptEngine timing for tasks: provides timing of Task classes .run() method
2
+ """
3
+
4
+ import copy
5
+ import functools
6
+ import time
7
+
8
+ from scriptengine.context import Context
9
+
10
+
11
+ def timed_runner(func):
12
+ """Wrapper for run() functions of SE tasks. To be used as decorator as follows:
13
+
14
+ from scriptengine.task_timing import timed_runner
15
+ class Foo(Task):
16
+ # ...
17
+ @timed_runner
18
+ def run(self, context):
19
+ # ...
20
+ """
21
+
22
+ @functools.wraps(func)
23
+ def wrap_timed(self, context):
24
+
25
+ mode = context.get("se.tasks.timing.mode")
26
+
27
+ if mode in ("basic", "classes", "instances"):
28
+
29
+ # timed function call
30
+ start_tic = time.perf_counter()
31
+ context_update = func(self, context) or Context()
32
+ elapsed_time = time.perf_counter() - start_tic
33
+
34
+ # logging
35
+ if context["se.tasks.timing.logging"] == "info":
36
+ self.log_info(f"Elapsed time: {elapsed_time:0.4f} seconds")
37
+ elif context["se.tasks.timing.logging"] == "debug":
38
+ self.log_debug(f"Elapsed time: {elapsed_time:0.4f} seconds")
39
+
40
+ # update timers
41
+ if mode in ("classes", "instances"):
42
+ timers = copy.deepcopy(context["se.tasks.timing.timers"])
43
+
44
+ class_t = timers.setdefault("classes", {})
45
+ class_t.setdefault(self.__class__.__name__, 0)
46
+ class_t[self.__class__.__name__] += elapsed_time
47
+
48
+ if mode == "instances":
49
+ instance_t = timers.setdefault("instances", {})
50
+ instance_t.setdefault(self.id, 0)
51
+ instance_t[self.id] += elapsed_time
52
+
53
+ timer_update = Context()
54
+ timer_update["se.tasks.timing.timers"] = timers
55
+
56
+ context_update += timer_update
57
+
58
+ return context_update
59
+
60
+ # if no timing, just return the function
61
+ return func(self, context)
62
+
63
+ return wrap_timed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: scriptengine
3
- Version: 1.0.0rc3
3
+ Version: 1.1.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
@@ -14,7 +14,7 @@ License-File: LICENSE
14
14
  Requires-Dist: python-dateutil
15
15
  Requires-Dist: deepmerge
16
16
  Requires-Dist: PyYAML
17
- Requires-Dist: jinja2
17
+ Requires-Dist: jinja2>=3.0.0
18
18
  Provides-Extra: tests
19
19
  Requires-Dist: coverage; extra == "tests"
20
20
  Requires-Dist: coveralls; extra == "tests"
@@ -46,4 +46,5 @@ src/scriptengine/tasks/core/timing.py
46
46
  src/scriptengine/yaml/__init__.py
47
47
  src/scriptengine/yaml/noparse_strings.py
48
48
  src/scriptengine/yaml/parser.py
49
+ tests/test_jinja_filters.py
49
50
  tests/test_logging.py
@@ -5,7 +5,7 @@ se = scriptengine.cli.se:main
5
5
  base.chdir = scriptengine.tasks.base.chdir:Chdir
6
6
  base.command = scriptengine.tasks.base.command:Command
7
7
  base.context = scriptengine.tasks.base.context:Context
8
- base.context.from = scriptengine.tasks.base.context:ContextFrom
8
+ base.context.load = scriptengine.tasks.base.context:ContextLoad
9
9
  base.copy = scriptengine.tasks.base.file.copy:Copy
10
10
  base.echo = scriptengine.tasks.base.echo:Echo
11
11
  base.exit = scriptengine.tasks.base.exit:Exit
@@ -1,7 +1,7 @@
1
1
  python-dateutil
2
2
  deepmerge
3
3
  PyYAML
4
- jinja2
4
+ jinja2>=3.0.0
5
5
 
6
6
  [all]
7
7
  scriptengine[docs,tests]
@@ -0,0 +1,143 @@
1
+ from datetime import date, datetime
2
+
3
+ import pytest
4
+ import yaml
5
+
6
+ from scriptengine.context import Context as SEContext
7
+ from scriptengine.yaml.parser import parse
8
+
9
+
10
+ def from_yaml(string):
11
+ return parse(yaml.load(string, Loader=yaml.FullLoader))
12
+
13
+
14
+ @pytest.mark.parametrize("test_value", (1, 1.5, "a_string"))
15
+ def test_jinja_no_filter(test_value):
16
+ context = SEContext(bar=test_value)
17
+ task = from_yaml("base.context: {foo: '{{ bar }}'}")
18
+ context += task.run(context)
19
+ assert context["foo"] == test_value
20
+
21
+
22
+ @pytest.mark.parametrize(
23
+ ("test_value", "format", "expected"),
24
+ (
25
+ ("2024/01/01", "%Y/%m/%d", date(2024, 1, 1)),
26
+ ("2024-01-01", "%Y-%m-%d", date(2024, 1, 1)),
27
+ ("2024-01-01 00:00:00", "%Y-%m-%d %H:%M:%S", date(2024, 1, 1)),
28
+ ),
29
+ )
30
+ def test_jinja_string_to_date(test_value, format, expected):
31
+ context = SEContext()
32
+ task = from_yaml(
33
+ f"""base.context: {{foo: "{{{{ '{test_value}' | date('{format}') }}}}"}}"""
34
+ )
35
+ context += task.run(context)
36
+ assert context["foo"] == expected
37
+
38
+
39
+ @pytest.mark.parametrize(
40
+ ("test_value", "format", "expected"),
41
+ (
42
+ ("2024-01-01", "%Y-%m-%d", datetime(2024, 1, 1)),
43
+ ("2024-01-01 00:00:00", "%Y-%m-%d %H:%M:%S", datetime(2024, 1, 1)),
44
+ ("2024-01-01 12:34:56", "%Y-%m-%d %H:%M:%S", datetime(2024, 1, 1, 12, 34, 56)),
45
+ ),
46
+ )
47
+ def test_jinja_string_to_datetime(test_value, format, expected):
48
+ context = SEContext()
49
+ task = from_yaml(
50
+ f"""base.context: {{foo: "{{{{ '{test_value}' | datetime('{format}') }}}}"}}"""
51
+ )
52
+ context += task.run(context)
53
+ assert context["foo"] == expected
54
+
55
+
56
+ @pytest.mark.parametrize(
57
+ ("start", "days", "hours", "minutes", "expected"),
58
+ (
59
+ ("2024-01-01 00:00:00", 0, 0, 0, datetime(2024, 1, 1)),
60
+ ("2024-01-01 00:00:00", 1, 0, 0, datetime(2024, 1, 2)),
61
+ ("2024-01-01 00:00:00", 0, 1, 0, datetime(2024, 1, 1, 1, 0)),
62
+ ),
63
+ )
64
+ def test_jinja_filter_increment_datetime(start, days, hours, minutes, expected):
65
+ context = SEContext()
66
+ task = from_yaml(
67
+ f"""
68
+ base.context:
69
+ foo: "{{{{ '{start}' | datetime | increment_datetime(days={days}, hours={hours}, minutes={minutes}) }}}}"
70
+ """
71
+ )
72
+ context += task.run(context)
73
+ assert context["foo"] == expected
74
+
75
+
76
+ @pytest.mark.parametrize(
77
+ ("test_value", "expected"),
78
+ (
79
+ ("foo", "foo"),
80
+ ("foo.txt", "foo.txt"),
81
+ ("/foo.txt", "foo.txt"),
82
+ ("/bar/foo.txt", "foo.txt"),
83
+ ("bar/foo.txt", "foo.txt"),
84
+ ("./foo.txt", "foo.txt"),
85
+ ),
86
+ )
87
+ def test_jinja_filter_basetime(test_value, expected):
88
+ context = SEContext(bar=test_value)
89
+ task = from_yaml("base.context: {foo: '{{ bar | basename }}'}")
90
+ context += task.run(context)
91
+ assert context["foo"] == expected
92
+
93
+
94
+ @pytest.mark.parametrize(
95
+ ("test_value", "expected"),
96
+ (
97
+ ("foo", None),
98
+ ("foo.txt", None),
99
+ ("/foo.txt", "/"),
100
+ ("/bar/foo.txt", "/bar"),
101
+ ("bar/foo.txt", "bar"),
102
+ ("./foo.txt", "."),
103
+ ),
104
+ )
105
+ def test_jinja_filter_dirtime(test_value, expected):
106
+ context = SEContext(bar=test_value)
107
+ task = from_yaml("base.context: {foo: '{{ bar | dirname }}'}")
108
+ context += task.run(context)
109
+ assert context["foo"] == expected
110
+
111
+
112
+ def test_jinja_filter_file_exist(tmp_path):
113
+ context = SEContext()
114
+ file = tmp_path / "foo.tmp"
115
+ file.touch()
116
+ task = from_yaml(f"""base.context: {{foo: "{{{{ '{file}' | exists }}}}"}}""")
117
+ context += task.run(context)
118
+ assert context["foo"] is True
119
+
120
+
121
+ def test_jinja_filter_dir_exist(tmp_path):
122
+ context = SEContext()
123
+ directory = tmp_path / "foo"
124
+ directory.mkdir()
125
+ task = from_yaml(f"""base.context: {{foo: "{{{{ '{directory}' | exists }}}}"}}""")
126
+ context += task.run(context)
127
+ assert context["foo"] is True
128
+
129
+
130
+ def test_jinja_filter_file_does_not_exist(tmp_path):
131
+ context = SEContext()
132
+ file = tmp_path / "foo.tmp"
133
+ task = from_yaml(f"""base.context: {{foo: "{{{{ '{file}' | exists }}}}"}}""")
134
+ context += task.run(context)
135
+ assert context["foo"] is False
136
+
137
+
138
+ def test_jinja_filter_dir_does_not_exist(tmp_path):
139
+ context = SEContext()
140
+ directory = tmp_path / "foo"
141
+ task = from_yaml(f"""base.context: {{foo: "{{{{ '{directory}' | exists }}}}"}}""")
142
+ context += task.run(context)
143
+ assert context["foo"] is False
@@ -1,88 +0,0 @@
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,140 +0,0 @@
1
- """ ScriptEngine logging.
2
- """
3
-
4
- import logging
5
- import logging.config
6
-
7
- from scriptengine.helpers import terminal_colors as tc
8
-
9
-
10
- class LogLevelFormatter:
11
-
12
- def __init__(self, formatters):
13
- self._formatters = formatters
14
-
15
- def format(self, record):
16
- return self._formatters[record.levelno].format(record)
17
-
18
-
19
- def configure(log_level=logging.INFO):
20
-
21
- levels = [
22
- logging.DEBUG,
23
- logging.INFO,
24
- logging.WARNING,
25
- logging.ERROR,
26
- logging.CRITICAL,
27
- ]
28
-
29
- colors = {
30
- logging.DEBUG: tc.CYAN,
31
- logging.INFO: tc.GREEN,
32
- logging.WARNING: tc.ORANGE,
33
- logging.ERROR: tc.RED,
34
- logging.CRITICAL: tc.RED,
35
- }
36
-
37
- formats = {
38
- 'basic': {
39
- lvl: f'{colors[lvl]}{{asctime}} '
40
- f'{tc.BOLD}{{levelname}}{tc.RESET}{colors[lvl]} '
41
- f'[{{name}}] {{message}}'
42
- f'{tc.RESET}'
43
- for lvl in levels
44
- },
45
- 'with_id': {
46
- lvl: f'{colors[lvl]}{{asctime}} '
47
- f'{tc.BOLD}{{levelname}}{tc.RESET}{colors[lvl]} '
48
- f'[{{name}} <{{id}}>] {{message}}'
49
- f'{tc.RESET}'
50
- for lvl in levels
51
- },
52
- 'with_id_and_type': {
53
- lvl: f'{colors[lvl]}{{asctime}} '
54
- f'{tc.BOLD}{{levelname}}{tc.RESET}{colors[lvl]} '
55
- f'[{{name}}:{{type}} <{{id}}>] {{message}}'
56
- f'{tc.RESET}'
57
- for lvl in levels
58
- },
59
- }
60
-
61
- date_format = '%Y-%m-%d %H:%M:%S'
62
-
63
- configuration = dict(
64
-
65
- version=1,
66
-
67
- formatters={
68
- 'basic': {
69
- '()': 'scriptengine.logging.LogLevelFormatter',
70
- 'formatters': {
71
- lvl: logging.Formatter(
72
- fmt=formats['basic'][lvl],
73
- style='{',
74
- datefmt=date_format
75
- )
76
- for lvl in levels
77
- }
78
- },
79
- 'job': {
80
- '()': 'scriptengine.logging.LogLevelFormatter',
81
- 'formatters': {
82
- lvl: logging.Formatter(
83
- fmt=formats['with_id'][lvl],
84
- style='{',
85
- datefmt=date_format
86
- )
87
- for lvl in levels
88
- }
89
- },
90
- 'task': {
91
- '()': 'scriptengine.logging.LogLevelFormatter',
92
- 'formatters': {
93
- lvl: logging.Formatter(
94
- fmt=formats['with_id_and_type'][lvl],
95
- style='{',
96
- datefmt=date_format
97
- )
98
- for lvl in levels
99
- }
100
- },
101
- },
102
-
103
- handlers={
104
- 'default': {
105
- 'class': 'logging.StreamHandler',
106
- 'formatter': 'basic',
107
- },
108
- 'job': {
109
- 'class': 'logging.StreamHandler',
110
- 'formatter': 'job',
111
- },
112
- 'task': {
113
- 'class': 'logging.StreamHandler',
114
- 'formatter': 'task',
115
- },
116
- },
117
-
118
- loggers={
119
- 'se': {
120
- 'handlers': ['default'],
121
- 'level': log_level,
122
- },
123
- 'se.job': {
124
- 'handlers': ['job'],
125
- 'level': log_level,
126
- 'propagate': False,
127
- },
128
- 'se.task': {
129
- 'handlers': ['task'],
130
- 'level': log_level,
131
- 'propagate': False,
132
- },
133
- 'se.task.loader': {
134
- 'handlers': ['default'],
135
- 'level': log_level,
136
- 'propagate': False,
137
- },
138
- },
139
- )
140
- logging.config.dictConfig(configuration)
@@ -1,58 +0,0 @@
1
- """ScriptEngine timing for tasks: provides timing of Task classes .run() method
2
- """
3
-
4
- import time
5
- import functools
6
-
7
-
8
- def timed_runner(func):
9
- """Wrapper for run() functions of SE tasks. To be used as decorator as follows:
10
-
11
- from scriptengine.task_timing import timed_runner
12
- class Foo(Task):
13
- # ...
14
- @timed_runner
15
- def run(self, context):
16
- # ...
17
- """
18
-
19
- @functools.wraps(func)
20
- def wrap_timed(self, context):
21
-
22
- try:
23
- mode = context['se']['tasks']['timing']['mode']
24
- except KeyError:
25
- mode = False
26
-
27
- if mode in ('basic', 'classes', 'instances'):
28
-
29
- # timed function call
30
- start_tic = time.perf_counter()
31
- func_return_value = func(self, context)
32
- elapsed_time = time.perf_counter() - start_tic
33
-
34
- # logging
35
- if context['se']['tasks']['timing']['logging'] == 'info':
36
- self.log_info(f'Elapsed time: {elapsed_time:0.4f} seconds')
37
- elif context['se']['tasks']['timing']['logging'] == 'debug':
38
- self.log_debug(f'Elapsed time: {elapsed_time:0.4f} seconds')
39
-
40
- # update timers
41
- if mode in ('classes', 'instances'):
42
- timers = context['se']['tasks']['timing']['timers']
43
-
44
- class_t = timers.setdefault('classes', {})
45
- class_t.setdefault(self.__class__.__name__, 0)
46
- class_t[self.__class__.__name__] += elapsed_time
47
-
48
- if mode == 'instances':
49
- instance_t = timers.setdefault('instances', {})
50
- instance_t.setdefault(self.id, 0)
51
- instance_t[self.id] += elapsed_time
52
-
53
- return func_return_value
54
-
55
- # if no timing, just return the function
56
- return func(self, context)
57
-
58
- return wrap_timed
File without changes
File without changes
File without changes
File without changes
@@ -4,8 +4,8 @@
4
4
 
5
5
  import datetime
6
6
 
7
- from scriptengine.tasks.core import Task, timed_runner
8
7
  from scriptengine.context import Context
8
+ from scriptengine.tasks.core import Task, timed_runner
9
9
 
10
10
 
11
11
  class Time(Task):