previty-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.
@@ -0,0 +1,320 @@
1
+ """check run / status / watch / list (US-5, US-6)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from typing import TYPE_CHECKING, Annotated, Any
7
+
8
+ import typer
9
+
10
+ from previty_cli import clock, exit_codes, output
11
+ from previty_cli.commands import _common as c
12
+ from previty_cli.errors import PrevityError, UsageError
13
+
14
+ if TYPE_CHECKING:
15
+ from previty_cli.api.client import ApiClient
16
+
17
+ app = typer.Typer(help="Start and follow checks.", no_args_is_help=True)
18
+
19
+ DEFAULT_WAIT = "30m"
20
+ MAX_NAME_LENGTH = 255
21
+ MAX_IDEMPOTENCY_KEY_LENGTH = 128
22
+ MIN_POLL = 5.0
23
+ DEFAULT_POLL = 10.0
24
+
25
+ TimeoutOpt = Annotated[
26
+ str,
27
+ typer.Option(
28
+ "--timeout",
29
+ help="Stop waiting after this long (e.g. 90s, 30m, 1h). Exit 8; "
30
+ "the check keeps running.",
31
+ ),
32
+ ]
33
+ FailOnOpt = Annotated[
34
+ c.FailOn | None,
35
+ typer.Option(
36
+ "--fail-on",
37
+ help="Exit 10 if findings match: 'fail' (fail, fail_critical) or "
38
+ "'unclear' (also unclear). Off by default.",
39
+ ),
40
+ ]
41
+
42
+
43
+ def is_terminal(check: dict[str, Any]) -> bool:
44
+ status = check.get("status")
45
+ if status == "completed":
46
+ return True
47
+ return status == "failed" and not check.get("retrying")
48
+
49
+
50
+ def matches_fail_on(counts: dict[str, int], fail_on: c.FailOn | None) -> bool:
51
+ if fail_on is None:
52
+ return False
53
+ hits = counts.get("fail", 0) + counts.get("failCritical", 0)
54
+ if fail_on is c.FailOn.unclear:
55
+ hits += counts.get("unclear", 0)
56
+ return hits > 0
57
+
58
+
59
+ class _Progress:
60
+ """Progress goes to stderr: a Rich status line in a terminal, plain lines else."""
61
+
62
+ def __init__(self, ctx: typer.Context) -> None:
63
+ self.ctx = ctx
64
+ self.tty = output.is_stderr_tty()
65
+ self._status: Any = None
66
+ self._last = ""
67
+
68
+ def __enter__(self) -> _Progress:
69
+ if self.tty:
70
+ self._status = c.err_console(self.ctx).status("Waiting for the check…")
71
+ self._status.start()
72
+ return self
73
+
74
+ def __exit__(self, *exc: object) -> None:
75
+ if self._status is not None:
76
+ self._status.stop()
77
+
78
+ def message(self, text: str) -> None:
79
+ if text == self._last:
80
+ return
81
+ self._last = text
82
+ if self._status is not None:
83
+ self._status.update(output.clean(text))
84
+ else:
85
+ c.note(text)
86
+
87
+ def update(self, check: dict[str, Any]) -> None:
88
+ status = str(check.get("status"))
89
+ if check.get("retrying"):
90
+ status += " (retrying)"
91
+ prog = check.get("progress") or {}
92
+ detail = ""
93
+ if prog.get("total"):
94
+ detail = (
95
+ f" {prog.get('checked', 0)}/{prog['total']} ({prog.get('percent', 0)}%)"
96
+ )
97
+ self.message(f"Check {check.get('id')}: {status}{detail}")
98
+
99
+
100
+ def _show(ctx: typer.Context, check: dict[str, Any], as_json: bool) -> None:
101
+ if as_json:
102
+ from previty_cli.output import json as out_json
103
+
104
+ out_json.emit(check)
105
+ return
106
+ from previty_cli.api import models as m
107
+ from previty_cli.output import table
108
+
109
+ table.check(c.console(ctx), c.parse(m.PublicCheck, check))
110
+
111
+
112
+ def _follow(
113
+ ctx: typer.Context,
114
+ client: ApiClient,
115
+ check: dict[str, Any],
116
+ *,
117
+ timeout: float,
118
+ fail_on: c.FailOn | None,
119
+ as_json: bool,
120
+ show_start: bool,
121
+ ) -> None:
122
+ """Poll until terminal or timeout, print the result, map to exit codes."""
123
+ deadline = clock.monotonic() + timeout
124
+ timed_out = False
125
+ if show_start and not as_json:
126
+ _show(ctx, check, False)
127
+ with _Progress(ctx) as progress:
128
+ progress.update(check)
129
+ while not is_terminal(check):
130
+ remaining = deadline - clock.monotonic()
131
+ if remaining <= 0:
132
+ timed_out = True
133
+ break
134
+ poll = check.get("pollAfterSeconds")
135
+ interval = max(MIN_POLL, float(poll) if poll else DEFAULT_POLL)
136
+ clock.sleep(min(interval, remaining))
137
+ check = client.get_check(str(check["id"]))
138
+ progress.update(check)
139
+ # JSON mode prints only the final (or last known) check object to stdout.
140
+ if as_json:
141
+ _show(ctx, check, True)
142
+ elif show_start:
143
+ _show_result(ctx, check)
144
+ else:
145
+ _show(ctx, check, False)
146
+ check_id = check.get("id")
147
+ if timed_out:
148
+ raise PrevityError(
149
+ "WAIT_TIMEOUT",
150
+ f"Stopped waiting for check {check_id}; it is still {check.get('status')}.",
151
+ exit_code=exit_codes.WAIT_TIMEOUT,
152
+ hint=f"Continue with `previty check watch {check_id}`.",
153
+ )
154
+ if check.get("status") == "failed":
155
+ failure = check.get("failure") or {}
156
+ raise PrevityError(
157
+ "CHECK_FAILED",
158
+ f"Check {check_id} failed: {failure.get('summary') or failure.get('code') or 'no details'}",
159
+ exit_code=exit_codes.CHECK_FAILED,
160
+ )
161
+ if matches_fail_on(check.get("summary") or {}, fail_on):
162
+ assert fail_on is not None
163
+ raise PrevityError(
164
+ "FAIL_ON_MATCHED",
165
+ f"Check {check_id} has findings matching --fail-on {fail_on.value}.",
166
+ exit_code=exit_codes.FAIL_ON,
167
+ hint=f"See `previty results {check_id} --status fail,unclear`.",
168
+ )
169
+
170
+
171
+ def _show_result(ctx: typer.Context, check: dict[str, Any]) -> None:
172
+ """Final human summary after `run --wait` (the start block was shown already)."""
173
+ from previty_cli.api import models as m
174
+ from previty_cli.output import table
175
+
176
+ console = c.console(ctx)
177
+ console.print("")
178
+ table.check(console, c.parse(m.PublicCheck, check), header=False)
179
+
180
+
181
+ @app.command("run")
182
+ def run(
183
+ ctx: typer.Context,
184
+ app: c.AppOpt,
185
+ wait: Annotated[
186
+ bool, typer.Option("--wait", help="Wait for the check to end (like `watch`).")
187
+ ] = False,
188
+ timeout: TimeoutOpt = DEFAULT_WAIT,
189
+ use_last_snapshot: Annotated[
190
+ bool,
191
+ typer.Option(
192
+ "--use-last-snapshot",
193
+ help="Continue with the last snapshot if a repository update fails.",
194
+ ),
195
+ ] = False,
196
+ allow_unchanged: Annotated[
197
+ bool,
198
+ typer.Option(
199
+ "--allow-unchanged",
200
+ help="Start even if nothing changed since the last completed check "
201
+ "(uses up one check).",
202
+ ),
203
+ ] = False,
204
+ name: Annotated[
205
+ str | None, typer.Option("--name", help="Name of the check.")
206
+ ] = None,
207
+ fail_on: FailOnOpt = None,
208
+ idempotency_key: Annotated[
209
+ str | None,
210
+ typer.Option(
211
+ "--idempotency-key",
212
+ help="Reuse a key to re-run a request safely (default: random UUID).",
213
+ ),
214
+ ] = None,
215
+ json_flag: c.JsonOpt = False,
216
+ ) -> None:
217
+ """Start a check on the application's data sources."""
218
+ timeout_s = c.parse_duration(timeout)
219
+ as_json = c.wants_json(ctx, json_flag)
220
+ if name and len(name) > MAX_NAME_LENGTH:
221
+ raise UsageError(f"--name must be at most {MAX_NAME_LENGTH} characters.")
222
+ if idempotency_key is not None and not (
223
+ 0 < len(idempotency_key) <= MAX_IDEMPOTENCY_KEY_LENGTH
224
+ ):
225
+ raise UsageError(
226
+ f"--idempotency-key must be 1 to {MAX_IDEMPOTENCY_KEY_LENGTH} characters."
227
+ )
228
+ key = idempotency_key or str(uuid.uuid4())
229
+ body: dict[str, Any] = {
230
+ "useLastSnapshot": use_last_snapshot,
231
+ "allowUnchanged": allow_unchanged,
232
+ }
233
+ if name:
234
+ body["name"] = name
235
+ announced = False
236
+
237
+ def on_wait() -> None:
238
+ nonlocal announced
239
+ if not announced and output.is_stderr_tty():
240
+ announced = True
241
+ c.note("Syncing repositories…")
242
+
243
+ with c.open_client(ctx) as client:
244
+ check = client.start_check(app, body, key, on_wait=on_wait)
245
+ if not wait:
246
+ _show(ctx, check, as_json)
247
+ return
248
+ _follow(
249
+ ctx,
250
+ client,
251
+ check,
252
+ timeout=timeout_s,
253
+ fail_on=fail_on,
254
+ as_json=as_json,
255
+ show_start=not as_json,
256
+ )
257
+
258
+
259
+ @app.command("status")
260
+ def status(
261
+ ctx: typer.Context,
262
+ check: Annotated[str, typer.Argument(help="Check ID.")],
263
+ json_flag: c.JsonOpt = False,
264
+ ) -> None:
265
+ """Show status, progress, sources and summary of a check."""
266
+ as_json = c.wants_json(ctx, json_flag)
267
+ with c.open_client(ctx) as client:
268
+ data = client.get_check(check)
269
+ _show(ctx, data, as_json)
270
+
271
+
272
+ @app.command("watch")
273
+ def watch(
274
+ ctx: typer.Context,
275
+ check: Annotated[str, typer.Argument(help="Check ID.")],
276
+ timeout: TimeoutOpt = DEFAULT_WAIT,
277
+ fail_on: FailOnOpt = None,
278
+ json_flag: c.JsonOpt = False,
279
+ ) -> None:
280
+ """Poll a check until it ends."""
281
+ timeout_s = c.parse_duration(timeout)
282
+ as_json = c.wants_json(ctx, json_flag)
283
+ with c.open_client(ctx) as client:
284
+ data = client.get_check(check)
285
+ _follow(
286
+ ctx,
287
+ client,
288
+ data,
289
+ timeout=timeout_s,
290
+ fail_on=fail_on,
291
+ as_json=as_json,
292
+ show_start=False,
293
+ )
294
+
295
+
296
+ @app.command("list")
297
+ def list_checks(
298
+ ctx: typer.Context,
299
+ app: c.AppOpt,
300
+ status: Annotated[
301
+ str | None, typer.Option("--status", help="Filter by status.")
302
+ ] = None,
303
+ limit: Annotated[
304
+ int, typer.Option("--limit", min=1, help="Maximum number of checks.")
305
+ ] = 25,
306
+ json_flag: c.JsonOpt = False,
307
+ ) -> None:
308
+ """List the checks of an application."""
309
+ as_json = c.wants_json(ctx, json_flag)
310
+ with c.open_client(ctx) as client:
311
+ data = client.list_checks(app, status, limit)
312
+ if as_json:
313
+ from previty_cli.output import json as out_json
314
+
315
+ out_json.emit(data)
316
+ return
317
+ from previty_cli.api import models as m
318
+ from previty_cli.output import table
319
+
320
+ table.check_list(c.console(ctx), c.parse(m.PublicCheckList, data))
@@ -0,0 +1,27 @@
1
+ """readiness (US-5)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from previty_cli import exit_codes
8
+ from previty_cli.commands import _common as c
9
+
10
+
11
+ def readiness(ctx: typer.Context, app: c.AppOpt, json_flag: c.JsonOpt = False) -> None:
12
+ """Show whether a check can be started. Exits 7 if it cannot."""
13
+ as_json = c.wants_json(ctx, json_flag)
14
+ with c.open_client(ctx) as client:
15
+ data = client.readiness(app)
16
+ if as_json:
17
+ from previty_cli.output import json as out_json
18
+
19
+ out_json.emit(data)
20
+ else:
21
+ from previty_cli.api import models as m
22
+ from previty_cli.output import table
23
+
24
+ parsed = c.parse(m.PublicReadiness, data)
25
+ table.readiness(c.console(ctx), parsed)
26
+ if not data.get("canStartCheck"):
27
+ raise typer.Exit(exit_codes.CONFLICT)
@@ -0,0 +1,77 @@
1
+ """results (US-7)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from enum import Enum
7
+ from typing import Annotated
8
+
9
+ import typer
10
+
11
+ from previty_cli import exit_codes
12
+ from previty_cli.commands import _common as c
13
+ from previty_cli.commands.checks import FailOnOpt
14
+ from previty_cli.errors import PrevityError, UsageError
15
+
16
+
17
+ class OutputFormat(str, Enum):
18
+ table = "table"
19
+ json = "json"
20
+ markdown = "markdown"
21
+
22
+
23
+ def results(
24
+ ctx: typer.Context,
25
+ check: Annotated[str, typer.Argument(help="Check ID.")],
26
+ status: Annotated[
27
+ str | None,
28
+ typer.Option("--status", help="Comma-separated, e.g. fail,unclear."),
29
+ ] = None,
30
+ format_: Annotated[
31
+ OutputFormat | None,
32
+ typer.Option(
33
+ "--format",
34
+ help="table (default in a terminal), json (default otherwise) or markdown.",
35
+ ),
36
+ ] = None,
37
+ fail_on: FailOnOpt = None,
38
+ json_flag: c.JsonOpt = False,
39
+ ) -> None:
40
+ """List the findings of a check. Pages through all results."""
41
+ if json_flag and format_ not in (None, OutputFormat.json):
42
+ raise UsageError("--json cannot be combined with --format table|markdown.")
43
+ if format_ is None:
44
+ fmt = OutputFormat.json if c.wants_json(ctx, json_flag) else OutputFormat.table
45
+ else:
46
+ fmt = format_
47
+ with c.open_client(ctx) as client:
48
+ data = client.list_results(check, status)
49
+
50
+ if fmt is OutputFormat.json:
51
+ from previty_cli.output import json as out_json
52
+
53
+ out_json.emit(data)
54
+ else:
55
+ from previty_cli.api import models as m
56
+
57
+ parsed = c.parse(m.PublicFindingList, data)
58
+ if fmt is OutputFormat.markdown:
59
+ from previty_cli.output import markdown
60
+
61
+ sys.stdout.write(markdown.render_results(parsed))
62
+ else:
63
+ from previty_cli.output import table
64
+
65
+ table.results(c.console(ctx), parsed)
66
+
67
+ if fail_on is not None:
68
+ bad = {"fail", "fail_critical"}
69
+ if fail_on is c.FailOn.unclear:
70
+ bad.add("unclear")
71
+ hits = sum(1 for item in data.get("items", []) if item.get("status") in bad)
72
+ if hits:
73
+ raise PrevityError(
74
+ "FAIL_ON_MATCHED",
75
+ f"{hits} finding(s) match --fail-on {fail_on.value}.",
76
+ exit_code=exit_codes.FAIL_ON,
77
+ )
@@ -0,0 +1,94 @@
1
+ """sources list / branches / set-branch (US-9, US-10)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Annotated
6
+
7
+ import typer
8
+
9
+ from previty_cli.commands import _common as c
10
+ from previty_cli.errors import PrevityError
11
+
12
+ app = typer.Typer(help="Data sources and their branches.", no_args_is_help=True)
13
+
14
+
15
+ @app.command("list")
16
+ def list_sources(
17
+ ctx: typer.Context, app: c.AppOpt, json_flag: c.JsonOpt = False
18
+ ) -> None:
19
+ """List the data sources of an application."""
20
+ as_json = c.wants_json(ctx, json_flag)
21
+ with c.open_client(ctx) as client:
22
+ data = client.list_data_sources(app)
23
+ if as_json:
24
+ from previty_cli.output import json as out_json
25
+
26
+ out_json.emit(data)
27
+ return
28
+ from previty_cli.api import models as m
29
+ from previty_cli.output import table
30
+
31
+ table.sources(c.console(ctx), c.parse(m.PublicDataSourceList, data))
32
+
33
+
34
+ @app.command("branches")
35
+ def branches(
36
+ ctx: typer.Context,
37
+ source: Annotated[str, typer.Argument(help="Data source ID.")],
38
+ search: Annotated[
39
+ str | None, typer.Option("--search", help="Filter by substring.")
40
+ ] = None,
41
+ json_flag: c.JsonOpt = False,
42
+ ) -> None:
43
+ """List the branches of a GitHub data source; the current one is marked."""
44
+ as_json = c.wants_json(ctx, json_flag)
45
+ with c.open_client(ctx) as client:
46
+ data = client.list_branches(source, search)
47
+ if as_json:
48
+ from previty_cli.output import json as out_json
49
+
50
+ out_json.emit(data)
51
+ return
52
+ from previty_cli.api import models as m
53
+ from previty_cli.output import table
54
+
55
+ table.branches(c.console(ctx), source, c.parse(m.PublicBranchList, data))
56
+
57
+
58
+ @app.command("set-branch")
59
+ def set_branch(
60
+ ctx: typer.Context,
61
+ source: Annotated[str, typer.Argument(help="Data source ID.")],
62
+ branch: Annotated[str, typer.Argument(help="Branch name.")],
63
+ json_flag: c.JsonOpt = False,
64
+ ) -> None:
65
+ """Change the branch of a data source (application owners only)."""
66
+ as_json = c.wants_json(ctx, json_flag)
67
+ with c.open_client(ctx) as client:
68
+ previous: str | None = None
69
+ if not as_json:
70
+ # Best effort, only to print "old -> new"; the PUT reports real errors.
71
+ try:
72
+ current = client.list_branches(source).get("items", [])
73
+ previous = next(
74
+ (b["name"] for b in current if b.get("isCurrent")), None
75
+ )
76
+ except PrevityError:
77
+ previous = None
78
+ data = client.set_branch(source, branch)
79
+ if as_json:
80
+ from previty_cli.output import json as out_json
81
+
82
+ out_json.emit(data)
83
+ return
84
+ from previty_cli.output import clean
85
+
86
+ repo = clean(data.get("repository") or data.get("name") or source)
87
+ new = clean(data.get("branch") or branch)
88
+ if previous is None:
89
+ msg = f"Branch of {repo} set to {new}."
90
+ elif previous == new:
91
+ msg = f"Branch of {repo} is already {new}."
92
+ else:
93
+ msg = f"Branch of {repo} changed: {clean(previous)} → {new}."
94
+ c.console(ctx).print(msg)