codemie-cdk-python 0.1.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.
- codemie_cdk_python-0.1.0.dist-info/METADATA +892 -0
- codemie_cdk_python-0.1.0.dist-info/RECORD +40 -0
- codemie_cdk_python-0.1.0.dist-info/WHEEL +4 -0
- codemie_cdk_python-0.1.0.dist-info/entry_points.txt +3 -0
- codemie_iac/__init__.py +49 -0
- codemie_iac/cli/__init__.py +17 -0
- codemie_iac/cli/__main__.py +24 -0
- codemie_iac/cli/commands/__init__.py +17 -0
- codemie_iac/cli/commands/apply.py +119 -0
- codemie_iac/cli/commands/plan.py +72 -0
- codemie_iac/cli/config_model.py +136 -0
- codemie_iac/cli/documents.py +59 -0
- codemie_iac/cli/env_file.py +62 -0
- codemie_iac/cli/exit_status.py +80 -0
- codemie_iac/cli/init_command.py +101 -0
- codemie_iac/cli/main.py +152 -0
- codemie_iac/cli/render.py +206 -0
- codemie_iac/cli/target_config.py +258 -0
- codemie_iac/credentials.py +99 -0
- codemie_iac/envelope.py +188 -0
- codemie_iac/plan_apply/__init__.py +70 -0
- codemie_iac/plan_apply/bulk_create.py +561 -0
- codemie_iac/plan_apply/credentials.py +306 -0
- codemie_iac/plan_apply/errors.py +223 -0
- codemie_iac/plan_apply/field_policy.py +188 -0
- codemie_iac/plan_apply/guards.py +221 -0
- codemie_iac/plan_apply/kinds.py +815 -0
- codemie_iac/plan_apply/lookup.py +313 -0
- codemie_iac/plan_apply/ordering.py +177 -0
- codemie_iac/plan_apply/single_apply.py +751 -0
- codemie_iac/resolver.py +61 -0
- codemie_iac/schema.py +106 -0
- codemie_iac/serializer.py +64 -0
- codemie_iac/specs/__init__.py +13 -0
- codemie_iac/specs/assistant.py +509 -0
- codemie_iac/specs/category.py +36 -0
- codemie_iac/specs/datasource.py +595 -0
- codemie_iac/specs/integration.py +103 -0
- codemie_iac/specs/skill.py +51 -0
- codemie_iac/specs/workflow.py +154 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# Copyright 2026 EPAM Systems, Inc. ("EPAM")
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Process exit statuses of the plan/apply CLI and the exception mapping."""
|
|
16
|
+
|
|
17
|
+
from enum import IntEnum
|
|
18
|
+
|
|
19
|
+
from pydantic import ValidationError
|
|
20
|
+
|
|
21
|
+
from ..plan_apply.errors import (
|
|
22
|
+
ApplyError,
|
|
23
|
+
PlatformRejectionError,
|
|
24
|
+
UnresolvableCredentialError,
|
|
25
|
+
UnresolvedReferenceError,
|
|
26
|
+
)
|
|
27
|
+
from ..resolver import ReferenceResolutionError
|
|
28
|
+
from ..schema import DocumentValidationError
|
|
29
|
+
from ..serializer import DocumentParseError
|
|
30
|
+
from .documents import InvalidDocumentError
|
|
31
|
+
from .target_config import ConfigError
|
|
32
|
+
|
|
33
|
+
__all__ = ["ExitStatus", "exit_status_for"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ExitStatus(IntEnum):
|
|
37
|
+
"""Exit codes; ``NOTHING_TO_DO`` is an alias of ``SUCCESS``."""
|
|
38
|
+
|
|
39
|
+
SUCCESS = 0
|
|
40
|
+
NOTHING_TO_DO = 0
|
|
41
|
+
CHANGES_PENDING = 1
|
|
42
|
+
APPLY_FAILED = 2
|
|
43
|
+
UNRESOLVED_INPUT = 3
|
|
44
|
+
CONFIG_ERROR = 4
|
|
45
|
+
INVALID_DOCUMENT = 5
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
#: Checked in order: subclasses of ``ApplyError`` precede ``ApplyError``
|
|
49
|
+
#: itself, which the guards raise for unsupported or inconsistent documents.
|
|
50
|
+
_MAPPING: tuple[tuple[tuple[type[BaseException], ...], ExitStatus], ...] = (
|
|
51
|
+
((ConfigError,), ExitStatus.CONFIG_ERROR),
|
|
52
|
+
(
|
|
53
|
+
(UnresolvedReferenceError, UnresolvableCredentialError),
|
|
54
|
+
ExitStatus.UNRESOLVED_INPUT,
|
|
55
|
+
),
|
|
56
|
+
((PlatformRejectionError,), ExitStatus.APPLY_FAILED),
|
|
57
|
+
(
|
|
58
|
+
(
|
|
59
|
+
ApplyError,
|
|
60
|
+
DocumentParseError,
|
|
61
|
+
DocumentValidationError,
|
|
62
|
+
ValidationError,
|
|
63
|
+
ReferenceResolutionError,
|
|
64
|
+
InvalidDocumentError,
|
|
65
|
+
),
|
|
66
|
+
ExitStatus.INVALID_DOCUMENT,
|
|
67
|
+
),
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def exit_status_for(
|
|
72
|
+
exc: BaseException, default: ExitStatus | None = None
|
|
73
|
+
) -> ExitStatus:
|
|
74
|
+
"""Return the exit status for ``exc``; ``default`` if unknown, else raise it."""
|
|
75
|
+
for types, status in _MAPPING:
|
|
76
|
+
if isinstance(exc, types):
|
|
77
|
+
return status
|
|
78
|
+
if default is None:
|
|
79
|
+
raise exc
|
|
80
|
+
return default
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Copyright 2026 EPAM Systems, Inc. ("EPAM")
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""``codemie-iac init``: write a ``codemie.yaml`` template."""
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import tempfile
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Optional, TextIO
|
|
22
|
+
|
|
23
|
+
from .config_model import ENVIRONMENT_KEYS, ConfigError
|
|
24
|
+
from .target_config import DEFAULT_CONFIG_PATH
|
|
25
|
+
|
|
26
|
+
__all__ = ["init_command", "render_template"]
|
|
27
|
+
|
|
28
|
+
#: Example variable names; the user may rename them in the generated file.
|
|
29
|
+
_PROJECT_VARIABLE = "CODEMIE_PROJECT"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# Names the Node.js tool already uses for these two keys, so one .env serves both.
|
|
33
|
+
_VARIABLE_NAMES = {
|
|
34
|
+
"auth_server_url": "CODEMIE_AUTH_URL",
|
|
35
|
+
"auth_realm_name": "CODEMIE_REALM",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _variable(key: str) -> str:
|
|
40
|
+
if key in _VARIABLE_NAMES:
|
|
41
|
+
return _VARIABLE_NAMES[key]
|
|
42
|
+
name = key.upper()
|
|
43
|
+
return name if name.startswith("CODEMIE_") else f"CODEMIE_{name}"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def render_template() -> str:
|
|
47
|
+
"""Build the file from the model's fields so it cannot drift from the model."""
|
|
48
|
+
lines = [
|
|
49
|
+
"# Values come from the shell or .env through ${NAME}; rename the variables freely.",
|
|
50
|
+
"project:",
|
|
51
|
+
f" name: ${{{_PROJECT_VARIABLE}:-}}",
|
|
52
|
+
"environment:",
|
|
53
|
+
]
|
|
54
|
+
lines += [f" {key}: ${{{_variable(key)}:-}}" for key in ENVIRONMENT_KEYS]
|
|
55
|
+
return "\n".join(lines) + "\n"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _create(path: Path, text: str) -> None:
|
|
59
|
+
try:
|
|
60
|
+
with open(path, "x", encoding="utf-8") as handle:
|
|
61
|
+
handle.write(text)
|
|
62
|
+
except FileExistsError:
|
|
63
|
+
raise ConfigError(f"{path} already exists; use --force to replace it") from None
|
|
64
|
+
except OSError:
|
|
65
|
+
raise ConfigError(f"Cannot write {path}") from None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _replace(path: Path, text: str) -> None:
|
|
69
|
+
try:
|
|
70
|
+
descriptor, temp_name = tempfile.mkstemp(
|
|
71
|
+
dir=path.parent, prefix=".codemie-init-"
|
|
72
|
+
)
|
|
73
|
+
except OSError:
|
|
74
|
+
raise ConfigError(f"Cannot write {path}") from None
|
|
75
|
+
try:
|
|
76
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
77
|
+
handle.write(text)
|
|
78
|
+
os.replace(temp_name, path)
|
|
79
|
+
except OSError:
|
|
80
|
+
Path(temp_name).unlink(missing_ok=True)
|
|
81
|
+
raise ConfigError(f"Cannot write {path}") from None
|
|
82
|
+
except BaseException:
|
|
83
|
+
Path(temp_name).unlink(missing_ok=True)
|
|
84
|
+
raise
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def init_command(
|
|
88
|
+
force: bool,
|
|
89
|
+
*,
|
|
90
|
+
config_path: Optional[str],
|
|
91
|
+
json_output: bool,
|
|
92
|
+
out: TextIO,
|
|
93
|
+
) -> int:
|
|
94
|
+
"""Write the template to ``config_path``; refuse to overwrite without force."""
|
|
95
|
+
path = Path(config_path or DEFAULT_CONFIG_PATH)
|
|
96
|
+
(_replace if force else _create)(path, render_template())
|
|
97
|
+
if json_output:
|
|
98
|
+
out.write(json.dumps({"path": str(path)}) + "\n")
|
|
99
|
+
else:
|
|
100
|
+
out.write(f"Wrote {path}\n")
|
|
101
|
+
return 0
|
codemie_iac/cli/main.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# Copyright 2026 EPAM Systems, Inc. ("EPAM")
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Entrypoint of the ``codemie-iac`` command line."""
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Callable, Optional, Sequence
|
|
21
|
+
|
|
22
|
+
from .commands.apply import apply_command
|
|
23
|
+
from .commands.plan import plan_command
|
|
24
|
+
from .exit_status import ExitStatus
|
|
25
|
+
from .init_command import init_command
|
|
26
|
+
from .render import render_error
|
|
27
|
+
from .target_config import ConfigError, TargetConfig
|
|
28
|
+
|
|
29
|
+
__all__ = ["main"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _add_plan(sub: argparse.ArgumentParser) -> None:
|
|
33
|
+
sub.add_argument("file", type=Path, help="document file to compare")
|
|
34
|
+
sub.add_argument("--id", dest="entity_id", default=None, help="entity id")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _add_apply(sub: argparse.ArgumentParser) -> None:
|
|
38
|
+
sub.add_argument("path", type=Path, help="document file or directory")
|
|
39
|
+
sub.add_argument("--id", dest="entity_id", default=None, help="entity id")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _add_init(sub: argparse.ArgumentParser) -> None:
|
|
43
|
+
sub.add_argument("--force", action="store_true", help="overwrite an existing file")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _run_init(args: argparse.Namespace, **context: Any) -> ExitStatus:
|
|
47
|
+
return ExitStatus(init_command(args.force, **context))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _run_plan(args: argparse.Namespace, **context: Any) -> ExitStatus:
|
|
51
|
+
return plan_command(args.file, args.entity_id, **context)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _run_apply(args: argparse.Namespace, **context: Any) -> ExitStatus:
|
|
55
|
+
return apply_command(args.path, args.entity_id, **context)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# name -> (help, argument registrar, runner); extend to add commands.
|
|
59
|
+
#: name -> (help text, argument registrar, runner, needs_target)
|
|
60
|
+
_COMMANDS: dict[str, tuple[str, Callable, Callable, bool]] = {
|
|
61
|
+
"plan": ("Show the diff against a live entity", _add_plan, _run_plan, True),
|
|
62
|
+
"apply": ("Apply documents to the platform", _add_apply, _run_apply, True),
|
|
63
|
+
"init": ("Write a codemie.yaml template", _add_init, _run_init, False),
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
68
|
+
parser = argparse.ArgumentParser(prog="codemie-iac")
|
|
69
|
+
parser.add_argument("--project", default=None, help="target project")
|
|
70
|
+
parser.add_argument("-c", "--config", default=None, help="codemie.yaml path")
|
|
71
|
+
parser.add_argument("--env-file", default=None, help=".env path")
|
|
72
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
73
|
+
for name, (help_text, register, _, _) in _COMMANDS.items():
|
|
74
|
+
sub = subparsers.add_parser(name, help=help_text)
|
|
75
|
+
register(sub)
|
|
76
|
+
sub.add_argument("--json", action="store_true", help="JSON output")
|
|
77
|
+
return parser
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _parse(argv: Optional[Sequence[str]]) -> Optional[argparse.Namespace]:
|
|
81
|
+
try:
|
|
82
|
+
return _build_parser().parse_args(argv)
|
|
83
|
+
except SystemExit as exc:
|
|
84
|
+
if exc.code in (0, None):
|
|
85
|
+
raise
|
|
86
|
+
raise SystemExit(int(ExitStatus.CONFIG_ERROR)) from None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _fail(exc: Exception, args: argparse.Namespace, status: ExitStatus) -> ExitStatus:
|
|
90
|
+
sys.stdout.write(render_error(exc, json_output=args.json, status=status))
|
|
91
|
+
return status
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _check_usage(args: argparse.Namespace) -> None:
|
|
95
|
+
"""Reject bad argument combinations before any network call is made."""
|
|
96
|
+
if args.command == "plan" and not args.entity_id:
|
|
97
|
+
raise ConfigError("plan requires --id of the entity to compare against")
|
|
98
|
+
if args.command == "apply" and args.entity_id and args.path.is_dir():
|
|
99
|
+
raise ConfigError("--id cannot be combined with a directory")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _print_warnings(warnings: Sequence[str]) -> None:
|
|
103
|
+
for text in dict.fromkeys(warnings):
|
|
104
|
+
sys.stderr.write(f"warning: {text}\n")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _connect(args: argparse.Namespace) -> tuple[TargetConfig, Any]:
|
|
108
|
+
"""Resolve the target and build the client; warnings are printed first."""
|
|
109
|
+
try:
|
|
110
|
+
target = TargetConfig.resolve(args.project, args.config, env_file=args.env_file)
|
|
111
|
+
except Exception as exc: # noqa: BLE001 - rendered by type name only
|
|
112
|
+
_print_warnings(getattr(exc, "warnings", ()))
|
|
113
|
+
raise
|
|
114
|
+
_print_warnings(target.warnings)
|
|
115
|
+
return target, target.build_client()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _context(args: argparse.Namespace, needs_target: bool) -> dict[str, Any]:
|
|
119
|
+
context: dict[str, Any] = {"json_output": args.json, "out": sys.stdout}
|
|
120
|
+
if not needs_target:
|
|
121
|
+
return {**context, "config_path": args.config}
|
|
122
|
+
target, client = _connect(args)
|
|
123
|
+
return {
|
|
124
|
+
**context,
|
|
125
|
+
"project": target.project,
|
|
126
|
+
"environ": target.environment,
|
|
127
|
+
"client": client,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _dispatch(args: argparse.Namespace) -> ExitStatus:
|
|
132
|
+
_, _, runner, needs_target = _COMMANDS[args.command]
|
|
133
|
+
try:
|
|
134
|
+
_check_usage(args)
|
|
135
|
+
context = _context(args, needs_target)
|
|
136
|
+
except Exception as exc: # noqa: BLE001 - rendered by type name only
|
|
137
|
+
return _fail(exc, args, ExitStatus.CONFIG_ERROR)
|
|
138
|
+
try:
|
|
139
|
+
return runner(args, **context)
|
|
140
|
+
except ConfigError as exc:
|
|
141
|
+
return _fail(exc, args, ExitStatus.CONFIG_ERROR)
|
|
142
|
+
except Exception as exc: # noqa: BLE001 - rendered by type name only
|
|
143
|
+
return _fail(exc, args, ExitStatus.APPLY_FAILED)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
147
|
+
"""Run the CLI and return the process exit code."""
|
|
148
|
+
try:
|
|
149
|
+
args = _parse(argv)
|
|
150
|
+
except SystemExit as exc:
|
|
151
|
+
return int(exc.code or 0)
|
|
152
|
+
return int(_dispatch(args))
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# Copyright 2026 EPAM Systems, Inc. ("EPAM")
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Text and JSON rendering of plan/apply results and errors.
|
|
16
|
+
|
|
17
|
+
Every renderer returns a ``str``. Only engine-scrubbed fields (``reason``,
|
|
18
|
+
``structured_errors``) are used for errors, never ``str(exc)``; the final
|
|
19
|
+
output is additionally passed through ``scrub()`` with any extra ``secrets``.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
from collections.abc import Iterable
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from pydantic import ValidationError
|
|
27
|
+
|
|
28
|
+
from ..plan_apply import (
|
|
29
|
+
ApplyError,
|
|
30
|
+
ApplyResult,
|
|
31
|
+
BulkCreateReport,
|
|
32
|
+
Plan,
|
|
33
|
+
)
|
|
34
|
+
from ..plan_apply.errors import platform_detail, scrub
|
|
35
|
+
from .documents import InvalidDocumentError
|
|
36
|
+
from .exit_status import ExitStatus
|
|
37
|
+
from .target_config import ConfigError
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"render_apply_result",
|
|
41
|
+
"render_bulk_report",
|
|
42
|
+
"render_error",
|
|
43
|
+
"render_plan",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _scrub_value(value: Any, secrets: tuple[str, ...]) -> Any:
|
|
48
|
+
if isinstance(value, str):
|
|
49
|
+
return scrub(value, secrets)
|
|
50
|
+
if isinstance(value, dict):
|
|
51
|
+
return {
|
|
52
|
+
_scrub_value(k, secrets): _scrub_value(v, secrets) for k, v in value.items()
|
|
53
|
+
}
|
|
54
|
+
if isinstance(value, list):
|
|
55
|
+
return [_scrub_value(v, secrets) for v in value]
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _emit_json(payload: dict, status: ExitStatus, secrets: Iterable[str]) -> str:
|
|
60
|
+
payload = {
|
|
61
|
+
**payload,
|
|
62
|
+
"status": ExitStatus(status).name.lower(),
|
|
63
|
+
"exit_code": int(status),
|
|
64
|
+
}
|
|
65
|
+
return (
|
|
66
|
+
json.dumps(_scrub_value(payload, tuple(secrets)), indent=2, default=str) + "\n"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _emit_text(lines: list[str], secrets: Iterable[str]) -> str:
|
|
71
|
+
return scrub("\n".join(lines), tuple(secrets)) + "\n"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _val(value: Any) -> str:
|
|
75
|
+
return json.dumps(value, default=str, sort_keys=True)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _field_error_lines(errors: Any, indent: str = " ") -> list[str]:
|
|
79
|
+
return [f"{indent}- {e.field}: {e.message}" for e in errors or []]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def render_plan(
|
|
83
|
+
plan: Plan,
|
|
84
|
+
*,
|
|
85
|
+
json_output: bool,
|
|
86
|
+
status: ExitStatus,
|
|
87
|
+
secrets: Iterable[str] = (),
|
|
88
|
+
) -> str:
|
|
89
|
+
"""Render a plan: differences, and ``cannot_compare`` as warnings."""
|
|
90
|
+
if json_output:
|
|
91
|
+
return _emit_json(plan.model_dump(mode="json"), status, secrets)
|
|
92
|
+
lines = ["No differences." if plan.is_empty else "Differences:"]
|
|
93
|
+
for d in plan.differences:
|
|
94
|
+
lines.append(f" {d.field}")
|
|
95
|
+
lines.append(f" document: {_val(d.document_value)}")
|
|
96
|
+
lines.append(f" live: {_val(d.live_value)}")
|
|
97
|
+
lines += [
|
|
98
|
+
f"warning: cannot compare {c.field}: {c.reason}" for c in plan.cannot_compare
|
|
99
|
+
]
|
|
100
|
+
return _emit_text(lines, secrets)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _id_suffix(entity_id: str | None) -> str:
|
|
104
|
+
# The platform does not return an id for every kind (e.g. integrations).
|
|
105
|
+
return f" (id: {entity_id})" if entity_id else ""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _apply_headline(result: ApplyResult) -> str:
|
|
109
|
+
if result.created:
|
|
110
|
+
return f"created{_id_suffix(result.id)}"
|
|
111
|
+
if not result.changed:
|
|
112
|
+
return f"no change made{_id_suffix(result.id)}"
|
|
113
|
+
return f"updated{_id_suffix(result.id)}"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def render_apply_result(
|
|
117
|
+
result: ApplyResult,
|
|
118
|
+
*,
|
|
119
|
+
json_output: bool,
|
|
120
|
+
status: ExitStatus,
|
|
121
|
+
secrets: Iterable[str] = (),
|
|
122
|
+
) -> str:
|
|
123
|
+
"""Render a single-entity apply outcome."""
|
|
124
|
+
if json_output:
|
|
125
|
+
return _emit_json(result.model_dump(mode="json"), status, secrets)
|
|
126
|
+
lines = [_apply_headline(result)]
|
|
127
|
+
lines += [f"warning: could not compare {f}" for f in result.uncomparable]
|
|
128
|
+
return _emit_text(lines, secrets)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def render_bulk_report(
|
|
132
|
+
report: BulkCreateReport,
|
|
133
|
+
*,
|
|
134
|
+
json_output: bool,
|
|
135
|
+
status: ExitStatus,
|
|
136
|
+
secrets: Iterable[str] = (),
|
|
137
|
+
) -> str:
|
|
138
|
+
"""Render a bulk create report: created entities and the first failure."""
|
|
139
|
+
if json_output:
|
|
140
|
+
return _emit_json(report.model_dump(mode="json"), status, secrets)
|
|
141
|
+
lines = [f"created {len(report.created)}:"]
|
|
142
|
+
lines += [f" {c.kind.value}/{c.name}{_id_suffix(c.id)}" for c in report.created]
|
|
143
|
+
failed = report.failed
|
|
144
|
+
if failed is not None:
|
|
145
|
+
lines.append(f"failed: {failed.kind.value}/{failed.name} [{failed.error_type}]")
|
|
146
|
+
lines.append(f" reason: {failed.reason}")
|
|
147
|
+
lines += _field_error_lines(failed.structured_errors)
|
|
148
|
+
return _emit_text(lines, secrets)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _validation_reason(exc: ValidationError) -> str:
|
|
152
|
+
"""``loc: message`` per problem; never the offending input value."""
|
|
153
|
+
return "; ".join(
|
|
154
|
+
f"{'.'.join(str(p) for p in e['loc'])}: {e['msg']}" for e in exc.errors()
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _error_payload(exc: BaseException) -> dict:
|
|
159
|
+
if isinstance(exc, ApplyError):
|
|
160
|
+
errors = getattr(exc, "structured_errors", None)
|
|
161
|
+
return {
|
|
162
|
+
"error_type": exc.error_type,
|
|
163
|
+
"kind": exc.entity_kind,
|
|
164
|
+
"name": exc.entity_name,
|
|
165
|
+
"reason": exc.reason,
|
|
166
|
+
"structured_errors": (
|
|
167
|
+
[e.model_dump(mode="json") for e in errors] if errors else None
|
|
168
|
+
),
|
|
169
|
+
}
|
|
170
|
+
if isinstance(exc, (ConfigError, InvalidDocumentError)):
|
|
171
|
+
reason = str(exc)
|
|
172
|
+
elif isinstance(exc, ValidationError):
|
|
173
|
+
reason = _validation_reason(exc)
|
|
174
|
+
else:
|
|
175
|
+
reason = platform_detail(exc) # the HTTP response body, scrubbed on emit
|
|
176
|
+
return {"error_type": type(exc).__name__, "reason": reason}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _error_lines(exc: BaseException, payload: dict) -> list[str]:
|
|
180
|
+
if isinstance(exc, ApplyError):
|
|
181
|
+
lines = [
|
|
182
|
+
f"error: {payload['kind']}/{payload['name']} [{payload['error_type']}]",
|
|
183
|
+
f" reason: {payload['reason']}",
|
|
184
|
+
]
|
|
185
|
+
return lines + _field_error_lines(getattr(exc, "structured_errors", None))
|
|
186
|
+
if payload["reason"]:
|
|
187
|
+
return [f"error: {payload['error_type']}: {payload['reason']}"]
|
|
188
|
+
return [f"error: {payload['error_type']}"]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def render_error(
|
|
192
|
+
exc: BaseException,
|
|
193
|
+
*,
|
|
194
|
+
json_output: bool,
|
|
195
|
+
status: ExitStatus,
|
|
196
|
+
secrets: Iterable[str] = (),
|
|
197
|
+
) -> str:
|
|
198
|
+
"""Render an error from its scrubbed fields; never ``str(exc)``.
|
|
199
|
+
|
|
200
|
+
Only ``ConfigError`` and ``InvalidDocumentError`` (documented secret-free)
|
|
201
|
+
expose their message.
|
|
202
|
+
"""
|
|
203
|
+
payload = _error_payload(exc)
|
|
204
|
+
if json_output:
|
|
205
|
+
return _emit_json(payload, status, secrets)
|
|
206
|
+
return _emit_text(_error_lines(exc, payload), secrets)
|