netherframe.sdk 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.
- netherframe/sdk/__init__.py +24 -0
- netherframe/sdk/analysis.py +150 -0
- netherframe/sdk/apps.py +61 -0
- netherframe/sdk/backend.py +156 -0
- netherframe/sdk/base.py +46 -0
- netherframe/sdk/changes.py +418 -0
- netherframe/sdk/config.py +73 -0
- netherframe/sdk/discover.py +450 -0
- netherframe/sdk/drift.py +385 -0
- netherframe/sdk/errors.py +69 -0
- netherframe/sdk/events.py +209 -0
- netherframe/sdk/execution.py +236 -0
- netherframe/sdk/follow.py +263 -0
- netherframe/sdk/generate.py +564 -0
- netherframe/sdk/generation_config.py +160 -0
- netherframe/sdk/graph_onboarding.py +144 -0
- netherframe/sdk/graph_state.py +291 -0
- netherframe/sdk/inputs.py +85 -0
- netherframe/sdk/legacy.py +222 -0
- netherframe/sdk/lifecycle.py +1124 -0
- netherframe/sdk/listing.py +19 -0
- netherframe/sdk/paths.py +74 -0
- netherframe/sdk/plans.py +118 -0
- netherframe/sdk/progress.py +147 -0
- netherframe/sdk/project.py +68 -0
- netherframe/sdk/project_config.py +93 -0
- netherframe/sdk/provider_versions.py +291 -0
- netherframe/sdk/providers.py +104 -0
- netherframe/sdk/py.typed +0 -0
- netherframe/sdk/run_reports.py +269 -0
- netherframe/sdk/runs.py +238 -0
- netherframe/sdk/scope.py +84 -0
- netherframe/sdk/sensitive.py +142 -0
- netherframe/sdk/settings.py +159 -0
- netherframe/sdk/skill.py +185 -0
- netherframe/sdk/stacks.py +363 -0
- netherframe/sdk/synthesis.py +369 -0
- netherframe/sdk/tooling.py +111 -0
- netherframe/sdk/tui.py +147 -0
- netherframe_sdk-0.1.0.dist-info/METADATA +36 -0
- netherframe_sdk-0.1.0.dist-info/RECORD +82 -0
- netherframe_sdk-0.1.0.dist-info/WHEEL +4 -0
- netherframe_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
- nf/sdk/__init__.py +4 -0
- nf/sdk/analysis.py +4 -0
- nf/sdk/apps.py +4 -0
- nf/sdk/backend.py +4 -0
- nf/sdk/base.py +4 -0
- nf/sdk/changes.py +4 -0
- nf/sdk/config.py +4 -0
- nf/sdk/discover.py +4 -0
- nf/sdk/drift.py +4 -0
- nf/sdk/errors.py +4 -0
- nf/sdk/events.py +4 -0
- nf/sdk/execution.py +4 -0
- nf/sdk/follow.py +4 -0
- nf/sdk/generate.py +4 -0
- nf/sdk/generation_config.py +4 -0
- nf/sdk/graph_onboarding.py +4 -0
- nf/sdk/graph_state.py +4 -0
- nf/sdk/inputs.py +4 -0
- nf/sdk/legacy.py +4 -0
- nf/sdk/lifecycle.py +4 -0
- nf/sdk/listing.py +4 -0
- nf/sdk/paths.py +4 -0
- nf/sdk/plans.py +4 -0
- nf/sdk/progress.py +4 -0
- nf/sdk/project.py +4 -0
- nf/sdk/project_config.py +4 -0
- nf/sdk/provider_versions.py +4 -0
- nf/sdk/providers.py +4 -0
- nf/sdk/py.typed +0 -0
- nf/sdk/run_reports.py +4 -0
- nf/sdk/runs.py +4 -0
- nf/sdk/scope.py +4 -0
- nf/sdk/sensitive.py +4 -0
- nf/sdk/settings.py +4 -0
- nf/sdk/skill.py +4 -0
- nf/sdk/stacks.py +4 -0
- nf/sdk/synthesis.py +4 -0
- nf/sdk/tooling.py +4 -0
- nf/sdk/tui.py +4 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Every nf command as a Python API.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
from nf.sdk import Project
|
|
6
|
+
|
|
7
|
+
project = Project(".", settings={"max_concurrent_resources": 20}, inputs={"env": "prod"})
|
|
8
|
+
plan = project.plan(app="web", plan_out="prod.plan")
|
|
9
|
+
run = project.apply(app="web", plan_file="prod.plan", auto_approve=True)
|
|
10
|
+
report = project.drift.check(paths=("infra",))
|
|
11
|
+
|
|
12
|
+
``Project`` has a method for each nf command (``nf drift check`` is ``project.drift.check``), with
|
|
13
|
+
the command's options as keyword arguments. Commands return structured results (what ``--json``
|
|
14
|
+
prints) and raise ``NfError``; they never print or exit. Settings are nf's flags
|
|
15
|
+
(``netherframe.sdk.settings``), and inputs the app factory's parameters (``++name=value``).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from .errors import Ambiguous, Declined, InputsError, NfError, NotFound, ProjectError, RunFailed, UsageError
|
|
21
|
+
from .project import Project
|
|
22
|
+
from .settings import SETTINGS, Setting
|
|
23
|
+
|
|
24
|
+
__all__ = ["SETTINGS", "Ambiguous", "Declined", "InputsError", "NfError", "NotFound", "Project", "ProjectError", "RunFailed", "Setting", "UsageError"]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Commands of the API: convert (a Terraform module into Python), lint (an app, offline)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from dataclasses import asdict, dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
|
+
|
|
10
|
+
from .base import ProjectBase
|
|
11
|
+
from .errors import NfError, ProjectError
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from netherframe.core.linting import Report
|
|
15
|
+
from netherframe.generation.convert import ConversionResult
|
|
16
|
+
|
|
17
|
+
#: Options of these commands that are how the CLI shows a result, not inputs of the command
|
|
18
|
+
CLI_ONLY: dict[str, dict[str, str]] = {
|
|
19
|
+
"nf lint": {
|
|
20
|
+
"all_failures": "how many findings the CLI prints; the report has every one",
|
|
21
|
+
"as_json": "the result is structured; --json is how the CLI prints it",
|
|
22
|
+
},
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class LintResult:
|
|
28
|
+
"""``nf lint``: the report of every lint of an app's resources, and whether it establishes that the app is valid."""
|
|
29
|
+
|
|
30
|
+
report: Report
|
|
31
|
+
#: Why the report does not establish validity (each finding, no check evaluated, unresolved values); None when it does
|
|
32
|
+
error: str | None = None
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def valid(self) -> bool:
|
|
36
|
+
return self.error is None
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def exit_code(self) -> int:
|
|
40
|
+
"""What nf exits with: 1 unless the report establishes validity."""
|
|
41
|
+
return 0 if self.valid else 1
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict[str, Any]:
|
|
44
|
+
report = self.report
|
|
45
|
+
return {**asdict(report), "evaluated": report.evaluated, "findings": len(report.findings), "deferred": len(report.deferred)}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def convert(
|
|
49
|
+
module_dir: str | Path,
|
|
50
|
+
*,
|
|
51
|
+
output: str | Path,
|
|
52
|
+
package: str | None,
|
|
53
|
+
generic: bool,
|
|
54
|
+
force: bool,
|
|
55
|
+
no_format: bool,
|
|
56
|
+
fetch_modules: bool,
|
|
57
|
+
module_cache: str | Path | None,
|
|
58
|
+
report: str | Path | None,
|
|
59
|
+
) -> ConversionResult:
|
|
60
|
+
from netherframe.generation.convert import ConversionError, HclSyntaxError, convert_module
|
|
61
|
+
|
|
62
|
+
try:
|
|
63
|
+
result = convert_module(
|
|
64
|
+
module_dir,
|
|
65
|
+
output,
|
|
66
|
+
package=package,
|
|
67
|
+
use_generated_bindings=not generic,
|
|
68
|
+
format_code=not no_format,
|
|
69
|
+
clean=force,
|
|
70
|
+
fetch_modules=fetch_modules,
|
|
71
|
+
module_cache=Path(module_cache) if module_cache is not None else None,
|
|
72
|
+
)
|
|
73
|
+
except (ConversionError, HclSyntaxError) as error:
|
|
74
|
+
raise NfError(str(error)) from error
|
|
75
|
+
if report is not None:
|
|
76
|
+
Path(report).write_text(result.report())
|
|
77
|
+
return result
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def lint(app_spec: str, *, pack_names: Sequence[str], require_resolved: bool) -> LintResult:
|
|
81
|
+
from netherframe.core import App
|
|
82
|
+
from netherframe.core.linting import LintError, Linter
|
|
83
|
+
|
|
84
|
+
from .apps import load_app_from_spec
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
linter = Linter.from_plugins(list(pack_names) or None)
|
|
88
|
+
except (ValueError, TypeError) as error:
|
|
89
|
+
raise NfError(str(error)) from error
|
|
90
|
+
if not linter.rules:
|
|
91
|
+
raise NfError("No lint rules loaded; install a lint pack such as netherframe.lint.hashicorp.aws.")
|
|
92
|
+
app = load_app_from_spec(app_spec)
|
|
93
|
+
if not isinstance(app, App):
|
|
94
|
+
raise ProjectError("The app spec must return an NF App.")
|
|
95
|
+
report = linter.lint_app(app)
|
|
96
|
+
try:
|
|
97
|
+
report.assert_valid(require_resolved=require_resolved)
|
|
98
|
+
except LintError as error:
|
|
99
|
+
return LintResult(report, str(error))
|
|
100
|
+
return LintResult(report)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class AnalysisCommands(ProjectBase):
|
|
104
|
+
"""convert, lint."""
|
|
105
|
+
|
|
106
|
+
def convert(
|
|
107
|
+
self,
|
|
108
|
+
module_dir: str | Path,
|
|
109
|
+
*,
|
|
110
|
+
output: str | Path = ".",
|
|
111
|
+
package: str | None = None,
|
|
112
|
+
generic: bool = False,
|
|
113
|
+
force: bool = False,
|
|
114
|
+
no_format: bool = False,
|
|
115
|
+
fetch_modules: bool = False,
|
|
116
|
+
module_cache: str | Path | None = None,
|
|
117
|
+
report: str | Path | None = None,
|
|
118
|
+
) -> ConversionResult:
|
|
119
|
+
"""The Terraform module in ``module_dir`` (and the local modules it calls) as a Python package under ``output``.
|
|
120
|
+
|
|
121
|
+
Writes the package ``package`` (default the module directory's name): a Stack subclass for
|
|
122
|
+
the module, a class per local module, typed constructs of the installed generated
|
|
123
|
+
provider packages (generic ``Resource(nf_type=...)`` ones with ``generic``), formatted
|
|
124
|
+
with Ruff unless ``no_format``. ``force`` replaces the package directory, ``fetch_modules``
|
|
125
|
+
downloads registry and archive modules (into ``module_cache``), ``report`` also writes
|
|
126
|
+
``result.report()`` to that file. Returns what was written and the TODO markers left;
|
|
127
|
+
raises ``NfError`` for a module that cannot be read or a package that exists.
|
|
128
|
+
"""
|
|
129
|
+
return self._run(
|
|
130
|
+
convert,
|
|
131
|
+
module_dir,
|
|
132
|
+
output=output,
|
|
133
|
+
package=package,
|
|
134
|
+
generic=generic,
|
|
135
|
+
force=force,
|
|
136
|
+
no_format=no_format,
|
|
137
|
+
fetch_modules=fetch_modules,
|
|
138
|
+
module_cache=module_cache,
|
|
139
|
+
report=report,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def lint(self, app_spec: str, *, pack_names: Sequence[str] = (), require_resolved: bool = False) -> LintResult:
|
|
143
|
+
"""Every lint of the resources of the app ``app_spec`` (``module.path:attribute``) builds, offline.
|
|
144
|
+
|
|
145
|
+
Uses the installed lint packs ``pack_names`` (default all), evaluating every check; the
|
|
146
|
+
result is valid when no check failed and some were evaluated (and, with
|
|
147
|
+
``require_resolved``, none waits on runtime values). Raises ``NfError`` when no rule is
|
|
148
|
+
loaded or a pack named is not installed, ``ProjectError`` when the spec builds no App.
|
|
149
|
+
"""
|
|
150
|
+
return self._run(lint, app_spec, pack_names=pack_names, require_resolved=require_resolved)
|
netherframe/sdk/apps.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Loading a project's apps: what an app spec names, and the app built from it with its inputs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from netherframe.core.inputs import InputError, build
|
|
11
|
+
|
|
12
|
+
from . import inputs as app_inputs
|
|
13
|
+
from .errors import InputsError, ProjectError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _ensure_import_context() -> None:
|
|
17
|
+
"""Import the project's modules from the current directory, through the nf_autoid codec when installed."""
|
|
18
|
+
cwd = str(Path.cwd())
|
|
19
|
+
if cwd not in sys.path:
|
|
20
|
+
sys.path.insert(0, cwd)
|
|
21
|
+
try:
|
|
22
|
+
from netherframe.codec.autoid import register_codec
|
|
23
|
+
|
|
24
|
+
register_codec()
|
|
25
|
+
except Exception: # noqa: BLE001,S110 - loading apps works without the codec, or with it registered already
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def load_target(app_spec: str) -> Any:
|
|
30
|
+
"""What a configured app spec (``module.path:attr``) names: an app, or a factory of one, not yet called."""
|
|
31
|
+
if ":" not in app_spec:
|
|
32
|
+
raise ProjectError(f"Invalid app spec '{app_spec}'. Expected 'module.path:app_attr'.")
|
|
33
|
+
|
|
34
|
+
module_path, app_attr = app_spec.rsplit(":", 1)
|
|
35
|
+
_ensure_import_context()
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
module = importlib.import_module(module_path)
|
|
39
|
+
except Exception as exc:
|
|
40
|
+
raise ProjectError(f"Failed to import module '{module_path}' from app spec '{app_spec}': {exc}") from exc
|
|
41
|
+
|
|
42
|
+
if not hasattr(module, app_attr):
|
|
43
|
+
raise ProjectError(f"Module '{module_path}' has no attribute '{app_attr}' from app spec '{app_spec}'.")
|
|
44
|
+
return getattr(module, app_attr)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def load_app_from_spec(app_spec: str, *, recorded: dict[str, Any] | None = None) -> Any:
|
|
48
|
+
"""The app a configured app spec builds: a factory called with the current inputs (or a saved plan's ``recorded`` ones)."""
|
|
49
|
+
app_or_factory = load_target(app_spec)
|
|
50
|
+
try:
|
|
51
|
+
app = build(app_or_factory, app_inputs.current(), name=app_spec, recorded=recorded)
|
|
52
|
+
except InputError as exc:
|
|
53
|
+
raise InputsError(str(exc)) from exc
|
|
54
|
+
except Exception as exc:
|
|
55
|
+
raise ProjectError(f"Failed to construct app '{app_spec}': {exc}") from exc
|
|
56
|
+
|
|
57
|
+
if app is None:
|
|
58
|
+
raise ProjectError(f"App '{app_spec}' resolved to None.")
|
|
59
|
+
|
|
60
|
+
app_inputs.took(app)
|
|
61
|
+
return app
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""nf backend: the state backend the settings choose for code that names none, and its resources.
|
|
2
|
+
|
|
3
|
+
The backend is the settings' (``backend_type`` and its options: ``nf --backend-type s3
|
|
4
|
+
--backend-s3-bucket ...``, or ``[tool.nf.config]``), else local; nothing is saved
|
|
5
|
+
(``netherframe.core.backends.backend_config``). ``show`` says which it is and where states go;
|
|
6
|
+
``bootstrap`` creates the resources it needs (an S3 bucket and lock table) and ``validate``
|
|
7
|
+
checks they exist. Bootstrapping uses the setting ``bootstrap_aws_provider_version``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass, replace
|
|
14
|
+
from typing import TYPE_CHECKING, Any
|
|
15
|
+
|
|
16
|
+
from .base import Group
|
|
17
|
+
from .errors import NfError, UsageError
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from netherframe.core.backends.backend_bootstrap import BackendResources
|
|
21
|
+
from netherframe.core.backends.backend_chain_models import BackendBootstrapAction, BackendBootstrapResult
|
|
22
|
+
from netherframe.core.backends.backend_config import BackendConfig
|
|
23
|
+
|
|
24
|
+
#: Where a hybrid app's local state is by default (``<outdir>/nf.tfstate``)
|
|
25
|
+
DEFAULT_OUTDIR = ".nf.out"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class ConfiguredBackend:
|
|
30
|
+
"""``nf backend show``: the backend the settings choose (else local), and where states go with it."""
|
|
31
|
+
|
|
32
|
+
config: BackendConfig
|
|
33
|
+
#: Where a hybrid app's state is (``s3://bucket/prefix/nf.tfstate``, ``.nf.out/nf.tfstate``); None when the settings cannot give it
|
|
34
|
+
hybrid_state: str | None
|
|
35
|
+
#: Where a legacy stack's state is
|
|
36
|
+
legacy_state: str
|
|
37
|
+
#: Why the settings cannot give a hybrid app's state
|
|
38
|
+
hybrid_problem: str | None = None
|
|
39
|
+
|
|
40
|
+
def to_dict(self) -> dict[str, Any]:
|
|
41
|
+
return {**self.config.to_dict(), "hybrid_state": self.hybrid_state, "legacy_state": self.legacy_state, "hybrid_problem": self.hybrid_problem}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class BootstrapReport:
|
|
46
|
+
"""``nf backend bootstrap`` and ``validate``: the backend, and what bootstrapping it did (or would do)."""
|
|
47
|
+
|
|
48
|
+
config: BackendConfig
|
|
49
|
+
result: BackendBootstrapResult
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def backend_type(self) -> str:
|
|
53
|
+
"""The backend bootstrapped (or the configuration's type, when none was built)."""
|
|
54
|
+
return self.result.backend.backend_type if self.result.backend is not None else self.config.backend_type
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def action(self) -> BackendBootstrapAction:
|
|
58
|
+
return self.result.action
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def reason(self) -> str:
|
|
62
|
+
return self.result.reason
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def resources(self) -> BackendResources | None:
|
|
66
|
+
"""What was created (bootstrapped only)."""
|
|
67
|
+
return self.result.resources
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def valid(self) -> bool:
|
|
71
|
+
"""The backend's resources exist (what ``validate`` checks)."""
|
|
72
|
+
from netherframe.core.backends.backend_chain_models import BackendBootstrapAction
|
|
73
|
+
|
|
74
|
+
return self.result.action is BackendBootstrapAction.ALREADY_EXISTS
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _configured() -> BackendConfig:
|
|
78
|
+
from netherframe.core.backends.backend_config import configured_backend
|
|
79
|
+
|
|
80
|
+
return configured_backend()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _bootstrap(config: BackendConfig, *, force: bool, dry_run: bool) -> BackendBootstrapResult:
|
|
84
|
+
from netherframe.core.backends.backend_chain import build_backend_chain_from_config
|
|
85
|
+
from netherframe.core.constructs.backend_base import Backend as StateBackend
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
chain = build_backend_chain_from_config(config=config, include_local_fallback=False, register=False)
|
|
89
|
+
except ValueError as exc:
|
|
90
|
+
raise NfError(str(exc)) from exc
|
|
91
|
+
policy = StateBackend.BootstrapPolicy.ALWAYS if force else StateBackend.BootstrapPolicy.IF_MISSING
|
|
92
|
+
return chain.bootstrap_resources(policy=policy, dry_run=dry_run)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def bootstrap(force: bool = False, dry_run: bool = False, tags: Mapping[str, str] | None = None) -> BootstrapReport:
|
|
96
|
+
config = _configured()
|
|
97
|
+
if tags:
|
|
98
|
+
config = replace(config, bootstrap_tags=dict(tags))
|
|
99
|
+
return BootstrapReport(config, _bootstrap(config, force=force, dry_run=dry_run))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def validate() -> BootstrapReport:
|
|
103
|
+
config = _configured()
|
|
104
|
+
return BootstrapReport(config, _bootstrap(config, force=False, dry_run=True))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def show() -> ConfiguredBackend:
|
|
108
|
+
from netherframe.core.exceptions import ConfigurationError
|
|
109
|
+
|
|
110
|
+
config = _configured()
|
|
111
|
+
try:
|
|
112
|
+
hybrid_state, problem = config.describe_state(DEFAULT_OUTDIR), None
|
|
113
|
+
except ConfigurationError as exc:
|
|
114
|
+
hybrid_state, problem = None, str(exc)
|
|
115
|
+
return ConfiguredBackend(config, hybrid_state, config.describe_stacks(), problem)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def parse_tags(tags: Mapping[str, str] | tuple[str, ...] | list[str] | None) -> dict[str, str]:
|
|
119
|
+
"""``KEY=VALUE`` strings (``nf backend bootstrap --tag``), or a mapping, as tags."""
|
|
120
|
+
if tags is None:
|
|
121
|
+
return {}
|
|
122
|
+
if isinstance(tags, Mapping):
|
|
123
|
+
return {str(key): str(value) for key, value in tags.items()}
|
|
124
|
+
parsed = {}
|
|
125
|
+
for tag in tags:
|
|
126
|
+
key, equals, value = tag.partition("=")
|
|
127
|
+
if not equals or not key:
|
|
128
|
+
raise UsageError(f"A tag is KEY=VALUE, not {tag!r}")
|
|
129
|
+
parsed[key] = value
|
|
130
|
+
return parsed
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class Backend(Group):
|
|
134
|
+
"""nf backend: ``show`` the state backend the settings choose, ``bootstrap`` and ``validate`` its resources.
|
|
135
|
+
|
|
136
|
+
The backend is the settings' (``Project(settings={"backend_type": "s3", "backend_s3_bucket": ...})``),
|
|
137
|
+
else local. It is the backend of the stacks (legacy synthesis) and apps (hybrid runs) whose
|
|
138
|
+
code names none.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
def show(self) -> ConfiguredBackend:
|
|
142
|
+
"""The backend the settings choose, where each of its values came from, and where states go with it."""
|
|
143
|
+
return self._run(show)
|
|
144
|
+
|
|
145
|
+
def bootstrap(self, force: bool = False, dry_run: bool = False, tags: Mapping[str, str] | tuple[str, ...] | list[str] | None = None) -> BootstrapReport:
|
|
146
|
+
"""Create the backend's resources, unless they exist (``force`` creates them anyway); ``dry_run`` only says what it would do.
|
|
147
|
+
|
|
148
|
+
``tags`` (a mapping, or ``KEY=VALUE`` strings) tag what it creates. The report's
|
|
149
|
+
``action`` says what happened: bootstrapped, already there, skipped, unsupported or a dry
|
|
150
|
+
run. Raises ``NfError`` for a backend that cannot be built.
|
|
151
|
+
"""
|
|
152
|
+
return self._run(bootstrap, force, dry_run, parse_tags(tags))
|
|
153
|
+
|
|
154
|
+
def validate(self) -> BootstrapReport:
|
|
155
|
+
"""Whether the backend's resources exist (``report.valid``), checked without changing anything."""
|
|
156
|
+
return self._run(validate)
|
netherframe/sdk/base.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""What every command of the API runs on: its project (root, settings, inputs) and the scope of a call."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Self
|
|
8
|
+
|
|
9
|
+
from . import settings as settings_table
|
|
10
|
+
from .scope import project_scope
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ProjectBase:
|
|
14
|
+
"""An nf project: the directory its ``pyproject.toml`` is in, the settings and app inputs its commands run with."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, root: str | Path = ".", *, settings: Mapping[str, Any] | None = None, inputs: Mapping[str, Any] | None = None) -> None:
|
|
17
|
+
self.root = Path(root).resolve()
|
|
18
|
+
#: Settings its commands run with, by key (``netherframe.sdk.settings``): above ``[tool.nf.config]`` and App arguments
|
|
19
|
+
self.settings = settings_table.check(settings or {})
|
|
20
|
+
#: App inputs its commands build apps with (Python values: ``{"env": "prod", "replicas": 3}``)
|
|
21
|
+
self.inputs = dict(inputs or {})
|
|
22
|
+
|
|
23
|
+
def using(self, *, settings: Mapping[str, Any] | None = None, inputs: Mapping[str, Any] | None = None) -> Self:
|
|
24
|
+
"""This project with more settings or inputs (they win over its own)."""
|
|
25
|
+
return type(self)(self.root, settings={**self.settings, **(settings or {})}, inputs={**self.inputs, **(inputs or {})})
|
|
26
|
+
|
|
27
|
+
def _run[T](self, function: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
|
|
28
|
+
"""``function`` run in the project's directory with its settings and inputs."""
|
|
29
|
+
with project_scope(self.root, self.settings, self.inputs):
|
|
30
|
+
return function(*args, **kwargs)
|
|
31
|
+
|
|
32
|
+
def __repr__(self) -> str:
|
|
33
|
+
return f"{type(self).__name__}({str(self.root)!r})"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Group:
|
|
37
|
+
"""A group of commands (``nf drift ...`` is ``project.drift``), run in its project's scope."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, project: ProjectBase) -> None:
|
|
40
|
+
self._project = project
|
|
41
|
+
|
|
42
|
+
def _run[T](self, function: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
|
|
43
|
+
return self._project._run(function, *args, **kwargs) # noqa: SLF001 - its own project's scope
|
|
44
|
+
|
|
45
|
+
def __repr__(self) -> str:
|
|
46
|
+
return f"{self._project!r}.{type(self).__name__.lower()}"
|