due-extractor 0.3.1__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.
Files changed (54) hide show
  1. due/__init__.py +16 -0
  2. due/_brand.py +14 -0
  3. due/cli/__init__.py +1 -0
  4. due/cli/main.py +610 -0
  5. due/decode/__init__.py +169 -0
  6. due/decode/formats.py +152 -0
  7. due/decode/select.py +63 -0
  8. due/decode/xmlsel.py +133 -0
  9. due/defaults.yaml +185 -0
  10. due/errors.py +169 -0
  11. due/hooks.py +66 -0
  12. due/http/__init__.py +7 -0
  13. due/http/auth.py +252 -0
  14. due/http/circuit.py +61 -0
  15. due/http/client.py +313 -0
  16. due/http/clock.py +39 -0
  17. due/http/limits.py +55 -0
  18. due/http/ratelimit.py +128 -0
  19. due/http/request.py +71 -0
  20. due/http/retry.py +49 -0
  21. due/lake/__init__.py +1 -0
  22. due/lake/keyindex.py +83 -0
  23. due/lake/layout.py +75 -0
  24. due/lake/lock.py +83 -0
  25. due/lake/store.py +286 -0
  26. due/lake/ulid.py +25 -0
  27. due/lake/writer.py +302 -0
  28. due/paginate/__init__.py +248 -0
  29. due/preview.py +128 -0
  30. due/run/__init__.py +1 -0
  31. due/run/planner.py +194 -0
  32. due/run/prune.py +82 -0
  33. due/run/records.py +144 -0
  34. due/run/runner.py +1055 -0
  35. due/secrets/__init__.py +6 -0
  36. due/secrets/dotenv.py +38 -0
  37. due/secrets/refs.py +58 -0
  38. due/secrets/resolver.py +149 -0
  39. due/sources/__init__.py +275 -0
  40. due/sources/window.py +132 -0
  41. due/spec/catalog.py +502 -0
  42. due/spec/loader.py +589 -0
  43. due/spec/merge.py +68 -0
  44. due/spec/models.py +1022 -0
  45. due/spec/params.py +102 -0
  46. due/spec/templating.py +126 -0
  47. due/spec/validate.py +167 -0
  48. due/spec/yamlio.py +117 -0
  49. due/units.py +92 -0
  50. due_extractor-0.3.1.dist-info/METADATA +180 -0
  51. due_extractor-0.3.1.dist-info/RECORD +54 -0
  52. due_extractor-0.3.1.dist-info/WHEEL +4 -0
  53. due_extractor-0.3.1.dist-info/entry_points.txt +2 -0
  54. due_extractor-0.3.1.dist-info/licenses/LICENSE +191 -0
