-
-
Notifications
You must be signed in to change notification settings - Fork 19.5k
/
make_rst.py
executable file
·2633 lines (2098 loc) · 103 KB
/
make_rst.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
#!/usr/bin/env python3
# This script makes RST files from the XML class reference for use with the online docs.
import argparse
import os
import re
import sys
import xml.etree.ElementTree as ET
from collections import OrderedDict
from typing import Any, Dict, List, Optional, TextIO, Tuple, Union
# Import hardcoded version information from version.py
root_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../")
sys.path.append(root_directory) # Include the root directory
import version # noqa: E402
# $DOCS_URL/path/to/page.html(#fragment-tag)
GODOT_DOCS_PATTERN = re.compile(r"^\$DOCS_URL/(.*)\.html(#.*)?$")
# Based on reStructuredText inline markup recognition rules
# https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
MARKUP_ALLOWED_PRECEDENT = " -:/'\"<([{"
MARKUP_ALLOWED_SUBSEQUENT = " -.,:;!?\\/'\")]}>"
# Used to translate section headings and other hardcoded strings when required with
# the --lang argument. The BASE_STRINGS list should be synced with what we actually
# write in this script (check `translate()` uses), and also hardcoded in
# `scripts/extract_classes.py` (godotengine/godot-editor-l10n repo) to include them in the source POT file.
BASE_STRINGS = [
"All classes",
"Globals",
"Nodes",
"Resources",
"Editor-only",
"Other objects",
"Variant types",
"Description",
"Tutorials",
"Properties",
"Constructors",
"Methods",
"Operators",
"Theme Properties",
"Signals",
"Enumerations",
"Constants",
"Annotations",
"Property Descriptions",
"Constructor Descriptions",
"Method Descriptions",
"Operator Descriptions",
"Theme Property Descriptions",
"Inherits:",
"Inherited By:",
"(overrides %s)",
"Default",
"Setter",
"value",
"Getter",
"This method should typically be overridden by the user to have any effect.",
"This method has no side effects. It doesn't modify any of the instance's member variables.",
"This method accepts any number of arguments after the ones described here.",
"This method is used to construct a type.",
"This method doesn't need an instance to be called, so it can be called directly using the class name.",
"This method describes a valid operator to use with this type as left-hand operand.",
"This value is an integer composed as a bitmask of the following flags.",
"No return value.",
"There is currently no description for this class. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There is currently no description for this signal. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There is currently no description for this enum. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There is currently no description for this constant. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There is currently no description for this annotation. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There is currently no description for this property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There is currently no description for this constructor. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There is currently no description for this method. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There is currently no description for this operator. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There is currently no description for this theme property. Please help us by :ref:`contributing one <doc_updating_the_class_reference>`!",
"There are notable differences when using this API with C#. See :ref:`doc_c_sharp_differences` for more information.",
"Deprecated:",
"Experimental:",
"This signal may be changed or removed in future versions.",
"This constant may be changed or removed in future versions.",
"This property may be changed or removed in future versions.",
"This constructor may be changed or removed in future versions.",
"This method may be changed or removed in future versions.",
"This operator may be changed or removed in future versions.",
"This theme property may be changed or removed in future versions.",
"[b]Note:[/b] The returned array is [i]copied[/i] and any changes to it will not update the original property value. See [%s] for more details.",
]
strings_l10n: Dict[str, str] = {}
STYLES: Dict[str, str] = {}
CLASS_GROUPS: Dict[str, str] = {
"global": "Globals",
"node": "Nodes",
"resource": "Resources",
"object": "Other objects",
"editor": "Editor-only",
"variant": "Variant types",
}
CLASS_GROUPS_BASE: Dict[str, str] = {
"node": "Node",
"resource": "Resource",
"object": "Object",
"variant": "Variant",
}
# Sync with editor\register_editor_types.cpp
EDITOR_CLASSES: List[str] = [
"FileSystemDock",
"ScriptCreateDialog",
"ScriptEditor",
"ScriptEditorBase",
]
# Sync with the types mentioned in https://docs.godotengine.org/en/stable/tutorials/scripting/c_sharp/c_sharp_differences.html
CLASSES_WITH_CSHARP_DIFFERENCES: List[str] = [
"@GlobalScope",
"String",
"StringName",
"NodePath",
"Signal",
"Callable",
"RID",
"Basis",
"Transform2D",
"Transform3D",
"Rect2",
"Rect2i",
"AABB",
"Quaternion",
"Projection",
"Color",
"Array",
"Dictionary",
"PackedByteArray",
"PackedColorArray",
"PackedFloat32Array",
"PackedFloat64Array",
"PackedInt32Array",
"PackedInt64Array",
"PackedStringArray",
"PackedVector2Array",
"PackedVector3Array",
"PackedVector4Array",
"Variant",
]
PACKED_ARRAY_TYPES: List[str] = [
"PackedByteArray",
"PackedColorArray",
"PackedFloat32Array",
"Packedfloat64Array",
"PackedInt32Array",
"PackedInt64Array",
"PackedStringArray",
"PackedVector2Array",
"PackedVector3Array",
"PackedVector4Array",
]
class State:
def __init__(self) -> None:
self.num_errors = 0
self.num_warnings = 0
self.classes: OrderedDict[str, ClassDef] = OrderedDict()
self.current_class: str = ""
# Additional content and structure checks and validators.
self.script_language_parity_check: ScriptLanguageParityCheck = ScriptLanguageParityCheck()
def parse_class(self, class_root: ET.Element, filepath: str) -> None:
class_name = class_root.attrib["name"]
self.current_class = class_name
class_def = ClassDef(class_name)
self.classes[class_name] = class_def
class_def.filepath = filepath
inherits = class_root.get("inherits")
if inherits is not None:
class_def.inherits = inherits
class_def.deprecated = class_root.get("deprecated")
class_def.experimental = class_root.get("experimental")
brief_desc = class_root.find("brief_description")
if brief_desc is not None and brief_desc.text:
class_def.brief_description = brief_desc.text
desc = class_root.find("description")
if desc is not None and desc.text:
class_def.description = desc.text
keywords = class_root.get("keywords")
if keywords is not None:
class_def.keywords = keywords
properties = class_root.find("members")
if properties is not None:
for property in properties:
assert property.tag == "member"
property_name = property.attrib["name"]
if property_name in class_def.properties:
print_error(f'{class_name}.xml: Duplicate property "{property_name}".', self)
continue
type_name = TypeName.from_element(property)
setter = property.get("setter") or None # Use or None so '' gets turned into None.
getter = property.get("getter") or None
default_value = property.get("default") or None
if default_value is not None:
default_value = f"``{default_value}``"
overrides = property.get("overrides") or None
property_def = PropertyDef(
property_name, type_name, setter, getter, property.text, default_value, overrides
)
property_def.deprecated = property.get("deprecated")
property_def.experimental = property.get("experimental")
class_def.properties[property_name] = property_def
constructors = class_root.find("constructors")
if constructors is not None:
for constructor in constructors:
assert constructor.tag == "constructor"
method_name = constructor.attrib["name"]
qualifiers = constructor.get("qualifiers")
return_element = constructor.find("return")
if return_element is not None:
return_type = TypeName.from_element(return_element)
else:
return_type = TypeName("void")
params = self.parse_params(constructor, "constructor")
desc_element = constructor.find("description")
method_desc = None
if desc_element is not None:
method_desc = desc_element.text
method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
method_def.definition_name = "constructor"
method_def.deprecated = constructor.get("deprecated")
method_def.experimental = constructor.get("experimental")
if method_name not in class_def.constructors:
class_def.constructors[method_name] = []
class_def.constructors[method_name].append(method_def)
methods = class_root.find("methods")
if methods is not None:
for method in methods:
assert method.tag == "method"
method_name = method.attrib["name"]
qualifiers = method.get("qualifiers")
return_element = method.find("return")
if return_element is not None:
return_type = TypeName.from_element(return_element)
else:
return_type = TypeName("void")
params = self.parse_params(method, "method")
desc_element = method.find("description")
method_desc = None
if desc_element is not None:
method_desc = desc_element.text
method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
method_def.deprecated = method.get("deprecated")
method_def.experimental = method.get("experimental")
if method_name not in class_def.methods:
class_def.methods[method_name] = []
class_def.methods[method_name].append(method_def)
operators = class_root.find("operators")
if operators is not None:
for operator in operators:
assert operator.tag == "operator"
method_name = operator.attrib["name"]
qualifiers = operator.get("qualifiers")
return_element = operator.find("return")
if return_element is not None:
return_type = TypeName.from_element(return_element)
else:
return_type = TypeName("void")
params = self.parse_params(operator, "operator")
desc_element = operator.find("description")
method_desc = None
if desc_element is not None:
method_desc = desc_element.text
method_def = MethodDef(method_name, return_type, params, method_desc, qualifiers)
method_def.definition_name = "operator"
method_def.deprecated = operator.get("deprecated")
method_def.experimental = operator.get("experimental")
if method_name not in class_def.operators:
class_def.operators[method_name] = []
class_def.operators[method_name].append(method_def)
constants = class_root.find("constants")
if constants is not None:
for constant in constants:
assert constant.tag == "constant"
constant_name = constant.attrib["name"]
value = constant.attrib["value"]
enum = constant.get("enum")
is_bitfield = constant.get("is_bitfield") == "true"
constant_def = ConstantDef(constant_name, value, constant.text, is_bitfield)
constant_def.deprecated = constant.get("deprecated")
constant_def.experimental = constant.get("experimental")
if enum is None:
if constant_name in class_def.constants:
print_error(f'{class_name}.xml: Duplicate constant "{constant_name}".', self)
continue
class_def.constants[constant_name] = constant_def
else:
if enum in class_def.enums:
enum_def = class_def.enums[enum]
else:
enum_def = EnumDef(enum, TypeName("int", enum), is_bitfield)
class_def.enums[enum] = enum_def
enum_def.values[constant_name] = constant_def
annotations = class_root.find("annotations")
if annotations is not None:
for annotation in annotations:
assert annotation.tag == "annotation"
annotation_name = annotation.attrib["name"]
qualifiers = annotation.get("qualifiers")
params = self.parse_params(annotation, "annotation")
desc_element = annotation.find("description")
annotation_desc = None
if desc_element is not None:
annotation_desc = desc_element.text
annotation_def = AnnotationDef(annotation_name, params, annotation_desc, qualifiers)
if annotation_name not in class_def.annotations:
class_def.annotations[annotation_name] = []
class_def.annotations[annotation_name].append(annotation_def)
signals = class_root.find("signals")
if signals is not None:
for signal in signals:
assert signal.tag == "signal"
signal_name = signal.attrib["name"]
if signal_name in class_def.signals:
print_error(f'{class_name}.xml: Duplicate signal "{signal_name}".', self)
continue
params = self.parse_params(signal, "signal")
desc_element = signal.find("description")
signal_desc = None
if desc_element is not None:
signal_desc = desc_element.text
signal_def = SignalDef(signal_name, params, signal_desc)
signal_def.deprecated = signal.get("deprecated")
signal_def.experimental = signal.get("experimental")
class_def.signals[signal_name] = signal_def
theme_items = class_root.find("theme_items")
if theme_items is not None:
for theme_item in theme_items:
assert theme_item.tag == "theme_item"
theme_item_name = theme_item.attrib["name"]
theme_item_data_name = theme_item.attrib["data_type"]
theme_item_id = "{}_{}".format(theme_item_data_name, theme_item_name)
if theme_item_id in class_def.theme_items:
print_error(
f'{class_name}.xml: Duplicate theme property "{theme_item_name}" of type "{theme_item_data_name}".',
self,
)
continue
default_value = theme_item.get("default") or None
if default_value is not None:
default_value = f"``{default_value}``"
theme_item_def = ThemeItemDef(
theme_item_name,
TypeName.from_element(theme_item),
theme_item_data_name,
theme_item.text,
default_value,
)
class_def.theme_items[theme_item_name] = theme_item_def
tutorials = class_root.find("tutorials")
if tutorials is not None:
for link in tutorials:
assert link.tag == "link"
if link.text is not None:
class_def.tutorials.append((link.text.strip(), link.get("title", "")))
self.current_class = ""
def parse_params(self, root: ET.Element, context: str) -> List["ParameterDef"]:
param_elements = root.findall("param")
params: Any = [None] * len(param_elements)
for param_index, param_element in enumerate(param_elements):
param_name = param_element.attrib["name"]
index = int(param_element.attrib["index"])
type_name = TypeName.from_element(param_element)
default = param_element.get("default")
if param_name.strip() == "" or param_name.startswith("_unnamed_arg"):
print_error(
f'{self.current_class}.xml: Empty argument name in {context} "{root.attrib["name"]}" at position {param_index}.',
self,
)
params[index] = ParameterDef(param_name, type_name, default)
cast: List[ParameterDef] = params
return cast
def sort_classes(self) -> None:
self.classes = OrderedDict(sorted(self.classes.items(), key=lambda t: t[0].lower()))
class TagState:
def __init__(self, raw: str, name: str, arguments: str, closing: bool) -> None:
self.raw = raw
self.name = name
self.arguments = arguments
self.closing = closing
class TypeName:
def __init__(self, type_name: str, enum: Optional[str] = None, is_bitfield: bool = False) -> None:
self.type_name = type_name
self.enum = enum
self.is_bitfield = is_bitfield
def to_rst(self, state: State) -> str:
if self.enum is not None:
return make_enum(self.enum, self.is_bitfield, state)
elif self.type_name == "void":
return "|void|"
else:
return make_type(self.type_name, state)
@classmethod
def from_element(cls, element: ET.Element) -> "TypeName":
return cls(element.attrib["type"], element.get("enum"), element.get("is_bitfield") == "true")
class DefinitionBase:
def __init__(
self,
definition_name: str,
name: str,
) -> None:
self.definition_name = definition_name
self.name = name
self.deprecated: Optional[str] = None
self.experimental: Optional[str] = None
class PropertyDef(DefinitionBase):
def __init__(
self,
name: str,
type_name: TypeName,
setter: Optional[str],
getter: Optional[str],
text: Optional[str],
default_value: Optional[str],
overrides: Optional[str],
) -> None:
super().__init__("property", name)
self.type_name = type_name
self.setter = setter
self.getter = getter
self.text = text
self.default_value = default_value
self.overrides = overrides
class ParameterDef(DefinitionBase):
def __init__(self, name: str, type_name: TypeName, default_value: Optional[str]) -> None:
super().__init__("parameter", name)
self.type_name = type_name
self.default_value = default_value
class SignalDef(DefinitionBase):
def __init__(self, name: str, parameters: List[ParameterDef], description: Optional[str]) -> None:
super().__init__("signal", name)
self.parameters = parameters
self.description = description
class AnnotationDef(DefinitionBase):
def __init__(
self,
name: str,
parameters: List[ParameterDef],
description: Optional[str],
qualifiers: Optional[str],
) -> None:
super().__init__("annotation", name)
self.parameters = parameters
self.description = description
self.qualifiers = qualifiers
class MethodDef(DefinitionBase):
def __init__(
self,
name: str,
return_type: TypeName,
parameters: List[ParameterDef],
description: Optional[str],
qualifiers: Optional[str],
) -> None:
super().__init__("method", name)
self.return_type = return_type
self.parameters = parameters
self.description = description
self.qualifiers = qualifiers
class ConstantDef(DefinitionBase):
def __init__(self, name: str, value: str, text: Optional[str], bitfield: bool) -> None:
super().__init__("constant", name)
self.value = value
self.text = text
self.is_bitfield = bitfield
class EnumDef(DefinitionBase):
def __init__(self, name: str, type_name: TypeName, bitfield: bool) -> None:
super().__init__("enum", name)
self.type_name = type_name
self.values: OrderedDict[str, ConstantDef] = OrderedDict()
self.is_bitfield = bitfield
class ThemeItemDef(DefinitionBase):
def __init__(
self, name: str, type_name: TypeName, data_name: str, text: Optional[str], default_value: Optional[str]
) -> None:
super().__init__("theme property", name)
self.type_name = type_name
self.data_name = data_name
self.text = text
self.default_value = default_value
class ClassDef(DefinitionBase):
def __init__(self, name: str) -> None:
super().__init__("class", name)
self.class_group = "variant"
self.editor_class = self._is_editor_class()
self.constants: OrderedDict[str, ConstantDef] = OrderedDict()
self.enums: OrderedDict[str, EnumDef] = OrderedDict()
self.properties: OrderedDict[str, PropertyDef] = OrderedDict()
self.constructors: OrderedDict[str, List[MethodDef]] = OrderedDict()
self.methods: OrderedDict[str, List[MethodDef]] = OrderedDict()
self.operators: OrderedDict[str, List[MethodDef]] = OrderedDict()
self.signals: OrderedDict[str, SignalDef] = OrderedDict()
self.annotations: OrderedDict[str, List[AnnotationDef]] = OrderedDict()
self.theme_items: OrderedDict[str, ThemeItemDef] = OrderedDict()
self.inherits: Optional[str] = None
self.brief_description: Optional[str] = None
self.description: Optional[str] = None
self.tutorials: List[Tuple[str, str]] = []
self.keywords: Optional[str] = None
# Used to match the class with XML source for output filtering purposes.
self.filepath: str = ""
def _is_editor_class(self) -> bool:
if self.name.startswith("Editor"):
return True
if self.name in EDITOR_CLASSES:
return True
return False
def update_class_group(self, state: State) -> None:
group_name = "variant"
if self.name.startswith("@"):
group_name = "global"
elif self.inherits:
inherits = self.inherits.strip()
while inherits in state.classes:
if inherits == "Node":
group_name = "node"
break
if inherits == "Resource":
group_name = "resource"
break
if inherits == "Object":
group_name = "object"
break
inode = state.classes[inherits].inherits
if inode:
inherits = inode.strip()
else:
break
self.class_group = group_name
# Checks if code samples have both GDScript and C# variations.
# For simplicity we assume that a GDScript example is always present, and ignore contexts
# which don't necessarily need C# examples.
class ScriptLanguageParityCheck:
def __init__(self) -> None:
self.hit_map: OrderedDict[str, List[Tuple[DefinitionBase, str]]] = OrderedDict()
self.hit_count = 0
def add_hit(self, class_name: str, context: DefinitionBase, error: str, state: State) -> None:
if class_name in ["@GDScript", "@GlobalScope"]:
return # We don't expect these contexts to have parity.
class_def = state.classes[class_name]
if class_def.class_group == "variant" and class_def.name != "Object":
return # Variant types are replaced with native types in C#, we don't expect parity.
self.hit_count += 1
if class_name not in self.hit_map:
self.hit_map[class_name] = []
self.hit_map[class_name].append((context, error))
# Entry point for the RST generator.
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("path", nargs="+", help="A path to an XML file or a directory containing XML files to parse.")
parser.add_argument("--filter", default="", help="The filepath pattern for XML files to filter.")
parser.add_argument("--lang", "-l", default="en", help="Language to use for section headings.")
parser.add_argument(
"--color",
action="store_true",
help="If passed, force colored output even if stdout is not a TTY (useful for continuous integration).",
)
group = parser.add_mutually_exclusive_group()
group.add_argument("--output", "-o", default=".", help="The directory to save output .rst files in.")
group.add_argument(
"--dry-run",
action="store_true",
help="If passed, no output will be generated and XML files are only checked for errors.",
)
parser.add_argument(
"--verbose",
action="store_true",
help="If passed, enables verbose printing.",
)
args = parser.parse_args()
should_color = bool(args.color or sys.stdout.isatty() or os.environ.get("CI"))
# Enable ANSI escape code support on Windows 10 and later (for colored console output).
# <https://github.com/python/cpython/issues/73245>
if should_color and sys.stdout.isatty() and sys.platform == "win32":
try:
from ctypes import WinError, byref, windll # type: ignore
from ctypes.wintypes import DWORD # type: ignore
stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11))
mode = DWORD(0)
if not windll.kernel32.GetConsoleMode(stdout_handle, byref(mode)):
raise WinError()
mode = DWORD(mode.value | 4)
if not windll.kernel32.SetConsoleMode(stdout_handle, mode):
raise WinError()
except Exception:
should_color = False
STYLES["red"] = "\x1b[91m" if should_color else ""
STYLES["green"] = "\x1b[92m" if should_color else ""
STYLES["yellow"] = "\x1b[93m" if should_color else ""
STYLES["bold"] = "\x1b[1m" if should_color else ""
STYLES["regular"] = "\x1b[22m" if should_color else ""
STYLES["reset"] = "\x1b[0m" if should_color else ""
# Retrieve heading translations for the given language.
if not args.dry_run and args.lang != "en":
lang_file = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "..", "translations", "{}.po".format(args.lang)
)
if os.path.exists(lang_file):
try:
import polib # type: ignore
except ImportError:
print("Base template strings localization requires `polib`.")
exit(1)
pofile = polib.pofile(lang_file)
for entry in pofile.translated_entries():
if entry.msgid in BASE_STRINGS:
strings_l10n[entry.msgid] = entry.msgstr
else:
print(f'No PO file at "{lang_file}" for language "{args.lang}".')
print("Checking for errors in the XML class reference...")
file_list: List[str] = []
for path in args.path:
# Cut off trailing slashes so os.path.basename doesn't choke.
if path.endswith("/") or path.endswith("\\"):
path = path[:-1]
if os.path.basename(path) in ["modules", "platform"]:
for subdir, dirs, _ in os.walk(path):
if "doc_classes" in dirs:
doc_dir = os.path.join(subdir, "doc_classes")
class_file_names = (f for f in os.listdir(doc_dir) if f.endswith(".xml"))
file_list += (os.path.join(doc_dir, f) for f in class_file_names)
elif os.path.isdir(path):
file_list += (os.path.join(path, f) for f in os.listdir(path) if f.endswith(".xml"))
elif os.path.isfile(path):
if not path.endswith(".xml"):
print(f'Got non-.xml file "{path}" in input, skipping.')
continue
file_list.append(path)
classes: Dict[str, Tuple[ET.Element, str]] = {}
state = State()
for cur_file in file_list:
try:
tree = ET.parse(cur_file)
except ET.ParseError as e:
print_error(f"{cur_file}: Parse error while reading the file: {e}", state)
continue
doc = tree.getroot()
name = doc.attrib["name"]
if name in classes:
print_error(f'{cur_file}: Duplicate class "{name}".', state)
continue
classes[name] = (doc, cur_file)
for name, data in classes.items():
try:
state.parse_class(data[0], data[1])
except Exception as e:
print_error(f"{name}.xml: Exception while parsing class: {e}", state)
state.sort_classes()
pattern = re.compile(args.filter)
# Create the output folder recursively if it doesn't already exist.
os.makedirs(args.output, exist_ok=True)
print("Generating the RST class reference...")
grouped_classes: Dict[str, List[str]] = {}
for class_name, class_def in state.classes.items():
if args.filter and not pattern.search(class_def.filepath):
continue
state.current_class = class_name
class_def.update_class_group(state)
make_rst_class(class_def, state, args.dry_run, args.output)
if class_def.class_group not in grouped_classes:
grouped_classes[class_def.class_group] = []
grouped_classes[class_def.class_group].append(class_name)
if class_def.editor_class:
if "editor" not in grouped_classes:
grouped_classes["editor"] = []
grouped_classes["editor"].append(class_name)
print("")
print("Generating the index file...")
make_rst_index(grouped_classes, args.dry_run, args.output)
print("")
# Print out checks.
if state.script_language_parity_check.hit_count > 0:
if not args.verbose:
print(
f'{STYLES["yellow"]}{state.script_language_parity_check.hit_count} code samples failed parity check. Use --verbose to get more information.{STYLES["reset"]}'
)
else:
print(
f'{STYLES["yellow"]}{state.script_language_parity_check.hit_count} code samples failed parity check:{STYLES["reset"]}'
)
for class_name in state.script_language_parity_check.hit_map.keys():
class_hits = state.script_language_parity_check.hit_map[class_name]
print(f'{STYLES["yellow"]}- {len(class_hits)} hits in class "{class_name}"{STYLES["reset"]}')
for context, error in class_hits:
print(f" - {error} in {format_context_name(context)}")
print("")
# Print out warnings and errors, or lack thereof, and exit with an appropriate code.
if state.num_warnings >= 2:
print(
f'{STYLES["yellow"]}{state.num_warnings} warnings were found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
)
elif state.num_warnings == 1:
print(
f'{STYLES["yellow"]}1 warning was found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
)
if state.num_errors >= 2:
print(
f'{STYLES["red"]}{state.num_errors} errors were found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
)
elif state.num_errors == 1:
print(
f'{STYLES["red"]}1 error was found in the class reference XML. Please check the messages above.{STYLES["reset"]}'
)
if state.num_warnings == 0 and state.num_errors == 0:
print(f'{STYLES["green"]}No warnings or errors found in the class reference XML.{STYLES["reset"]}')
if not args.dry_run:
print(f"Wrote reStructuredText files for each class to: {args.output}")
else:
exit(1)
# Common helpers.
def print_error(error: str, state: State) -> None:
print(f'{STYLES["red"]}{STYLES["bold"]}ERROR:{STYLES["regular"]} {error}{STYLES["reset"]}')
state.num_errors += 1
def print_warning(warning: str, state: State) -> None:
print(f'{STYLES["yellow"]}{STYLES["bold"]}WARNING:{STYLES["regular"]} {warning}{STYLES["reset"]}')
state.num_warnings += 1
def translate(string: str) -> str:
"""Translate a string based on translations sourced from `doc/translations/*.po`
for a language if defined via the --lang command line argument.
Returns the original string if no translation exists.
"""
return strings_l10n.get(string, string)
def get_git_branch() -> str:
if hasattr(version, "docs") and version.docs != "latest":
return version.docs
return "master"
# Generator methods.
def make_rst_class(class_def: ClassDef, state: State, dry_run: bool, output_dir: str) -> None:
class_name = class_def.name
with open(
os.devnull if dry_run else os.path.join(output_dir, f"class_{class_name.lower()}.rst"),
"w",
encoding="utf-8",
newline="\n",
) as f:
# Remove the "Edit on Github" button from the online docs page.
f.write(":github_url: hide\n\n")
# Add keywords metadata.
if class_def.keywords is not None and class_def.keywords != "":
f.write(f".. meta::\n\t:keywords: {class_def.keywords}\n\n")
# Warn contributors not to edit this file directly.
# Also provide links to the source files for reference.
git_branch = get_git_branch()
source_xml_path = os.path.relpath(class_def.filepath, root_directory).replace("\\", "/")
source_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/{source_xml_path}"
generator_github_url = f"https://github.com/godotengine/godot/tree/{git_branch}/doc/tools/make_rst.py"
f.write(".. DO NOT EDIT THIS FILE!!!\n")
f.write(".. Generated automatically from Godot engine sources.\n")
f.write(f".. Generator: {generator_github_url}.\n")
f.write(f".. XML source: {source_github_url}.\n\n")
# Document reference id and header.
f.write(f".. _class_{class_name}:\n\n")
f.write(make_heading(class_name, "=", False))
f.write(make_deprecated_experimental(class_def, state))
### INHERITANCE TREE ###
# Ascendants
if class_def.inherits:
inherits = class_def.inherits.strip()
f.write(f'**{translate("Inherits:")}** ')
first = True
while inherits in state.classes:
if not first:
f.write(" **<** ")
else:
first = False
f.write(make_type(inherits, state))
inode = state.classes[inherits].inherits
if inode:
inherits = inode.strip()
else:
break
f.write("\n\n")
# Descendants
inherited: List[str] = []
for c in state.classes.values():
if c.inherits and c.inherits.strip() == class_name:
inherited.append(c.name)
if len(inherited):
f.write(f'**{translate("Inherited By:")}** ')
for i, child in enumerate(inherited):
if i > 0:
f.write(", ")
f.write(make_type(child, state))
f.write("\n\n")
### INTRODUCTION ###
has_description = False
# Brief description
if class_def.brief_description is not None and class_def.brief_description.strip() != "":
has_description = True
f.write(f"{format_text_block(class_def.brief_description.strip(), class_def, state)}\n\n")
# Class description
if class_def.description is not None and class_def.description.strip() != "":
has_description = True
f.write(".. rst-class:: classref-introduction-group\n\n")
f.write(make_heading("Description", "-"))
f.write(f"{format_text_block(class_def.description.strip(), class_def, state)}\n\n")
if not has_description:
f.write(".. container:: contribute\n\n\t")