-
Notifications
You must be signed in to change notification settings - Fork 28
/
domain.py
1251 lines (1071 loc) · 45 KB
/
domain.py
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Implements the `json` domain and `json:schema` directive."""
import dataclasses
import json
import os
import re
from typing import (
List,
Any,
Optional,
Dict,
cast,
NamedTuple,
Tuple,
Iterator,
Set,
Union,
Iterable,
)
import docutils
import docutils.parsers.rst.directives
try:
import jsonschema.validators
_jsonschema_validation_supported = True
except ImportError:
_jsonschema_validation_supported = False
import sphinx
import sphinx.addnodes
import sphinx.application
import sphinx.directives
import sphinx.domains
import sphinx.environment
import sphinx.project
import sphinx.roles
import sphinx.util
import sphinx.util.docutils
import sphinx.util.logging
import sphinx.util.matching
import yaml # pylint: disable=import-error
from .. import object_description_options
from . import json_pprint
from ... import sphinx_utils
from .. import apigen_utils
logger = sphinx.util.logging.getLogger(__name__)
class JsonSchemaMapEntry(NamedTuple):
path: str
pointer: str
schema: Any
id: str
top_level_schema: Any
JsonSchema = Any
"""JSON schema represented as a JSON object (i.e. dict)."""
YamlSourceInfoMap = Dict[int, Tuple[str, int]]
"""For each literal string parsed from a schema YAML file, maps `id(s)` to the
`(source_file, lineno)`.
When embedding strings from the YAML files as reStructuredText content in the
documentation, this is used to include proper source information to Sphinx,
which in turn can include it in error messages.
"""
@dataclasses.dataclass
class LoadedSchemaData:
id_map: Dict[str, JsonSchemaMapEntry] = dataclasses.field(default_factory=dict)
"""Maps JSON schema ids to the loaded schema entry.
This contains an entry for both top-level and sub-schemas, including schemas
for individual properties.
The same schema entry may be contained under multiple keys. In addition to
the canonical id (defined by the $id member), if any, the schema is also
present under a JSON pointer key `<parent>#/json/pointer/path`, if applicable.
Additionally, as schemas are rendered to a document tree, additional aliases
are added for member property ids `<parent>.<member>` and for string constant
oneOfs `<parent>.<value>`.
"""
source_info_map: YamlSourceInfoMap = dataclasses.field(default_factory=dict)
"""Combined source map for all schemas loaded in `id_map`."""
identity_map: Dict[int, JsonSchemaMapEntry] = dataclasses.field(
default_factory=dict
)
"""Maps `id(entry.schema)` -> `entry` for every entry in `id_map`.
This allows the entry to be determined from arbitrary nested schemas.
"""
supertype_map: Dict[str, List[str]] = dataclasses.field(default_factory=dict)
"""Maps the canonical schema id to a list of types it "extends" (via allOf)."""
subtype_map: Dict[str, List[str]] = dataclasses.field(default_factory=dict)
"""Maps the canonical schema id to a list of types that "extend" it).
This is the inverse of `supertype_map`.
"""
def register_subtype_relationships(self, schema: JsonSchema) -> None:
"""Registers subtype relationships involving `schema`.
These are stored in the `subtype_map` and `schema_supertype_map` maps.
This relationship information is used to render the "Extends" and "Subtypes"
sections for a JSON schema description.
:param schema: Schema to process.
"""
schema_id = schema["$id"]
# Don't show types with ids containing "#"
if "#" in schema_id:
return
allof = schema.get("allOf")
if not allof:
return
for supertype in allof:
supertype_id = supertype.get("$ref")
if supertype_id is None:
continue
supertype_entry = self.id_map[supertype_id]
if "$id" not in supertype_entry.schema:
continue
# Don't show types with ids containing "#"
if "#" in supertype_entry.id:
continue
supertype_id = supertype_entry.id
self.subtype_map.setdefault(supertype_id, []).append(schema_id)
self.supertype_map.setdefault(schema_id, []).append(supertype_id)
def load_json_schema(
self, path: str, full_path: str, seen_ids: Dict[str, str], validate: bool
) -> None:
"""Loads a single JSON schema into the global registry.
All relative schema ids are resolved to absolute ids.
The top-level schema as well as any sub-schemas are included in the registry.
:param path: Path relative to documentation source dir.
:param full_path: Full path to schema file.
:param seen_ids: Dictionary of schema ids to populate.
"""
with open(full_path, "r", encoding="utf-8") as f:
top_level_schema, source_info_map = yaml_load(f, source_path=full_path)
self.source_info_map.update(source_info_map)
if validate:
jsonschema.validators.validator_for(top_level_schema).check_schema(
top_level_schema
)
top_level_id = top_level_schema.get("$id")
_fix_jsonschema_ids(
top_level_schema, top_level_id, path, seen_ids, self.source_info_map
)
# Register an individual schema/sub-schema.
def _process_schema(schema: JsonSchema, pointer: str):
pointer_based_id = top_level_id
if pointer:
pointer_based_id += "#" + pointer
canonical_id = pointer_based_id
if "$id" in schema:
canonical_id = schema["$id"] = _normalize_jsonschema_id(
schema["$id"], top_level_id
)
schema_entry = JsonSchemaMapEntry(
path=path,
pointer=pointer,
schema=schema,
id=canonical_id,
top_level_schema=top_level_schema,
)
self.identity_map[id(schema)] = schema_entry
self.id_map[canonical_id] = schema_entry
if canonical_id != pointer_based_id:
self.id_map[pointer_based_id] = schema_entry
for sub_schema, pointer in _traverse_sub_schemas(top_level_schema):
_process_schema(sub_schema, pointer)
def yaml_load( # pylint: disable=invalid-name
stream,
source_path: str,
) -> Tuple[Any, YamlSourceInfoMap]:
"""Loads a yaml file, preserving object key order and source line information.
:param stream: File-like stream to read from.
:param source_path: Path to source file for inclusion in source info map.
:param Loader: YAML loader class.
:returns: Tuple of loaded YAML value and source info map.
"""
source_info_map: YamlSourceInfoMap = {}
class Loader(yaml.SafeLoader):
def compose_scalar_node(self, anchor):
line = self.line
node = super().compose_scalar_node(anchor)
if isinstance(node.value, str):
source_info_map[id(node.value)] = (source_path, line)
return node
result = yaml.load(stream, Loader)
return result, source_info_map
def _globs_to_re(globs: List[str]) -> re.Pattern:
return re.compile(
"|".join(
"(?:" + sphinx.util.matching._translate_pattern(x) + ")" for x in globs
)
)
def _get_json_schema_files(app: sphinx.application.Sphinx):
"""Finds all schema files.
:param app: Sphinx application object.
:Yields: Each schema path relative to ``app.srcdir``.
"""
include_globs = app.config.json_schemas
if not include_globs:
return
exclude_globs = (
app.config.exclude_patterns
+ app.config.templates_path
+ sphinx.project.EXCLUDE_PATHS
)
if sphinx.version_info >= (6, 0):
yield from sphinx.util.matching.get_matching_files(
app.srcdir, include_patterns=include_globs, exclude_patterns=exclude_globs
)
return
# Use older predicate-based `get_matching_files`.
include_re = _globs_to_re(include_globs)
exclude_re = _globs_to_re(exclude_globs)
matching_files = sphinx.util.get_matching_files(
app.srcdir, (lambda s: exclude_re.fullmatch(s) is not None,)
)
for name in matching_files:
if not include_re.fullmatch(name):
continue
yield name
def _populate_json_schema_id_map(app: sphinx.application.Sphinx):
"""Finds all schema files and loads them into `_json_schema_id_map`."""
schema_data = LoadedSchemaData()
setattr(app.env, "json_schema_data", schema_data)
seen_ids: Dict[str, str] = {}
all_paths = list(_get_json_schema_files(app))
validate = app.config.json_schema_validate
if all_paths and validate and not _jsonschema_validation_supported:
logger.error("jsonschema package required for json_schema_validate option")
validate = False
for i, path in enumerate(all_paths):
logger.info("[%d/%d] Loading JSON schema: %s", i + 1, len(all_paths), path)
schema_data.load_json_schema(
path=path,
full_path=os.path.join(app.srcdir, path),
seen_ids=seen_ids,
validate=validate,
)
for key, path in seen_ids.items():
if key in schema_data.id_map:
continue
logger.error("Undefined jsonschema $ref: %s: %s", path, key)
for schema_id, schema_entry in schema_data.id_map.items():
if schema_entry.id != schema_id:
# Don't process under an alias, in order to avoid processing the same type
# more than once.
continue
schema = schema_entry.schema
if "$id" not in schema:
continue
schema_data.register_subtype_relationships(schema)
def _is_object_with_properties(schema_node: JsonSchema) -> bool:
"""Returns `True` if `schema_node` is an object schema with properties.
An `allOf` schema is also assumed to be an object schema.
:param schema_node: JSON schema to check.
"""
if not isinstance(schema_node, dict):
return False
return ("type" not in schema_node and "allOf" in schema_node) or (
schema_node.get("type") == "object" and schema_node.get("properties", {})
)
def _is_object_array_with_properties(schema_node: JsonSchema):
return schema_node.get("type") == "array" and _is_object_with_properties(
schema_node.get("items")
)
def _is_object_or_object_array_with_properties(schema_node: JsonSchema):
return _is_object_with_properties(schema_node) or _is_object_array_with_properties(
schema_node
)
def _normalize_jsonschema_id(id_str: str, top_level_id: Optional[str]) -> str:
if id_str.startswith("#") and top_level_id is not None:
return top_level_id + id_str
return id_str
def _traverse_sub_schemas(
schema: JsonSchema, pointer: str = ""
) -> Iterator[Tuple[JsonSchema, str]]:
"""Invokes `callback` on `schema` and any sub-schemas.
:param schema: JSON schema.
:param pointer: Initial JSON pointer.
"""
yield (schema, pointer)
def _handle_prop(prop):
obj = schema.get(prop)
if obj is None:
return
items: Iterable[Tuple[Union[int, str], JsonSchema]]
if isinstance(obj, list):
items = enumerate(obj)
elif isinstance(obj, dict):
items = obj.items()
else:
raise TypeError
for key, sub_schema in items:
yield from _traverse_sub_schemas(
sub_schema, "%s/%s/%s" % (pointer, prop, key)
)
for prop in ("definitions", "properties", "allOf", "oneOf"):
yield from _handle_prop(prop)
items_data = schema.get("items")
if items_data is not None:
if isinstance(items_data, list):
yield from _handle_prop("items")
else:
yield from _traverse_sub_schemas(items_data, "%s/items" % (pointer,))
def _fix_jsonschema_ids(
schema: JsonSchema,
top_level_id: Optional[str],
path: str,
seen_ids: Dict[str, str],
source_info: YamlSourceInfoMap,
):
"""Makes relative `$id` and `$ref` members absolute.
Also collects all ids that are seen in order to warn about unresolved
references.
:param schema: JSON schema, modified in place.
:param top_level_id: Top-level id to use for resolving relative ids.
:param path: Path to the file containing `schema`.
:param seen_ids: Dictionary mapping seen ids to paths.
:param source_info: Source info map to update.
"""
def _fix_ids(sub_schema):
for prop in ("$id", "$ref"):
if prop in sub_schema:
value = sub_schema[prop]
normalized = _normalize_jsonschema_id(value, top_level_id)
info = source_info.get(id(value))
if info is not None:
source_info[id(normalized)] = info
seen_ids.setdefault(normalized, path)
sub_schema[prop] = normalized
for sub_schema, pointer in _traverse_sub_schemas(schema):
_fix_ids(sub_schema)
def _get_json_schema_node_id(fully_qualified_name: str) -> str:
"""Returns the reference id (i.e. HTML fragment id) for a schema."""
return "json-%s" % (fully_qualified_name,)
def _schema_to_xref(schema_id: str) -> sphinx.addnodes.pending_xref:
"""Creates a pending_xref node that references a json schema.
The result is similar to that of the json:schema role but just a bare
pending_xref is constructed, without a code element.
:param schema_id: Schema id.
:returns: The pending_xref node.
"""
return sphinx.addnodes.pending_xref(
"",
docutils.nodes.Text(schema_id),
refdomain="json",
reftype="schema",
reftarget=schema_id,
)
def _json_literal(self, j: Any) -> docutils.nodes.Node:
return docutils.nodes.literal(
text=json.dumps(j),
classes=["code", "json"],
language="json",
)
class JsonSchemaDirective(sphinx.directives.ObjectDescription):
"""json:schema directive."""
required_arguments = 1
has_content = False
objtype = "schema"
option_spec = {
"fully_qualified_name": str,
"title": str,
"toc_title": str,
"exclude_from_toc": docutils.parsers.rst.directives.flag,
"nested": docutils.parsers.rst.directives.flag,
"noindex": docutils.parsers.rst.directives.flag,
}
_rendered_title: Optional[docutils.nodes.inline]
def _get_schema_entry(self) -> JsonSchemaMapEntry:
schema_data: LoadedSchemaData = getattr(self.env, "json_schema_data")
return schema_data.id_map[self.arguments[0]]
def _get_schema(self):
return self._get_schema_entry().schema
def _inline_text(self, text: str) -> List[docutils.nodes.Node]:
nodes, messages = self.state.inline_text(text, self.lineno)
return nodes + cast(List[docutils.nodes.Node], messages)
def _json_sig_type(self, name: str):
return sphinx.addnodes.desc_type(name, name)
def _get_type_description_line_ref(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
return [
sphinx.addnodes.desc_type("", "", _schema_to_xref(schema_node.get("$ref")))
]
def _get_type_description_line_oneof(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
result: List[docutils.nodes.Node] = []
for x in schema_node.get("oneOf"):
if result:
result.append(sphinx.addnodes.desc_sig_punctuation("", " | "))
part = self._get_type_description_line(x)
if part is None:
return None
result += part
return result
def _get_type_description_line_const(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
return [_json_literal(self.state, schema_node["const"])]
def _get_type_description_line_enum(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
result: List[docutils.nodes.Node] = []
for x in schema_node.get("enum"):
if result:
result.append(sphinx.addnodes.desc_sig_punctuation("", " | "))
result.append(_json_literal(self.state, x))
return result
def _get_type_description_line_number(
self, schema_node: JsonSchema, t: str
) -> Optional[List[docutils.nodes.Node]]:
explicit_lower = True
if schema_node.get("minimum") is not None:
lower_punct = "["
lower_node = _json_literal(self.state, schema_node.get("minimum"))
elif schema_node.get("exclusiveMinimum") is not None:
lower_punct = "("
lower_node = _json_literal(self.state, schema_node.get("exclusiveMinimum"))
else:
lower_punct = "("
lower_node = sphinx.addnodes.desc_sig_operator("", "-∞")
explicit_lower = False
explicit_upper = True
if schema_node.get("maximum") is not None:
upper_punct = "]"
upper_node = _json_literal(self.state, schema_node.get("maximum"))
elif schema_node.get("exclusiveMaximum") is not None:
upper_punct = ")"
upper_node = _json_literal(self.state, schema_node.get("exclusiveMaximum"))
else:
upper_punct = ")"
upper_node = sphinx.addnodes.desc_sig_operator("", "+∞")
explicit_upper = False
result = [self._json_sig_type(t)]
if explicit_lower or explicit_upper:
result.append(
docutils.nodes.subscript(
"",
"",
sphinx.addnodes.desc_sig_punctuation("", lower_punct),
lower_node,
sphinx.addnodes.desc_sig_punctuation("", ", "),
upper_node,
sphinx.addnodes.desc_sig_punctuation("", upper_punct),
)
)
return result
def _get_type_description_line_boolean(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
return [self._json_sig_type("boolean")]
def _get_type_description_line_string(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
result = [self._json_sig_type("string")]
subscript_parts: List[docutils.nodes.Node] = []
if (
schema_node.get("minLength") is not None
or schema_node.get("maxLength") is not None
):
subscript_parts.append(sphinx.addnodes.desc_sig_punctuation("", "["))
min_length = schema_node.get("minLength")
if min_length:
subscript_parts.append(_json_literal(self.state, min_length))
subscript_parts.append(sphinx.addnodes.desc_sig_punctuation("", ".."))
max_length = schema_node.get("maxLength")
if max_length:
subscript_parts.append(_json_literal(self.state, max_length))
subscript_parts.append(sphinx.addnodes.desc_sig_punctuation("", "]"))
result.append(docutils.nodes.subscript("", "", *subscript_parts))
return result
def _get_type_description_line_array(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
items = schema_node.get("items")
prefix = [self._json_sig_type("array")]
if "minItems" in schema_node or "maxItems" in schema_node:
prefix.append(sphinx.addnodes.desc_sig_punctuation("", "["))
if schema_node.get("minItems") == schema_node.get("maxItems"):
prefix.append(_json_literal(self.state, schema_node["minItems"]))
else:
if schema_node["minItems"]:
prefix.append(_json_literal(self.state, schema_node["minItems"]))
prefix.append(sphinx.addnodes.desc_sig_punctuation("", ".."))
if schema_node["maxItems"]:
prefix.append(_json_literal(self.state, schema_node["maxItems"]))
prefix.append(sphinx.addnodes.desc_sig_punctuation("", "]"))
if "items" in schema_node and isinstance(items, dict):
items_desc = self._get_type_description_line(items)
if items_desc is None:
return None
return prefix + [docutils.nodes.emphasis("", " of ")] + items_desc
if "items" in schema_node and isinstance(items, list):
result: List[docutils.nodes.Node] = []
result.append(sphinx.addnodes.desc_sig_punctuation("", "["))
for i, item in enumerate(items):
if i != 0:
result.append(sphinx.addnodes.desc_sig_punctuation("", ","))
result.append(docutils.nodes.Text(" "))
item_desc = self._get_type_description_line(item)
if item_desc is None:
return prefix
result.extend(item_desc)
result.append(sphinx.addnodes.desc_sig_punctuation("", "]"))
return result
return prefix
def _get_type_description_line_null(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
return [_json_literal(self.state, None)]
def _get_type_description_line_object(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
return [self._json_sig_type("object")]
def _get_type_description_line(
self, schema_node: JsonSchema
) -> Optional[List[docutils.nodes.Node]]:
"""Renders a short type description for use in the signature."""
if "$ref" in schema_node:
return self._get_type_description_line_ref(schema_node)
if "oneOf" in schema_node:
return self._get_type_description_line_oneof(schema_node)
if "const" in schema_node:
return self._get_type_description_line_const(schema_node)
if "enum" in schema_node:
return self._get_type_description_line_enum(schema_node)
t = schema_node.get("type")
if "allOf" in schema_node and t is None:
t = "object"
if t in ("integer", "number"):
return self._get_type_description_line_number(schema_node, t)
if t == "boolean":
return self._get_type_description_line_boolean(schema_node)
if t == "string":
return self._get_type_description_line_string(schema_node)
if t == "array":
return self._get_type_description_line_array(schema_node)
if t == "null":
return self._get_type_description_line_null(schema_node)
if t == "object":
return self._get_type_description_line_object(schema_node)
return None
def _collect_object_properties(
self,
schema_node: JsonSchema,
properties: Dict[str, JsonSchema],
required: Set[str],
) -> None:
"""Collects the object properties for a schema.
:param schema_node: JSON schema to process.
:param properties: Dict to be filled with members.
:param required: Set to which required members are added.
"""
schema_data: LoadedSchemaData = getattr(self.env, "json_schema_data")
if "$ref" in schema_node:
schema_node = schema_data.id_map[schema_node["$ref"]].schema
if schema_node.get("type") == "object":
properties.update(schema_node.get("properties", {}))
required.update(schema_node.get("required", []))
elif _is_object_array_with_properties(schema_node):
self._collect_object_properties(schema_node["items"], properties, required)
else:
for sub_node in schema_node.get("allOf", []):
self._collect_object_properties(sub_node, properties, required)
def _add_sub_schema(
self, entry: JsonSchemaMapEntry, **kwargs: Union[str, bool, None]
) -> List[docutils.nodes.Node]:
"""Renders a nested schema.
:param entry: Entry for the nested schema.
:param kwargs: Options for the json:schema directive.
:returns: The rendered result as a list of docutils nodes.
"""
return sphinx_utils.parse_rst(
self.state,
sphinx_utils.format_directive("json:schema", entry.id, options=kwargs),
*self.get_source_info(),
)
def _make_field(
self, label: str
) -> Tuple[docutils.nodes.field_list, docutils.nodes.field_body]:
field_list = docutils.nodes.field_list()
field = docutils.nodes.field()
field_list += field
field_name = docutils.nodes.field_name(label, label)
field += field_name
if not self._noindex and self._objdesc_options["include_fields_in_toc"]:
field_name["ids"].append(
docutils.nodes.make_id(label) + "-" + cast(str, self._node_id)
)
field_name["toc_title"] = label
body = docutils.nodes.field_body(classes=["noindent"])
field += body
return field_list, body
def _render_oneofs(self) -> List[docutils.nodes.Node]:
"""Renders a long-form list of oneof sub-schemas.
:returns: The rendered result as a list of docutils nodes.
"""
schema_data: LoadedSchemaData = getattr(self.env, "json_schema_data")
field_list, body = self._make_field("One of")
one_ofs = self._schema_entry.schema["oneOf"]
# If all oneof options are constant strings, generate fully-qualified
# ids.
generate_oneof_ids = all(isinstance(x.get("const"), str) for x in one_ofs)
for x in one_ofs:
fully_qualified_name = None
title = None
if generate_oneof_ids:
title = x["const"]
fully_qualified_name = "%s.%s" % (self._fully_qualified_name, title)
body.extend(
self._add_sub_schema(
schema_data.identity_map[id(x)],
nested=True,
fully_qualified_name=fully_qualified_name,
exclude_from_toc=self._exclude_from_toc or not generate_oneof_ids,
noindex=self._noindex,
toc_title=title,
)
)
return [field_list]
def _get_source_info_from_schema_string(
self, source_string: str
) -> Tuple[str, int]:
"""Obtains the source information for a schema string.
If no source information is found, just returns the path of the current
schema file without a valid line number.
:param source_string: String literal obtained from a JSON schema.
:returns: A tuple (path, line) specifying the source information.
"""
schema_data: LoadedSchemaData = getattr(self.env, "json_schema_data")
source_info = schema_data.source_info_map.get(id(source_string))
if source_info is None:
source_info = (self._schema_entry.path, -1)
return source_info
def _parse_rst_from_schema_string(
self, source_string: str
) -> List[docutils.nodes.Node]:
"""Renders RST markup obtained from a schema.
:param source_string: String literal obtained from a JSON schema.
:returns: The rendered result as a list of docutils nodes.
"""
rst_input = docutils.statemachine.StringList()
sphinx_utils.append_multiline_string_to_stringlist(
rst_input,
".. highlight-push::\n\n" + self.env.config.json_schema_rst_prolog + "\n\n",
"<json_schema_rst_prolog>",
-2,
)
sphinx_utils.append_multiline_string_to_stringlist(
rst_input,
source_string,
*self._get_source_info_from_schema_string(source_string),
)
sphinx_utils.append_multiline_string_to_stringlist(
rst_input,
"\n\n"
+ self.env.config.json_schema_rst_epilog
+ "\n\n.. highlight-pop::\n\n",
"<json_schema_rst_prolog>",
-2,
)
with apigen_utils.save_rst_defaults(self.env):
return sphinx_utils.parse_rst(
self.state,
rst_input,
*self._get_source_info_from_schema_string(source_string),
)
def _render_body(self) -> List[docutils.nodes.Node]:
"""Renders the body of the schema."""
schema_data: LoadedSchemaData = getattr(self.env, "json_schema_data")
schema_node = self._schema_entry.schema
result: List[docutils.nodes.Node] = []
if self._rendered_title is not None:
p = self._rendered_title
p += docutils.nodes.Text(" ")
result.append(p)
if "description" in schema_node:
result += self._parse_rst_from_schema_string(schema_node.get("description"))
def _render_related_type_list(related: Optional[List[str]], label: str) -> None:
if not related:
return
field_list, body = self._make_field(label)
result.append(field_list)
bullet_list = docutils.nodes.bullet_list()
body += bullet_list
for schema_id in related:
related_schema = schema_data.id_map[schema_id].schema
list_item = docutils.nodes.list_item()
bullet_list += list_item
p = docutils.nodes.paragraph()
list_item += p
p += self._inline_text(f":json:schema:`{schema_id}`")
related_title = related_schema.get("title")
if related_title:
p += self._inline_text(f" — {related_title}")
_render_related_type_list(
schema_data.supertype_map.get(self._schema_entry.id), "Extends"
)
subtypes = schema_data.subtype_map.get(self._schema_entry.id)
if subtypes:
subtypes = sorted(subtypes)
_render_related_type_list(subtypes, "Subtypes")
if "oneOf" in schema_node and any(
("title" in x or "description" in x) for x in schema_node["oneOf"]
):
result.extend(self._render_oneofs())
if _is_object_or_object_array_with_properties(schema_node):
properties: Dict[str, JsonSchema] = {}
required_properties: Set[str] = set()
self._collect_object_properties(
schema_node, properties, required_properties
)
for required in [True, False]:
if not any(
(member_name in required_properties) == required
for member_name in properties
):
continue
heading = "%s members" % ("Required" if required else "Optional")
field_list, body = self._make_field(heading)
result.append(field_list)
for member_name, member_schema in properties.items():
if (member_name in required_properties) != required:
continue
body.extend(
self._add_sub_schema(
schema_data.identity_map[id(member_schema)],
title=member_name,
fully_qualified_name="%s.%s"
% (self._fully_qualified_name, member_name),
nested=True,
exclude_from_toc=self._exclude_from_toc,
noindex=self._noindex,
)
)
def add_example(value, caption, admonition_class="example"):
nonlocal result
result += sphinx_utils.parse_rst(
self.state,
sphinx_utils.format_directive(
"admonition",
caption,
options={"class": admonition_class},
content=sphinx_utils.format_directive(
"code-block",
"json",
content=json_pprint.pformat(value, indent=2),
),
),
*self._get_source_info_from_schema_string(value),
)
if self._long_default_value:
add_example(schema_node["default"], "Default", "note")
if "examples" in schema_node:
for example in schema_node["examples"]:
add_example(example, "Example")
return result
def before_content(self):
# Set ref_context information which will be used to resolve cross references
# in the body.
self.env.ref_context["json:schema"] = self._fully_qualified_name
self.env.ref_context.setdefault("json:schemas", []).append( # type: ignore
self._fully_qualified_name
)
def after_content(self):
# Clear the ref_context information set by `.before_context`.
schemas = self.env.ref_context["json:schemas"]
schemas.pop()
self.env.ref_context["json:schema"] = schemas[-1] if schemas else None
def transform_content(self, contentnode: sphinx.addnodes.desc_content) -> None:
contentnode += self._render_body()
def handle_signature(
self, sig: str, signode: sphinx.addnodes.desc_signature
) -> Any:
# Renders the header for the JSON schema.
schema_entry = self._schema_entry
if not self._nested:
signode += sphinx.addnodes.desc_annotation("json ", "json ")
type_line = self._type_line
title = self._title
if title is not None:
signode += sphinx.addnodes.desc_name(title, title)
if type_line:
signode += sphinx.addnodes.desc_sig_punctuation("", " : ")
signode += type_line
if self._short_default_value:
signode += sphinx.addnodes.desc_sig_punctuation("", " = ")
signode += docutils.nodes.literal(
text=self._short_default_value,
classes=["code", "json"],
language="json",
)
if not self._exclude_from_toc and self._toc_title:
signode["toc_title"] = self._toc_title
return schema_entry.id
def add_target_and_index(
self, name: Any, sig: str, signode: sphinx.addnodes.desc_signature
) -> None:
del name
if self._noindex:
return
signode["ids"].append(self._node_id)
def run(self) -> List[docutils.nodes.Node]:
schema_data: LoadedSchemaData = self.env.json_schema_data # type: ignore
schema_id = self.arguments[0]
schema_entry = schema_data.id_map.get(schema_id)
if schema_entry is None:
logger.error(
"Undefined JSON schema: %r", schema_id, location=self.get_source_info()
)
return []
self._schema_entry = schema_entry
self._fully_qualified_name = self.options.get("fully_qualified_name")
self._noindex = "noindex" in self.options
self._exclude_from_toc = "exclude_from_toc" in self.options
self._nested = "nested" in self.options
self._objtype = "schema" if not self._nested else "subschema"
self._objdesc_options = (
object_description_options.get_object_description_options(
self.env, "json", self._objtype
)
)
if self._fully_qualified_name:
schema_data.id_map.setdefault(
self._fully_qualified_name, self._schema_entry
)
else:
self._fully_qualified_name = self._schema_entry.id
if "#/" in self._fully_qualified_name:
self._noindex = True
if self._noindex:
self._exclude_from_toc = True
self._node_id = None
if not self._noindex:
self._node_id = _get_json_schema_node_id(self._fully_qualified_name)
schema_node = self._schema_entry.schema
type_line = self._get_type_description_line(schema_node)
# Determine how to display the default value. If it is short enough, it is
# displayed inline after the type. Otherwise, it is displayed in a separate
# block after the description.
self._long_default_value = None
self._short_default_value = None
has_default_value = "default" in schema_node
if has_default_value:
formatted_default = json_pprint.pformat(
schema_node["default"], indent=2
).strip()
if "\n" not in formatted_default and len(formatted_default) < 40:
self._short_default_value = formatted_default
has_default_value = False
else:
self._long_default_value = formatted_default
self._type_line = type_line
if "title" in self.options:
self._title = self.options["title"]
elif not self._nested:
self._title = self._fully_qualified_name
else:
self._title = None
self._toc_title = self.options.get("toc_title") or self._title
schema = self._schema_entry.schema
if "title" in schema:
self._rendered_title = docutils.nodes.inline()