-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathexport_reference_docs.py
More file actions
executable file
·533 lines (473 loc) · 18.8 KB
/
Copy pathexport_reference_docs.py
File metadata and controls
executable file
·533 lines (473 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
#!/usr/bin/env python3
"""Generate CLI, configuration, and extraction-schema references from source."""
from __future__ import annotations
import argparse
import difflib
import json
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterator
from pydantic_core import PydanticUndefined
from parsehawk.cli.main import (
CLI_COMMAND_EXAMPLES,
CLI_CONFIG_DESCRIPTIONS,
CONFIG_ENV_OVERRIDES,
DEFAULT_CLI_CONFIG,
build_parser,
)
from parsehawk.config import Settings
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
REFERENCE_ROOT = REPOSITORY_ROOT / "apps" / "docs" / "src" / "content" / "docs" / "reference"
CLI_OUTPUT = REFERENCE_ROOT / "cli.md"
CONFIG_OUTPUT = REFERENCE_ROOT / "configuration.md"
EXTRACTION_SCHEMA_SOURCE = (
REPOSITORY_ROOT / "docs" / "schemas" / "parsehawk-extraction-schema.schema.json"
)
EXTRACTION_SCHEMA_OUTPUT = REFERENCE_ROOT / "extraction-schema.md"
GENERATED_NOTICE = "<!-- Generated by `just references-export`; do not edit by hand. -->"
@dataclass(frozen=True)
class Command:
parser: argparse.ArgumentParser
aliases: tuple[str, ...] = ()
def _build_deterministic_parser() -> argparse.ArgumentParser:
"""Build CLI metadata without inheriting a developer's API URL override."""
previous = os.environ.pop("PARSEHAWK_API_URL", None)
try:
return build_parser()
finally:
if previous is not None:
os.environ["PARSEHAWK_API_URL"] = previous
def iter_commands(parser: argparse.ArgumentParser) -> Iterator[Command]:
"""Yield each canonical command once while retaining its aliases."""
yield Command(parser=parser)
for action in parser._actions:
if not isinstance(action, argparse._SubParsersAction):
continue
grouped: dict[int, tuple[argparse.ArgumentParser, list[str]]] = {}
for name, child in action.choices.items():
entry = grouped.setdefault(id(child), (child, []))
entry[1].append(name)
for child, names in grouped.values():
yield Command(parser=child, aliases=tuple(names[1:]))
yield from list(iter_commands(child))[1:]
def _argument_syntax(action: argparse.Action) -> str:
if action.option_strings:
if action.nargs == 0:
return ", ".join(f"`{option}`" for option in action.option_strings)
metavar = action.metavar or action.dest.upper()
return ", ".join(f"`{option} {metavar}`" for option in action.option_strings)
metavar = str(action.metavar or action.dest)
if action.nargs == "?":
metavar = f"[{metavar}]"
elif action.nargs == "*":
metavar = f"[{metavar} ...]"
elif action.nargs == "+":
metavar = f"{metavar} [{metavar} ...]"
return f"`{metavar}`"
def _is_required(parser: argparse.ArgumentParser, action: argparse.Action) -> str:
for group in parser._mutually_exclusive_groups:
if action in group._group_actions and group.required:
return "One of group"
if action.option_strings:
return "Yes" if action.required else "No"
return "No" if action.nargs in {"?", "*"} else "Yes"
def _stable_value(value: Any) -> str:
if value is None or value is PydanticUndefined or value == argparse.SUPPRESS:
return "—"
if isinstance(value, bool):
return f"`{str(value).lower()}`"
if isinstance(value, Path):
try:
value = Path("~") / value.relative_to(Path.home())
except ValueError:
pass
if isinstance(value, (list, tuple, dict)):
value = json.dumps(value, ensure_ascii=False, sort_keys=True)
elif value == "":
value = '""'
return f"`{value}`"
def _table_cell(value: str) -> str:
return value.replace("|", "\\|").replace("\n", " ").strip()
def _action_description(action: argparse.Action) -> str:
description = action.help or ""
if action.choices is not None:
choices = ", ".join(f"`{choice}`" for choice in action.choices)
description = f"{description} Choices: {choices}."
return _table_cell(description)
def _usage(parser: argparse.ArgumentParser) -> str:
usage = parser.format_usage().strip()
return " ".join(usage.removeprefix("usage: ").split())
def _command_anchor(command: str) -> str:
return command.lower().replace(" ", "-")
def _related_commands(command: str, commands: set[str]) -> list[str]:
parts = command.split()
related: list[str] = []
if len(parts) > 1:
related.append(" ".join(parts[:-1]))
prefix = f"{command} "
related.extend(
candidate
for candidate in sorted(commands)
if candidate.startswith(prefix) and " " not in candidate.removeprefix(prefix)
)
return list(dict.fromkeys(related))
def render_cli_reference() -> str:
"""Render every argparse command and option as stable Markdown."""
commands = list(iter_commands(_build_deterministic_parser()))
command_names = {command.parser.prog for command in commands}
if command_names != CLI_COMMAND_EXAMPLES.keys():
missing = sorted(command_names - CLI_COMMAND_EXAMPLES.keys())
extra = sorted(CLI_COMMAND_EXAMPLES.keys() - command_names)
raise ValueError(f"CLI example metadata is stale (missing={missing}, extra={extra})")
lines = [
"---",
"title: CLI reference",
"description: Every ParseHawk command, argument, option, and default generated from argparse.",
"sidebar:",
" order: 2",
" badge:",
" text: Generated",
" variant: success",
"editUrl: false",
"---",
"",
GENERATED_NOTICE,
"",
"This page is generated from the same `argparse` definitions used by the installed",
"`parsehawk` command. Change CLI help in code, run `just references-export`, and commit",
"the updated page.",
"",
"## Exit status",
"",
"| Code | Meaning |",
"| --- | --- |",
"| `0` | Command completed successfully. |",
"| `1` | Runtime, API, configuration, validation, or local-environment failure. |",
"| `2` | Command-line usage error reported by `argparse`. |",
"",
"Errors are written to standard error. API failures include the HTTP status and response",
"body; connection failures include the target API URL.",
"",
"## Command index",
"",
]
for command in commands:
label = command.parser.prog
anchor = _command_anchor(label)
lines.append(f"- [`{label}`](#{anchor})")
for command in commands:
parser = command.parser
lines.extend(["", f"## {parser.prog}", "", parser.description or "", ""])
if command.aliases:
aliases = ", ".join(f"`{alias}`" for alias in command.aliases)
lines.extend([f"Aliases: {aliases}", ""])
lines.extend(["```console", f"$ {_usage(parser)}", "```", ""])
lines.extend(
[
"### Example",
"",
"```console",
f"$ {CLI_COMMAND_EXAMPLES[parser.prog]}",
"```",
"",
]
)
related = _related_commands(parser.prog, command_names)
if related:
lines.extend(["### Related commands", ""])
lines.extend(
f"- [`{related_command}`](#{_command_anchor(related_command)})"
for related_command in related
)
lines.append("")
actions = [
action
for action in parser._actions
if not isinstance(action, argparse._SubParsersAction)
]
if not actions:
lines.append("This command has no arguments or options.")
continue
lines.extend(
[
"| Argument | Description | Required | Default |",
"| --- | --- | --- | --- |",
]
)
for action in actions:
lines.append(
"| "
+ " | ".join(
[
_argument_syntax(action),
_action_description(action),
_is_required(parser, action),
_stable_value(action.default),
]
)
+ " |"
)
return "\n".join(lines).rstrip() + "\n"
def _schema_type(schema: dict[str, Any]) -> str:
if "anyOf" in schema:
types = [_schema_type(option) for option in schema["anyOf"]]
return " or ".join(dict.fromkeys(types))
schema_type = schema.get("type", "value")
if schema_type == "null":
return "null"
return str(schema_type)
def _constraints(schema: dict[str, Any]) -> str:
labels = {
"minimum": "minimum",
"exclusiveMinimum": "greater than",
"maximum": "maximum",
"exclusiveMaximum": "less than",
"minLength": "minimum length",
"maxLength": "maximum length",
}
values = [f"{label} `{schema[key]}`" for key, label in labels.items() if key in schema]
return "; ".join(values)
def _field_default(name: str) -> Any:
field = Settings.model_fields[name]
return field.get_default(call_default_factory=True)
def render_configuration_reference() -> str:
"""Render environment and persistent CLI settings from typed source metadata."""
settings_schema = Settings.model_json_schema(mode="validation")
properties = settings_schema["properties"]
lines = [
"---",
"title: Configuration reference",
"description: Environment variables and persistent CLI settings generated from typed source metadata.",
"sidebar:",
" order: 3",
" badge:",
" text: Generated",
" variant: success",
"editUrl: false",
"---",
"",
GENERATED_NOTICE,
"",
"ParseHawk service settings are typed with Pydantic and use the `PARSEHAWK_` prefix.",
"Values are read when each process starts.",
"",
"## Service environment variables",
"",
"| Environment variable | Type | Default | Description |",
"| --- | --- | --- | --- |",
]
for name, field in Settings.model_fields.items():
schema = properties[name]
env_name = f"PARSEHAWK_{name.upper()}"
description = field.description or ""
constraints = _constraints(schema)
if constraints:
description = f"{description} Constraint: {constraints}."
if schema.get("writeOnly"):
description = f"{description} Sensitive value; never expose it in logs or docs."
lines.append(
"| "
+ " | ".join(
[
f"`{env_name}`",
_schema_type(schema),
_stable_value(_field_default(name)),
_table_cell(description),
]
)
+ " |"
)
lines.extend(
[
"",
"## Persistent CLI configuration",
"",
"The CLI stores explicitly set values in `~/.parsehawk/config.json`. Override that",
"location with `PARSEHAWK_CONFIG_PATH`. Environment overrides take precedence when",
"the relevant command loads effective CLI configuration.",
"",
"| Key | Environment override | Default | Description |",
"| --- | --- | --- | --- |",
]
)
for key, default in DEFAULT_CLI_CONFIG.items():
if key == "data.dir" and default == "":
rendered_default = "`./data` in a source checkout; otherwise `~/.parsehawk/data`"
else:
rendered_default = _stable_value(default)
lines.append(
"| "
+ " | ".join(
[
f"`{key}`",
f"`{CONFIG_ENV_OVERRIDES[key]}`",
rendered_default,
_table_cell(CLI_CONFIG_DESCRIPTIONS[key]),
]
)
+ " |"
)
lines.extend(
[
"",
"## Cross-cutting environment controls",
"",
"| Environment variable | Purpose |",
"| --- | --- |",
"| `PARSEHAWK_CONFIG_PATH` | Override the persistent CLI configuration file path. |",
"| `DO_NOT_TRACK` | Disable anonymous telemetry when set to a truthy value. |",
"| `OTEL_SDK_DISABLED` | Disable OpenTelemetry export when set to `true`. |",
"| `OTEL_EXPORTER_OTLP_ENDPOINT` | Send traces to an external OTLP endpoint. |",
]
)
return "\n".join(lines).rstrip() + "\n"
def render_extraction_schema_reference() -> str:
"""Render the supported authoring dialect from its canonical meta-schema."""
schema = json.loads(EXTRACTION_SCHEMA_SOURCE.read_text(encoding="utf-8"))
definitions = schema["$defs"]
semantic_values = definitions["parsehawkExtension"]["properties"]["semantic"]["enum"]
semantic_rows = [
("Text", ["string", "verbatim-string"]),
("Scalar", ["integer", "number", "boolean"]),
("Date and time", ["date", "time", "date-time", "duration"]),
("Locale", ["country", "currency", "language", "language-tag", "script"]),
("Identifiers", ["url", "email-address", "phone-number", "iban", "bic", "unit-code"]),
("Regions", [value for value in semantic_values if value.startswith("region:")]),
]
rendered_semantics = {value for _, values in semantic_rows for value in values}
if rendered_semantics != set(semantic_values):
missing = sorted(set(semantic_values) - rendered_semantics)
extra = sorted(rendered_semantics - set(semantic_values))
raise ValueError(f"Semantic reference groups are stale (missing={missing}, extra={extra})")
lines = [
"---",
"title: Extraction schema reference",
"description: The JSON Schema authoring dialect ParseHawk accepts, generated from its canonical meta-schema.",
"sidebar:",
" order: 4",
" badge:",
" text: Generated",
" variant: success",
"editUrl: false",
"---",
"",
GENERATED_NOTICE,
"",
"ParseHawk accepts a focused JSON Schema Draft 2020-12 authoring dialect. The",
"dialect is intentionally smaller than general JSON Schema so an extractor can turn",
"the same contract into model guidance, output validation, and typed downstream data.",
"",
"[Download the canonical meta-schema](/schemas/parsehawk-extraction-schema.schema.json)",
"or validate a file with `parsehawk schemas validate schema.json`.",
"",
"## Supported shapes",
"",
"| Shape | Supported authoring fields |",
"| --- | --- |",
"| Object | `type`, `properties`, `required`, `additionalProperties`, `title`, `description` |",
"| Array | `type`, `items`, `title`, `description` |",
"| String | `type`, `pattern`, `minLength`, `maxLength`, `title`, `description` |",
"| Number, integer, boolean | `type`, `title`, `description` |",
"| Enum | `type`, `enum`, optional `x-parsehawk`, `title`, `description` |",
"| Enum union | `oneOf` or `anyOf` branches containing `const` or `enum` |",
'| Nullable value | A two-item type union such as `["string", "null"]` |',
"",
"The root must be an object with `type` and `properties`. Object schemas must set",
"`additionalProperties` to `false`. Unknown schema keywords are rejected.",
"",
"## Minimal schema",
"",
"```json",
"{",
' "$schema": "https://json-schema.org/draft/2020-12/schema",',
' "type": "object",',
' "properties": {',
' "invoice_number": {',
' "type": ["string", "null"],',
' "description": "The invoice number exactly as printed."',
" },",
' "total": {',
' "type": ["number", "null"],',
' "description": "The final amount due."',
" }",
" },",
' "required": ["invoice_number", "total"],',
' "additionalProperties": false',
"}",
"```",
"",
"## Semantic hints",
"",
"Set `x-parsehawk.semantic` on a string field to express the value's meaning more",
"precisely than JSON Schema's primitive type. These hints guide compatible models;",
"the JSON output still uses ordinary strings, numbers, integers, or booleans.",
"",
"| Family | Values |",
"| --- | --- |",
]
for family, values in semantic_rows:
lines.append(f"| {family} | {', '.join(f'`{value}`' for value in values)} |")
lines.extend(
[
"",
"```json",
"{",
' "type": ["string", "null"],',
' "description": "Invoice date in ISO 8601 format.",',
' "x-parsehawk": { "semantic": "date" }',
"}",
"```",
"",
"## Source of truth",
"",
"The canonical meta-schema is committed at",
"`docs/schemas/parsehawk-extraction-schema.schema.json`. The generated page and",
"download endpoint are checked for drift in pre-commit and CI.",
]
)
return "\n".join(lines).rstrip() + "\n"
def _check_output(path: Path, expected: str) -> bool:
if not path.exists():
print(f"Generated reference is missing: {path.relative_to(REPOSITORY_ROOT)}")
return False
actual = path.read_text(encoding="utf-8")
if actual == expected:
print(f"Reference is in sync: {path.relative_to(REPOSITORY_ROOT)}")
return True
relative = path.relative_to(REPOSITORY_ROOT)
print(f"Generated reference is stale: {relative}")
print(
"".join(
difflib.unified_diff(
actual.splitlines(keepends=True),
expected.splitlines(keepends=True),
fromfile=str(relative),
tofile=f"generated/{relative}",
)
),
end="",
)
return False
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--check",
action="store_true",
help="verify committed references without modifying the working tree",
)
args = parser.parse_args()
outputs = {
CLI_OUTPUT: render_cli_reference(),
CONFIG_OUTPUT: render_configuration_reference(),
EXTRACTION_SCHEMA_OUTPUT: render_extraction_schema_reference(),
}
if args.check:
return 0 if all(_check_output(path, content) for path, content in outputs.items()) else 1
for path, content in outputs.items():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
print(f"Wrote {path.relative_to(REPOSITORY_ROOT)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())