xiii-cli-core 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,643 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import re
6
+ from collections import Counter, defaultdict
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from xiii_cli_core.errors import ConfigurationError
11
+
12
+ MANIFEST_VERSION = 2
13
+ HTTP_METHODS = {"delete", "get", "head", "patch", "post", "put"}
14
+ PREPOSITIONS = {"as", "by", "for", "from", "in", "into", "of", "on", "to", "with"}
15
+ # The keyword arguments and flags every generated command carries itself
16
+ # (`xiii_cli_core.direct._command_signature`). An API field of the same name is
17
+ # renamed after its location, so `?output=` becomes `--query-output`.
18
+ COMMAND_ARGUMENTS = frozenset(
19
+ {
20
+ "all_pages",
21
+ "connection",
22
+ "dry_run",
23
+ "input_file",
24
+ "json_output",
25
+ "max_items",
26
+ "output",
27
+ "overwrite",
28
+ "yes",
29
+ }
30
+ )
31
+ COMMAND_OPTIONS = frozenset(
32
+ {"all", "dry-run", "input", "json", "max-items", "output", "overwrite", "yes"}
33
+ )
34
+
35
+
36
+ def build_command_manifest(document: dict[str, Any], *, product: str) -> dict[str, Any]:
37
+ """Build the customer CLI contract from one product app OpenAPI document."""
38
+ security_scheme = _pat_security_scheme(document, product)
39
+ schemas = document.get("components", {}).get("schemas", {})
40
+ if not isinstance(schemas, dict):
41
+ raise ConfigurationError("OpenAPI components.schemas must be an object")
42
+
43
+ modules: dict[str, list[dict[str, Any]]] = defaultdict(list)
44
+ excluded_event_stream_operations: list[dict[str, str]] = []
45
+ paths = document.get("paths")
46
+ if not isinstance(paths, dict):
47
+ raise ConfigurationError("OpenAPI document has no paths object")
48
+
49
+ for path, path_item in sorted(paths.items()):
50
+ if not isinstance(path_item, dict):
51
+ continue
52
+ inherited_parameters = path_item.get("parameters", [])
53
+ for method, operation in path_item.items():
54
+ if method not in HTTP_METHODS or not isinstance(operation, dict):
55
+ continue
56
+ if not _uses_security_scheme(operation, security_scheme):
57
+ continue
58
+ response_content_types = _response_content_types(operation)
59
+ if "text/event-stream" in response_content_types:
60
+ excluded_event_stream_operations.append(
61
+ {
62
+ "operation_id": str(operation.get("operationId") or "unknown"),
63
+ "method": method.upper(),
64
+ "path": path,
65
+ }
66
+ )
67
+ continue
68
+ operation_id = operation.get("operationId")
69
+ if not isinstance(operation_id, str) or not operation_id:
70
+ raise ConfigurationError(f"{method.upper()} {path} has no operationId")
71
+ module = _module_name(operation, path)
72
+ parameters = _parameters(
73
+ [*inherited_parameters, *operation.get("parameters", [])],
74
+ schemas,
75
+ module,
76
+ )
77
+ body = _request_body(operation.get("requestBody"), schemas, module)
78
+ modules[module].append(
79
+ {
80
+ "operation_id": operation_id,
81
+ "method": method.upper(),
82
+ "path": path,
83
+ "summary": operation.get("summary") or operation_id,
84
+ "description": operation.get("description"),
85
+ "parameters": parameters,
86
+ "body": body,
87
+ "response_content_types": response_content_types,
88
+ "dangerous": method not in {"get", "head"},
89
+ "pagination": _pagination(method, parameters, operation, schemas),
90
+ }
91
+ )
92
+
93
+ rendered_modules: list[dict[str, Any]] = []
94
+ for module, operations in sorted(modules.items()):
95
+ ordered = sorted(operations, key=lambda item: item["operation_id"])
96
+ candidates = [_command_name(item["operation_id"], module) for item in ordered]
97
+ contested = {name for name, count in Counter(candidates).items() if count > 1}
98
+ keepers = _single_resource_keepers(ordered, candidates, contested)
99
+ used_names: set[str] = set()
100
+ rendered_operations: list[dict[str, Any]] = []
101
+ for index, (operation, candidate) in enumerate(
102
+ zip(ordered, candidates, strict=True)
103
+ ):
104
+ if candidate in contested and index not in keepers:
105
+ candidate = operation["operation_id"].replace("_", "-")
106
+ if candidate in used_names:
107
+ raise ConfigurationError(
108
+ f"Duplicate CLI command {module} {candidate} in OpenAPI"
109
+ )
110
+ used_names.add(candidate)
111
+ rendered_operations.append({"name": candidate, **operation})
112
+ rendered_modules.append(
113
+ {
114
+ "name": module,
115
+ "operations": rendered_operations,
116
+ }
117
+ )
118
+
119
+ canonical = json.dumps(document, sort_keys=True, separators=(",", ":"))
120
+ return {
121
+ "manifest_version": MANIFEST_VERSION,
122
+ "product": product,
123
+ "openapi_sha256": hashlib.sha256(canonical.encode()).hexdigest(),
124
+ "security_scheme": security_scheme,
125
+ "module_count": len(rendered_modules),
126
+ "operation_count": sum(
127
+ len(module["operations"]) for module in rendered_modules
128
+ ),
129
+ "excluded_event_stream_operation_count": len(excluded_event_stream_operations),
130
+ "excluded_event_stream_operations": excluded_event_stream_operations,
131
+ "modules": rendered_modules,
132
+ }
133
+
134
+
135
+ def write_command_manifest(
136
+ document_path: Path, output_path: Path, *, product: str
137
+ ) -> None:
138
+ try:
139
+ document = json.loads(document_path.read_text())
140
+ except (OSError, json.JSONDecodeError) as exc:
141
+ raise ConfigurationError(
142
+ f"Could not read OpenAPI document {document_path}: {exc}"
143
+ ) from exc
144
+ if not isinstance(document, dict):
145
+ raise ConfigurationError("OpenAPI document root must be an object")
146
+ manifest = build_command_manifest(document, product=product)
147
+ output_path.parent.mkdir(parents=True, exist_ok=True)
148
+ output_path.write_text(
149
+ json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
150
+ )
151
+
152
+
153
+ def _pat_security_scheme(document: dict[str, Any], product: str) -> str:
154
+ schemes = document.get("components", {}).get("securitySchemes", {})
155
+ if not isinstance(schemes, dict):
156
+ raise ConfigurationError("OpenAPI document has no security schemes")
157
+ expected = f"{product.title()}PersonalAccessToken"
158
+ scheme = schemes.get(expected)
159
+ if isinstance(scheme, dict) and scheme.get("scheme") == "bearer":
160
+ return expected
161
+ candidates = [
162
+ name
163
+ for name, value in schemes.items()
164
+ if isinstance(value, dict)
165
+ and value.get("type") == "http"
166
+ and value.get("scheme") == "bearer"
167
+ ]
168
+ if len(candidates) != 1:
169
+ raise ConfigurationError(
170
+ f"Expected one bearer security scheme for {product}, found {candidates}"
171
+ )
172
+ return candidates[0]
173
+
174
+
175
+ def _uses_security_scheme(operation: dict[str, Any], scheme: str) -> bool:
176
+ security = operation.get("security")
177
+ return isinstance(security, list) and any(
178
+ isinstance(requirement, dict) and scheme in requirement
179
+ for requirement in security
180
+ )
181
+
182
+
183
+ def _module_name(operation: dict[str, Any], path: str) -> str:
184
+ tags = operation.get("tags", [])
185
+ for tag in tags:
186
+ if isinstance(tag, str) and tag.startswith("app-"):
187
+ return tag.removeprefix("app-")
188
+ segment = path.strip("/").split("/", 1)[0]
189
+ if not segment or segment.startswith("{"):
190
+ raise ConfigurationError(f"Cannot derive CLI module for path {path}")
191
+ return segment
192
+
193
+
194
+ def _parameters(
195
+ raw_parameters: list[Any], schemas: dict[str, Any], module: str
196
+ ) -> list[dict[str, Any]]:
197
+ parameters: list[dict[str, Any]] = []
198
+ used_arguments: set[str] = set(COMMAND_ARGUMENTS)
199
+ for raw in raw_parameters:
200
+ parameter = _resolve(raw, schemas)
201
+ if not isinstance(parameter, dict):
202
+ continue
203
+ location = parameter.get("in")
204
+ name = parameter.get("name")
205
+ if location == "cookie" or location not in {"path", "query", "header"}:
206
+ continue
207
+ if not isinstance(name, str) or not name:
208
+ continue
209
+ argument = _unique_argument(name, location, used_arguments)
210
+ used_arguments.add(argument)
211
+ parameters.append(
212
+ {
213
+ "argument": argument,
214
+ "name": name,
215
+ "option": _option_name(name, module, location),
216
+ "location": location,
217
+ "required": bool(parameter.get("required")),
218
+ "description": parameter.get("description"),
219
+ "schema": _schema_descriptor(parameter.get("schema", {}), schemas),
220
+ }
221
+ )
222
+ return parameters
223
+
224
+
225
+ def _request_body(
226
+ raw_body: Any, schemas: dict[str, Any], module: str
227
+ ) -> dict[str, Any] | None:
228
+ body = _resolve(raw_body, schemas)
229
+ if not isinstance(body, dict):
230
+ return None
231
+ content = body.get("content")
232
+ if not isinstance(content, dict) or not content:
233
+ return None
234
+ content_type = (
235
+ "application/json"
236
+ if "application/json" in content
237
+ else "multipart/form-data"
238
+ if "multipart/form-data" in content
239
+ else sorted(content)[0]
240
+ )
241
+ media = content.get(content_type)
242
+ schema = (
243
+ _resolve(media.get("schema", {}), schemas) if isinstance(media, dict) else {}
244
+ )
245
+ if not isinstance(schema, dict):
246
+ schema = {}
247
+ properties = schema.get("properties")
248
+ required_fields = schema.get("required", [])
249
+ rendered_properties: list[dict[str, Any]] = []
250
+ if isinstance(properties, dict):
251
+ used_arguments: set[str] = set()
252
+ for name, property_schema in properties.items():
253
+ if not isinstance(name, str):
254
+ continue
255
+ argument = _unique_argument(name, "body", used_arguments)
256
+ used_arguments.add(argument)
257
+ resolved = _resolve(property_schema, schemas)
258
+ rendered_properties.append(
259
+ {
260
+ "argument": argument,
261
+ "name": name,
262
+ "option": _option_name(name, module, "body"),
263
+ "required": name in required_fields,
264
+ "sensitive": bool(
265
+ isinstance(resolved, dict)
266
+ and (
267
+ resolved.get("writeOnly") is True
268
+ or resolved.get("x-sensitive") is True
269
+ )
270
+ ),
271
+ "description": (
272
+ resolved.get("description")
273
+ if isinstance(resolved, dict)
274
+ else None
275
+ ),
276
+ "schema": _schema_descriptor(property_schema, schemas),
277
+ }
278
+ )
279
+ return {
280
+ "required": bool(body.get("required")),
281
+ "content_type": content_type,
282
+ "properties": rendered_properties,
283
+ "structured": isinstance(properties, dict),
284
+ "schema": _validation_schema(
285
+ media.get("schema", {}) if isinstance(media, dict) else {}, schemas
286
+ ),
287
+ }
288
+
289
+
290
+ def _schema_descriptor(raw_schema: Any, schemas: dict[str, Any]) -> dict[str, Any]:
291
+ decimal = _decimal_descriptor(raw_schema, schemas)
292
+ if decimal is not None:
293
+ return decimal
294
+ resolved_schema = _resolve(raw_schema, schemas)
295
+ outer_constraints = (
296
+ _constraints(resolved_schema) if isinstance(resolved_schema, dict) else {}
297
+ )
298
+ schema, nullable = _unwrap_schema(raw_schema, schemas)
299
+ if not isinstance(schema, dict):
300
+ return {"kind": "json", "nullable": nullable}
301
+ schema_type = schema.get("type")
302
+ enum = schema.get("enum")
303
+ if isinstance(enum, list) and enum:
304
+ return {
305
+ "kind": "enum",
306
+ "values": enum,
307
+ "nullable": nullable,
308
+ **_constraints(schema),
309
+ **outer_constraints,
310
+ }
311
+ if schema_type == "array":
312
+ return {
313
+ "kind": "array",
314
+ "items": _schema_descriptor(schema.get("items", {}), schemas),
315
+ "nullable": nullable,
316
+ **_constraints(schema),
317
+ **outer_constraints,
318
+ }
319
+ if schema_type in {"string", "integer", "number", "boolean"}:
320
+ return {
321
+ "kind": "file"
322
+ if schema_type == "string"
323
+ and (
324
+ schema.get("format") == "binary"
325
+ or schema.get("contentMediaType") == "application/octet-stream"
326
+ )
327
+ else schema_type,
328
+ "format": schema.get("format"),
329
+ "nullable": nullable,
330
+ **_constraints(schema),
331
+ **outer_constraints,
332
+ }
333
+ return {
334
+ "kind": "json",
335
+ "nullable": nullable,
336
+ **_constraints(schema),
337
+ **outer_constraints,
338
+ }
339
+
340
+
341
+ def _unwrap_schema(
342
+ raw_schema: Any, schemas: dict[str, Any]
343
+ ) -> tuple[dict[str, Any], bool]:
344
+ schema = _resolve(raw_schema, schemas)
345
+ if not isinstance(schema, dict):
346
+ return {}, False
347
+ nullable = schema.get("nullable") is True
348
+ variants = schema.get("anyOf") or schema.get("oneOf")
349
+ if isinstance(variants, list):
350
+ non_null = []
351
+ for variant in variants:
352
+ resolved = _resolve(variant, schemas)
353
+ if isinstance(resolved, dict) and resolved.get("type") == "null":
354
+ nullable = True
355
+ else:
356
+ non_null.append(resolved)
357
+ if len(non_null) == 1 and isinstance(non_null[0], dict):
358
+ schema = non_null[0]
359
+ return schema, nullable
360
+
361
+
362
+ def _resolve(raw: Any, schemas: dict[str, Any]) -> Any:
363
+ if not isinstance(raw, dict):
364
+ return raw
365
+ reference = raw.get("$ref")
366
+ if not isinstance(reference, str):
367
+ return raw
368
+ prefix = "#/components/schemas/"
369
+ if not reference.startswith(prefix):
370
+ return raw
371
+ resolved = schemas.get(reference.removeprefix(prefix))
372
+ if not isinstance(resolved, dict):
373
+ return raw
374
+ siblings = {key: value for key, value in raw.items() if key != "$ref"}
375
+ return {**resolved, **siblings}
376
+
377
+
378
+ def _constraints(schema: dict[str, Any]) -> dict[str, Any]:
379
+ keys = (
380
+ "const",
381
+ "default",
382
+ "exclusiveMaximum",
383
+ "exclusiveMinimum",
384
+ "maximum",
385
+ "maxItems",
386
+ "maxLength",
387
+ "maxProperties",
388
+ "minimum",
389
+ "minItems",
390
+ "minLength",
391
+ "minProperties",
392
+ "multipleOf",
393
+ "pattern",
394
+ "uniqueItems",
395
+ "x-allowedContentTypes",
396
+ "x-maxSizeBytes",
397
+ )
398
+ return {key: schema[key] for key in keys if key in schema}
399
+
400
+
401
+ def _decimal_descriptor(
402
+ raw_schema: Any, schemas: dict[str, Any]
403
+ ) -> dict[str, Any] | None:
404
+ schema = _resolve(raw_schema, schemas)
405
+ if not isinstance(schema, dict):
406
+ return None
407
+ variants = schema.get("anyOf") or schema.get("oneOf")
408
+ if not isinstance(variants, list):
409
+ return None
410
+ nullable = False
411
+ number: dict[str, Any] | None = None
412
+ string: dict[str, Any] | None = None
413
+ for variant in variants:
414
+ resolved = _resolve(variant, schemas)
415
+ if not isinstance(resolved, dict):
416
+ return None
417
+ if resolved.get("type") == "null":
418
+ nullable = True
419
+ elif resolved.get("type") == "number" and number is None:
420
+ number = resolved
421
+ elif resolved.get("type") == "string" and string is None:
422
+ string = resolved
423
+ else:
424
+ return None
425
+ if number is None or string is None or not string.get("pattern"):
426
+ return None
427
+ return {
428
+ "kind": "decimal",
429
+ "nullable": nullable,
430
+ **_constraints(number),
431
+ **_constraints(string),
432
+ }
433
+
434
+
435
+ def _validation_schema(
436
+ raw_schema: Any,
437
+ schemas: dict[str, Any],
438
+ seen: frozenset[str] = frozenset(),
439
+ ) -> dict[str, Any]:
440
+ if not isinstance(raw_schema, dict):
441
+ return {}
442
+ reference = raw_schema.get("$ref")
443
+ if isinstance(reference, str) and reference.startswith("#/components/schemas/"):
444
+ name = reference.removeprefix("#/components/schemas/")
445
+ if name in seen:
446
+ return {}
447
+ resolved = schemas.get(name)
448
+ if not isinstance(resolved, dict):
449
+ return {}
450
+ next_seen = seen | {name}
451
+ referenced = _validation_schema(resolved, schemas, next_seen)
452
+ siblings = {key: value for key, value in raw_schema.items() if key != "$ref"}
453
+ return {
454
+ **referenced,
455
+ **_validation_schema(siblings, schemas, next_seen),
456
+ }
457
+
458
+ scalar_keys = (
459
+ "additionalProperties",
460
+ "const",
461
+ "enum",
462
+ "exclusiveMaximum",
463
+ "exclusiveMinimum",
464
+ "format",
465
+ "maximum",
466
+ "maxItems",
467
+ "maxLength",
468
+ "maxProperties",
469
+ "minimum",
470
+ "minItems",
471
+ "minLength",
472
+ "minProperties",
473
+ "multipleOf",
474
+ "nullable",
475
+ "pattern",
476
+ "required",
477
+ "type",
478
+ "uniqueItems",
479
+ "writeOnly",
480
+ "x-allowedContentTypes",
481
+ "x-maxSizeBytes",
482
+ "x-sensitive",
483
+ )
484
+ rendered = {key: raw_schema[key] for key in scalar_keys if key in raw_schema}
485
+ properties = raw_schema.get("properties")
486
+ if isinstance(properties, dict):
487
+ rendered["properties"] = {
488
+ str(name): _validation_schema(value, schemas, seen)
489
+ for name, value in properties.items()
490
+ if isinstance(name, str)
491
+ }
492
+ items = raw_schema.get("items")
493
+ if isinstance(items, dict):
494
+ rendered["items"] = _validation_schema(items, schemas, seen)
495
+ for keyword in ("anyOf", "oneOf"):
496
+ variants = raw_schema.get(keyword)
497
+ if isinstance(variants, list):
498
+ rendered[keyword] = [
499
+ _validation_schema(variant, schemas, seen)
500
+ for variant in variants
501
+ if isinstance(variant, dict)
502
+ ]
503
+ return rendered
504
+
505
+
506
+ def _response_content_types(operation: dict[str, Any]) -> list[str]:
507
+ content_types: set[str] = set()
508
+ responses = operation.get("responses", {})
509
+ if not isinstance(responses, dict):
510
+ return []
511
+ for status, response in responses.items():
512
+ if not str(status).startswith("2") or not isinstance(response, dict):
513
+ continue
514
+ content = response.get("content", {})
515
+ if isinstance(content, dict):
516
+ content_types.update(content)
517
+ return sorted(content_types)
518
+
519
+
520
+ def _pagination(
521
+ method: str,
522
+ parameters: list[dict[str, Any]],
523
+ operation: dict[str, Any],
524
+ schemas: dict[str, Any],
525
+ ) -> dict[str, str] | None:
526
+ """Name the list a `--all` run collects, or None when it cannot page.
527
+
528
+ A list pages when it takes `limit` and `offset` and answers with nothing
529
+ but one array, `has_more` and an optional `total`; a page with further
530
+ fields (a default id, per-currency sums) would lose them when merged.
531
+ """
532
+ query = {item["name"] for item in parameters if item["location"] == "query"}
533
+ if method != "get" or not {"limit", "offset"} <= query:
534
+ return None
535
+ response = operation.get("responses", {}).get("200", {})
536
+ content = response.get("content", {}) if isinstance(response, dict) else {}
537
+ media = content.get("application/json") if isinstance(content, dict) else None
538
+ schema = _resolve(media.get("schema"), schemas) if isinstance(media, dict) else None
539
+ properties = schema.get("properties") if isinstance(schema, dict) else None
540
+ if not isinstance(properties, dict) or "has_more" not in properties:
541
+ return None
542
+ arrays = [
543
+ name
544
+ for name, value in properties.items()
545
+ if isinstance(value, dict) and _resolve(value, schemas).get("type") == "array"
546
+ ]
547
+ if len(arrays) != 1 or set(properties) - {arrays[0], "has_more", "total"}:
548
+ return None
549
+ return {"items": arrays[0]}
550
+
551
+
552
+ def _option_name(name: str, module: str, location: str) -> str:
553
+ singular = _singular(module.replace("-", "_"))
554
+ normalized = name.replace("-", "_")
555
+ if normalized == f"{singular}_type":
556
+ return "type"
557
+ option = normalized.replace("_", "-")
558
+ if option in COMMAND_OPTIONS:
559
+ return f"{location}-{option}"
560
+ return option
561
+
562
+
563
+ def _unique_argument(name: str, location: str, used: set[str]) -> str:
564
+ argument = re.sub(r"\W+", "_", name).strip("_") or "value"
565
+ if argument[0].isdigit():
566
+ argument = f"value_{argument}"
567
+ if argument in used:
568
+ argument = f"{location}_{argument}"
569
+ return argument
570
+
571
+
572
+ def _single_resource_keepers(
573
+ operations: list[dict[str, Any]],
574
+ candidates: list[str],
575
+ contested: set[str],
576
+ ) -> set[int]:
577
+ """Award a contested name to the one rival that addresses a single resource.
578
+
579
+ Two operations shorten to the same name when one acts on a collection and the
580
+ other on one member of it. The member route is the one carrying more path
581
+ parameters, and it keeps the short name; its rivals fall back to their full
582
+ operation ID, so the two never differ by an "s" alone.
583
+ """
584
+ keepers: set[int] = set()
585
+ for name in contested:
586
+ rivals = [index for index, value in enumerate(candidates) if value == name]
587
+ depths = [operations[index]["path"].count("{") for index in rivals]
588
+ deepest = max(depths)
589
+ if depths.count(deepest) == 1:
590
+ keepers.add(rivals[depths.index(deepest)])
591
+ return keepers
592
+
593
+
594
+ def _command_name(operation_id: str, module: str) -> str:
595
+ """Name a command without repeating the module noun it is already filed under."""
596
+ tokens = operation_id.replace("_", "-").split("-")
597
+ span = _module_noun_span(tokens, module)
598
+ if span is None:
599
+ return "-".join(tokens)
600
+ start, length = span
601
+ remaining = [*tokens[:start], *tokens[start + length :]]
602
+ if not remaining:
603
+ return "-".join(tokens)
604
+ return "-".join(remaining)
605
+
606
+
607
+ def _module_noun_span(tokens: list[str], module: str) -> tuple[int, int] | None:
608
+ """Locate the module's own noun in a command name, longest spelling first."""
609
+ module_name = module.replace("_", "-")
610
+ singular = _singular(module_name)
611
+ forms = sorted(
612
+ {module_name, singular, _plural(singular)},
613
+ key=lambda form: (-form.count("-"), form),
614
+ )
615
+ for start in range(len(tokens)):
616
+ if start and tokens[start - 1] in PREPOSITIONS:
617
+ continue
618
+ for form in forms:
619
+ words = form.split("-")
620
+ if tokens[start : start + len(words)] == words:
621
+ return start, len(words)
622
+ return None
623
+
624
+
625
+ def _singular(value: str) -> str:
626
+ if value.endswith("ies"):
627
+ return f"{value[:-3]}y"
628
+ if value.endswith(("ches", "shes", "xes", "zes", "sses")):
629
+ return value[:-2]
630
+ if value.endswith("s") and not value.endswith("ss"):
631
+ return value[:-1]
632
+ return value
633
+
634
+
635
+ def _plural(value: str) -> str:
636
+ if value.endswith("y") and not value.endswith(("ay", "ey", "oy", "uy")):
637
+ return f"{value[:-1]}ies"
638
+ if value.endswith(("ch", "sh", "s", "x", "z")):
639
+ return f"{value}es"
640
+ return f"{value}s"
641
+
642
+
643
+ __all__ = ["MANIFEST_VERSION", "build_command_manifest", "write_command_manifest"]
xiii_cli_core/py.typed ADDED
File without changes
@@ -0,0 +1,44 @@
1
+ import json
2
+ from typing import Any
3
+
4
+ from rich.console import Console
5
+ from rich.table import Table
6
+
7
+ console = Console()
8
+
9
+
10
+ def render_json(payload: Any) -> None:
11
+ console.print_json(json.dumps(payload, default=str))
12
+
13
+
14
+ def render_rows(payload: Any) -> None:
15
+ rows = payload.get("items") if isinstance(payload, dict) else payload
16
+ if not isinstance(rows, list) or not rows:
17
+ render_json(payload)
18
+ return
19
+ if not all(isinstance(row, dict) for row in rows):
20
+ render_json(payload)
21
+ return
22
+
23
+ columns: list[str] = []
24
+ for row in rows[:20]:
25
+ for key in row:
26
+ if key not in columns:
27
+ columns.append(key)
28
+ if len(columns) == 8:
29
+ break
30
+ if len(columns) == 8:
31
+ break
32
+
33
+ table = Table(show_lines=False)
34
+ for column in columns:
35
+ table.add_column(column)
36
+ for row in rows:
37
+ table.add_row(*[_cell(row.get(column)) for column in columns])
38
+ console.print(table)
39
+
40
+
41
+ def _cell(value: Any) -> str:
42
+ if isinstance(value, (dict, list)):
43
+ return json.dumps(value, ensure_ascii=False, default=str)
44
+ return "" if value is None else str(value)