@docpage.html
001|
002| from sys import argv, exc_info, path as syspath
003| from traceback import extract_tb
004| from os import path
005| from xml.sax.saxutils import escape
006| from logger import logger,info,debug,trace, LogFilenameTimestamp
007| from goodies import KWARG
008| from files import fileobj
009| from webpage import WebPage
010|
011| BasePath = r'C:\CJS\prj\Python\app'
012| Log = logger('docpage')
013|
014| CMND = ''
015| ARGS = {
016|
017|
018| }
019|
020|
021| CSS = '''
021| body {
021| background-color: #f7f9fc;
021| color: #000000;
021| font-family: "Verdana", "Arial", "Helvetica", sans-serif;
021| font-size: 12px;
021| font-weight: normal;
021| font-style: normal;
021| line-height: 1.33;
021| text-decoration: none;
021| text-align: left;
021| vertical-align: top;
021| padding: 0;
021| border: 0;
021| margin: 0;
021| }
021| h1, h2, h3, h4, h5, h6 {
021| font-family: "Tahoma", "Verdana", "Arial", "Helvetica", sans-serif;
021| font-weight: bold;
021| font-style: normal;
021| line-height: 1.0;
021| text-decoration: none;
021| text-align: left;
021| vertical-align: bottom;
021| padding: 0;
021| border: 0;
021| margin: 0;
021| }
021| h1 {
021| color: #000000;
021| font-size: 12px;
021| font-weight: normal;
021| font-style: italic;
021| text-align: right;
021| }
021| h2 {
021| color: #000000;
021| font-size: 15px;
021| text-align: right;
021| }
021| h3 {
021| color: #603018;
021| font-size: 19px;
021| text-align: left;
021| margin-bottom: 9px;
021| }
021| h4 {
021| color: #804020;
021| font-size: 16px;
021| padding: 9px 9px 18px 9px;
021| border: 1px solid black;
021| margin-top: 15px;
021| margin-bottom: 0;
021| }
021| pre {
021| font-family: "Lucida Console", "Courier New", "Courier", monospace;
021| font-size: 11px;
021| font-weight: normal;
021| font-style: normal;
021| line-height: 1.20;
021| padding: 5px 10px 20px 10px;
021| margin: 0 0 15px 0;
021| }
021| #PageHead {
021| background-color: #e0e7ef;
021| padding: 6px 20px 8px 6px;
021| border-bottom: 2px solid black;
021| margin: 0;
021| }
021| #PageBody {
021| padding: 6px 24px 18px 12px;
021| margin: 0;
021| }
021| #PageFoot {
021| background-color: #c0c7cf;
021| color: #808080;
021| font-family: sans-serif;
021| font-size: 9px;
021| font-weight: normal;
021| font-style: normal;
021| line-height: 1.0;
021| text-align: center;
021| padding: 4px 12px 8px 12px;
021| border-top: 1px solid black;
021| margin: 0;
021| }
021| #PageFoot .Lt {
021| float: left;
021| text-align: left;
021| }
021| #PageFoot .Rt {
021| float: right;
021| text-align: right;
021| }
021| .ModuleDoc {
021| background-color: #fffff7;
021| padding: 8px 20px 16px 15px;
021| border: 2px solid black;
021| }
021| .ObjectDoc {
021| border-right: 1px solid black;
021| border-bottom: 1px solid black;
021| border-left: 1px solid black;
021| background-color: #f7ffff;
021| }
021| .function {background-color:#ffffbf; color:#000000;}
021| .lambda {background-color:#ffdfbf; color:#000000;}
021| .class {background-color:#bfffff; color:#000000;}
021| .int, .float, .str {background-color:#dfffdf; color:#000000;}
021| .tuple, .list, .dict {background-color:#ffdfdf; color:#000000;}
021|
021| '''
022|
023|
024| def module_docs (names, fpath):
025| '''Generate single HTML file from multiple Python files in a given directory.'''
026|
027| Log.info(f'module_docs({names}, {fpath})')
028| Log.info()
029|
030|
031| htmlname = path.join(fpath, f'{names[0]}-doc.html')
032|
033|
034| if fpath not in syspath:
035| syspath.append(fpath)
036|
037| hdrs = []
038| records = []
039| for modname in names:
040| m = __import__(modname)
041| h = m.__doc__ if hasattr(m,'__doc__') else None
042| h = escape(h.strip()) if h else '(no Module Doc)'
043| hdrs.append(h)
044|
045|
046| for k in m.__dict__:
047|
048| obj = m.__dict__[k]
049|
050|
051|
052| mod_name = obj.__module__ if hasattr(obj,'__module__') else ''
053| if mod_name is None:
054| Log.info(f'skipping: {k} (mod_name is None)')
055| continue
056| if mod_name != m.__name__:
057| if k.startswith('__') or (0 < len(mod_name)):
058| Log.info(f'skipping: {k} ({mod_name})')
059| continue
060|
061|
062| obj_name = obj.__name__ if hasattr(obj,'__name__') else ''
063| obj_doc = obj.__doc__ if hasattr(obj,'__doc__') else ''
064| obj_type = type(obj).__name__
065| if obj_type == "module":
066| continue
067|
068| if obj_type in ['list','tuple','dict']:
069| obj_doc = f'length={len(obj)}'
070|
071| elif obj_type in ['int','float']:
072| obj_doc = str(obj)
073|
074| elif obj_type == 'str':
075| s = str(obj).replace('\n',' ')
076| if 80 < len(s):
077| s = f'{s[:38]} ... {s[-38:]} ({len(s)})'
078| else:
079| s = f'{s} ({len(s)})'
080| obj_doc = s
081|
082| elif obj_type == 'type':
083| obj_type = 'class'
084|
085| if obj_name == '<lambda>':
086| obj_type = 'lambda'
087|
088| Log.info(f'object: {k}, {obj_type}, {obj_name}')
089|
090|
091| t = (modname, k, obj_type, obj_name, obj_doc)
092| records.append(t)
093|
094|
095| props = dict(
096| h1='CJSonnack',
097| h2='Python Apps',
098| h3=f'{names[0]}',
099| css=[], csstxt=CSS
100| )
101| pg = WebPage(modname.upper(), **props)
102| pg.add()
103| for h in hdrs:
104| pg.add(f'<pre class="ModuleDoc">{h}</pre>')
105| pg.add()
106|
107| def section (rcd_type):
108| rcds = [r for r in records if r[2]==rcd_type]
109| skey = lambda r:(r[0],r[1])
110| for rcd in sorted(rcds, key=skey):
111| mod = rcd[0]
112| nam = rcd[1]
113| typ = rcd[2]
114| txt = rcd[4]
115| pg.add(f'<h4 class="{typ}"><span style="font-weight:normal;">{typ}</span> {mod}.{nam}</h4>')
116|
117| if (txt is not None) and (0 < len(txt)):
118| s = escape(txt.strip())
119| pg.add(f'<pre class="ObjectDoc">{s}</pre>')
120| pg.add()
121|
122| section('class')
123| section('function')
124| section('lambda')
125| section('dict')
126| section('tuple')
127| section('list')
128| section('str')
129| section('int')
130| section('float')
131|
132| pg.save(htmlname)
133|
134| return htmlname
135|
136|
137| def do_docpage (**kwargs):
138| """CMND: Generate a DocPage from a Python file."""
139| fpath = KWARG('fpath', '', str, kwargs)
140| names = KWARG('names', '', str, kwargs)
141| Log.info('docpage:: %s' % str(list(kwargs.keys())))
142| Log.debug(f'{fpath=}')
143| Log.debug(f'{names=}')
144| Log.info()
145| if not fpath:
146| Log.error('Directory path (fpath) is required.')
147| Log.error()
148| return 'Oops!'
149|
150| module_docs(names.split(','), fpath)
151|
152| Log.info()
153| return 'Done'
154|
155|
156| def do_test (**kwargs):
157| """CMND: Do a test."""
158| fpath = KWARG('fpath', BasePath, str, kwargs)
159| fname = KWARG('fname', 'test.out', str, kwargs)
160| Log.info(f'test:: {list(kwargs.keys())}')
161| Log.debug(f'{fpath=}')
162| Log.debug(f'{fname=}')
163| Log.info()
164| Log.info()
165| return 'Done'
166|
167| def dispatch (cmd, **kwargs):
168| """Dispatch to a module function based on CMD."""
169| Log.info(f'CMD: {cmd}')
170| for kw in kwargs:
171| Log.debug(f'argument[{kw}]: {kwargs[kw]}')
172| Log.info()
173| if cmd == 'page': return do_docpage(**kwargs)
174| if cmd == 'test': return do_test(**kwargs)
175| return 'Nothing to do!'
176|
177| if __name__ == '__main__':
178| print(f'autorun: {argv[0]}')
179| Log.start(path.join(BasePath,'docpage.log'))
180| Log.level(trace())
181| Log.info(argv[0])
182| Log.info()
183| cmd = argv[1] if 1 < len(argv) else CMND
184| kwargs = ARGS
185| for a in argv[2:]:
186| nv = a.split('=', 1)
187| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
188| Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
189| try:
190| print(f'CMD: {cmd}')
191| print()
192| obj = dispatch(cmd, **kwargs)
193| print()
194| print(obj)
195| Log.info()
196| Log.info(obj)
197| except:
198| etype, evalue, tb = exc_info()
199| ts = extract_tb(tb)
200| Log.error()
201| Log.error(f'{etype.__name__}: {evalue!s}')
202| Log.error()
203| for t in ts[-5:]:
204| Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
205| Log.error(f' {t[3]}')
206| Log.error()
207| raise
208| finally:
209| Log.end()
210|
211| '''eof'''
212|