datadouble 0.0.3__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.
- datadouble/__init__.py +10 -0
- datadouble/announce.py +380 -0
- datadouble/anonymize.py +165 -0
- datadouble/api.py +1159 -0
- datadouble/boundary.py +47 -0
- datadouble/catalog.py +677 -0
- datadouble/channels.py +62 -0
- datadouble/ci.py +1357 -0
- datadouble/cli.py +940 -0
- datadouble/closure.py +712 -0
- datadouble/engine.py +435 -0
- datadouble/files.py +78 -0
- datadouble/images.py +265 -0
- datadouble/jailer.py +403 -0
- datadouble/names.py +114 -0
- datadouble/notify.py +262 -0
- datadouble/objects.py +195 -0
- datadouble/outcome.py +27 -0
- datadouble/pii.py +109 -0
- datadouble/planner.py +1492 -0
- datadouble/programs.py +68 -0
- datadouble/promote.py +190 -0
- datadouble/prune.py +258 -0
- datadouble/py.typed +0 -0
- datadouble/redaction.py +131 -0
- datadouble/registry.py +128 -0
- datadouble/replicate.py +562 -0
- datadouble/resolve.py +201 -0
- datadouble/run.py +1075 -0
- datadouble/runtime.py +154 -0
- datadouble/secrets.py +57 -0
- datadouble/settings.py +81 -0
- datadouble/signing.py +98 -0
- datadouble/spec.py +1590 -0
- datadouble/staging.py +346 -0
- datadouble/storage.py +222 -0
- datadouble/strict.py +498 -0
- datadouble/subset.py +406 -0
- datadouble/verify.py +171 -0
- datadouble/versions.py +25 -0
- datadouble-0.0.3.dist-info/METADATA +36 -0
- datadouble-0.0.3.dist-info/RECORD +45 -0
- datadouble-0.0.3.dist-info/WHEEL +4 -0
- datadouble-0.0.3.dist-info/entry_points.txt +12 -0
- datadouble-0.0.3.dist-info/licenses/LICENSE +21 -0
datadouble/cli.py
ADDED
|
@@ -0,0 +1,940 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The command-line interface.
|
|
5
|
+
|
|
6
|
+
The CLI only builds JSON requests for :mod:`datadouble.api`. ``--dry-run``
|
|
7
|
+
prints the request it would send, and ``datadouble api`` reads a request from
|
|
8
|
+
standard input, so anything the CLI can do is also available as JSON.
|
|
9
|
+
|
|
10
|
+
A request that names its CI system (``--ci``, or ``ci`` in JSON) has its
|
|
11
|
+
resolved secrets masked in the system's logs while it runs, and its response
|
|
12
|
+
reported to the system afterwards: outputs, a summary and the outcome, in
|
|
13
|
+
the system's own form, with the exit code the system expects.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import signal
|
|
20
|
+
import sys
|
|
21
|
+
import threading
|
|
22
|
+
from collections.abc import Callable, Sequence
|
|
23
|
+
from types import FrameType
|
|
24
|
+
from typing import NoReturn, TextIO, assert_never, override
|
|
25
|
+
|
|
26
|
+
import yaml
|
|
27
|
+
from pydantic import JsonValue
|
|
28
|
+
|
|
29
|
+
from datadouble import api
|
|
30
|
+
from datadouble.catalog import describe_changes
|
|
31
|
+
from datadouble.ci import Agent, JobKind, Side, SpecSourceKind, masking
|
|
32
|
+
from datadouble.outcome import ExitCode
|
|
33
|
+
from datadouble.prune import PruneTarget
|
|
34
|
+
from datadouble.registry import RegistryError, installed
|
|
35
|
+
from datadouble.replicate import Copy
|
|
36
|
+
from datadouble.run import Stage
|
|
37
|
+
from datadouble.spec import ImageFormat, ObjectLevel, Strategy, StrictKind, StrictLevel
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _Arguments(argparse.Namespace):
|
|
41
|
+
"""Typed view of the parsed command line."""
|
|
42
|
+
|
|
43
|
+
command: str
|
|
44
|
+
ci_command: str
|
|
45
|
+
json: bool
|
|
46
|
+
dry_run: bool
|
|
47
|
+
ci: str | None
|
|
48
|
+
ci_directory: str | None
|
|
49
|
+
ci_job: str | None
|
|
50
|
+
ci_record: str | None
|
|
51
|
+
spec: str | None
|
|
52
|
+
lock: str | None
|
|
53
|
+
strict: list[tuple[str, str]] | None
|
|
54
|
+
strategy: str | None
|
|
55
|
+
formats: list[str] | None
|
|
56
|
+
stages: list[str]
|
|
57
|
+
work: str | None
|
|
58
|
+
resume: str | None
|
|
59
|
+
groups: list[str] | None
|
|
60
|
+
generation: str | None
|
|
61
|
+
owner: str | None
|
|
62
|
+
all_at_once: bool
|
|
63
|
+
no_announce: bool
|
|
64
|
+
copy_ids: list[str]
|
|
65
|
+
model: str
|
|
66
|
+
datamodel: str
|
|
67
|
+
output: str | None
|
|
68
|
+
expired: bool
|
|
69
|
+
target: str
|
|
70
|
+
report_only: bool
|
|
71
|
+
retry_key: str | None
|
|
72
|
+
system: str
|
|
73
|
+
jobs: list[list[str]]
|
|
74
|
+
runner: str | None
|
|
75
|
+
side: str | None
|
|
76
|
+
image: str | None
|
|
77
|
+
environment: list[str] | None
|
|
78
|
+
docker: str | None
|
|
79
|
+
docker_socket: str | None
|
|
80
|
+
agent: str | None
|
|
81
|
+
cloud: str | None
|
|
82
|
+
spec_source: str | None
|
|
83
|
+
spec_dir: str | None
|
|
84
|
+
spec_config_map: str | None
|
|
85
|
+
spec_repository: str | None
|
|
86
|
+
spec_ref: str | None
|
|
87
|
+
spec_credential: str | None
|
|
88
|
+
manual: bool
|
|
89
|
+
library_remote: str | None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class UsageError(Exception):
|
|
93
|
+
"""Command-line options that cannot be put together into a request."""
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _stages(text: str) -> list[str]:
|
|
97
|
+
names = [part.strip() for part in text.split(",") if part.strip()]
|
|
98
|
+
known = {stage.value for stage in Stage}
|
|
99
|
+
unknown = [name for name in names if name not in known]
|
|
100
|
+
if unknown or not names:
|
|
101
|
+
message = f"stages are a comma-separated list of: {', '.join(Stage)}"
|
|
102
|
+
raise argparse.ArgumentTypeError(message)
|
|
103
|
+
return names
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class CommandParser(argparse.ArgumentParser):
|
|
107
|
+
"""An argument parser that lists its arguments, for the CLI reference."""
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def arguments(self) -> list[argparse.Action]:
|
|
111
|
+
"""Every argument, in the order added, groups' and sub-commands' included."""
|
|
112
|
+
return list(self._actions)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def commands(self) -> dict[str, "CommandParser"]:
|
|
116
|
+
"""The sub-commands added with :meth:`command`, in order."""
|
|
117
|
+
found: dict[str, CommandParser] = self.__dict__.setdefault("_commands", {})
|
|
118
|
+
return found
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
type _Add = Callable[[str, str], CommandParser]
|
|
122
|
+
|
|
123
|
+
_JOB_COMMANDS = frozenset(
|
|
124
|
+
{
|
|
125
|
+
api.Command.RUN,
|
|
126
|
+
api.Command.PROMOTE,
|
|
127
|
+
api.Command.LOCK,
|
|
128
|
+
api.Command.FETCH,
|
|
129
|
+
api.Command.REPLICATE,
|
|
130
|
+
api.Command.RELEASE,
|
|
131
|
+
api.Command.PRUNE,
|
|
132
|
+
api.Command.ACTIVATE,
|
|
133
|
+
}
|
|
134
|
+
)
|
|
135
|
+
"""The commands generated jobs run, which keep a record of their outcome when told to."""
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _jobs(text: str) -> list[str]:
|
|
139
|
+
names = [part.strip() for part in text.split(",") if part.strip()]
|
|
140
|
+
known = {job.value for job in JobKind}
|
|
141
|
+
if not names or any(name not in known for name in names):
|
|
142
|
+
message = f"jobs are a comma-separated list of: {', '.join(JobKind)}"
|
|
143
|
+
raise argparse.ArgumentTypeError(message)
|
|
144
|
+
return names
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _spec_arguments(parser: argparse.ArgumentParser) -> None:
|
|
148
|
+
parser.add_argument("--spec", required=True, help="the spec file, in YAML or JSON")
|
|
149
|
+
parser.add_argument(
|
|
150
|
+
"--lock",
|
|
151
|
+
help="the catalog lock file (default: the spec's path with the suffix .lock, such as"
|
|
152
|
+
" shop.lock for shop.yml)",
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _strict_setting(text: str) -> tuple[str, str]:
|
|
157
|
+
kind, _, level = text.partition("=")
|
|
158
|
+
kinds = {k.value for k in StrictKind}
|
|
159
|
+
levels = {lv.value for lv in (StrictLevel if kind == StrictKind.DATA else ObjectLevel)}
|
|
160
|
+
if kind not in kinds or level not in levels:
|
|
161
|
+
message = (
|
|
162
|
+
f"give KIND=LEVEL: data=off|tables|columns, or one of "
|
|
163
|
+
f"{', '.join(k.value for k in StrictKind if k is not StrictKind.DATA)}=off|warn|fail"
|
|
164
|
+
)
|
|
165
|
+
raise argparse.ArgumentTypeError(message)
|
|
166
|
+
return kind, level
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _override_arguments(parser: argparse.ArgumentParser) -> None:
|
|
170
|
+
parser.add_argument(
|
|
171
|
+
"--strict",
|
|
172
|
+
metavar="KIND=LEVEL",
|
|
173
|
+
type=_strict_setting,
|
|
174
|
+
action="append",
|
|
175
|
+
help=(
|
|
176
|
+
"override strict mode's level for one kind, such as data=tables or functions=fail"
|
|
177
|
+
" (repeatable)"
|
|
178
|
+
),
|
|
179
|
+
)
|
|
180
|
+
parser.add_argument(
|
|
181
|
+
"--strategy",
|
|
182
|
+
choices=[s.value for s in Strategy],
|
|
183
|
+
help="override the spec's subset strategy",
|
|
184
|
+
)
|
|
185
|
+
parser.add_argument(
|
|
186
|
+
"--format",
|
|
187
|
+
dest="formats",
|
|
188
|
+
action="append",
|
|
189
|
+
choices=[f.value for f in ImageFormat],
|
|
190
|
+
help="an image format to produce, in place of the spec's package.formats (repeatable)",
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _group_arguments(parser: argparse.ArgumentParser) -> None:
|
|
195
|
+
parser.add_argument("--spec", required=True, help="the spec file, in YAML or JSON")
|
|
196
|
+
parser.add_argument(
|
|
197
|
+
"--group",
|
|
198
|
+
dest="groups",
|
|
199
|
+
action="append",
|
|
200
|
+
help="an image group to work on (repeatable; default: every group)",
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _operation_parsers(add: _Add) -> None:
|
|
205
|
+
promote = add(api.Command.PROMOTE, "copy verified, signed images to the export stores")
|
|
206
|
+
_group_arguments(promote)
|
|
207
|
+
promote.add_argument("--generation", help="the generation to promote (default: the newest)")
|
|
208
|
+
fetch = add(api.Command.FETCH, "bring new promoted images into staging")
|
|
209
|
+
_group_arguments(fetch)
|
|
210
|
+
activate = add(
|
|
211
|
+
api.Command.ACTIVATE,
|
|
212
|
+
"point the staging channel at a staged generation, such as an older one to roll back",
|
|
213
|
+
)
|
|
214
|
+
activate.add_argument("generation", help="the staged generation to point the channel at")
|
|
215
|
+
_group_arguments(activate)
|
|
216
|
+
replicate = add(
|
|
217
|
+
api.Command.REPLICATE, "fill the pool, or make on-demand copies, and announce them"
|
|
218
|
+
)
|
|
219
|
+
_group_arguments(replicate)
|
|
220
|
+
replicate.add_argument("--owner", help="who on-demand copies are for")
|
|
221
|
+
replicate.add_argument(
|
|
222
|
+
"--all-at-once",
|
|
223
|
+
action="store_true",
|
|
224
|
+
help="replace stale pool copies before refilling the pool",
|
|
225
|
+
)
|
|
226
|
+
replicate.add_argument(
|
|
227
|
+
"--no-announce", action="store_true", help="make copies without announcing them"
|
|
228
|
+
)
|
|
229
|
+
claim = add(api.Command.CLAIM, "take an unclaimed copy from the pool")
|
|
230
|
+
_group_arguments(claim)
|
|
231
|
+
claim.add_argument("--owner", required=True, help="who is taking the copy")
|
|
232
|
+
claim.add_argument(
|
|
233
|
+
"--no-announce", action="store_true", help="claim the copy without announcing it"
|
|
234
|
+
)
|
|
235
|
+
release = add(api.Command.RELEASE, "destroy copies, chosen by ID, owner or expiry")
|
|
236
|
+
release.add_argument(
|
|
237
|
+
"copy_ids", nargs="*", metavar="COPY_ID", help="the IDs of copies to release"
|
|
238
|
+
)
|
|
239
|
+
_group_arguments(release)
|
|
240
|
+
release.add_argument("--owner", help="release every copy this owner has")
|
|
241
|
+
release.add_argument(
|
|
242
|
+
"--expired", action="store_true", help="release every copy past its expiry time"
|
|
243
|
+
)
|
|
244
|
+
announce = add(api.Command.ANNOUNCE, "announce existing copies again")
|
|
245
|
+
_group_arguments(announce)
|
|
246
|
+
announce.add_argument(
|
|
247
|
+
"--owner", help="announce this owner's copies (default: the pool's unclaimed copies)"
|
|
248
|
+
)
|
|
249
|
+
copies = add(api.Command.COPIES, "list copies")
|
|
250
|
+
_group_arguments(copies)
|
|
251
|
+
prune = add(api.Command.PRUNE, "remove old images, as the spec's prune settings say")
|
|
252
|
+
prune.add_argument("--spec", required=True, help="the spec file, in YAML or JSON")
|
|
253
|
+
prune.add_argument(
|
|
254
|
+
"--target",
|
|
255
|
+
required=True,
|
|
256
|
+
choices=[target.value for target in PruneTarget],
|
|
257
|
+
help="where to prune: the build's stores, the export stores, or staging",
|
|
258
|
+
)
|
|
259
|
+
prune.add_argument(
|
|
260
|
+
"--dry-run",
|
|
261
|
+
dest="report_only",
|
|
262
|
+
action="store_true",
|
|
263
|
+
help="report what would be removed, and the space it would recover, without removing it",
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _ci_parsers(add: _Add) -> None:
|
|
268
|
+
ci = add("ci", "work with CI/CD configuration")
|
|
269
|
+
actions = ci.add_subparsers(dest="ci_command", required=True, metavar="ACTION")
|
|
270
|
+
summary = "write CI/CD configuration for a spec's jobs"
|
|
271
|
+
init = actions.add_parser("init", help=summary, description=summary)
|
|
272
|
+
ci.commands["init"] = init
|
|
273
|
+
init.add_argument("--system", required=True, help="the CI/CD system, such as github-actions")
|
|
274
|
+
init.add_argument(
|
|
275
|
+
"--job",
|
|
276
|
+
dest="jobs",
|
|
277
|
+
type=_jobs,
|
|
278
|
+
action="append",
|
|
279
|
+
required=True,
|
|
280
|
+
help=(
|
|
281
|
+
"the jobs to write, comma-separated or repeated, all on one side of the"
|
|
282
|
+
f" boundary: {','.join(JobKind)}"
|
|
283
|
+
),
|
|
284
|
+
)
|
|
285
|
+
init.add_argument("--spec", required=True, help="the spec file, in YAML or JSON")
|
|
286
|
+
init.add_argument(
|
|
287
|
+
"--runner",
|
|
288
|
+
help="the runner the jobs run on. Jobs on the production side (build, promote, lock,"
|
|
289
|
+
" and prune there) need it, and so does every job on GitLab, Jenkins and Argo CD",
|
|
290
|
+
)
|
|
291
|
+
init.add_argument(
|
|
292
|
+
"--work",
|
|
293
|
+
help="the build's work directory, an absolute path in production scratch space."
|
|
294
|
+
" Build needs it, and so does every production job when notify sends recoveries to a"
|
|
295
|
+
" webhook, since jobs record their last outcome there",
|
|
296
|
+
)
|
|
297
|
+
init.add_argument(
|
|
298
|
+
"--side",
|
|
299
|
+
choices=[side.value for side in Side],
|
|
300
|
+
help="the side of the boundary prune runs on, when prune is the only job",
|
|
301
|
+
)
|
|
302
|
+
init.add_argument("--output", help="the repository root to write into (default: .)")
|
|
303
|
+
init.add_argument("--image", help="the Datadouble image the jobs run (default: this version's)")
|
|
304
|
+
init.add_argument(
|
|
305
|
+
"--agent",
|
|
306
|
+
choices=[agent.value for agent in Agent],
|
|
307
|
+
help="where jobs run Datadouble: on a runner with Docker, or in a Kubernetes pod"
|
|
308
|
+
" (default: the system's own)",
|
|
309
|
+
)
|
|
310
|
+
init.add_argument(
|
|
311
|
+
"--cloud",
|
|
312
|
+
help="the Kubernetes cloud that Kubernetes agents start in (default: the system's)",
|
|
313
|
+
)
|
|
314
|
+
init.add_argument(
|
|
315
|
+
"--manual",
|
|
316
|
+
action="store_true",
|
|
317
|
+
help="leave out every schedule and follow-on trigger, so only a person starts the jobs"
|
|
318
|
+
" (or a request, for on-demand copies): for trying a branch's jobs beside the real"
|
|
319
|
+
" ones",
|
|
320
|
+
)
|
|
321
|
+
init.add_argument(
|
|
322
|
+
"--library-remote",
|
|
323
|
+
metavar="URL",
|
|
324
|
+
help="the Git URL of a mirror of Datadouble's repository, holding the release's tag,"
|
|
325
|
+
" that Jenkins loads the shared library from, or Argo CD the chart (default: the"
|
|
326
|
+
" public repository)",
|
|
327
|
+
)
|
|
328
|
+
init.add_argument(
|
|
329
|
+
"--env",
|
|
330
|
+
dest="environment",
|
|
331
|
+
action="append",
|
|
332
|
+
metavar="NAME",
|
|
333
|
+
help="another environment variable that every job passes on (repeatable)",
|
|
334
|
+
)
|
|
335
|
+
init.add_argument(
|
|
336
|
+
"--spec-source",
|
|
337
|
+
choices=[kind.value for kind in SpecSourceKind],
|
|
338
|
+
help="where jobs find the spec's directory (the spec, the specs it extends and its"
|
|
339
|
+
" lock): the CI system's checkout of this repository, a directory already in the job,"
|
|
340
|
+
" or another repository the job clones. --spec is still read here, to check it"
|
|
341
|
+
" (default: checkout)",
|
|
342
|
+
)
|
|
343
|
+
init.add_argument(
|
|
344
|
+
"--spec-dir",
|
|
345
|
+
metavar="DIR",
|
|
346
|
+
help="with --spec-source mounted, the spec's directory: an absolute path in the job;"
|
|
347
|
+
" with git, its directory in the repository (default: the repository's root)",
|
|
348
|
+
)
|
|
349
|
+
init.add_argument(
|
|
350
|
+
"--spec-config-map",
|
|
351
|
+
metavar="NAME",
|
|
352
|
+
help="with --spec-source mounted on Kubernetes agents, the ConfigMap that holds the"
|
|
353
|
+
" spec's directory, which someone else manages",
|
|
354
|
+
)
|
|
355
|
+
init.add_argument(
|
|
356
|
+
"--spec-repository",
|
|
357
|
+
metavar="URL",
|
|
358
|
+
help="with --spec-source git, the repository's URL",
|
|
359
|
+
)
|
|
360
|
+
init.add_argument(
|
|
361
|
+
"--spec-ref",
|
|
362
|
+
metavar="REF",
|
|
363
|
+
help="with --spec-source git, what to check out: a branch by its name, a tag as"
|
|
364
|
+
" refs/tags/<tag>, or a commit by its full SHA",
|
|
365
|
+
)
|
|
366
|
+
init.add_argument(
|
|
367
|
+
"--spec-credential",
|
|
368
|
+
metavar="NAME",
|
|
369
|
+
help="with --spec-source git, the CI system's secret that can read the repository: a"
|
|
370
|
+
" GitHub secret, a GitLab CI/CD variable or a Jenkins credential ID",
|
|
371
|
+
)
|
|
372
|
+
init.add_argument(
|
|
373
|
+
"--docker",
|
|
374
|
+
metavar="COMMAND",
|
|
375
|
+
help="the Docker command that steps run the image with (default: the runner's"
|
|
376
|
+
" DATADOUBLE_DOCKER, or docker)",
|
|
377
|
+
)
|
|
378
|
+
init.add_argument(
|
|
379
|
+
"--docker-socket",
|
|
380
|
+
metavar="PATH",
|
|
381
|
+
help="the Docker daemon's socket on the runner, as an absolute path (default: the"
|
|
382
|
+
" runner's DATADOUBLE_DOCKER_SOCKET, or /var/run/docker.sock)",
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def build_parser() -> CommandParser:
|
|
387
|
+
"""Build the argument parser."""
|
|
388
|
+
parser = CommandParser(
|
|
389
|
+
prog="datadouble",
|
|
390
|
+
description="Realistic, safe copies of production data for development and testing.",
|
|
391
|
+
)
|
|
392
|
+
parser.add_argument(
|
|
393
|
+
"--json",
|
|
394
|
+
action="store_true",
|
|
395
|
+
help="print the JSON response instead of a summary",
|
|
396
|
+
)
|
|
397
|
+
parser.add_argument(
|
|
398
|
+
"--dry-run",
|
|
399
|
+
action="store_true",
|
|
400
|
+
help="print the JSON request instead of running it",
|
|
401
|
+
)
|
|
402
|
+
parser.add_argument(
|
|
403
|
+
"--ci",
|
|
404
|
+
metavar="SYSTEM",
|
|
405
|
+
help="the CI/CD system to report to, such as github-actions. Where the system lets"
|
|
406
|
+
" a job mask values in its log, Datadouble masks the secrets it reads",
|
|
407
|
+
)
|
|
408
|
+
parser.add_argument(
|
|
409
|
+
"--ci-job",
|
|
410
|
+
choices=list(JobKind),
|
|
411
|
+
metavar="JOB",
|
|
412
|
+
help="the generated job this command runs for. It sends notifications as the spec's"
|
|
413
|
+
" `notify` section says",
|
|
414
|
+
)
|
|
415
|
+
parser.add_argument(
|
|
416
|
+
"--ci-directory",
|
|
417
|
+
metavar="DIR",
|
|
418
|
+
help="the directory where the CI/CD adapter writes outputs, for the native step to pick up",
|
|
419
|
+
)
|
|
420
|
+
commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
|
|
421
|
+
|
|
422
|
+
def add(name: str, summary: str) -> CommandParser:
|
|
423
|
+
"""A command, with its summary as both its help and its description."""
|
|
424
|
+
child = commands.add_parser(name, help=summary, description=summary)
|
|
425
|
+
parser.commands[name] = child
|
|
426
|
+
if name in _JOB_COMMANDS:
|
|
427
|
+
child.add_argument(
|
|
428
|
+
"--ci-record",
|
|
429
|
+
metavar="FILE",
|
|
430
|
+
help="with --ci-job, the file the generated job records its last outcome in, so"
|
|
431
|
+
" that a success after anything else notifies as a recovery. ci init names it",
|
|
432
|
+
)
|
|
433
|
+
return child
|
|
434
|
+
|
|
435
|
+
add(api.Command.VERSION, "show the installed version")
|
|
436
|
+
add(api.Command.SCHEMA, "print the JSON Schema that specs are checked against")
|
|
437
|
+
showing = add(
|
|
438
|
+
api.Command.SPEC,
|
|
439
|
+
"print a spec merged with the specs it extends, and the files it was read from",
|
|
440
|
+
)
|
|
441
|
+
showing.add_argument("--spec", required=True, help="the spec file, in YAML or JSON")
|
|
442
|
+
lock = add(
|
|
443
|
+
api.Command.LOCK,
|
|
444
|
+
"write the catalog lock for a spec, and list what changed since the last one",
|
|
445
|
+
)
|
|
446
|
+
_spec_arguments(lock)
|
|
447
|
+
lock.add_argument(
|
|
448
|
+
"--output",
|
|
449
|
+
help=(
|
|
450
|
+
"a directory to write the new lock (named after the spec, such as shop.lock) and"
|
|
451
|
+
" its changes (changes.txt) to, leaving the current lock as it is"
|
|
452
|
+
),
|
|
453
|
+
)
|
|
454
|
+
importing = add(
|
|
455
|
+
api.Command.IMPORT_JAILER,
|
|
456
|
+
"translate a Jailer subset into native spec settings, and lock the catalog",
|
|
457
|
+
)
|
|
458
|
+
_spec_arguments(importing)
|
|
459
|
+
importing.add_argument("--model", required=True, help="the Jailer extraction model, a .jm file")
|
|
460
|
+
importing.add_argument("--datamodel", required=True, help="the Jailer data model folder")
|
|
461
|
+
importing.add_argument(
|
|
462
|
+
"--output", required=True, help="the file to write the native subset settings to, as YAML"
|
|
463
|
+
)
|
|
464
|
+
planning = add(api.Command.PLAN, "plan a build without extracting anything")
|
|
465
|
+
_spec_arguments(planning)
|
|
466
|
+
_override_arguments(planning)
|
|
467
|
+
run = add(api.Command.RUN, "run build stages, or resume a generation")
|
|
468
|
+
run.add_argument(
|
|
469
|
+
"stages", type=_stages, help=f"the stages to run, comma-separated: {','.join(Stage)}"
|
|
470
|
+
)
|
|
471
|
+
_spec_arguments(run)
|
|
472
|
+
_override_arguments(run)
|
|
473
|
+
run.add_argument("--work", help="the work directory (default: .datadouble)")
|
|
474
|
+
resuming = run.add_mutually_exclusive_group()
|
|
475
|
+
resuming.add_argument("--resume", metavar="GENERATION", help="resume this generation")
|
|
476
|
+
resuming.add_argument(
|
|
477
|
+
"--retry-key",
|
|
478
|
+
metavar="KEY",
|
|
479
|
+
help="the CI system's ID for this run. A retry of the run resumes the generation it"
|
|
480
|
+
" started",
|
|
481
|
+
)
|
|
482
|
+
_operation_parsers(add)
|
|
483
|
+
_ci_parsers(add)
|
|
484
|
+
add("api", "read a JSON request from standard input, and run it")
|
|
485
|
+
return parser
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _spec_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
489
|
+
fields: dict[str, JsonValue] = {"spec": arguments.spec}
|
|
490
|
+
if arguments.lock:
|
|
491
|
+
fields["lock"] = arguments.lock
|
|
492
|
+
return fields
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _override_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
496
|
+
fields = _spec_fields(arguments)
|
|
497
|
+
if arguments.strict:
|
|
498
|
+
fields["strict"] = dict[str, JsonValue](arguments.strict)
|
|
499
|
+
if arguments.strategy:
|
|
500
|
+
fields["strategy"] = arguments.strategy
|
|
501
|
+
if arguments.formats:
|
|
502
|
+
fields["formats"] = list(arguments.formats)
|
|
503
|
+
return fields
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _run_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
507
|
+
fields = _override_fields(arguments)
|
|
508
|
+
fields["stages"] = list(arguments.stages)
|
|
509
|
+
if arguments.work:
|
|
510
|
+
fields["work"] = arguments.work
|
|
511
|
+
return _set(fields, arguments, "resume", "retry_key")
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _group_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
515
|
+
fields: dict[str, JsonValue] = {"spec": arguments.spec}
|
|
516
|
+
if arguments.groups:
|
|
517
|
+
fields["groups"] = list(arguments.groups)
|
|
518
|
+
return fields
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _set(fields: dict[str, JsonValue], arguments: _Arguments, *names: str) -> dict[str, JsonValue]:
|
|
522
|
+
"""Copy the named arguments that were given into the request."""
|
|
523
|
+
for name in names:
|
|
524
|
+
value: JsonValue = getattr(arguments, name, None)
|
|
525
|
+
if value:
|
|
526
|
+
fields[name] = list(value) if isinstance(value, list) else value
|
|
527
|
+
return fields
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _promote_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
531
|
+
return _set(_group_fields(arguments), arguments, "generation")
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _activate_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
535
|
+
return _set(_group_fields(arguments), arguments, "generation")
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _replicate_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
539
|
+
fields = _set(_group_fields(arguments), arguments, "owner", "all_at_once")
|
|
540
|
+
if arguments.no_announce:
|
|
541
|
+
fields["announce"] = False
|
|
542
|
+
return fields
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _claim_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
546
|
+
fields = _set(_group_fields(arguments), arguments, "owner")
|
|
547
|
+
if arguments.no_announce:
|
|
548
|
+
fields["announce"] = False
|
|
549
|
+
return fields
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _release_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
553
|
+
return _set(_group_fields(arguments), arguments, "copy_ids", "owner", "expired")
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _announce_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
557
|
+
return _set(_group_fields(arguments), arguments, "owner")
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _prune_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
561
|
+
fields: dict[str, JsonValue] = {"spec": arguments.spec, "target": arguments.target}
|
|
562
|
+
if arguments.report_only:
|
|
563
|
+
fields["dry_run"] = True
|
|
564
|
+
return fields
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
_SPEC_SOURCE_OPTIONS = {
|
|
568
|
+
SpecSourceKind.MOUNTED: {"spec_dir": "path", "spec_config_map": "config_map"},
|
|
569
|
+
SpecSourceKind.GIT: {
|
|
570
|
+
"spec_repository": "url",
|
|
571
|
+
"spec_ref": "ref",
|
|
572
|
+
"spec_dir": "path",
|
|
573
|
+
"spec_credential": "credential",
|
|
574
|
+
},
|
|
575
|
+
}
|
|
576
|
+
"""Each spec source's options, and the request fields they set."""
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def _spec_source(arguments: _Arguments) -> JsonValue:
|
|
580
|
+
kind = SpecSourceKind(arguments.spec_source or SpecSourceKind.CHECKOUT)
|
|
581
|
+
fitting = _SPEC_SOURCE_OPTIONS.get(kind, {})
|
|
582
|
+
every = sorted({name for names in _SPEC_SOURCE_OPTIONS.values() for name in names})
|
|
583
|
+
stray = [n for n in every if n not in fitting and getattr(arguments, n) is not None]
|
|
584
|
+
if stray:
|
|
585
|
+
options = ", ".join("--" + name.replace("_", "-") for name in stray)
|
|
586
|
+
message = f"--spec-source {kind} takes no {options}"
|
|
587
|
+
raise UsageError(message)
|
|
588
|
+
if not fitting:
|
|
589
|
+
return str(kind)
|
|
590
|
+
settings: dict[str, JsonValue] = {
|
|
591
|
+
field: getattr(arguments, name)
|
|
592
|
+
for name, field in fitting.items()
|
|
593
|
+
if getattr(arguments, name) is not None
|
|
594
|
+
}
|
|
595
|
+
return {str(kind): settings}
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _ci_init_fields(arguments: _Arguments) -> dict[str, JsonValue]:
|
|
599
|
+
fields: dict[str, JsonValue] = {
|
|
600
|
+
"system": arguments.system,
|
|
601
|
+
"jobs": list(dict.fromkeys(name for names in arguments.jobs for name in names)),
|
|
602
|
+
"spec": arguments.spec,
|
|
603
|
+
}
|
|
604
|
+
if arguments.spec_source is not None or any(
|
|
605
|
+
getattr(arguments, name) is not None
|
|
606
|
+
for names in _SPEC_SOURCE_OPTIONS.values()
|
|
607
|
+
for name in names
|
|
608
|
+
):
|
|
609
|
+
fields["spec_source"] = _spec_source(arguments)
|
|
610
|
+
return _set(
|
|
611
|
+
fields,
|
|
612
|
+
arguments,
|
|
613
|
+
"runner",
|
|
614
|
+
"work",
|
|
615
|
+
"side",
|
|
616
|
+
"output",
|
|
617
|
+
"image",
|
|
618
|
+
"environment",
|
|
619
|
+
"agent",
|
|
620
|
+
"cloud",
|
|
621
|
+
"docker",
|
|
622
|
+
"docker_socket",
|
|
623
|
+
"manual",
|
|
624
|
+
"library_remote",
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
_FIELDS: dict[str, Callable[[_Arguments], dict[str, JsonValue]]] = {
|
|
629
|
+
api.Command.VERSION: lambda _: {},
|
|
630
|
+
api.Command.SCHEMA: lambda _: {},
|
|
631
|
+
api.Command.SPEC: lambda arguments: {"spec": arguments.spec},
|
|
632
|
+
api.Command.LOCK: lambda arguments: _set(_spec_fields(arguments), arguments, "output"),
|
|
633
|
+
api.Command.IMPORT_JAILER: lambda arguments: {
|
|
634
|
+
**_spec_fields(arguments),
|
|
635
|
+
"model": arguments.model,
|
|
636
|
+
"datamodel": arguments.datamodel,
|
|
637
|
+
"output": arguments.output,
|
|
638
|
+
},
|
|
639
|
+
api.Command.PLAN: _override_fields,
|
|
640
|
+
api.Command.RUN: _run_fields,
|
|
641
|
+
api.Command.PROMOTE: _promote_fields,
|
|
642
|
+
api.Command.FETCH: _group_fields,
|
|
643
|
+
api.Command.ACTIVATE: _activate_fields,
|
|
644
|
+
api.Command.REPLICATE: _replicate_fields,
|
|
645
|
+
api.Command.CLAIM: _claim_fields,
|
|
646
|
+
api.Command.RELEASE: _release_fields,
|
|
647
|
+
api.Command.ANNOUNCE: _announce_fields,
|
|
648
|
+
api.Command.COPIES: _group_fields,
|
|
649
|
+
api.Command.PRUNE: _prune_fields,
|
|
650
|
+
api.Command.CI_INIT: _ci_init_fields,
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def build_request(arguments: _Arguments) -> str:
|
|
655
|
+
"""Turn parsed command-line arguments into a JSON request.
|
|
656
|
+
|
|
657
|
+
The parser only accepts commands listed here, so the lookup cannot miss.
|
|
658
|
+
"""
|
|
659
|
+
command = f"ci.{arguments.ci_command}" if arguments.command == "ci" else arguments.command
|
|
660
|
+
fields = _FIELDS[command](arguments)
|
|
661
|
+
if arguments.ci:
|
|
662
|
+
bridge: dict[str, JsonValue] = {"system": arguments.ci}
|
|
663
|
+
if arguments.ci_directory:
|
|
664
|
+
bridge["directory"] = arguments.ci_directory
|
|
665
|
+
if arguments.ci_job:
|
|
666
|
+
bridge["job"] = arguments.ci_job
|
|
667
|
+
if getattr(arguments, "ci_record", None):
|
|
668
|
+
bridge["record"] = arguments.ci_record
|
|
669
|
+
fields["ci"] = bridge
|
|
670
|
+
return json.dumps({"command": command, **fields})
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _option(location: str) -> str:
|
|
674
|
+
"""A problem's location, with the command-line option that sets it, if one does."""
|
|
675
|
+
parts = location.split(".")
|
|
676
|
+
for kind, options in _SPEC_SOURCE_OPTIONS.items():
|
|
677
|
+
for name, field in options.items():
|
|
678
|
+
if parts[:2] == ["spec_source", kind] and parts[-1] == field:
|
|
679
|
+
return f"{location} (--{name.replace('_', '-')})"
|
|
680
|
+
return location
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _error_lines(response: api.ErrorResponse) -> list[str]:
|
|
684
|
+
lines = [f"error: {response.message}"]
|
|
685
|
+
lines.extend(f" {_option(detail.location)}: {detail.problem}" for detail in response.details)
|
|
686
|
+
if response.strict is not None:
|
|
687
|
+
for finding in response.strict.findings:
|
|
688
|
+
if finding.resolutions:
|
|
689
|
+
lines.append(f" to resolve {finding.object}:")
|
|
690
|
+
lines.extend(f" - {way}" for way in finding.resolutions)
|
|
691
|
+
return lines
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
def _plan_lines(response: api.PlanResponse) -> list[str]:
|
|
695
|
+
planned = response.plan
|
|
696
|
+
excluded = len(planned.excludes.excluded())
|
|
697
|
+
lines = [
|
|
698
|
+
(
|
|
699
|
+
f"plan for {planned.spec}: {len(planned.extracted())} tables, {excluded} excluded, "
|
|
700
|
+
f"strategy {planned.strategy}, as of {planned.as_of.isoformat()}"
|
|
701
|
+
),
|
|
702
|
+
]
|
|
703
|
+
lines.extend(f" image {g.name}: {len(g.tables)} tables" for g in planned.groups)
|
|
704
|
+
lines.extend(f"warning: {w}" for w in planned.warnings)
|
|
705
|
+
return lines
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def _run_lines(response: api.RunResponse) -> list[str]:
|
|
709
|
+
result = response.result
|
|
710
|
+
lines = [f"generation {result.generation} ({response.outcome}), work in {result.work}"]
|
|
711
|
+
for record in result.stages:
|
|
712
|
+
where = f" [{record.group}]" if record.group else ""
|
|
713
|
+
lines.append(f" {record.stage}{where}: {record.status} in {record.seconds:.1f}s")
|
|
714
|
+
for report in result.verification:
|
|
715
|
+
verdict = "passed" if report.passed() else "FAILED"
|
|
716
|
+
lines.append(f" verify [{report.group}]: {verdict}")
|
|
717
|
+
lines.extend(
|
|
718
|
+
f" {check.kind} {check.name}: {check.detail}"
|
|
719
|
+
for check in report.checks()
|
|
720
|
+
if not check.passed
|
|
721
|
+
)
|
|
722
|
+
lines.extend(f" stored {key}" for key in result.stored)
|
|
723
|
+
lines.extend(f"warning: {w}" for w in result.warnings)
|
|
724
|
+
return lines
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def _copy_line(copy: Copy, verb: str) -> str:
|
|
728
|
+
where = ", ".join(f"{k}={v}" for k, v in copy.location.items())
|
|
729
|
+
owner = f" for {copy.owner}" if copy.owner else ""
|
|
730
|
+
return f" {verb} {copy.id} ({copy.kind}, {copy.generation}{owner}) {where}".rstrip()
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def _operation_lines(
|
|
734
|
+
response: api.PromoteResponse
|
|
735
|
+
| api.FetchResponse
|
|
736
|
+
| api.ActivateResponse
|
|
737
|
+
| api.CopiesResponse
|
|
738
|
+
| api.PruneResponse,
|
|
739
|
+
) -> list[str]:
|
|
740
|
+
match response:
|
|
741
|
+
case api.PromoteResponse():
|
|
742
|
+
return [
|
|
743
|
+
f"promoted {p.summary.identity.prefix()}/{p.summary.identity.generation} "
|
|
744
|
+
f"to channel {p.channel} in {', '.join(p.stores)}"
|
|
745
|
+
for p in response.promoted
|
|
746
|
+
]
|
|
747
|
+
case api.FetchResponse():
|
|
748
|
+
return [f"{f.prefix}: {f.status} {f.generation}" for f in response.fetched]
|
|
749
|
+
case api.ActivateResponse():
|
|
750
|
+
return [f"channel {c.name} now points at {c.generation}" for c in response.channels]
|
|
751
|
+
case api.CopiesResponse():
|
|
752
|
+
result = response.result
|
|
753
|
+
made = "claimed" if response.command is api.Command.CLAIM else "made"
|
|
754
|
+
lines = [_copy_line(c, made) for c in result.created]
|
|
755
|
+
lines.extend(_copy_line(c, "removed") for c in result.removed)
|
|
756
|
+
if response.command in {api.Command.COPIES, api.Command.ANNOUNCE}:
|
|
757
|
+
lines.extend(
|
|
758
|
+
_copy_line(c, "claimed" if c.claimed else "ready") for c in result.copies
|
|
759
|
+
)
|
|
760
|
+
lines.extend(f" announced to {target}" for target in response.announced)
|
|
761
|
+
lines.extend(f" withdrew {target}" for target in response.withdrawn)
|
|
762
|
+
return [f"{response.command}: {len(result.copies)} copies recorded", *lines]
|
|
763
|
+
case api.PruneResponse():
|
|
764
|
+
verb = "would remove" if response.result.dry_run else "removed"
|
|
765
|
+
lines = [
|
|
766
|
+
f" {verb} {p.prefix}/{p.generation} from {p.location} ({p.bytes} bytes)"
|
|
767
|
+
for p in response.result.removed
|
|
768
|
+
]
|
|
769
|
+
lines.extend(f" {verb} copy {c}" for c in response.result.copies_removed)
|
|
770
|
+
return [f"prune: {verb} {response.bytes} bytes", *lines]
|
|
771
|
+
case _:
|
|
772
|
+
assert_never(response)
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def _ci_lines(response: api.CiInitResponse) -> list[str]:
|
|
776
|
+
lines = [f"wrote {response.system} configuration for the {response.side} side:"]
|
|
777
|
+
lines.extend(f" {path}" for path in response.files)
|
|
778
|
+
if response.environment:
|
|
779
|
+
lines.append("define these as secrets where the jobs run:")
|
|
780
|
+
lines.extend(f" {name}" for name in response.environment)
|
|
781
|
+
if response.instructions:
|
|
782
|
+
lines.append("then, in the CI system:")
|
|
783
|
+
lines.extend(f" {line}" for line in response.instructions)
|
|
784
|
+
return lines
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
class _BlockDumper(yaml.SafeDumper):
|
|
788
|
+
"""Block-style YAML with sequences indented under their keys, as the docs write it."""
|
|
789
|
+
|
|
790
|
+
@override
|
|
791
|
+
def increase_indent(self, flow: bool = False, indentless: bool = False) -> None:
|
|
792
|
+
del indentless
|
|
793
|
+
super().increase_indent(flow, indentless=False)
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def _spec_text(response: api.SpecResponse) -> str:
|
|
797
|
+
"""The merged spec as block-style YAML, after comments naming the files it was read from."""
|
|
798
|
+
lines = ["# read from, in the order they merged:"]
|
|
799
|
+
lines.extend(f"# {layer.path} ({layer.digest})" for layer in response.layers)
|
|
800
|
+
text = yaml.dump(
|
|
801
|
+
response.spec,
|
|
802
|
+
Dumper=_BlockDumper,
|
|
803
|
+
sort_keys=False,
|
|
804
|
+
default_flow_style=False,
|
|
805
|
+
allow_unicode=True,
|
|
806
|
+
)
|
|
807
|
+
return "\n".join(lines) + "\n" + text.rstrip("\n")
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def _simple(
|
|
811
|
+
response: api.VersionResponse
|
|
812
|
+
| api.SchemaResponse
|
|
813
|
+
| api.SpecResponse
|
|
814
|
+
| api.LockResponse
|
|
815
|
+
| api.CiInitResponse,
|
|
816
|
+
) -> str:
|
|
817
|
+
match response:
|
|
818
|
+
case api.VersionResponse():
|
|
819
|
+
return f"datadouble {response.version} (Python {response.python})"
|
|
820
|
+
case api.SchemaResponse():
|
|
821
|
+
return json.dumps(response.schema_, indent=2)
|
|
822
|
+
case api.SpecResponse():
|
|
823
|
+
return _spec_text(response)
|
|
824
|
+
case api.LockResponse():
|
|
825
|
+
lines = [f"wrote {response.lock}: {response.tables} tables ({response.fingerprint})"]
|
|
826
|
+
if response.changes_file is not None:
|
|
827
|
+
lines.append(f"wrote {response.changes_file}")
|
|
828
|
+
lines.extend(describe_changes(response.changes, response.unreadable))
|
|
829
|
+
return "\n".join(lines)
|
|
830
|
+
case api.CiInitResponse():
|
|
831
|
+
return "\n".join(_ci_lines(response))
|
|
832
|
+
case _:
|
|
833
|
+
assert_never(response)
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def summarize(response: api.Response) -> str:
|
|
837
|
+
"""Describe a response for people, the default output without ``--json``."""
|
|
838
|
+
match response:
|
|
839
|
+
case (
|
|
840
|
+
api.VersionResponse()
|
|
841
|
+
| api.SchemaResponse()
|
|
842
|
+
| api.SpecResponse()
|
|
843
|
+
| api.LockResponse()
|
|
844
|
+
| api.CiInitResponse()
|
|
845
|
+
):
|
|
846
|
+
return _simple(response)
|
|
847
|
+
case api.ImportJailerResponse():
|
|
848
|
+
lines = [f"wrote {response.output} and {response.lock}"]
|
|
849
|
+
lines.extend(f" {line}" for line in response.report)
|
|
850
|
+
return "\n".join(lines)
|
|
851
|
+
case api.PlanResponse():
|
|
852
|
+
return "\n".join(_plan_lines(response))
|
|
853
|
+
case api.RunResponse():
|
|
854
|
+
return "\n".join(_run_lines(response))
|
|
855
|
+
case api.ErrorResponse():
|
|
856
|
+
return "\n".join(_error_lines(response))
|
|
857
|
+
case (
|
|
858
|
+
api.PromoteResponse()
|
|
859
|
+
| api.FetchResponse()
|
|
860
|
+
| api.ActivateResponse()
|
|
861
|
+
| api.CopiesResponse()
|
|
862
|
+
| api.PruneResponse()
|
|
863
|
+
):
|
|
864
|
+
return "\n".join(_operation_lines(response))
|
|
865
|
+
case _:
|
|
866
|
+
assert_never(response)
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
def _respond(raw: str) -> tuple[api.Response, ExitCode]:
|
|
870
|
+
"""Carry out a JSON request, bridged to its CI system if it names one."""
|
|
871
|
+
request = api.parse_request(raw)
|
|
872
|
+
if isinstance(request, api.ErrorResponse):
|
|
873
|
+
return request, api.exit_code(request)
|
|
874
|
+
if request.ci is None:
|
|
875
|
+
response = api.handle(request)
|
|
876
|
+
return response, api.exit_code(response)
|
|
877
|
+
try:
|
|
878
|
+
adapter = installed().ci_system(request.ci.system)
|
|
879
|
+
except RegistryError as error:
|
|
880
|
+
failed = api.ErrorResponse(error=api.ErrorCode.ADAPTER_MISSING, message=str(error))
|
|
881
|
+
return failed, api.exit_code(failed)
|
|
882
|
+
with masking(adapter.mask):
|
|
883
|
+
previous, recalled = api.previous_outcome(request)
|
|
884
|
+
response = api.handle(request)
|
|
885
|
+
report = api.ci_report(response, summarize(response))
|
|
886
|
+
notified = api.notify(request, report, adapter.run_url(os.environ), previous=previous)
|
|
887
|
+
problems = (*recalled, *notified)
|
|
888
|
+
for problem in problems:
|
|
889
|
+
sys.stderr.write(f"warning: a notification failed, {problem}\n")
|
|
890
|
+
return response, adapter.report(report, request.ci.directory)
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def _terminated(signum: int, frame: FrameType | None) -> NoReturn:
|
|
894
|
+
del frame
|
|
895
|
+
raise SystemExit(128 + signum)
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def stop_on_sigterm() -> None:
|
|
899
|
+
"""Turn SIGTERM into :class:`SystemExit`.
|
|
900
|
+
|
|
901
|
+
A CI system cancels a job with SIGTERM; unwinding instead of dying lets
|
|
902
|
+
``finally`` blocks (temporary credentials, containers) clean up.
|
|
903
|
+
"""
|
|
904
|
+
if threading.current_thread() is threading.main_thread():
|
|
905
|
+
signal.signal(signal.SIGTERM, _terminated)
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def main(
|
|
909
|
+
argv: Sequence[str] | None = None,
|
|
910
|
+
*,
|
|
911
|
+
stdin: TextIO | None = None,
|
|
912
|
+
stdout: TextIO | None = None,
|
|
913
|
+
) -> int:
|
|
914
|
+
"""Run the command line and return the process exit code."""
|
|
915
|
+
stop_on_sigterm()
|
|
916
|
+
source: TextIO = sys.stdin if stdin is None else stdin
|
|
917
|
+
sink: TextIO = sys.stdout if stdout is None else stdout
|
|
918
|
+
parser = build_parser()
|
|
919
|
+
arguments = parser.parse_args(argv, namespace=_Arguments())
|
|
920
|
+
|
|
921
|
+
if arguments.command == "api":
|
|
922
|
+
response, code = _respond(source.read())
|
|
923
|
+
sink.write(response.model_dump_json() + "\n")
|
|
924
|
+
return code
|
|
925
|
+
|
|
926
|
+
try:
|
|
927
|
+
request = build_request(arguments)
|
|
928
|
+
except UsageError as error:
|
|
929
|
+
parser.error(str(error))
|
|
930
|
+
if arguments.dry_run:
|
|
931
|
+
sink.write(request + "\n")
|
|
932
|
+
return ExitCode.SUCCESS
|
|
933
|
+
|
|
934
|
+
response, code = _respond(request)
|
|
935
|
+
sink.write((response.model_dump_json() if arguments.json else summarize(response)) + "\n")
|
|
936
|
+
return code
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
if __name__ == "__main__":
|
|
940
|
+
sys.exit(main())
|