command-execution 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- command_execution/__init__.py +12 -0
- command_execution/actions/__init__.py +26 -0
- command_execution/actions/application.py +137 -0
- command_execution/actions/domain.py +61 -0
- command_execution/actions/interpreters.py +11 -0
- command_execution/actions/process.py +15 -0
- command_execution/actions/transport.py +80 -0
- command_execution/configuration/__init__.py +57 -0
- command_execution/configuration/application.py +119 -0
- command_execution/configuration/domain.py +101 -0
- command_execution/configuration/json_file.py +53 -0
- command_execution/configuration/json_patch.py +35 -0
- command_execution-1.0.0.dist-info/METADATA +7 -0
- command_execution-1.0.0.dist-info/RECORD +16 -0
- command_execution-1.0.0.dist-info/WHEEL +5 -0
- command_execution-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Independent configuration and command preparation/execution APIs."""
|
|
2
|
+
__version__ = "1.0.0"
|
|
3
|
+
|
|
4
|
+
from .actions import execute_action, plan_action
|
|
5
|
+
from .configuration import (
|
|
6
|
+
add_requirement,
|
|
7
|
+
clear_requirements,
|
|
8
|
+
delete_requirement,
|
|
9
|
+
list_requirement_ids,
|
|
10
|
+
read_requirements,
|
|
11
|
+
update_requirement,
|
|
12
|
+
)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Public action operations composed with the external process adapter."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .application import ActionExecutor, ResultInterpreter, prepare_action
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def plan_action(
|
|
10
|
+
action: dict[str, Any], parameters: dict[str, Any], *,
|
|
11
|
+
base_dir: str | Path, interpreters: dict[str, ResultInterpreter],
|
|
12
|
+
) -> dict[str, Any]:
|
|
13
|
+
"""Prepare every declared command without running processes or interpreters."""
|
|
14
|
+
return prepare_action(action, parameters, base_dir=base_dir, interpreters=interpreters)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def execute_action(
|
|
18
|
+
action: dict[str, Any], parameters: dict[str, Any], *,
|
|
19
|
+
base_dir: str | Path, interpreters: dict[str, ResultInterpreter],
|
|
20
|
+
) -> dict[str, Any]:
|
|
21
|
+
"""Run the prepared chain and preserve each attempted command's full result."""
|
|
22
|
+
from .process import run_command
|
|
23
|
+
|
|
24
|
+
return ActionExecutor(run_command).execute(
|
|
25
|
+
action, parameters, base_dir=base_dir, interpreters=interpreters
|
|
26
|
+
)
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Prepare actions once and execute their ordered commands through narrow ports."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from string import Template
|
|
7
|
+
from typing import Any, Protocol
|
|
8
|
+
|
|
9
|
+
from .domain import declared_commands, interpreted_result, validate_command
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ResultInterpreter(Protocol):
|
|
13
|
+
def interpret(self, result: dict[str, Any], options: dict[str, Any]) -> dict[str, Any]:
|
|
14
|
+
...
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
ProcessRunner = Callable[[dict[str, Any]], dict[str, Any]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _prepare_command(
|
|
21
|
+
command: dict[str, Any], parameters: dict[str, Any], base_dir: Path, index: int
|
|
22
|
+
) -> dict[str, Any]:
|
|
23
|
+
try:
|
|
24
|
+
argv = [Template(part).substitute(parameters) for part in command["argv"]]
|
|
25
|
+
cwd = Template(command["cwd"]).substitute(parameters)
|
|
26
|
+
env = {
|
|
27
|
+
key: Template(value).substitute(parameters)
|
|
28
|
+
for key, value in command["env"].items()
|
|
29
|
+
}
|
|
30
|
+
except (KeyError, ValueError) as exc:
|
|
31
|
+
raise ValueError(f"commands[{index}] template: {exc}") from exc
|
|
32
|
+
prepared = dict(
|
|
33
|
+
argv=argv, cwd=cwd, env=env,
|
|
34
|
+
interpreter=deepcopy(command["interpreter"]),
|
|
35
|
+
)
|
|
36
|
+
validate_command(prepared, index)
|
|
37
|
+
directory = Path(cwd)
|
|
38
|
+
if not directory.is_absolute():
|
|
39
|
+
directory = base_dir / directory
|
|
40
|
+
prepared["cwd"] = str(directory)
|
|
41
|
+
return prepared
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def validate_execution_inputs(
|
|
45
|
+
parameters: dict[str, Any], base_dir: str | Path,
|
|
46
|
+
interpreters: dict[str, ResultInterpreter],
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Validate shared invocation inputs independently of command selection."""
|
|
49
|
+
if not isinstance(parameters, dict):
|
|
50
|
+
raise ValueError("parameters must be a scalar map")
|
|
51
|
+
for name, value in parameters.items():
|
|
52
|
+
if not isinstance(name, str) or not isinstance(value, (str, int, float, bool)):
|
|
53
|
+
raise ValueError(f"parameters[{name}]: expected a named scalar")
|
|
54
|
+
if (
|
|
55
|
+
not isinstance(base_dir, (str, Path)) or not str(base_dir)
|
|
56
|
+
or not Path(base_dir).is_absolute()
|
|
57
|
+
):
|
|
58
|
+
raise ValueError("base_dir must be an absolute path")
|
|
59
|
+
if not isinstance(interpreters, dict):
|
|
60
|
+
raise ValueError("interpreters must be a map")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def prepare_action(
|
|
64
|
+
action: dict[str, Any], parameters: dict[str, Any], *,
|
|
65
|
+
base_dir: str | Path, interpreters: dict[str, ResultInterpreter],
|
|
66
|
+
) -> dict[str, Any]:
|
|
67
|
+
commands = declared_commands(action)
|
|
68
|
+
validate_execution_inputs(parameters, base_dir, interpreters)
|
|
69
|
+
prepared = []
|
|
70
|
+
for index, command in enumerate(commands):
|
|
71
|
+
name = command["interpreter"]["name"]
|
|
72
|
+
if name not in interpreters or not callable(
|
|
73
|
+
getattr(interpreters[name], "interpret", None)
|
|
74
|
+
):
|
|
75
|
+
raise ValueError(f"commands[{index}].interpreter {name}: callable interpret is required")
|
|
76
|
+
prepared.append(_prepare_command(command, parameters, Path(base_dir), index))
|
|
77
|
+
return dict(commands=prepared)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ActionExecutor:
|
|
81
|
+
def __init__(self, run_command: ProcessRunner):
|
|
82
|
+
self._run_command = run_command
|
|
83
|
+
|
|
84
|
+
def execute(
|
|
85
|
+
self, action: dict[str, Any], parameters: dict[str, Any], *,
|
|
86
|
+
base_dir: str | Path, interpreters: dict[str, ResultInterpreter],
|
|
87
|
+
) -> dict[str, Any]:
|
|
88
|
+
plan = prepare_action(action, parameters, base_dir=base_dir, interpreters=interpreters)
|
|
89
|
+
records = []
|
|
90
|
+
error = None
|
|
91
|
+
for index, command in enumerate(plan["commands"]):
|
|
92
|
+
record = self._execute_command(
|
|
93
|
+
command, interpreters[command["interpreter"]["name"]], index
|
|
94
|
+
)
|
|
95
|
+
records.append(record)
|
|
96
|
+
error = record["error"]
|
|
97
|
+
if error is not None:
|
|
98
|
+
break
|
|
99
|
+
return dict(
|
|
100
|
+
status="succeeded" if error is None else "failed",
|
|
101
|
+
commands=records, error=error,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
def _execute_command(
|
|
105
|
+
self, command: dict[str, Any], interpreter: ResultInterpreter, index: int
|
|
106
|
+
) -> dict[str, Any]:
|
|
107
|
+
invocation = {field: deepcopy(command[field]) for field in ("argv", "cwd", "env")}
|
|
108
|
+
record = dict(
|
|
109
|
+
invocation=invocation, interpreter=deepcopy(command["interpreter"]),
|
|
110
|
+
exit_code=None, stdout=b"", stderr=b"", interpretation=None, error=None,
|
|
111
|
+
)
|
|
112
|
+
try:
|
|
113
|
+
raw = self._run_command(deepcopy(invocation))
|
|
114
|
+
except (OSError, ValueError) as exc:
|
|
115
|
+
record["error"] = f"commands[{index}] launch argv/cwd: {exc}"
|
|
116
|
+
return record
|
|
117
|
+
record.update(raw)
|
|
118
|
+
interpretation, error = self._interpret(raw, command["interpreter"], interpreter)
|
|
119
|
+
record.update(interpretation=interpretation, error=error)
|
|
120
|
+
return record
|
|
121
|
+
|
|
122
|
+
def _interpret(
|
|
123
|
+
self, raw: dict[str, Any], configuration: dict[str, Any], interpreter: ResultInterpreter
|
|
124
|
+
) -> tuple[dict[str, Any] | None, str | None]:
|
|
125
|
+
name = configuration["name"]
|
|
126
|
+
try:
|
|
127
|
+
answer = interpreter.interpret(
|
|
128
|
+
deepcopy(raw), deepcopy(configuration["options"])
|
|
129
|
+
)
|
|
130
|
+
interpretation = interpreted_result(answer)
|
|
131
|
+
except Exception as exc:
|
|
132
|
+
return None, f"interpreter {name}: {exc}"
|
|
133
|
+
error = (
|
|
134
|
+
None if interpretation["success"]
|
|
135
|
+
else f"interpreter {name}: {interpretation['error']}"
|
|
136
|
+
)
|
|
137
|
+
return interpretation, error
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Rules for declared command chains and interpreted execution outcomes."""
|
|
2
|
+
|
|
3
|
+
from copy import deepcopy
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def validate_command(command: dict[str, Any], index: int) -> None:
|
|
8
|
+
"""Apply the same required-field rules before and after substitution."""
|
|
9
|
+
context = f"commands[{index}]"
|
|
10
|
+
if not isinstance(command, dict):
|
|
11
|
+
raise ValueError(f"{context} must be an object")
|
|
12
|
+
argv = command.get("argv")
|
|
13
|
+
if (
|
|
14
|
+
not isinstance(argv, list) or not argv
|
|
15
|
+
or any(not isinstance(part, str) for part in argv) or not argv[0]
|
|
16
|
+
):
|
|
17
|
+
raise ValueError(f"{context}.argv must be a string array with a nonempty executable")
|
|
18
|
+
cwd = command.get("cwd")
|
|
19
|
+
if not isinstance(cwd, str) or not cwd:
|
|
20
|
+
raise ValueError(f"{context}.cwd must be a nonempty string")
|
|
21
|
+
env = command.get("env")
|
|
22
|
+
if not isinstance(env, dict) or any(
|
|
23
|
+
not isinstance(key, str) or not isinstance(value, str)
|
|
24
|
+
for key, value in env.items()
|
|
25
|
+
):
|
|
26
|
+
raise ValueError(f"{context}.env must be a string map")
|
|
27
|
+
interpreter = command.get("interpreter")
|
|
28
|
+
if not isinstance(interpreter, dict):
|
|
29
|
+
raise ValueError(f"{context}.interpreter must be an object")
|
|
30
|
+
name = interpreter.get("name")
|
|
31
|
+
if not isinstance(name, str) or not name:
|
|
32
|
+
raise ValueError(f"{context}.interpreter.name must be a nonempty string")
|
|
33
|
+
if not isinstance(interpreter.get("options"), dict):
|
|
34
|
+
raise ValueError(f"{context}.interpreter.options must be an object")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def declared_commands(action: dict[str, Any]) -> list[dict[str, Any]]:
|
|
38
|
+
if not isinstance(action, dict):
|
|
39
|
+
raise ValueError("action must be an object")
|
|
40
|
+
commands = action.get("commands")
|
|
41
|
+
if not isinstance(commands, list) or not commands:
|
|
42
|
+
raise ValueError("action.commands must be a nonempty array")
|
|
43
|
+
for index, command in enumerate(commands):
|
|
44
|
+
validate_command(command, index)
|
|
45
|
+
return deepcopy(commands)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def interpreted_result(answer: dict[str, Any]) -> dict[str, Any]:
|
|
49
|
+
if not isinstance(answer, dict):
|
|
50
|
+
raise ValueError("interpreter result must be an object")
|
|
51
|
+
for field in ("success", "value", "error"):
|
|
52
|
+
if field not in answer:
|
|
53
|
+
raise ValueError(f"interpreter result requires {field}")
|
|
54
|
+
if type(answer["success"]) is not bool:
|
|
55
|
+
raise ValueError("interpreter result.success must be bool")
|
|
56
|
+
if answer["success"]:
|
|
57
|
+
if answer["error"] is not None:
|
|
58
|
+
raise ValueError("successful interpreter result.error must be None")
|
|
59
|
+
elif not isinstance(answer["error"], str) or not answer["error"]:
|
|
60
|
+
raise ValueError("failed interpreter result.error must be a nonempty string")
|
|
61
|
+
return deepcopy(answer)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Optional generic interpretations of declared command exit codes."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ExitCodeInterpreter:
|
|
5
|
+
def interpret(self, result, options):
|
|
6
|
+
success = result["exit_code"] in options["accept"]
|
|
7
|
+
return dict(success=success, value=result["exit_code"],
|
|
8
|
+
error=None if success else "command exit code is not accepted")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
exit_result = ExitCodeInterpreter()
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""External command adapter preserving complete byte streams and actual codes."""
|
|
2
|
+
|
|
3
|
+
from copy import deepcopy
|
|
4
|
+
import subprocess
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def run_command(invocation: dict[str, Any]) -> dict[str, Any]:
|
|
9
|
+
result = subprocess.run(
|
|
10
|
+
invocation["argv"], cwd=invocation["cwd"], env=invocation["env"],
|
|
11
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
12
|
+
shell=False, check=False,
|
|
13
|
+
)
|
|
14
|
+
return dict(invocation=deepcopy(invocation), exit_code=result.returncode,
|
|
15
|
+
stdout=result.stdout, stderr=result.stderr)
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Shared ordinary JSON transport for configured action consumers."""
|
|
2
|
+
import base64
|
|
3
|
+
from copy import deepcopy
|
|
4
|
+
import importlib
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .application import ResultInterpreter, prepare_action
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _require_json_data(value: Any) -> None:
|
|
12
|
+
if value is None or type(value) in (str, bool, int, float):
|
|
13
|
+
return
|
|
14
|
+
if type(value) is list:
|
|
15
|
+
for item in value:
|
|
16
|
+
_require_json_data(item)
|
|
17
|
+
return
|
|
18
|
+
if type(value) is dict:
|
|
19
|
+
for key, item in value.items():
|
|
20
|
+
if type(key) is not str:
|
|
21
|
+
raise ValueError("JSON objects require string keys")
|
|
22
|
+
_require_json_data(item)
|
|
23
|
+
return
|
|
24
|
+
raise ValueError(f"Unsupported JSON value type: {type(value).__name__}")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def validate_json_data(value: Any) -> None:
|
|
28
|
+
"""Validate transport data without silent coercion or numeric overflow."""
|
|
29
|
+
_require_json_data(value)
|
|
30
|
+
json.dumps(value, allow_nan=False)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class JsonResultInterpreter:
|
|
34
|
+
def __init__(self, interpreter: ResultInterpreter):
|
|
35
|
+
self._interpreter = interpreter
|
|
36
|
+
|
|
37
|
+
def interpret(self, raw: dict[str, Any], options: dict[str, Any]) -> dict[str, Any]:
|
|
38
|
+
answer = self._interpreter.interpret(raw, options)
|
|
39
|
+
validate_json_data(answer)
|
|
40
|
+
return answer
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def load_interpreters(document: dict[str, Any]) -> dict[str, ResultInterpreter]:
|
|
44
|
+
declarations = document.get('interpreters')
|
|
45
|
+
if not isinstance(declarations, dict):
|
|
46
|
+
raise ValueError("interpreters must be an object")
|
|
47
|
+
result = {}
|
|
48
|
+
for name, declaration in declarations.items():
|
|
49
|
+
if not isinstance(name, str) or not name:
|
|
50
|
+
raise ValueError("interpreters require nonempty names")
|
|
51
|
+
if not isinstance(declaration, dict):
|
|
52
|
+
raise ValueError(f"interpreter {name}: expected module/attribute object")
|
|
53
|
+
module, attribute = declaration.get('module'), declaration.get('attribute')
|
|
54
|
+
if not isinstance(module, str) or not module or not isinstance(attribute, str) or not attribute:
|
|
55
|
+
raise ValueError(f"interpreter {name}: module and attribute must be nonempty strings")
|
|
56
|
+
try:
|
|
57
|
+
interpreter = getattr(importlib.import_module(module), attribute)
|
|
58
|
+
except Exception as exc:
|
|
59
|
+
raise ValueError(f"interpreter {name} {module}:{attribute}: {exc}") from exc
|
|
60
|
+
if not callable(getattr(interpreter, 'interpret', None)):
|
|
61
|
+
raise ValueError(f"interpreter {name} {module}:{attribute}: callable interpret is required")
|
|
62
|
+
result[name] = JsonResultInterpreter(interpreter)
|
|
63
|
+
return result
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def plan_for_json_transport(action, parameters, *, base_dir, interpreters):
|
|
67
|
+
plan = prepare_action(action, parameters, base_dir=base_dir, interpreters=interpreters)
|
|
68
|
+
validate_json_data(plan)
|
|
69
|
+
return plan
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def encode_action_result(result: dict[str, Any]) -> dict[str, Any]:
|
|
73
|
+
"""Encode raw streams only; interpreted JSON retains its original types."""
|
|
74
|
+
encoded = deepcopy(result)
|
|
75
|
+
for command in encoded['commands']:
|
|
76
|
+
for field in ('stdout', 'stderr'):
|
|
77
|
+
command[field] = dict(
|
|
78
|
+
encoding='base64', data=base64.b64encode(command[field]).decode('ascii')
|
|
79
|
+
)
|
|
80
|
+
return encoded
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Public configuration operations composed with their external adapters."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from ..configuration.json_file import read_json
|
|
7
|
+
from .application import ConfigurationReader, ConfigurationWriter
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def list_requirement_ids(config_path: str | Path, operation: str) -> list[str]:
|
|
11
|
+
"""Return identifiers from the explicitly selected operation configuration."""
|
|
12
|
+
return ConfigurationReader(read_json).list_ids(config_path, operation)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def read_requirements(
|
|
16
|
+
config_path: str | Path,
|
|
17
|
+
operation: str,
|
|
18
|
+
selection: list[str] | str,
|
|
19
|
+
) -> list[dict[str, Any]]:
|
|
20
|
+
"""Return complete objects for an identifier array or the literal all mode."""
|
|
21
|
+
return ConfigurationReader(read_json).read(config_path, operation, selection)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _writer() -> ConfigurationWriter:
|
|
25
|
+
from .json_file import write_json
|
|
26
|
+
from .json_patch import apply_changes
|
|
27
|
+
|
|
28
|
+
return ConfigurationWriter(read_json, write_json, apply_changes)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def add_requirement(
|
|
32
|
+
config_path: str | Path, operation: str, requirement: dict[str, Any]
|
|
33
|
+
) -> None:
|
|
34
|
+
"""Append one complete requirement to the selected configuration."""
|
|
35
|
+
_writer().add(config_path, operation, requirement)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def update_requirement(
|
|
39
|
+
config_path: str | Path,
|
|
40
|
+
operation: str,
|
|
41
|
+
identifier: str,
|
|
42
|
+
changes: list[dict[str, Any]],
|
|
43
|
+
) -> None:
|
|
44
|
+
"""Apply the supported standard patch operations to one selected requirement."""
|
|
45
|
+
_writer().update(config_path, operation, identifier, changes)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def delete_requirement(
|
|
49
|
+
config_path: str | Path, operation: str, identifier: str
|
|
50
|
+
) -> None:
|
|
51
|
+
"""Remove one selected requirement and preserve the remaining document."""
|
|
52
|
+
_writer().delete(config_path, operation, identifier)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def clear_requirements(config_path: str | Path, operation: str) -> None:
|
|
56
|
+
"""Explicitly empty the selected requirement list and preserve its metadata."""
|
|
57
|
+
_writer().clear(config_path, operation)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Configuration use cases compose domain changes with injected external ports."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .domain import Requirements, configuration_for_operation
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
DocumentReader = Callable[[Path], dict[str, Any]]
|
|
11
|
+
DocumentWriter = Callable[[Path, dict[str, Any]], None]
|
|
12
|
+
RequirementPatcher = Callable[
|
|
13
|
+
[dict[str, Any], list[dict[str, Any]]], dict[str, Any]
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def read_operation_configuration(
|
|
18
|
+
read_document: DocumentReader, config_path: str | Path, operation: str
|
|
19
|
+
) -> tuple[Path, dict[str, Any]]:
|
|
20
|
+
main_path = Path(config_path)
|
|
21
|
+
main_document = read_document(main_path)
|
|
22
|
+
selected_path = Path(configuration_for_operation(main_document, operation))
|
|
23
|
+
if not selected_path.is_absolute():
|
|
24
|
+
selected_path = main_path.parent / selected_path
|
|
25
|
+
return selected_path, read_document(selected_path)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ConfigurationReader:
|
|
29
|
+
def __init__(self, read_document: DocumentReader):
|
|
30
|
+
self._read_document = read_document
|
|
31
|
+
|
|
32
|
+
def _requirements(self, config_path: str | Path, operation: str) -> Requirements:
|
|
33
|
+
_, document = read_operation_configuration(
|
|
34
|
+
self._read_document, config_path, operation
|
|
35
|
+
)
|
|
36
|
+
try:
|
|
37
|
+
return Requirements(document, "applications" if operation == "run" else "requirements")
|
|
38
|
+
except ValueError as exc:
|
|
39
|
+
raise ValueError(f"{operation} configuration {config_path}: {exc}") from exc
|
|
40
|
+
|
|
41
|
+
def read_for_execution(self, config_path, operation, selection):
|
|
42
|
+
try:
|
|
43
|
+
return self._requirements(config_path, operation).select_available(selection)
|
|
44
|
+
except ValueError as exc:
|
|
45
|
+
raise ValueError(f"{operation} configuration {config_path}: {exc}") from exc
|
|
46
|
+
|
|
47
|
+
def list_ids(self, config_path: str | Path, operation: str) -> list[str]:
|
|
48
|
+
return self._requirements(config_path, operation).identifiers()
|
|
49
|
+
|
|
50
|
+
def read(
|
|
51
|
+
self,
|
|
52
|
+
config_path: str | Path,
|
|
53
|
+
operation: str,
|
|
54
|
+
selection: list[str] | str,
|
|
55
|
+
) -> list[dict[str, Any]]:
|
|
56
|
+
return self._requirements(config_path, operation).select(selection)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class ConfigurationWriter:
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
read_document: DocumentReader,
|
|
63
|
+
write_document: DocumentWriter,
|
|
64
|
+
apply_changes: RequirementPatcher,
|
|
65
|
+
):
|
|
66
|
+
self._read_document = read_document
|
|
67
|
+
self._write_document = write_document
|
|
68
|
+
self._apply_changes = apply_changes
|
|
69
|
+
|
|
70
|
+
def _edit(
|
|
71
|
+
self,
|
|
72
|
+
config_path: str | Path,
|
|
73
|
+
operation: str,
|
|
74
|
+
transformation: Callable[[Requirements], Requirements],
|
|
75
|
+
) -> None:
|
|
76
|
+
path = Path(config_path)
|
|
77
|
+
try:
|
|
78
|
+
path, document = read_operation_configuration(
|
|
79
|
+
self._read_document, config_path, operation
|
|
80
|
+
)
|
|
81
|
+
result = transformation(Requirements(document, "applications" if operation == "run" else "requirements"))
|
|
82
|
+
self._write_document(path, result.document())
|
|
83
|
+
except ValueError as exc:
|
|
84
|
+
raise ValueError(f"{operation} configuration {path}: {exc}") from exc
|
|
85
|
+
|
|
86
|
+
def add(
|
|
87
|
+
self, config_path: str | Path, operation: str, requirement: dict[str, Any]
|
|
88
|
+
) -> None:
|
|
89
|
+
self._edit(config_path, operation, lambda items: items.with_added(requirement))
|
|
90
|
+
|
|
91
|
+
def _updated(
|
|
92
|
+
self,
|
|
93
|
+
requirements: Requirements,
|
|
94
|
+
identifier: str,
|
|
95
|
+
changes: list[dict[str, Any]],
|
|
96
|
+
) -> Requirements:
|
|
97
|
+
original = requirements.select([identifier])[0]
|
|
98
|
+
result = self._apply_changes(original, changes)
|
|
99
|
+
return requirements.with_replaced(identifier, result)
|
|
100
|
+
|
|
101
|
+
def update(
|
|
102
|
+
self,
|
|
103
|
+
config_path: str | Path,
|
|
104
|
+
operation: str,
|
|
105
|
+
identifier: str,
|
|
106
|
+
changes: list[dict[str, Any]],
|
|
107
|
+
) -> None:
|
|
108
|
+
self._edit(
|
|
109
|
+
config_path, operation,
|
|
110
|
+
lambda items: self._updated(items, identifier, changes),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def delete(
|
|
114
|
+
self, config_path: str | Path, operation: str, identifier: str
|
|
115
|
+
) -> None:
|
|
116
|
+
self._edit(config_path, operation, lambda items: items.without(identifier))
|
|
117
|
+
|
|
118
|
+
def clear(self, config_path: str | Path, operation: str) -> None:
|
|
119
|
+
self._edit(config_path, operation, lambda items: items.cleared())
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Selection rules for operation configurations and complete requirements."""
|
|
2
|
+
|
|
3
|
+
from copy import deepcopy
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def configuration_for_operation(document: dict[str, Any], operation: str) -> str:
|
|
8
|
+
operations = document.get("operations")
|
|
9
|
+
if not isinstance(operations, dict):
|
|
10
|
+
raise ValueError("operations must be an object")
|
|
11
|
+
if operation not in operations:
|
|
12
|
+
raise ValueError(f"Unknown operation: {operation}")
|
|
13
|
+
selected = operations[operation]
|
|
14
|
+
if not isinstance(selected, str) or not selected:
|
|
15
|
+
raise ValueError(f"operations[{operation}]: expected a configuration path")
|
|
16
|
+
return selected
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def validate_selection(selection: list[str] | str) -> None:
|
|
20
|
+
if selection == "all":
|
|
21
|
+
return
|
|
22
|
+
if not isinstance(selection, list):
|
|
23
|
+
raise ValueError('selection must be an array of identifiers or "all"')
|
|
24
|
+
seen = set()
|
|
25
|
+
for position, identifier in enumerate(selection):
|
|
26
|
+
if not isinstance(identifier, str):
|
|
27
|
+
raise ValueError(f"selection[{position}]: expected an identifier")
|
|
28
|
+
if identifier in seen:
|
|
29
|
+
raise ValueError(f"Duplicate selected id {identifier} at position {position}; remove the repeated id")
|
|
30
|
+
seen.add(identifier)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Requirements:
|
|
34
|
+
"""Own full-document preservation, unique identifiers and ordered changes."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, document: dict[str, Any], array_name: str = "requirements"):
|
|
37
|
+
self._array_name = array_name
|
|
38
|
+
self._document = deepcopy(document)
|
|
39
|
+
items = self._document.get(array_name)
|
|
40
|
+
if not isinstance(items, list):
|
|
41
|
+
raise ValueError(f"{array_name} must be an array")
|
|
42
|
+
self._by_id: dict[str, dict[str, Any]] = {}
|
|
43
|
+
for position, item in enumerate(items):
|
|
44
|
+
if not isinstance(item, dict):
|
|
45
|
+
raise ValueError(f"requirements[{position}] must be an object")
|
|
46
|
+
identifier = item.get("id")
|
|
47
|
+
if not isinstance(identifier, str) or not identifier:
|
|
48
|
+
raise ValueError(f"requirements[{position}]: expected a nonempty id")
|
|
49
|
+
if identifier in self._by_id:
|
|
50
|
+
raise ValueError(f"Duplicate {array_name} id {identifier} at position {position}; remove the duplicate or assign a unique id")
|
|
51
|
+
self._by_id[identifier] = item
|
|
52
|
+
|
|
53
|
+
def identifiers(self) -> list[str]:
|
|
54
|
+
return list(self._by_id)
|
|
55
|
+
|
|
56
|
+
def select(self, selection: list[str] | str) -> list[dict[str, Any]]:
|
|
57
|
+
result, missing = self.select_available(selection)
|
|
58
|
+
if missing:
|
|
59
|
+
raise ValueError(f"Unknown requirement id: {missing[0]}")
|
|
60
|
+
return result
|
|
61
|
+
|
|
62
|
+
def select_available(self, selection):
|
|
63
|
+
validate_selection(selection)
|
|
64
|
+
if selection == "all":
|
|
65
|
+
return deepcopy(list(self._by_id.values())), []
|
|
66
|
+
result, missing = [], []
|
|
67
|
+
for identifier in selection:
|
|
68
|
+
if identifier not in self._by_id:
|
|
69
|
+
missing.append(identifier)
|
|
70
|
+
else:
|
|
71
|
+
result.append(deepcopy(self._by_id[identifier]))
|
|
72
|
+
return result, missing
|
|
73
|
+
|
|
74
|
+
def document(self) -> dict[str, Any]:
|
|
75
|
+
return deepcopy(self._document)
|
|
76
|
+
|
|
77
|
+
def _with_items(self, items: list[dict[str, Any]]) -> "Requirements":
|
|
78
|
+
document = self.document()
|
|
79
|
+
document[self._array_name] = items
|
|
80
|
+
return Requirements(document, self._array_name)
|
|
81
|
+
|
|
82
|
+
def with_added(self, requirement: dict[str, Any]) -> "Requirements":
|
|
83
|
+
return self._with_items([*self.select("all"), requirement])
|
|
84
|
+
|
|
85
|
+
def with_replaced(
|
|
86
|
+
self, identifier: str, requirement: dict[str, Any]
|
|
87
|
+
) -> "Requirements":
|
|
88
|
+
self.select([identifier])
|
|
89
|
+
return self._with_items([
|
|
90
|
+
requirement if item["id"] == identifier else item
|
|
91
|
+
for item in self.select("all")
|
|
92
|
+
])
|
|
93
|
+
|
|
94
|
+
def without(self, identifier: str) -> "Requirements":
|
|
95
|
+
self.select([identifier])
|
|
96
|
+
return self._with_items([
|
|
97
|
+
item for item in self.select("all") if item["id"] != identifier
|
|
98
|
+
])
|
|
99
|
+
|
|
100
|
+
def cleared(self) -> "Requirements":
|
|
101
|
+
return self._with_items([])
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Publish one complete selected JSON document through a local temporary file."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import stat
|
|
7
|
+
import tempfile
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _unique_pairs(pairs):
|
|
12
|
+
result = {}
|
|
13
|
+
for key, value in pairs:
|
|
14
|
+
if key in result:
|
|
15
|
+
raise ValueError(f"Duplicate JSON key: {key}")
|
|
16
|
+
result[key] = value
|
|
17
|
+
return result
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def read_json(path: Path) -> dict[str, Any]:
|
|
21
|
+
path = Path(path)
|
|
22
|
+
try:
|
|
23
|
+
value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=_unique_pairs)
|
|
24
|
+
if not isinstance(value, dict):
|
|
25
|
+
raise ValueError("Expected JSON object")
|
|
26
|
+
return value
|
|
27
|
+
except (OSError, UnicodeError, ValueError, RecursionError) as exc:
|
|
28
|
+
raise ValueError(f"Cannot read {path}: {exc}") from exc
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def write_json(path: Path, document: dict[str, Any]) -> None:
|
|
32
|
+
temporary = None
|
|
33
|
+
try:
|
|
34
|
+
payload = json.dumps(document, ensure_ascii=False, indent=2, allow_nan=False)
|
|
35
|
+
mode = stat.S_IMODE(path.stat().st_mode)
|
|
36
|
+
with tempfile.NamedTemporaryFile(
|
|
37
|
+
mode="w",
|
|
38
|
+
encoding="utf-8",
|
|
39
|
+
dir=path.parent,
|
|
40
|
+
prefix=".",
|
|
41
|
+
suffix=".tmp",
|
|
42
|
+
delete=False,
|
|
43
|
+
) as stream:
|
|
44
|
+
temporary = Path(stream.name)
|
|
45
|
+
stream.write(payload + "\n")
|
|
46
|
+
temporary.chmod(mode)
|
|
47
|
+
os.replace(temporary, path)
|
|
48
|
+
temporary = None
|
|
49
|
+
except (OSError, TypeError, ValueError) as exc:
|
|
50
|
+
raise ValueError(f"Cannot write {path}: {exc}") from exc
|
|
51
|
+
finally:
|
|
52
|
+
if temporary is not None:
|
|
53
|
+
temporary.unlink(missing_ok=True)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Adapt the supported change operations to the standard JSON Patch engine."""
|
|
2
|
+
|
|
3
|
+
from copy import deepcopy
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from jsonpatch import JsonPatch, JsonPatchException
|
|
7
|
+
from jsonpointer import JsonPointerException
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def apply_changes(
|
|
11
|
+
requirement: dict[str, Any], changes: list[dict[str, Any]]
|
|
12
|
+
) -> dict[str, Any]:
|
|
13
|
+
if not isinstance(changes, list):
|
|
14
|
+
raise ValueError("changes must be an array")
|
|
15
|
+
result = deepcopy(requirement)
|
|
16
|
+
for position, change in enumerate(changes):
|
|
17
|
+
if not isinstance(change, dict):
|
|
18
|
+
raise ValueError(f"changes[{position}] must be an object")
|
|
19
|
+
operation = change.get("op")
|
|
20
|
+
if not isinstance(operation, str) or operation not in {
|
|
21
|
+
"add",
|
|
22
|
+
"replace",
|
|
23
|
+
"remove",
|
|
24
|
+
}:
|
|
25
|
+
raise ValueError(f"changes[{position}].op is unsupported: {operation}")
|
|
26
|
+
path = change.get("path")
|
|
27
|
+
if not isinstance(path, str):
|
|
28
|
+
raise ValueError(f"changes[{position}].path must be a string")
|
|
29
|
+
try:
|
|
30
|
+
result = JsonPatch([deepcopy(change)]).apply(result, in_place=True)
|
|
31
|
+
except (JsonPatchException, JsonPointerException) as exc:
|
|
32
|
+
raise ValueError(
|
|
33
|
+
f"changes[{position}] {operation} {path!r}: {exc}"
|
|
34
|
+
) from exc
|
|
35
|
+
return result
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
command_execution/__init__.py,sha256=DrFVLIrkAmVJRpdyjQM3FbfD6Dz7bxYHsi3Cdyy5W8c,317
|
|
2
|
+
command_execution/actions/__init__.py,sha256=SrLI1sAcWk1G_ICQqPEBsfjhakpyV1nerG_y8qMyBvQ,966
|
|
3
|
+
command_execution/actions/application.py,sha256=kYBTUelQMisrFJzGQFVLwb4wyvLYRYbBIxlqHToEYgw,5325
|
|
4
|
+
command_execution/actions/domain.py,sha256=nKMfp0h510_Dwh4VgCTzy4RzQueoCdb8K14ssiObSLs,2706
|
|
5
|
+
command_execution/actions/interpreters.py,sha256=UMXSabltmTDkXpV6bucZ3FX0IGJcWGSnK8uXnOpwc0E,387
|
|
6
|
+
command_execution/actions/process.py,sha256=bd56845tFQCUNALkPBSSHqB11A8J5gyktrt6KqtNFFc,578
|
|
7
|
+
command_execution/actions/transport.py,sha256=aoHfQA9rraSlEAhBaMq0EBq0XjhnFhcZoWq6NgMNQn8,3218
|
|
8
|
+
command_execution/configuration/__init__.py,sha256=aVLiB3_vrGfsUvj_jHUfkIbi6cztkgNojxqNe5kWlSE,1934
|
|
9
|
+
command_execution/configuration/application.py,sha256=Ad7ZJCM1VIINc9lL3GA8a7p3QVgGJ7eMfn3fyDdF5Cw,4258
|
|
10
|
+
command_execution/configuration/domain.py,sha256=GhOS85lQivTzdBbk8onBx1DzpLF_qEpgb3_lcD9MWhI,4085
|
|
11
|
+
command_execution/configuration/json_file.py,sha256=dlu4IF7HPkM9BciSXgF2FCB35Ns-_mkQZ-hKGXP0ri0,1640
|
|
12
|
+
command_execution/configuration/json_patch.py,sha256=dUQuncU_fR8IfGdZxFnrPqWwW7RFgSppzIJyJmWAYRc,1322
|
|
13
|
+
command_execution-1.0.0.dist-info/METADATA,sha256=dfDU2rV23SfeBK3Md2Do29kiorPIB0_CKVnQarDNhxk,211
|
|
14
|
+
command_execution-1.0.0.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
|
|
15
|
+
command_execution-1.0.0.dist-info/top_level.txt,sha256=FINGZxz5CUqn5CqyL9-_OKf6nH4-XNtqD3sxhq6c4tE,18
|
|
16
|
+
command_execution-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
command_execution
|