-
Notifications
You must be signed in to change notification settings - Fork 2
/
scrape-docs.py
165 lines (134 loc) · 5.19 KB
/
scrape-docs.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
import os
import json
import sys
from typing import Iterator, Sequence, TypedDict
class RawType(TypedDict):
title: str
description: str
raw_properties: list[dict]
class JsonschemaType(TypedDict):
title: str
description: str
# enable markdown in monaco
# https://github.com/microsoft/monaco-editor/issues/1816
markdownDescription: str
properties: dict[str, dict]
additionalProperties: bool
KNOWN_BAD_RESOLVES = ("FakeDnsObject", "metricsObject", "TransportObject", "noiseObject", "DnsServerObject")
USED_OBJECTS = set()
def parse(stdin: Iterator[str]) -> Iterator[JsonschemaType]:
current_obj: RawType | None = None
for line in stdin:
if line.startswith("##"):
if current_obj:
description = current_obj['description']
yield {
"title": current_obj['title'],
"description": description,
"markdownDescription": description,
"properties": {
x['name']: x
for x in current_obj['raw_properties']
},
# turn off additionalProperties so that monaco will warn on
# unknown properties. xray does allow for unknown
# properties but most likely, setting them is a mistake. we
# only do this if we have any props ourselves, otherwise
# there is no point.
"additionalProperties": not current_obj["raw_properties"]
}
current_obj = {
"title": line.split(" ", 1)[-1].strip(),
"description": "",
"raw_properties": []
}
elif line.startswith("> ") and ":" in line and current_obj:
name, ty = line[2:].split(":", 1)
if name == "Tony":
continue
name = name.strip(" `")
current_obj['raw_properties'].append({
"name": name,
"description": "",
"markdownDescription": "",
**parse_type(ty),
})
elif current_obj:
if current_obj['raw_properties']:
current_obj['raw_properties'][-1]['description'] += line
current_obj['raw_properties'][-1]['markdownDescription'] += line
else:
current_obj['description'] += line
def parse_type(input: str) -> dict:
input = input \
.replace('<Badge text="WIP" type="warning"/>', '') \
.replace('<Badge text="BETA" type="warning"/>', '') \
.strip()
if not input:
return {}
if input.startswith("\\[") and input.endswith("\\]"):
return {
"type": "array",
"items": parse_type(input[2:-2])
}
if input.startswith("[") and input.endswith("]"):
return {
"type": "array",
"items": parse_type(input[1:-1])
}
if (input.startswith("[") and input.endswith(")")) or input.endswith("Object"):
name = input.split("]")[0].strip("[]")
if name in KNOWN_BAD_RESOLVES:
# If there is a dangling reference, monaco editor will turn off
# all inline validation markers, as the root object has a warning.
# So we catch all dangling references here and replace them with
# object.
return {"type": "object"}
else:
USED_OBJECTS.add(name)
return {
"$ref": f"#/definitions/{name}"
}
if input in ("true", "false", "true | false", "bool"):
return {"type": "boolean"}
if " | " in input:
return {"anyOf": [parse_type(x) for x in input.split(" | ")]}
if input in ("address", "address_port", "CIDR"):
return {"type": "string"}
if input in ("string", "number"):
return {"type": input}
if input == "int":
return {"type": "integer"}
if input.startswith("map"):
return {"type": "object"}
if input.startswith('"') and input.endswith('"'):
return {"const": input[1:-1]}
if input.startswith("a list of"):
return {}
if input == "string array":
return {"type": "array", "items": {"type": "string"}}
if input.startswith("string, any of"):
return {"type": "string"}
raise Exception(input)
def main():
definitions = {}
for definition in parse(sys.stdin):
key = definition['title']
if key in definitions:
# Handle multiple instances of
# InboundConfigurationObject/OutboundConfigurationObject
if "anyOf" not in definitions[key]:
definitions[key] = {"anyOf": [definitions[key]]}
definitions[key]['anyOf'].append(definition)
else:
definitions[key] = definition
for name in USED_OBJECTS:
assert name in definitions, f"Cannot resolve {name}, add to KNOWN_BAD_RESOLVES?"
schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "#/definitions/Basic Configuration Modules",
"definitions": definitions
}
print(json.dumps(schema, indent=2))
if __name__ == "__main__":
main()