dcycle-cli 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.
dcycle_cli/__init__.py ADDED
@@ -0,0 +1,244 @@
1
+ """dcycle-cli — command-line interface for the Dcycle platform.
2
+
3
+ Dcycle is a build-and-deploy loop runner for data and ML pipelines. The ``dc``
4
+ binary talks to a Dcycle control plane to schedule cycles, stream logs, and
5
+ reconcile environments. This package implements both the Python API
6
+ (:class:`DcycleClient`) and the ``dc`` CLI dispatch.
7
+
8
+ Public CLI (per README):
9
+
10
+ - ``dc cycle <run|status|cancel> <name>``
11
+ - ``dc env <list|diff|switch>``
12
+ - ``dc manifest render <path>``
13
+ - ``dc whoami``
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ import sys
22
+ import urllib.error
23
+ import urllib.request
24
+ from dataclasses import dataclass, field
25
+ from typing import Any, Mapping, Protocol, Sequence
26
+
27
+ __all__ = [
28
+ "DcycleClient",
29
+ "Cycle",
30
+ "Environment",
31
+ "DcycleError",
32
+ "CycleRun",
33
+ "EnvDiff",
34
+ "manifest_render",
35
+ "list_environments",
36
+ "whoami",
37
+ ]
38
+
39
+ __version__ = "0.1.0"
40
+
41
+
42
+ class DcycleError(Exception):
43
+ """Base error for the dcycle-cli package."""
44
+
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # Models ---------------------------------------------------------------------
48
+ # ---------------------------------------------------------------------------
49
+
50
+
51
+ @dataclass
52
+ class Cycle:
53
+ """A Dcycle cycle definition."""
54
+
55
+ name: str
56
+ status: str = "pending"
57
+ env: str = "default"
58
+ started_at: str | None = None
59
+ finished_at: str | None = None
60
+ logs: list[str] = field(default_factory=list)
61
+
62
+
63
+ @dataclass
64
+ class CycleRun:
65
+ """The result of starting a cycle run."""
66
+
67
+ name: str
68
+ env: str
69
+ run_id: str
70
+ status: str = "running"
71
+ logs: list[str] = field(default_factory=list)
72
+
73
+
74
+ @dataclass
75
+ class Environment:
76
+ """A Dcycle environment."""
77
+
78
+ name: str
79
+ endpoint: str
80
+ variables: dict[str, str] = field(default_factory=dict)
81
+ active: bool = False
82
+
83
+
84
+ @dataclass
85
+ class EnvDiff:
86
+ """A diff between two environments."""
87
+
88
+ a: str
89
+ b: str
90
+ changes: list[dict[str, Any]] = field(default_factory=list)
91
+
92
+
93
+ # ---------------------------------------------------------------------------
94
+ # Client ---------------------------------------------------------------------
95
+ # ---------------------------------------------------------------------------
96
+
97
+
98
+ class _Transport(Protocol):
99
+ def request(self, method: str, url: str, *, headers: Mapping[str, str],
100
+ body: bytes | None) -> tuple[int, Any]: ...
101
+
102
+
103
+ class _UrllibTransport:
104
+ def request(self, method, url, *, headers, body):
105
+ req = urllib.request.Request(url, data=body, headers=dict(headers), method=method)
106
+ try:
107
+ with urllib.request.urlopen(req, timeout=30) as resp: # noqa: S310
108
+ raw = resp.read()
109
+ return resp.status, (json.loads(raw) if raw else None)
110
+ except urllib.error.HTTPError as exc:
111
+ raw = exc.read()
112
+ try:
113
+ data = json.loads(raw) if raw else None
114
+ except json.JSONDecodeError:
115
+ data = None
116
+ return exc.code, data
117
+
118
+
119
+ class DcycleClient:
120
+ """Typed client for the Dcycle control plane.
121
+
122
+ Args:
123
+ endpoint: Control plane URL (also read from ``DCOYNTROL_ENDPOINT``).
124
+ token: Auth token (also read from ``DCOYNTROL_TOKEN``).
125
+ transport: Injectable HTTP transport.
126
+ """
127
+
128
+ def __init__(self, *, endpoint: str | None = None,
129
+ token: str | None = None,
130
+ transport: _Transport | None = None) -> None:
131
+ self.endpoint = (endpoint or os.environ.get("DCOYNTROL_ENDPOINT", "")).rstrip("/")
132
+ self.token = token or os.environ.get("DCOYNTROL_TOKEN", "")
133
+ self.transport = transport or _UrllibTransport()
134
+ if not self.endpoint:
135
+ raise DcycleError("endpoint is required (set DCOYNTROL_ENDPOINT)")
136
+
137
+ def _request(self, method: str, path: str, *,
138
+ body: Mapping[str, Any] | None = None) -> tuple[int, Any]:
139
+ url = f"{self.endpoint}{path}"
140
+ headers = {"Accept": "application/json"}
141
+ if self.token:
142
+ headers["Authorization"] = f"Bearer {self.token}"
143
+ payload: bytes | None = None
144
+ if body is not None:
145
+ payload = json.dumps(body).encode("utf-8")
146
+ headers["Content-Type"] = "application/json"
147
+ status, data = self.transport.request(method, url, headers=headers, body=payload)
148
+ if status >= 400:
149
+ msg = "Dcycle API error"
150
+ if isinstance(data, Mapping):
151
+ msg = str(data.get("error") or data.get("message") or msg)
152
+ raise DcycleError(f"{msg} (status {status})")
153
+ return status, data
154
+
155
+ # ---- cycle -------------------------------------------------------------
156
+
157
+ def cycle_run(self, name: str, *, env: str = "default",
158
+ tail: bool = False) -> CycleRun:
159
+ """Start a named cycle. ``tail=True`` requests streamed logs."""
160
+ status, data = self._request("POST", f"/v1/cycles/{name}/run",
161
+ body={"env": env, "tail": tail})
162
+ return CycleRun(name=name, env=env, run_id=str(data.get("run_id", "")),
163
+ status=str(data.get("status", "running")),
164
+ logs=list(data.get("logs", [])))
165
+
166
+ def cycle_status(self, name: str) -> Cycle:
167
+ status, data = self._request("GET", f"/v1/cycles/{name}")
168
+ return Cycle(name=name, status=str(data.get("status", "pending")),
169
+ env=str(data.get("env", "default")),
170
+ started_at=data.get("started_at"),
171
+ finished_at=data.get("finished_at"),
172
+ logs=list(data.get("logs", [])))
173
+
174
+ def cycle_cancel(self, name: str) -> Cycle:
175
+ status, data = self._request("POST", f"/v1/cycles/{name}/cancel")
176
+ return Cycle(name=name, status=str(data.get("status", "cancelled")),
177
+ env=str(data.get("env", "default")))
178
+
179
+ # ---- env ---------------------------------------------------------------
180
+
181
+ def env_list(self) -> list[Environment]:
182
+ _, data = self._request("GET", "/v1/envs")
183
+ return [Environment(name=str(e.get("name", "")),
184
+ endpoint=str(e.get("endpoint", "")),
185
+ variables=dict(e.get("variables", {})),
186
+ active=bool(e.get("active", False)))
187
+ for e in data.get("items", [])]
188
+
189
+ def env_diff(self, a: str, b: str) -> EnvDiff:
190
+ _, data = self._request("GET", f"/v1/envs/{a}/diff/{b}")
191
+ return EnvDiff(a=a, b=b, changes=list(data.get("changes", [])))
192
+
193
+ def env_switch(self, name: str) -> Environment:
194
+ _, data = self._request("POST", f"/v1/envs/{name}/activate")
195
+ return Environment(name=name, endpoint=str(data.get("endpoint", "")),
196
+ variables=dict(data.get("variables", {})), active=True)
197
+
198
+ # ---- whoami ------------------------------------------------------------
199
+
200
+ def whoami(self) -> dict[str, Any]:
201
+ _, data = self._request("GET", "/v1/whoami")
202
+ return dict(data)
203
+
204
+
205
+ # ---------------------------------------------------------------------------
206
+ # Manifest rendering --------------------------------------------------------
207
+ # ---------------------------------------------------------------------------
208
+
209
+
210
+ _VAR_RE = re.compile(r"\$\{(\w+)\}")
211
+
212
+
213
+ def manifest_render(path: str, *, values: Mapping[str, str] | None = None) -> str:
214
+ """Render a Dcycle manifest with environment values.
215
+
216
+ Replaces ``${VAR}`` placeholders using ``values`` (or env vars). Returns
217
+ the rendered manifest text.
218
+ """
219
+ if not os.path.exists(path):
220
+ raise DcycleError(f"manifest not found: {path!r}")
221
+ with open(path, encoding="utf-8") as fh:
222
+ text = fh.read()
223
+ vals = dict(values or {})
224
+ # Fall back to environment for missing keys.
225
+ full = dict(os.environ)
226
+ full.update(vals)
227
+
228
+ def _sub(match: re.Match[str]) -> str:
229
+ key = match.group(1)
230
+ if key in full:
231
+ return str(full[key])
232
+ return match.group(0)
233
+
234
+ return _VAR_RE.sub(_sub, text)
235
+
236
+
237
+ def list_environments(client: DcycleClient) -> list[Environment]:
238
+ """Return environments from the control plane."""
239
+ return client.env_list()
240
+
241
+
242
+ def whoami(client: DcycleClient) -> dict[str, Any]:
243
+ """Return the authenticated user and active environment."""
244
+ return client.whoami()
dcycle_cli/cli.py ADDED
@@ -0,0 +1,155 @@
1
+ """Command-line interface for the Dcycle platform — the ``dc`` binary.
2
+
3
+ Dispatches ``cycle``, ``env``, ``manifest``, and ``whoami`` subcommands against
4
+ a :class:`dcycle_cli.DcycleClient`. JSON output mode (``-o json``) is supported
5
+ for piping into ``jq`` and friends.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import sys
14
+ from dataclasses import asdict
15
+ from typing import Sequence
16
+
17
+ from . import DcycleClient, DcycleError, manifest_render
18
+
19
+
20
+ def _client(args: argparse.Namespace) -> DcycleClient:
21
+ return DcycleClient(endpoint=os.environ.get("DCOYNTROL_ENDPOINT"),
22
+ token=os.environ.get("DCOYNTROL_TOKEN"))
23
+
24
+
25
+ def _emit(args: argparse.Namespace, obj: object) -> None:
26
+ if args.output == "json":
27
+ print(json.dumps(asdict(obj) if hasattr(obj, "__dataclass_fields__") else obj,
28
+ indent=2, default=str))
29
+ else:
30
+ if hasattr(obj, "__dataclass_fields__"):
31
+ for k, v in asdict(obj).items():
32
+ print(f"{k}: {v}")
33
+ elif isinstance(obj, list):
34
+ for item in obj:
35
+ if hasattr(item, "__dataclass_fields__"):
36
+ print(asdict(item).get("name", item))
37
+ else:
38
+ print(item)
39
+ else:
40
+ print(obj)
41
+
42
+
43
+ def _cmd_cycle_run(args: argparse.Namespace) -> int:
44
+ client = _client(args)
45
+ run = client.cycle_run(args.name, env=args.env, tail=args.tail)
46
+ _emit(args, run)
47
+ return 0
48
+
49
+
50
+ def _cmd_cycle_status(args: argparse.Namespace) -> int:
51
+ client = _client(args)
52
+ _emit(args, client.cycle_status(args.name))
53
+ return 0
54
+
55
+
56
+ def _cmd_cycle_cancel(args: argparse.Namespace) -> int:
57
+ client = _client(args)
58
+ _emit(args, client.cycle_cancel(args.name))
59
+ return 0
60
+
61
+
62
+ def _cmd_env_list(args: argparse.Namespace) -> int:
63
+ client = _client(args)
64
+ _emit(args, client.env_list())
65
+ return 0
66
+
67
+
68
+ def _cmd_env_diff(args: argparse.Namespace) -> int:
69
+ client = _client(args)
70
+ _emit(args, client.env_diff(args.a, args.b))
71
+ return 0
72
+
73
+
74
+ def _cmd_env_switch(args: argparse.Namespace) -> int:
75
+ client = _client(args)
76
+ _emit(args, client.env_switch(args.name))
77
+ return 0
78
+
79
+
80
+ def _cmd_manifest_render(args: argparse.Namespace) -> int:
81
+ text = manifest_render(args.path)
82
+ print(text)
83
+ return 0
84
+
85
+
86
+ def _cmd_whoami(args: argparse.Namespace) -> int:
87
+ client = _client(args)
88
+ _emit(args, client.whoami())
89
+ return 0
90
+
91
+
92
+ def build_parser() -> argparse.ArgumentParser:
93
+ """Construct the argparse parser for the ``dc`` CLI."""
94
+ parser = argparse.ArgumentParser(prog="dc",
95
+ description="Dcycle control plane CLI.")
96
+ parser.add_argument("-o", "--output", default="text", choices=("text", "json"))
97
+ sub = parser.add_subparsers(dest="command", required=True)
98
+
99
+ p_cycle = sub.add_parser("cycle", help="drive cycles")
100
+ csub = p_cycle.add_subparsers(dest="cycle_command", required=True)
101
+
102
+ p_run = csub.add_parser("run", help="start a named cycle")
103
+ p_run.add_argument("name")
104
+ p_run.add_argument("--env", default="default")
105
+ p_run.add_argument("--tail", action="store_true")
106
+ p_run.set_defaults(func=_cmd_cycle_run)
107
+
108
+ p_st = csub.add_parser("status", help="cycle status")
109
+ p_st.add_argument("name")
110
+ p_st.set_defaults(func=_cmd_cycle_status)
111
+
112
+ p_can = csub.add_parser("cancel", help="cancel a cycle")
113
+ p_can.add_argument("name")
114
+ p_can.set_defaults(func=_cmd_cycle_cancel)
115
+
116
+ p_env = sub.add_parser("env", help="inspect/reconcile environments")
117
+ esub = p_env.add_subparsers(dest="env_command", required=True)
118
+
119
+ p_el = esub.add_parser("list", help="list environments")
120
+ p_el.set_defaults(func=_cmd_env_list)
121
+
122
+ p_ed = esub.add_parser("diff", help="diff two environments")
123
+ p_ed.add_argument("a")
124
+ p_ed.add_argument("b")
125
+ p_ed.set_defaults(func=_cmd_env_diff)
126
+
127
+ p_es = esub.add_parser("switch", help="activate an environment")
128
+ p_es.add_argument("name")
129
+ p_es.set_defaults(func=_cmd_env_switch)
130
+
131
+ p_man = sub.add_parser("manifest", help="render a manifest")
132
+ msub = p_man.add_subparsers(dest="manifest_command", required=True)
133
+ p_mr = msub.add_parser("render", help="render a manifest with values")
134
+ p_mr.add_argument("path")
135
+ p_mr.set_defaults(func=_cmd_manifest_render)
136
+
137
+ p_who = sub.add_parser("whoami", help="show the authenticated user")
138
+ p_who.set_defaults(func=_cmd_whoami)
139
+
140
+ return parser
141
+
142
+
143
+ def main(argv: Sequence[str] | None = None) -> int:
144
+ """Entry point for the ``dc`` console script."""
145
+ parser = build_parser()
146
+ args = parser.parse_args(argv)
147
+ try:
148
+ return int(args.func(args))
149
+ except DcycleError as exc:
150
+ print(f"error: {exc}", file=sys.stderr)
151
+ return 1
152
+
153
+
154
+ if __name__ == "__main__":
155
+ raise SystemExit(main())
@@ -0,0 +1,56 @@
1
+ Metadata-Version: 2.4
2
+ Name: dcycle-cli
3
+ Version: 0.1.0
4
+ Summary: Command-line interface for the Dcycle platform — schedule cycles, stream logs, and reconcile environments from a build-and-deploy loop runner.
5
+ Author:
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # dcycle-cli
11
+
12
+ `dcycle-cli` is the command-line interface for the Dcycle platform, a build-and-deploy loop
13
+ runner for data and ML pipelines. The `dc` binary it installs talks to a Dcycle control plane to
14
+ schedule cycles, stream logs, and reconcile environments so you can drive complex release
15
+ topologies without leaving your terminal. It is designed for CI runners, laptops, and
16
+ interactive operators alike, with subcommands that map cleanly onto the underlying REST API.
17
+
18
+ ## Features
19
+
20
+ - `dc cycle run` starts a named cycle and tails structured logs to stdout in real time.
21
+ - First-class support for GitOps flows: pull a manifest, render it, and apply it in one command.
22
+ - Built-in environment switching (`--env staging`) with credentials pulled from your OS keychain.
23
+ - JSON output mode (`-o json`) for piping into `jq`, `fzf`, or other Unix tools.
24
+ - Plugins loaded from `~/.dcycle/plugins/` extend subcommands with team-specific workflows.
25
+ - Shell completion for bash, zsh, and fish.
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ pipx install dcycle-cli
31
+ ```
32
+
33
+ ## Quick start
34
+
35
+ ```bash
36
+ dc login https://dcycle.example.local
37
+ dc cycle run etl-nightly --env prod --tail
38
+ dc env diff staging prod --output json | jq '.changes[]'
39
+ ```
40
+
41
+ ## CLI
42
+
43
+ - `dc cycle <run|status|cancel> <name>` — drive cycles from the command line.
44
+ - `dc env <list|diff|switch>` — inspect and reconcile environments.
45
+ - `dc manifest render <path>` — render a Dcycle manifest with environment values.
46
+ - `dc whoami` — show the authenticated user and active environment.
47
+
48
+ ## Configuration
49
+
50
+ `dc` reads a config file at `~/.dcycle/config.toml`. Tokens are stored in the system keychain;
51
+ run `dc login` to set them up. `DCOYNTROL_ENDPOINT` and `DCOYNTROL_TOKEN` environment variables
52
+ override the file for headless runners.
53
+
54
+ ## License
55
+
56
+ MIT
@@ -0,0 +1,7 @@
1
+ dcycle_cli/__init__.py,sha256=dsvXrZPxdWnZA_sVYlma_JbUmOItrC60a0h019xsnh4,8419
2
+ dcycle_cli/cli.py,sha256=YZdNyWuRvxmNeBijQ79eqMKWLCtui3YNqgQPNCwwmts,4833
3
+ dcycle_cli-0.1.0.dist-info/METADATA,sha256=YLMctgcmzq8lHNeqLvsqPdToCTw0nFfNdiqBY04MQ1g,2081
4
+ dcycle_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ dcycle_cli-0.1.0.dist-info/entry_points.txt,sha256=aj_jNaAF2PQy2gOuuqtPw5FfPPR7m0TTLJEcdEaL65I,51
6
+ dcycle_cli-0.1.0.dist-info/top_level.txt,sha256=Am8LIEbsiswc4sVO4OJb7Xv5R21rVi5uvAtyAbCsLpI,11
7
+ dcycle_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ dcycle-cli = dcycle_cli.cli:main
@@ -0,0 +1 @@
1
+ dcycle_cli