due/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """DUE: Declarative Universal Extractor · by Abhishek Manjunatha.
2
+
3
+ Extract from any API and land it in your data lake, with no custom scripts.
4
+ """
5
+
6
+ from importlib.metadata import PackageNotFoundError
7
+ from importlib.metadata import version as _dist_version
8
+
9
+ from due._brand import BYLINE, DIST, PRODUCT, TAGLINE
10
+
11
+ try:
12
+ __version__ = _dist_version(DIST)
13
+ except PackageNotFoundError: # running from a source checkout without install
14
+ __version__ = "0.0.0+local"
15
+
16
+ __all__ = ["BYLINE", "DIST", "PRODUCT", "TAGLINE", "__version__"]
due/_brand.py ADDED
@@ -0,0 +1,14 @@
1
+ """Branding: the one sanctioned place for the product name and byline (ADR-011 allow-list)."""
2
+
3
+ PRODUCT = "DUE"
4
+ TAGLINE = "Declarative Universal Extractor"
5
+ BYLINE = "by Abhishek Manjunatha"
6
+
7
+
8
+ def version_line(version: str) -> str:
9
+ """`DUE 0.1.0 · by Abhishek Manjunatha`, used by `due --version` and report/alert footers."""
10
+ return f"{PRODUCT} {version} · {BYLINE}"
11
+
12
+
13
+ DIST = "due-extractor"
14
+ """PyPI distribution name (`pip install due-extractor`); the command and import stay `due`."""
due/cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """DUE command-line interface."""
due/cli/main.py ADDED
@@ -0,0 +1,610 @@
1
+ """`due` CLI (M1: --version, validate, config show)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import errno
6
+ import os
7
+ import sys
8
+ from datetime import timedelta
9
+ from pathlib import Path
10
+ from typing import Annotated, Any
11
+
12
+ import typer
13
+ from rich.console import Console
14
+ from rich.markup import escape
15
+ from rich.table import Table
16
+
17
+ from due import __version__
18
+ from due._brand import BYLINE, PRODUCT, TAGLINE, version_line
19
+ from due.errors import (
20
+ ConfigError,
21
+ DueError,
22
+ ExitCode,
23
+ HookError,
24
+ LimitExceeded,
25
+ MissingExtra,
26
+ SecretError,
27
+ )
28
+ from due.spec.loader import PROJECT_FILE, load_project
29
+ from due.spec.merge import Origins, get_path
30
+ from due.spec.validate import validate as run_validate
31
+ from due.units import format_duration
32
+
33
+ app = typer.Typer(
34
+ name="due",
35
+ help=(
36
+ f"[bold]{PRODUCT}[/bold]: {TAGLINE}. Extract from any API into your data lake.\n\n[dim]{BYLINE}[/dim]"
37
+ ),
38
+ no_args_is_help=True,
39
+ add_completion=False,
40
+ rich_markup_mode="rich",
41
+ pretty_exceptions_enable=False,
42
+ )
43
+ config_app = typer.Typer(
44
+ help="Inspect effective settings and where each value comes from.", no_args_is_help=True
45
+ )
46
+ app.add_typer(config_app, name="config")
47
+ spec_app = typer.Typer(
48
+ help="Spec reference: field tags (* mandatory / optional), JSON Schema.", no_args_is_help=True
49
+ )
50
+ app.add_typer(spec_app, name="spec")
51
+
52
+ # soft_wrap: never hard-break messages, so file paths and keys stay copy-pasteable
53
+ out = Console(highlight=False, soft_wrap=True)
54
+ err = Console(stderr=True, highlight=False, soft_wrap=True)
55
+
56
+ ProjectOpt = Annotated[Path, typer.Option("--project", "-C", help="Project directory.", show_default=False)]
57
+ ProfileOpt = Annotated[str | None, typer.Option("--profile", "-p", help="Profile to use.")]
58
+
59
+
60
+ def _version_callback(value: bool) -> None:
61
+ if value:
62
+ out.print(version_line(__version__))
63
+ raise typer.Exit()
64
+
65
+
66
+ @app.callback()
67
+ def main(
68
+ version: Annotated[
69
+ bool, typer.Option("--version", "-V", callback=_version_callback, is_eager=True, help="Show version.")
70
+ ] = False,
71
+ ) -> None:
72
+ """DUE: Declarative Universal Extractor."""
73
+
74
+
75
+ # ---------------------------------------------------------------- validate
76
+
77
+
78
+ @app.command("validate")
79
+ def validate_cmd(
80
+ target: Annotated[
81
+ Path | None, typer.Argument(help="Project directory, due_project.yaml, or a single source file.")
82
+ ] = None,
83
+ project: ProjectOpt = Path(),
84
+ profile: ProfileOpt = None,
85
+ check_secrets: Annotated[
86
+ bool, typer.Option("--check-secrets", help="Warn about ${ENV} references that are not set.")
87
+ ] = False,
88
+ strict: Annotated[bool, typer.Option("--strict", help="Treat warnings as errors.")] = False,
89
+ allow_literal_secrets: Annotated[
90
+ bool, typer.Option("--allow-literal-secrets", help="Accept literal values in secret fields.")
91
+ ] = False,
92
+ ) -> None:
93
+ """Validate specs: schema, references, secrets syntax, templates and hooks."""
94
+ report = run_validate(
95
+ target or project,
96
+ profile=profile,
97
+ check_secrets=check_secrets,
98
+ allow_literal_secrets=allow_literal_secrets,
99
+ )
100
+ for res in report.profiles:
101
+ mark = "[green]✔[/green]" if res.ok else "[red]✖[/red]"
102
+ detail = f"{res.sources} source(s), {res.streams} stream(s)" if res.ok else "invalid"
103
+ out.print(f"{mark} profile [bold]{res.profile}[/bold]: {detail}")
104
+ for issue in report.errors:
105
+ out.print(f" [red]error[/red] {issue.render()}")
106
+ for issue in report.warnings:
107
+ out.print(f" [yellow]warning[/yellow] {issue.render()}")
108
+ failed = bool(report.errors) or (strict and bool(report.warnings))
109
+ summary = f"{len(report.errors)} error(s), {len(report.warnings)} warning(s)"
110
+ out.print(f"[red]✖ {summary}[/red]" if failed else f"[green]✔ valid[/green] ({summary})")
111
+ raise typer.Exit(ExitCode.CONFIG if failed else ExitCode.OK)
112
+
113
+
114
+ # ---------------------------------------------------------------- config show
115
+
116
+
117
+ def _fmt(value: Any) -> str:
118
+ if isinstance(value, timedelta):
119
+ return format_duration(value)
120
+ if value is None:
121
+ return "null"
122
+ if isinstance(value, bool):
123
+ return str(value).lower()
124
+ return str(value)
125
+
126
+
127
+ def _table(title: str, values: dict[str, Any], origins: Origins) -> Table:
128
+ table = Table(title=title, title_justify="left", show_lines=False, pad_edge=False)
129
+ table.add_column("setting", style="bold")
130
+ table.add_column("value")
131
+ table.add_column("from", style="dim")
132
+ for path in sorted(origins):
133
+ table.add_row(".".join(path), _fmt(get_path(values, path)), origins[path])
134
+ return table
135
+
136
+
137
+ @config_app.command("show")
138
+ def config_show(
139
+ selection: Annotated[
140
+ str | None, typer.Argument(help="Nothing (project), 'source', or 'source.stream'.")
141
+ ] = None,
142
+ project: ProjectOpt = Path(),
143
+ profile: ProfileOpt = None,
144
+ ) -> None:
145
+ """Show effective settings and the layer each value came from (defaults, project, profile, …)."""
146
+ loaded = load_project(project, profile)
147
+ caption = f"profile: {loaded.profile or '(none)'} · secrets are shown as references, never values"
148
+ if not selection:
149
+ table = _table(f"{PROJECT_FILE} (effective)", loaded.values, loaded.origins)
150
+ else:
151
+ src_name, _, stream_name = selection.partition(".")
152
+ src = loaded.sources.get(src_name)
153
+ if src is None:
154
+ raise ConfigError_(f"unknown source '{src_name}'; available: {', '.join(loaded.sources)}")
155
+ if not stream_name:
156
+ table = _table(f"source {src_name} (effective)", src.values, src.origins)
157
+ else:
158
+ stream = src.streams.get(stream_name)
159
+ if stream is None:
160
+ raise ConfigError_(f"unknown stream '{stream_name}'; available: {', '.join(src.streams)}")
161
+ table = _table(f"stream {selection} (effective)", stream.values, stream.origins)
162
+ table.caption = caption
163
+ out.print(table)
164
+
165
+
166
+ class ConfigError_(DueError):
167
+ pass
168
+
169
+
170
+ # ---------------------------------------------------------------- preview
171
+
172
+
173
+ def _parse_partition(values: list[str] | None) -> dict[str, str] | None:
174
+ if not values:
175
+ return None
176
+ out: dict[str, str] = {}
177
+ for item in values:
178
+ key, sep, value = item.partition("=")
179
+ if not sep:
180
+ raise ConfigError_(f"--partition expects key=value, got '{item}'")
181
+ out[key] = value
182
+ return out
183
+
184
+
185
+ @app.command("preview")
186
+ def preview_cmd(
187
+ selection: Annotated[str, typer.Argument(help="Stream to preview, as 'source.stream'.")],
188
+ project: ProjectOpt = Path(),
189
+ profile: ProfileOpt = None,
190
+ limit: Annotated[int | None, typer.Option("--limit", "-n", help="Records to fetch.")] = None,
191
+ partition: Annotated[
192
+ list[str] | None, typer.Option("--partition", help="Matrix partition, e.g. repo=python/cpython.")
193
+ ] = None,
194
+ as_json: Annotated[bool, typer.Option("--json", help="Print records as NDJSON.")] = False,
195
+ ) -> None:
196
+ """Fetch the first records of a stream from the live API. Nothing is written."""
197
+ import asyncio
198
+
199
+ from due.preview import preview
200
+ from due.sources import dumps_record
201
+ from due.spec.loader import builtin_defaults
202
+
203
+ loaded = load_project(project, profile)
204
+ n = limit or int(builtin_defaults()["internal"]["extract"]["preview_records"])
205
+ result = asyncio.run(preview(loaded, selection, limit=n, partition=_parse_partition(partition)))
206
+ if as_json:
207
+ for record in result.records:
208
+ out.print(dumps_record(record), markup=False, highlight=False, soft_wrap=True)
209
+ return
210
+ where = (
211
+ f" · partition {result.partition} (1 of {result.partitions_available})" if result.partition else ""
212
+ )
213
+ window = f" · window {result.window}" if result.window else ""
214
+ out.print(
215
+ f"[bold]{result.source}.{result.stream}[/bold]: {len(result.records)} record(s) from "
216
+ f"{result.pages} page(s), {result.requests} request(s){where}{window}"
217
+ )
218
+ if not result.records:
219
+ return
220
+ columns = result.fields[: int(builtin_defaults()["internal"]["extract"]["preview_columns"])]
221
+ table = Table(pad_edge=False, show_lines=False)
222
+ for col in columns:
223
+ table.add_column(
224
+ escape(col),
225
+ overflow="ellipsis",
226
+ no_wrap=True,
227
+ max_width=int(builtin_defaults()["internal"]["extract"]["preview_column_width"]),
228
+ ) # due: allow-literal — display width
229
+ for record in result.records:
230
+ table.add_row(*(escape(_cell(record.get(col))) for col in columns))
231
+ more = len(result.fields) - len(columns)
232
+ if more > 0:
233
+ table.caption = f"+{more} more field(s); use --json to see full records"
234
+ out.print(table)
235
+
236
+
237
+ def _cell(value: Any) -> str:
238
+ if value is None:
239
+ return ""
240
+ if isinstance(value, dict | list):
241
+ from due.sources import dumps_record
242
+
243
+ return dumps_record(value) if isinstance(value, dict) else str(value)
244
+ return str(value)
245
+
246
+
247
+ # ---------------------------------------------------------------- run
248
+
249
+
250
+ _JSON_INDENT = 2 # due: allow-literal — display formatting
251
+ _STATUS_STYLE = {
252
+ "committed": "green",
253
+ "up_to_date": "dim",
254
+ "planned": "cyan",
255
+ "skipped": "yellow",
256
+ "failed": "red",
257
+ "limit": "yellow",
258
+ }
259
+
260
+
261
+ @app.command("run")
262
+ def run_cmd(
263
+ selection: Annotated[
264
+ list[str] | None,
265
+ typer.Argument(help="Sources or streams, e.g. 'github' or 'github.issues' (default: all)."),
266
+ ] = None,
267
+ project: ProjectOpt = Path(),
268
+ profile: ProfileOpt = None,
269
+ dry_run: Annotated[
270
+ bool, typer.Option("--dry-run", help="Plan units and windows; fetch nothing.")
271
+ ] = False,
272
+ ) -> None:
273
+ """Extract streams into the lake."""
274
+ import asyncio
275
+
276
+ from due.run.runner import run_project
277
+
278
+ loaded = load_project(project, profile)
279
+ _render_run(asyncio.run(run_project(loaded, selection, dry_run=dry_run)), dry_run)
280
+
281
+
282
+ @app.command("backfill")
283
+ def backfill_cmd(
284
+ selection: Annotated[str, typer.Argument(help="Incremental stream, as 'source.stream'.")],
285
+ start: Annotated[str, typer.Option("--from", help="Start (ISO date/time, UTC), inclusive.")],
286
+ end: Annotated[str, typer.Option("--to", help="End (ISO date/time, UTC), exclusive.")],
287
+ project: ProjectOpt = Path(),
288
+ profile: ProfileOpt = None,
289
+ dry_run: Annotated[bool, typer.Option("--dry-run", help="Plan the windows; fetch nothing.")] = False,
290
+ ) -> None:
291
+ """Re-extract an explicit time range. Existing windows are replaced; the watermark never moves back."""
292
+ import asyncio
293
+
294
+ from due.run.planner import backfill_windows
295
+ from due.run.runner import run_project
296
+ from due.spec.templating import _as_datetime
297
+
298
+ loaded = load_project(project, profile)
299
+ src_name, _, stream_name = selection.partition(".")
300
+ src = loaded.sources.get(src_name)
301
+ if src is None or stream_name not in src.streams:
302
+ raise ConfigError_(f"unknown stream '{selection}'")
303
+ stream = src.streams[stream_name].spec
304
+ if stream.incremental is None:
305
+ raise ConfigError_(f"'{selection}' is not incremental; backfill needs incremental windows")
306
+ lo, hi = _as_datetime(start), _as_datetime(end)
307
+ if lo >= hi:
308
+ raise ConfigError_("--from must be earlier than --to")
309
+ windows = {(src_name, stream_name): backfill_windows(stream, lo, hi)}
310
+ _render_run(asyncio.run(run_project(loaded, [selection], windows=windows, dry_run=dry_run)), dry_run)
311
+
312
+
313
+ @app.command("retry")
314
+ def retry_cmd(
315
+ run_id: Annotated[str, typer.Argument(help="Run whose failed units to re-run.")],
316
+ project: ProjectOpt = Path(),
317
+ profile: ProfileOpt = None,
318
+ ) -> None:
319
+ """Re-run only the failed units of a previous run, with their original (frozen) windows."""
320
+ import asyncio
321
+
322
+ from due.run.runner import run_project
323
+
324
+ loaded = load_project(project, profile)
325
+ _render_run(asyncio.run(run_project(loaded, retry_of=run_id)), False)
326
+
327
+
328
+ def _render_run(result: Any, dry_run: bool) -> None:
329
+ for warning in result.warnings:
330
+ out.print(f"[yellow]warning[/yellow] {escape(warning)}")
331
+ title = f"run {result.run_id}" + (" (dry run)" if dry_run else "")
332
+ table = Table(pad_edge=False, title=title, title_justify="left")
333
+ for col in (
334
+ "stream",
335
+ "partition",
336
+ "window",
337
+ "status",
338
+ "written",
339
+ "ins/upd",
340
+ "skipped",
341
+ "rejected",
342
+ "pages",
343
+ ):
344
+ table.add_column(col, overflow="fold")
345
+ for u in result.units:
346
+ c = u.counts
347
+ style = _STATUS_STYLE.get(u.status, "")
348
+ marks = (" ↺" if u.superseded else "") + (" ⟳" if u.resumed else "")
349
+ deleted = f" −{c['deleted']}" if c.get("deleted") else ""
350
+ table.add_row(
351
+ escape(f"{u.source}.{u.stream}"),
352
+ escape(u.partition or ""),
353
+ escape(u.window),
354
+ f"[{style}]{u.status}[/{style}]{marks}",
355
+ f"{c.get('written', '')}{deleted}",
356
+ f"{c.get('inserted', 0)}/{c.get('updated', 0)}" if c else "",
357
+ str(c.get("skipped_overlap", 0) + c.get("deduped", 0)) if c else "",
358
+ str(c.get("rejected", "")),
359
+ str(c.get("pages", "")),
360
+ )
361
+ table.caption = f"lake: {result.lake} · ↺ replaced the window · ⟳ resumed · −n tombstones"
362
+ out.print(table)
363
+ for u in result.units:
364
+ if u.error:
365
+ err.print(f"[red]{escape(u.source)}.{escape(u.stream)}[/red]: {escape(u.error)}")
366
+ raise typer.Exit(result.exit_code)
367
+
368
+
369
+ def _stream_store(selection: str, project: Path, profile: str | None) -> tuple[Any, Any, Any]:
370
+ from due.lake.layout import StreamLayout
371
+ from due.run.runner import stream_store
372
+
373
+ loaded = load_project(project, profile)
374
+ src_name, _, stream_name = selection.partition(".")
375
+ if src_name not in loaded.sources or stream_name not in loaded.sources[src_name].streams:
376
+ raise ConfigError_(f"unknown stream '{selection}'")
377
+ return loaded, stream_store(loaded, src_name, stream_name), StreamLayout(src_name, stream_name)
378
+
379
+
380
+ @app.command("unlock")
381
+ def unlock_cmd(
382
+ selection: Annotated[str, typer.Argument(help="Stream whose lock to release, as 'source.stream'.")],
383
+ project: ProjectOpt = Path(),
384
+ profile: ProfileOpt = None,
385
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Do not ask for confirmation.")] = False,
386
+ ) -> None:
387
+ """Force-release a stream's lock left by a crashed or killed run (ADR-006)."""
388
+ _, store, layout = _stream_store(selection, project, profile)
389
+ holder, _ = store.read_json(layout.lock)
390
+ if holder is None:
391
+ out.print(f"{escape(selection)} is not locked")
392
+ return
393
+ owner, expires = holder.get("owner"), holder.get("expires_at")
394
+ out.print(f"lock held by run {holder.get('run_id')} on {owner}, expires {expires}")
395
+ if not yes and not typer.confirm("Release it? Only do this if that run is no longer running"):
396
+ raise typer.Exit(ExitCode.FAILED)
397
+ store.delete(layout.lock)
398
+ out.print(f"[green]✔[/green] released the lock on {escape(selection)}")
399
+
400
+
401
+ @app.command("state")
402
+ def state_cmd(
403
+ action: Annotated[str, typer.Argument(help="show | reset")],
404
+ selection: Annotated[str, typer.Argument(help="Stream, as 'source.stream'.")],
405
+ project: ProjectOpt = Path(),
406
+ profile: ProfileOpt = None,
407
+ partition: Annotated[
408
+ str | None, typer.Option("--partition", help="Partition slug (default: all).")
409
+ ] = None,
410
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Do not ask for confirmation.")] = False,
411
+ ) -> None:
412
+ """Show a stream's saved progress, or reset it so the next run starts from `incremental.start`."""
413
+ import json as _json
414
+
415
+ _, store, layout = _stream_store(selection, project, profile)
416
+ names = [n.removesuffix(".json") for n in store.list_dir(f"{layout.meta}/state")]
417
+ parts = [partition] if partition else names
418
+ if action == "show":
419
+ if not parts:
420
+ out.print(f"{escape(selection)} has no saved state yet")
421
+ for part in parts:
422
+ state, _ = store.read_json(f"{layout.meta}/state/{part}.json")
423
+ out.print(f"[bold]{escape(selection)}[/bold] partition {escape(part)}")
424
+ out.print(_json.dumps(state, indent=_JSON_INDENT, default=str), markup=False, highlight=False)
425
+ return
426
+ if action != "reset":
427
+ raise ConfigError_("action must be 'show' or 'reset'")
428
+ if not parts:
429
+ out.print(f"{escape(selection)} has no saved state")
430
+ return
431
+ question = f"Reset {len(parts)} partition state(s)? The next run re-extracts from the start (data stays)."
432
+ if not yes and not typer.confirm(question):
433
+ raise typer.Exit(ExitCode.FAILED)
434
+ for part in parts:
435
+ store.delete(f"{layout.meta}/state/{part}.json")
436
+ store.remove_tree(f"{layout.meta}/keys/{part}")
437
+ out.print(f"[green]✔[/green] reset {len(parts)} partition(s) of {escape(selection)}")
438
+
439
+
440
+ @app.command("prune")
441
+ def prune_cmd(
442
+ project: ProjectOpt = Path(),
443
+ profile: ProfileOpt = None,
444
+ dry_run: Annotated[bool, typer.Option("--dry-run", help="List what would be removed.")] = False,
445
+ ) -> None:
446
+ """Apply `retention` (keep_days / keep_runs): remove superseded attempts and old run summaries."""
447
+ from due.lake.layout import StreamLayout
448
+ from due.run.prune import prune
449
+ from due.run.runner import Lakes, project_resolver
450
+
451
+ loaded = load_project(project, profile)
452
+ retention = loaded.project.retention
453
+ if retention.keep_days is None and retention.keep_runs is None:
454
+ out.print("retention is not configured (retention.keep_days / keep_runs); nothing to prune")
455
+ return
456
+ layouts = [StreamLayout(s, n) for s, src in loaded.sources.items() for n in src.streams]
457
+ lakes = Lakes(loaded, project_resolver(loaded))
458
+ report = prune(
459
+ lakes.project_lake,
460
+ layouts,
461
+ retention,
462
+ dry_run=dry_run,
463
+ stream_store=lambda lay: lakes.for_stream(lay.source, lay.stream),
464
+ )
465
+ verb = "would remove" if dry_run else "removed"
466
+ out.print(
467
+ f"{verb} {len(report.removed_attempts)} superseded attempt(s) and {len(report.removed_runs)} "
468
+ f"run summary(ies); {report.kept_current} current attempt(s) untouched"
469
+ )
470
+ for item in report.removed_attempts:
471
+ out.print(f" {escape(item)}")
472
+
473
+
474
+ # ---------------------------------------------------------------- spec fields / schema
475
+
476
+
477
+ @spec_app.command("fields")
478
+ def spec_fields(
479
+ path: Annotated[
480
+ str | None, typer.Argument(help="Field path prefix, e.g. 'source.auth', 'streams.*.incremental'.")
481
+ ] = None,
482
+ kind: Annotated[str | None, typer.Option("--kind", "-k", help="project | source | stream")] = None,
483
+ mandatory: Annotated[
484
+ bool, typer.Option("--mandatory", "-m", help="Only mandatory and conditional fields.")
485
+ ] = False,
486
+ fmt: Annotated[str, typer.Option("--format", "-f", help="table | markdown")] = "table",
487
+ ) -> None:
488
+ """List spec fields with their tag: * mandatory, * when … (conditional), or optional + default."""
489
+ from due.spec.catalog import KINDS, catalog, find, render_markdown
490
+
491
+ if kind is not None and kind not in KINDS:
492
+ raise ConfigError_(f"--kind must be one of {', '.join(KINDS)}")
493
+ entries = find(path, kind) if path else catalog(kind)
494
+ if mandatory:
495
+ entries = [e for e in entries if e.tag != "optional"]
496
+ if not entries:
497
+ raise ConfigError_(f"no fields match '{path}'")
498
+ if fmt == "markdown":
499
+ out.print(render_markdown(entries), markup=False, highlight=False)
500
+ return
501
+ if fmt != "table":
502
+ raise ConfigError_("--format must be 'table' or 'markdown'")
503
+ table = Table(pad_edge=False, caption="* mandatory · * when … conditional · 🔒 secret")
504
+ for col, style in (
505
+ ("field", "bold"),
506
+ ("req", ""),
507
+ ("type", "dim"),
508
+ ("default", ""),
509
+ ("rules", "dim"),
510
+ ("description", ""),
511
+ ):
512
+ table.add_column(col, style=style, overflow="fold")
513
+ for e in entries:
514
+ req = {"mandatory": "[red]*[/red]", "optional": "[dim]optional[/dim]"}.get(
515
+ e.tag, f"[yellow]* {escape(e.condition or '')}[/yellow]"
516
+ )
517
+ desc = e.description + (" 🔒" if e.secret else "")
518
+ cells = [e.path, e.type, e.default_text, e.rule or "", desc]
519
+ path, typ, default, rule, desc = (escape(c) for c in cells) # '[bearer]' is not rich markup
520
+ table.add_row(path, req, typ, default, rule, desc)
521
+ out.print(table)
522
+
523
+
524
+ @spec_app.command("schema")
525
+ def spec_schema(
526
+ kind: Annotated[str, typer.Option("--kind", "-k", help="project | source")] = "source",
527
+ output: Annotated[
528
+ Path | None, typer.Option("--output", "-o", help="Write to a file instead of stdout.")
529
+ ] = None,
530
+ ) -> None:
531
+ """JSON Schema for editor autocomplete/validation; `required` lists only truly mandatory fields."""
532
+ import json
533
+
534
+ from due.spec.catalog import json_schema
535
+
536
+ if kind not in ("project", "source"):
537
+ raise ConfigError_("--kind must be 'project' or 'source'")
538
+ schema = json_schema(kind) # type: ignore[arg-type]
539
+ text = json.dumps(schema, indent=2, ensure_ascii=False) # due: allow-literal — JSON indent width
540
+ if output:
541
+ output.write_text(text + "\n", encoding="utf-8")
542
+ out.print(f"[green]✔[/green] wrote {output}")
543
+ else:
544
+ out.print(text, markup=False, highlight=False, soft_wrap=True)
545
+
546
+
547
+ # ---------------------------------------------------------------- entry point
548
+
549
+
550
+ def ensure_utf8_output() -> None:
551
+ """Make stdout/stderr UTF-8 when the platform default is not (e.g. Windows cp1252 when output
552
+ is piped to CI logs or Task Scheduler). Without this, printing ✔/✖/· crashes the CLI."""
553
+ for stream in (sys.stdout, sys.stderr):
554
+ encoding = (getattr(stream, "encoding", None) or "").lower().replace("-", "")
555
+ reconfigure = getattr(stream, "reconfigure", None)
556
+ if encoding != "utf8" and callable(reconfigure):
557
+ reconfigure(encoding="utf-8", errors="replace")
558
+
559
+
560
+ def _silence_stdout() -> None:
561
+ """After the reader closed the pipe, point stdout at devnull so interpreter shutdown is quiet."""
562
+ try:
563
+ devnull = os.open(os.devnull, os.O_WRONLY)
564
+ os.dup2(devnull, sys.stdout.fileno())
565
+ except (OSError, ValueError):
566
+ pass
567
+
568
+
569
+ def run() -> None:
570
+ """Console-script entry point: maps DUE errors to exit codes and readable messages."""
571
+ ensure_utf8_output()
572
+ try:
573
+ # standalone_mode=False makes click *return* exit codes (e.g. from --version) instead of exiting
574
+ code = app(standalone_mode=False)
575
+ sys.exit(code if isinstance(code, int) else ExitCode.OK)
576
+ except typer.Exit as exc:
577
+ sys.exit(exc.exit_code)
578
+ except ConfigError as exc:
579
+ for issue in exc.issues:
580
+ label = "[red]error[/red] " if issue.severity == "error" else "[yellow]warning[/yellow]"
581
+ err.print(f"{label} {issue.render()}")
582
+ sys.exit(ExitCode.CONFIG)
583
+ except LimitExceeded as exc:
584
+ err.print(f"[yellow]stopped[/yellow] {escape(str(exc))}")
585
+ sys.exit(ExitCode.LIMIT)
586
+ except (ConfigError_, SecretError, MissingExtra, HookError) as exc:
587
+ err.print(f"[red]error[/red] {escape(str(exc))}")
588
+ sys.exit(ExitCode.CONFIG)
589
+ except DueError as exc: # runtime failures: HTTP, decoding, pagination, source errors
590
+ err.print(f"[red]error[/red] {escape(str(exc))}")
591
+ sys.exit(ExitCode.FAILED)
592
+ except (typer.Abort, KeyboardInterrupt):
593
+ err.print("aborted")
594
+ sys.exit(ExitCode.FAILED)
595
+ except BrokenPipeError:
596
+ _silence_stdout()
597
+ sys.exit(ExitCode.OK)
598
+ except OSError as exc:
599
+ # Windows reports a reader that closed early (`due preview … | head`) as EINVAL, not EPIPE
600
+ if exc.errno in (errno.EPIPE, errno.EINVAL):
601
+ _silence_stdout()
602
+ sys.exit(ExitCode.OK)
603
+ raise
604
+ except Exception as exc:
605
+ # click usage errors (typer may vendor click, so match the interface, not the class)
606
+ show, code = getattr(exc, "show", None), getattr(exc, "exit_code", None)
607
+ if callable(show) and isinstance(code, int):
608
+ show()
609
+ sys.exit(code)
610
+ raise