tools/scripts/mydoc/mydoc.py
2021-11-16 15:11:32 +08:00

81 lines
3.1 KiB
Python

# -*- coding: utf-8 -*-
import os
import sys
import json
from urllib import parse as urlparse
class MyDoc(object):
def __init__(self, workDir):
self._workDir = workDir + '/doc/'
def convert(self):
self._env = json.loads(open(self._workDir + 'env.json', 'r').read())
self._wf = open(self.getOutFileName(), 'w')
self._wf.write('<?php\n\n')
self._wf.write('class Doc\n{\n')
sys.path.append(self._workDir)
for file in os.listdir(self._workDir):
if file[0:1] == '_' or file[-3:] != '.py':
continue
m = __import__(file.replace('.py', ''))
for name in dir(m):
if name[0:1] != '_':
t = getattr(m, name)
if type(t).__name__ != 'type':
continue
c = t()
self._convertClass(c)
self._wf.write('\n}')
self._wf.close()
def getOutFileName(self):
return self._workDir + self._env['name'] + '.doc.php'
def _convertClass(self, c):
def getParamType(param):
if type(param[1]) in (int, float):
return 'Number'
if type(param[1]) in (str,):
return 'String'
return 'Number'
def outParam(param):
self._wf.write(' * @apiParam {%s} %s %s\n' % (getParamType(param), param[0], param[2]))
def getJsonValue(val):
if type(val) in (int, float):
return val
if type(val) in (str,):
return '"%s"' % (val)
return val
def outRsp(item, ident):
self._wf.write(' * %s"%s": %s, //%s\n' %
(''.join([' ' for i in range(ident)]),
item[0],
getJsonValue(item[1]),
item[2]))
for item in c.apis:
self._wf.write('\n /**\n')
self._wf.write(' * @api {%s} %s %s\n' % (item.get('method', 'GET'), item['url'], item['desc']))
self._wf.write(' * @apiPermission %s\n' % (item.get('permission', 'none')))
if 'group' in item:
self._wf.write(' * @apiGroup %s\n' % (item.get('group', '')))
self._wf.write(' * @apiVersion %s\n' % (item.get('version', '0.0.1')))
self._wf.write(' * @apiDescription %s\n' % (item.get('desc', '')))
for param in item['params']:
if isinstance(param, list):
outParam(param)
else:
[outParam(p) for p in param.params]
self._wf.write(' * @apiSuccessExample {json} Success-Response:\n')
self._wf.write(' * HTTP/1.1 200 OK\n')
self._wf.write(' * {\n')
for item in item['response']:
if isinstance(item, list):
outRsp(item, 1)
else:
[outRsp(p, 1) for p in item.fields]
self._wf.write(' * }\n')
self._wf.write(' */\n')