forked from PatLittle/OpenCanadaAPI
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsplityaml.py
70 lines (62 loc) · 1.89 KB
/
splityaml.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
"""
usage:
splityaml.py openapi.yaml en openapi-en.json
splityaml.py openapi.yaml fr openapi-fr.json
"""
LANGUAGES = {'en', 'fr'}
POST_GET = 'post/get'
import json
import yaml
import sys
def split(d, lng):
if isinstance(d, dict):
if d.keys() == LANGUAGES:
return d[lng]
if d.keys() == {POST_GET}:
return {
'get': split(convert_post_to_get_params(d[POST_GET]), lng),
'post': split(d[POST_GET], lng),
}
if isinstance(d, dict):
return {k: split(v, lng) for (k, v) in d.items()}
if isinstance(d, list):
return [split(i, lng) for i in d]
return d
def convert_post_to_get_params(post):
props = post['requestBody']['content']['application/json']['schema']['properties']
params = []
for k, v in props.items():
if 'oneOf' in v:
# XXX: assume first version is the string version of the parameter
v = v['oneOf'][0]
p = {
'name': k,
'in': 'query',
'description': v['description'],
'schema': {
'type': v['type'],
},
}
if 'examples' in v:
# need to pop so that post schema validated
p['examples'] = v.pop('examples')
if 'default' in v:
p['schema']['default'] = v.pop('default')
if 'enum' in v:
p['schema']['enum'] = v['enum']
if 'format' in v:
p['schema']['format'] = v['format']
params.append(p)
return {
'summary': post['summary'],
'description': post['description'],
'parameters': params,
'responses': post['responses'],
'tags': post['tags'],
}
with open(sys.argv[1], encoding='utf-8') as r:
doc = yaml.safe_load(r)
lang = sys.argv[2]
out = split(doc, lang)
with open(sys.argv[3], 'w', encoding='utf-8') as w:
json.dump(out, w)