-
Notifications
You must be signed in to change notification settings - Fork 26
/
extractor.py
executable file
·209 lines (143 loc) · 4.9 KB
/
extractor.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
#!/usr/bin/env python3
import json
import os
import requests
import pyperclip
DEBUG = True
REPLACE = True
WEB = True
URL = "https://raw.githubusercontent.com/rockneurotiko/telegram_api_json/master/exports/tg_api.json"
# URL = "https://raw.githack.com/rockneurotiko/telegram_api_json/master/exports/tg_api_pretty.json"
def debug(t):
if DEBUG:
print("\n# " + t)
def maybe_atom(name, is_return):
return ":{}".format(name) if not is_return else name
def parse_type_name(name, is_return):
if name == "int":
return ":integer" # maybe_atom("integer", is_return)
if name == "str":
return ":string" # return "String" if is_return else ":string"
if name == "bool":
return ":boolean" # maybe_atom("boolean", is_return)
if name == "float":
return ":float" # maybe_atom("float", is_return)
if name == "file":
return ":file" # maybe_atom("file", is_return)
if name == "True" or name == "true":
return "true"
if name == "String":
return "String"
if name[0].isupper():
return "ExGram.Model.{}".format(name) if is_return else name
if name[0] == "array":
ts = [parse_type_name(x, is_return) for x in name[1]]
t = ts[0] if len(ts) == 1 else "[{}]".format(", ".join(ts))
return "{{:array, {}}}".format(t)
return ":any"
def generate_type(typ, is_return):
if len(typ) == 0:
return [":any"]
if len(typ) == 1:
return [parse_type_name(typ[0], is_return)]
if typ[0] == "array":
array_type = parse_type_name(typ[1][0], is_return)
return ["[{}]".format(array_type)]
return [parse_type_name(x, is_return) for x in typ]
def generate_param(param, model):
param_s = "{{{}, {}{}}}"
name = ":{}".format(param['name']) if model else param['name']
debug("Extracting type: " + name)
ts = generate_type(param['type'], False)
t = "[{}]".format(', '.join(ts))
debug(str(t))
extra = "" if not param['optional'] else ", :optional"
return param_s.format(name, t, extra)
def clean_description(description):
return description.replace("\n", " ")
def generate_model(model):
model_s = "model({}, [{}], \"{}\")"
name = model['name']
description = model['description']
debug("Generating model: " + name)
params = [generate_param(param, True) for param in model['params']]
return model_s.format(name, ", ".join(params), clean_description(description))
def generate_method(method):
method_s = """method({}, "{}", [{}], {}, "{}")"""
name = method['name']
description = method['description']
debug("Generating method: " + name)
typ = ":get" if method['type'] == 'get' else ':post'
args = [generate_param(param, False) for param in method['params']]
returned = generate_type(method['return'], True)[0]
return method_s.format(typ, name, ", ".join(args), returned, clean_description(description))
def generate_generic(model):
name = model['name']
types_s = ", ".join(model['subtypes'])
types_t = " | ".join(["{}.t()".format(x) for x in model['subtypes']])
return """defmodule {} do
@moduledoc \"\"\"
{} model. Valid subtypes: {}
\"\"\"
@type t :: {}
defstruct []
def decode_as, do: %{}
def subtypes do
[{}]
end
end""".format(name, name, types_s, types_t, "{}", types_s)
def definition_from_web():
return requests.get(URL).json()
def definition_from_file():
with open("tg_api.json") as f:
return json.load(f)
def get_definition():
if WEB:
return definition_from_web()
return definition_from_file()
def maybe_replace(text):
if not REPLACE:
return
new_text = ""
with open("lib/ex_gram.ex", "r") as f:
current = f.read()
start = current[:current.find("# START AUTO GENERATED")].strip()
end_ind = current.find("# END AUTO GENERATED") + 20
end = current[end_ind:]
new_text = start + text + end
if new_text:
with open("lib/ex_gram.ex", "w") as f:
f.write(new_text)
os.system("mix format lib/ex_gram.ex")
def main():
definition = get_definition()
models = [generate_model(model) for model in definition['models']]
methods = [generate_method(method) for method in definition['methods']]
generics = [generate_generic(generic) for generic in definition['generics']]
methods_str = "\n\n".join(methods)
models_str = "\n\n ".join(models)
generics_str = "\n\n ".join(generics)
text = """
# START AUTO GENERATED
# ----------METHODS-----------
# Methods
{}
# {} methods
# ----------MODELS-----------
# Models
defmodule Model do
@moduledoc \"\"\"
Telegram API Model structures
\"\"\"
{}
# {} models
{}
# {} generics
end
# END AUTO GENERATED
""".format(methods_str, len(methods), models_str, len(models), generics_str, len(generics))
print(text)
pyperclip.copy(text)
maybe_replace(text)
if __name__ == "__main__":
main()