-
Notifications
You must be signed in to change notification settings - Fork 2
/
processMethod.py
executable file
·186 lines (141 loc) · 5.59 KB
/
processMethod.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from processArguments import processArguments
import json
import sys
import re
# Constants
REQUIRED_PERMISSIONS="Required permissions:"
NOTES = "Notes:"
debugPrint = False
# Methods
def prepareNote(soup) :
notes_line = soup.next_element
aryNotes = []
phrase = ''
while notes_line != None :
if NOTES not in notes_line :
if isinstance(notes_line, type(soup)) :
phrase = ''.join(['\'' + ' '.join(notes_line.stripped_strings).strip() + '\''])
aryNotes.append(phrase)
else :
phrase = notes_line.strip()
aryNotes.append(phrase)
notes_line = notes_line.next_sibling
return ' '.join(aryNotes)
def fixFieldName(theField) : # get first full word and if _id is a suffix make it a prefix
split_field = theField.split()
field = split_field[0]
if "_id" in field :
field = field.replace('_id', '')
field = 'id{}'.format(field.title())
if len(split_field) > 1 and "id" in split_field[1] :
field = 'id{}'.format(field.title())
return field
def preparePath(path, basePath) : # detect/prepare and flag the contained path parmeters
namePath = path.replace('[', '{').replace(']', '}').strip()
namePath = namePath.replace(basePath, '')
fields = []
for span in re.finditer('\[(.*?)\]', path):
aField = path[span.start()+1:span.end()-1]
nameField = fixFieldName(aField)
namePath = namePath.replace(aField, nameField)
# print '{} - ({} vs {})'.format(namePath, aField, nameField)
fields.append({nameField : aField})
return {"namePath" : namePath, "fields" : fields }
http2crud = {'get' : 'get', 'post' : 'add', 'put' : 'update', 'delete' : 'delete'}
def makeOperationId(method, defPath) : # get first full word and if _id is a suffix make it a prefix
bits = defPath["namePath"].split('/')
parms = []
nouns = []
for bit in bits :
if '{' in bit :
parm = bit.strip().replace('{', '').replace('}', '')
parms.append('{}{}'.format(parm[:1].title(), parm[1:]))
else :
noun = bit.strip()
nouns.append('{}{}'.format(noun[:1].title(), noun[1:]))
parmClause = 'By'.join(parms)
if len(parmClause) > 0 :
parmClause = 'By{}'.format(parmClause)
operationId = '{}{}{}'.format(http2crud[method], ''.join(nouns), parmClause)
if debugPrint : print 'Operation Id : {}\n\n'.format(operationId)
return operationId
def processMethod(soup, swagger, entity):
'''
print "# {}".format(soup)
sys.exit()
'''
defPath = preparePath(soup.h2.span.text, swagger["basePath"])
namePath = defPath["namePath"]
nameMethod = soup.h2.next_element.lower().strip()
cursor = {'entity' : entity, 'path' : namePath, 'method' : nameMethod}
if cursor['entity'] == "cardxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
and cursor['method'] == "delete":
debugPrint = True
else:
debugPrint = False
print "Method : {}, Path : {}".format(nameMethod, namePath)
# if debugPrint : print "Method : {}, Path : {}".format(nameMethod, namePath)
if namePath not in swagger['paths'] :
swagger['paths'][namePath] = {}
if nameMethod not in swagger['paths'][namePath] :
swagger['paths'][namePath][nameMethod] = {
"responses" : {
"200" : {
"description" : "Success"
},
"400" : {
"description" : "Server rejection"
}
},
"tags" : [entity]
}
swagger['paths'][namePath][nameMethod]['operationId'] = makeOperationId(nameMethod, defPath)
swagger['paths'][namePath][nameMethod]['summary'] = '{}()'.format(swagger['paths'][namePath][nameMethod]['operationId'])
soup.h2.extract()
if NOTES in soup.ul.li.next_element :
swagger['paths'][namePath][nameMethod]['description'] = prepareNote(soup.ul.li)
# print swagger['paths'][namePath][nameMethod]['description']
soup.ul.li.extract()
if REQUIRED_PERMISSIONS in soup.ul.li.next_element :
permission = ' and'.join(''.join(soup.ul.li.stripped_strings).replace(REQUIRED_PERMISSIONS, '').rsplit(',', 1))
auth = ["read:boards"]
if "get" not in nameMethod : auth.append("write:boards")
swagger['paths'][namePath][nameMethod]['security'] = [ { "trello_auth": auth } ]
# print swagger['paths'][namePath][nameMethod]['security']
soup.ul.li.extract()
arguments = soup.ul.li
'''
print ' ---- '
print arguments
print ' ---- '
'''
swagger['paths'][namePath][nameMethod]['parameters'] = []
processArguments(arguments, swagger, defPath["fields"], cursor)
return
# - - - - - - - - - - -
# Main routine (for testing)
def main():
from test.testdataMethod import test_values
from test.testdataMethod import swagger
from test.testdataMethod import sampleAPI
idx = 0
for frag in test_values :
print(" - - - - - - - - - - - - - - ")
soup = BeautifulSoup(frag)
# if idx == 0 :
if idx != -1 :
processMethod(soup.body.contents[0], swagger, "OneOfTheTrelloEntities")
idx = idx + 1
print(">> - - - - - - - - - - ? - - - - - - - - - - -<<")
print "JSON {}".format(json.dumps(swagger))
print("<< - - - - - - - - - - - - - - - - - - - - - - ->>")
TrelloAPI = json.loads(sampleAPI)
TrelloAPI['paths'] = swagger['paths']
# now write output to a file
TrelloAPI_json = open("TrelloAPI_test.json", "w")
TrelloAPI_json.write(json.dumps(TrelloAPI, indent=2, sort_keys=False))
TrelloAPI_json.close()
if __name__ == "__main__": main()