forked from williamngan/pt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docgen.py
227 lines (164 loc) · 6.19 KB
/
docgen.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/python
# -*- coding: utf-8 -*-
# A quick and dirty documentation generator for coffeescript. Outputs JSON files.
# Based on Docco and Pycco (https://fitzgen.github.io/pycco/).
# Command Line Example:
# python docgen.py -i ./src/coffee/core -o ./docs/json/core
# python docgen.py -i ./src/coffee/extend -o ./docs/json/extend
import sys
import getopt
import os
from os.path import isfile, join
import markdown
import copy
import json
import re
import ntpath
inputfile = ''
outputfile = ''
def parse( path ):
cls = {
"cls": '',
"props": [],
"funcs": [],
"statics": []
}
lines = open(path, "r").read().split("\n")
classes = []
class_start = False
section_start = True
sec = {"name": "", "description":"", "param": []}
print "------------"
for line in lines:
line = line.strip()
# new section
if line.startswith("# #") and not section_start:
sec = { "name": "", "description": md(line[1:]), "param": []}
section_start = True
elif section_start:
# next '#' means more description about the section
if line.startswith("#"):
if "@param" in line:
sec["param"].append( md(line.split("@param")[1].strip()) )
elif "@return" in line:
sec["return"] = md(line.split("@return")[1].strip())
elif "@eg" in line:
sec["eg"] = md(line.split("@eg")[1].strip())
elif "@demo" in line:
sec["demo"] = line.split("@demo")[1].strip()
else:
# sec["description"].append( md(line[1:]) )
sec["description"] = sec["description"] + md(line[1:])
# no more comments in the section. get the first line of code and analyze its type
else:
if len(line) > 4:
head = getType(line)
t = head["type"]
if t == "cls":
# if it's another class in the file
if class_start:
classes.append( copy.deepcopy(cls) )
# class info
cls[t] = head["name"]
cls["extend"] = head["extend"] if "extend" in head else ""
cls["description"] = sec["description"] if "description" in sec else ""
cls["file"] = ntpath.basename( path )
cls["props"] = []
cls["funcs"] = []
cls["statics"] = []
elif t:
sec["name"] = head["name"]
if sec["name"].strip() == 'constructor':
sec["name"] = cls["cls"]
# if t == 'statics':
# sec["name"] = cls["cls"]+"."+sec["name"]
if "param" in head:
sec["pname"] = head["param"]
# add if function or property doesn't start with underscore
if sec["name"][0] != "_":
cls[t].append( sec )
section_start = False
class_start = True
# create JSONs
classes.append( cls )
for c in classes:
createJSON( c )
return classes
def createJSON( cls ):
if len(cls["cls"]) > 1 and len(outputfile) > 1:
outjson = open( join(outputfile, cls["cls"]+".json"), "w" )
json.dump( cls, outjson, indent=4, sort_keys=True )
else:
print "Cannot generate JSON for class "+cls
def createAll( classes ):
outjson = open( join(outputfile, "all.json"), "w" )
json.dump( classes, outjson, indent=2, sort_keys=True )
def md(text):
try:
return markdown.markdown( text.strip() )
except UnicodeDecodeError:
print "Error decoding markdown: "+text
return text
# Get the type of the section based on the text on that line
def getType(line):
# class
if "class" in line:
print line
temp = line.split(" ")
cls = {"type": "cls", "name": temp[1]}
if len(temp) > 3:
cls["extend"] = temp[3]
return cls
# coffeescript function
elif "->" in line:
# print line
temp = line.split(":")
temp2 = temp[1].split("->")
param = temp2[0].strip()[1:-1]
# static function or object function
t = "statics" if line[0] == "@" else "funcs"
return {"type": t,
"name": temp[0][1:].strip() if t == 'statics' else temp[0].strip(),
"param": param.strip() }
# property
elif "@" in line:
temp = line.split("=")
return {"type": "props", "name": temp[0][1:].strip()}
else:
print "Unknown line: "+line
return {"type": False, "name": ""}
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["ifile=", "ofile="])
except getopt.GetoptError:
print 'docgen.py -i <input file or folder> -o <output folder>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'docgen.py -i <input file or folder> -o <output folder>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
if len(inputfile) == 0:
print 'Input file not found: docgen.py -i <input file or folder> -o <output folder>'
sys.exit()
if len(outputfile) == 0 or isfile(outputfile):
print 'Output file not valid: docgen.py -i <input file or folder> -o <output folder>'
sys.exit()
if isfile( inputfile ):
parse( inputfile )
else:
# pull all the files
files = os.listdir(inputfile)
allcls = {}
for f in files:
file_path = join(inputfile, f)
if isfile(file_path) and f.endswith(".coffee"):
cs = parse(file_path)
# collect all classes for a single json
for c in cs:
allcls[c["cls"]] = c
# create single json
createAll( allcls )