tmake.html


001| '''Table Maker. Turns shorthand input into complex HTML tables.
001| 
001| format:
001|     <make-file> := {"/css" <css-section>} "/table" <table-props> <table-section>
001| 
001|     <table-props> := "#"<id> | "."<class> | "{" <style-text> "}"
001| 
001|     <table-section> := <command> <properties>
001|     <css-section> := <command> <properties>
001| 
001|     <command> := "/caption" | "/head" | "/foot" | "/head+foot" | "/body" | "/tr" | "/th" | "/td" | "/end"
001| 
001|     <properties> := "#"<id> | "."<class> | "{" <style-text> "}" | "$r"# | "$c"# | <dqt> <cell-text> <dqt>
001| 
001| 
001| Classes:
001|     tablemaker
001| 
001| Commands:
001|     make        do_make_table
001|     test        do_test
001| 
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from logger import logger,info,debug,trace, LogFilenameTimestamp
007| from goodies import KWARG, typename
008| from files import textfile
009| ##TODO: Parser should build most of the HTML?
010| ####################################################################################################
011| BasePath = r'C:\CJS\prj\Python\app\tmake'
012| FileName0 = 'table-000.in'
013| FileName1 = 'table-001.in'
014| FileName2 = 'table-002.in'
015| Log = logger('TMake')
016| 
017| CMND = ''
018| ARGS = {
019|     'fname': FileName0,
020|     'fpath': BasePath,
021| }
022| 
023| ##================================================================================================##
024| def compress (s, char=' '):
025|     if s is None: return None
026|     if len(s)==0: return ''
027|     if char not in s: return s
028|     buf = []
029|     count = 0
030|     for ch in s:
031|         if ch == char:
032|             count += 1
033|             if 1 < count:
034|                 continue
035|         else:
036|             count = 0
037|         buf.append(ch)
038| 
039|     return ''.join(buf).replace('; ',';').replace(': ',':').strip()
040| 
041| 
042| ##------------------------------------------------------------------------------------------------##
043| TableCommands = ['end','css', 'table','caption','head+foot','head','foot','body','tr','th','td']
044| 
045| ##------------------------------------------------------------------------------------------------##
046| SpecialChars = ['#', '.', '"', '$', '{','}']
047| 
048| 
049| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
050| class tablemaker:
051|     '''Table Maker class.'''
052|     def __init__ (self, text=''):
053|         self.table_id = ''
054|         self.table_class = ''
055|         self.table_css = ''
056|         self.caption = ''
057|         self.caption_id = ''
058|         self.caption_class = ''
059|         self.caption_css = ''
060|         self.styles = []
061|         self.thead = []
062|         self.tbody = []
063|         self.tfoot = []
064|         self.curr_section = 'tbody'
065|         self.row_class = dict(thead='', tfoot='', tbody='')
066|         self._reset()
067|         self._parser(text)
068| 
069|     def _reset (self):
070|         '''Reset row parameters.'''
071|         self.curr_row = []
072|         self.curr_col = 0
073|         self.row_id = ''
074|         self.row_css = ''
075|         self.cell_id = ''
076|         self.cell_class = ''
077|         self.cell_css = ''
078|         self.cell_span = []
079| 
080|     def content (self):
081|         '''Return HTML table content.'''
082|         buf = []
083|         # CSS...
084|         if 0 < len(self.styles):
085|             buf.append('<style type="text/css">')
086|             for name,style in self.styles:
087|                 # Check for combined thead+tfoot declarations...
088|                 if 'thead+tfoot' in name:
089|                     # thead
090|                     thead = name.replace('thead+tfoot', 'thead')
091|                     buf.append('%s {%s}' % (thead, style))
092|                     # tfoot
093|                     tfoot = name.replace('thead+tfoot', 'tfoot')
094|                     buf.append('%s {%s}' % (tfoot, style))
095|                     continue
096|                 # Default...
097|                 buf.append('%s {%s}' % (name, style))
098|             buf.append('</style>')
099|             buf.append('')
100|         # <TABLE>...
101|         eid = (' id="%s"' % self.table_id) if self.table_id else ''
102|         cls = (' class="%s"' % self.table_class) if self.table_class else ''
103|         css = (' style="%s"' % self.table_css) if self.table_css else ''
104|         buf.append('<table%s%s%s>' % (eid, cls, css))
105|         # Caption...
106|         if 0 < len(self.caption):
107|             eid = (' id="%s"' % self.caption_id) if self.caption_id else ''
108|             cls = (' class="%s"' % self.caption_class) if self.caption_class else ''
109|             css = (' style="%s"' % self.caption_css) if self.caption_css else ''
110|             txt = self.caption
111|             buf.append('<caption%s%s%s>%s</caption>' % (eid, cls, css, txt))
112|         # THead...
113|         if 0 < len(self.thead):
114|             buf.append('<thead>')
115|             for row in self.thead:
116|                 cls = (' class="%s"' % self.row_class['thead']) if self.row_class['thead'] else ''
117|                 buf.append('<tr%s>' % cls)
118|                 for cell in row:
119|                     buf.append(cell)
120|                 buf.append('</tr>')
121|             buf.append('</thead>')
122|         # TBody...
123|         if 0 < len(self.tbody):
124|             buf.append('<tbody>')
125|             for row in self.tbody:
126|                 cls = (' class="%s"' % self.row_class['tbody']) if self.row_class['tbody'] else ''
127|                 buf.append('<tr%s>' % cls)
128|                 for cell in row:
129|                     buf.append(cell)
130|                 buf.append('</tr>')
131|             buf.append('</tbody>')
132|         # TFoot...
133|         if 0 < len(self.tfoot):
134|             buf.append('<tfoot>')
135|             for row in self.tfoot:
136|                 cls = (' class="%s"' % self.row_class['tfoot']) if self.row_class['tfoot'] else ''
137|                 buf.append('<tr%s>' % cls)
138|                 for cell in row:
139|                     buf.append(cell)
140|                 buf.append('</tr>')
141|             buf.append('</tfoot>')
142|         # </TABLE>...
143|         buf.append('</table>')
144|         return '\n'.join(buf)
145| 
146|     def _parser (self, text):
147|         '''Parse and process table-maker commands.'''
148|         # Condition text for parsing...
149|         xtab = str.maketrans('','','\t\n')
150|         self.text = text.translate(xtab)
151|         self.mode = 0 # normal mode, table elements
152|         # Split into table command groups...
153|         self.cmds = self.text.split('/')
154|         # Process table commands...
155|         for cmd in self.cmds:
156|             if len(cmd) == 0:
157|                 continue
158|             # For each known command...
159|             self.parse_command(cmd)
160| 
161|     def parse_command (self, cmd):
162|         '''Parse a table command.'''
163|         for tc in TableCommands:
164|             # If command starts with it...
165|             if cmd.startswith(tc):
166|                 # Get the rest of the text...
167|                 txt = cmd[len(tc):]
168|                 Log.debug()
169|                 Log.debug('%s: "%s"' % (tc.upper(), txt))
170|                 # Parse the command...
171|                 props = self.parse_properties(txt)
172|                 name = 'do_%s_%d' % (tc.replace('+',''), self.mode)
173|                 method = type(self).__dict__[name]
174|                 method(self, props)
175|                 return
176|         # Should have returned by now!...
177|         raise RuntimeError('Unknown command: %s' % cmd)
178| 
179|     def parse_properties (self, cmd):
180|         '''Parse text.'''
181|         chs = list(cmd)
182|         txt = []    # element text
183|         eid = ''    # element id
184|         cls = []    # element class
185|         css = ''    # element style
186|         spn = []    # row/col span
187| 
188|         def find_end (cs, spcl=SpecialChars):
189|             for ix,c in enumerate(cs):
190|                 if c in spcl:
191|                     return ix
192|             return len(cs)
193| 
194|         # Consume the characters...
195|         while 0 < len(chs):
196|             ch = chs.pop(0)
197|             match ch:
198|                 case '#':
199|                     end = find_end(chs)
200|                     eid = ''.join(chs[0:end]).strip()
201|                     del chs[0:end]
202|                 case '.':
203|                     end = find_end(chs)
204|                     cls.append(''.join(chs[0:end]).strip())
205|                     del chs[0:end]
206|                 case '$':
207|                     end = find_end(chs)
208|                     spn.append(''.join(chs[0:end]).strip())
209|                     del chs[0:end]
210|                 case '{':
211|                     end = find_end(chs, spcl=['}'])
212|                     css = compress(''.join(chs[0:end]))
213|                     del chs[0:end+1]
214|                 case '"':
215|                     end = find_end(chs, spcl=['"'])
216|                     txt.append(''.join(chs[0:end]))
217|                     del chs[0:end+1]
218|                 case _:
219|                     Log.trace('Ignoring: "%s"' % ch)
220|         # Return a dictionary of element properties...
221|         return dict(txt=txt, eid=eid, cls=cls, css=css, spn=spn)
222| 
223|     def do_css_0 (self, props):
224|         '''CMND: Table.'''
225|         Log.trace('Css: %s' % str(props))
226|         self.mode = 1
227|         for cmd,txt in props.items():
228|             match cmd:
229|                 case 'eid':
230|                     Log.trace('set table id "%s"' % txt)
231|                     self.table_id = txt
232|                 case 'cls':
233|                     Log.trace('set table class "%s"' % txt)
234|                     self.table_class = ' '.join(txt)
235|                 case _:
236|                     Log.trace('Ignore: %s:%s' % (cmd,txt))
237| 
238|         eid = ('#%s' % self.table_id) if 0<len(self.table_id) else ''
239|         cls = ('.%s' % self.table_class) if 0<len(self.table_class) else ''
240|         self.styles.append(('table%s%s' % (eid,cls), props['css']))
241| 
242|     def do_caption_1 (self, props):
243|         '''CMND: CSS Caption.'''
244|         Log.trace('css-caption: %s' % str(props))
245|         eid = ('#%s' % self.table_id) if 0<len(self.table_id) else ''
246|         cls = ('.%s' % self.table_class) if 0<len(self.table_class) else ''
247|         self.styles.append(('table%s%s caption' % (eid,cls), props['css']))
248| 
249|     def do_headfoot_1 (self, props):
250|         '''CMND: CSS Header+Footer.'''
251|         Log.trace('css-head+foot: %s' % str(props))
252|         self.curr_section = 'thead+tfoot'
253| 
254|     def do_head_1 (self, props):
255|         '''CMND: CSS Header.'''
256|         Log.trace('css-head: %s' % str(props))
257|         self.curr_section = 'thead'
258| 
259|     def do_foot_1 (self, props):
260|         '''CMND: CSS Footer.'''
261|         Log.trace('css-foot: %s' % str(props))
262|         self.curr_section = 'tfoot'
263| 
264|     def do_body_1 (self, props):
265|         '''CMND: CSS Body.'''
266|         Log.trace('css-body: %s' % str(props))
267|         self.curr_section = 'tbody'
268| 
269|     def do_tr_1 (self, props):
270|         '''CMND: CSS Row.'''
271|         Log.trace('css-tr: %s' % str(props))
272| 
273|     def do_th_1 (self, props):
274|         '''CMND: CSS Header.'''
275|         Log.trace('css-th: %s' % str(props))
276|         teid = ('#%s' % self.table_id) if 0<len(self.table_id) else ''
277|         tcls = ('.%s' % self.table_class) if 0<len(self.table_class) else ''
278|         sec = (' %s' % self.curr_section)
279|         eid = ('#%s' % props['eid']) if props['eid'] else ''
280|         cls = ('.%s' % props['cls'][0]) if props['cls'] else ''
281|         self.styles.append(('table%s%s%s th%s%s' % (teid,tcls,sec,eid,cls), props['css']))
282| 
283|     def do_td_1 (self, props):
284|         '''CMND: CSS Cell.'''
285|         Log.trace('css-td: %s' % str(props))
286|         teid = ('#%s' % self.table_id) if 0<len(self.table_id) else ''
287|         tcls = ('.%s' % self.table_class) if 0<len(self.table_class) else ''
288|         sec = (' %s' % self.curr_section)
289|         eid = ('#%s' % props['eid']) if props['eid'] else ''
290|         cls = ('.%s' % props['cls'][0]) if props['cls'] else ''
291|         self.styles.append(('table%s%s%s td%s%s' % (teid,tcls,sec,eid,cls), props['css']))
292| 
293|     def do_table_1 (self, props):
294|         '''CMD: Table. Used when in CSS mode.'''
295|         self.mode = 0
296|         self.curr_section = 'tbody'
297|         self.do_table_0(props)
298| 
299|     def do_table_0 (self, props):
300|         '''CMND: Table.'''
301|         Log.debug('Table: %s' % str(props))
302|         for cmd,txt in props.items():
303|             if len(txt) == 0:
304|                 continue
305|             match cmd:
306|                 case 'eid':
307|                     Log.trace('set table id "%s"' % txt)
308|                     self.table_id = txt
309|                 case 'cls':
310|                     Log.trace('set table class "%s"' % txt)
311|                     self.table_class = ' '.join(txt)
312|                 case 'css':
313|                     Log.trace('set table CSS {%s}' % txt)
314|                     self.table_css = txt
315|                 case _:
316|                     Log.trace('Ignore: %s:%s' % (cmd,txt))
317| 
318|     def do_caption_0 (self, props):
319|         '''CMND: Table Caption.'''
320|         Log.debug('Caption: %s' % str(props))
321|         for cmd,txt in props.items():
322|             match cmd:
323|                 case 'eid':
324|                     Log.trace('set caption id "%s"' % txt)
325|                     self.caption_id = txt
326|                 case 'cls':
327|                     Log.trace('set caption class "%s"' % txt)
328|                     self.caption_class = ' '.join(txt)
329|                 case 'css':
330|                     Log.trace('set caption CSS {%s}' % txt)
331|                     self.caption_css = txt
332|                 case 'txt':
333|                     Log.trace('set caption text "%s"' % txt)
334|                     self.caption = '<br>'.join(txt)
335|                 case _:
336|                     Log.trace('Ignore: %s:%s' % (cmd,txt))
337| 
338|     def do_head_0 (self, props):
339|         '''CMND: Table Header.'''
340|         Log.debug('Head: %s' % str(props))
341|         Log.trace('set thead')
342|         self._buffer_check()
343|         self.curr_section = 'thead'
344| 
345|     def do_foot_0 (self, props):
346|         '''CMND: Table Footer.'''
347|         Log.debug('Foot: %s' % str(props))
348|         Log.trace('set tfoot')
349|         self._buffer_check()
350|         self.curr_section = 'tfoot'
351| 
352|     def do_body_0 (self, props):
353|         '''CMND: Table Body.'''
354|         Log.debug('Body: %s' % str(props))
355|         Log.trace('set tbody')
356|         self._buffer_check()
357|         self.curr_section = 'tbody'
358| 
359|     def do_tr_0 (self, props):
360|         '''CMND: Table Row.'''
361|         Log.debug('Trow: %s' % str(props))
362|         self._buffer_check()
363|         # Reset for a new row...
364|         self._reset()
365|         for cmd,txt in sorted(props.items(), key=lambda t:t[0]):
366|             if len(txt) == 0:
367|                 continue
368|             match cmd:
369|                 case 'eid':
370|                     Log.trace('set %s tr id "%s"' % (self.curr_section,txt))
371|                     self.row_id = txt
372|                 case 'cls':
373|                     Log.trace('set %s tr class "%s"' % (self.curr_section,txt))
374|                     self.row_class[self.curr_section] = ' '.join(txt)
375|                 case 'css':
376|                     Log.trace('set %s tr CSS {%s}' % (self.curr_section,txt))
377|                     self.row_css = txt
378|                 case 'txt':
379|                     cls = self.cell_class
380|                     css = self.cell_css
381|                     for cell in txt:
382|                         self.cell_class = cls
383|                         self.cell_css = css
384|                         Log.trace('set td text "%s"' % cell)
385|                         self._make_cell('td', cell)
386|                 case _:
387|                     Log.trace('Ignore: %s:%s' % (cmd,txt))
388| 
389|     def do_th_0 (self, props):
390|         '''CMND: Table Header.'''
391|         Log.debug('Th: %s' % str(props))
392|         for cmd,txt in sorted(props.items(), key=lambda t:t[0]):
393|             if len(txt) == 0:
394|                 continue
395|             match cmd:
396|                 case 'eid':
397|                     Log.trace('set th id "%s"' % txt)
398|                     self.cell_id = txt
399|                 case 'cls':
400|                     Log.trace('set th class "%s"' % txt)
401|                     self.cell_class = ' '.join(txt)
402|                 case 'css':
403|                     Log.trace('set th CSS {%s}' % txt)
404|                     self.cell_css = txt
405|                 case 'spn':
406|                     Log.trace('set th span "%s"' % txt)
407|                     self._spanner(txt)
408|                 case 'txt':
409|                     for cell in txt:
410|                         Log.trace('set th text "%s"' % cell)
411|                         self._make_cell('th', ''.join(cell))
412|                 case _:
413|                     Log.trace('Ignore: %s:%s' % (cmd,txt))
414| 
415|     def do_td_0 (self, props):
416|         '''CMND: Table Cell.'''
417|         Log.debug('Td: %s' % str(props))
418|         for cmd,txt in sorted(props.items(), key=lambda t:t[0]):
419|             if len(txt) == 0:
420|                 continue
421|             match cmd:
422|                 case 'eid':
423|                     Log.trace('set td id "%s"' % txt)
424|                     self.cell_id = txt
425|                 case 'cls':
426|                     Log.trace('set td class "%s"' % txt)
427|                     self.cell_class = ' '.join(txt)
428|                 case 'css':
429|                     Log.trace('set td CSS {%s}' % txt)
430|                     self.cell_css = txt
431|                 case 'spn':
432|                     Log.trace('set td span "%s"' % txt)
433|                     self._spanner(txt)
434|                 case 'txt':
435|                     for cell in txt:
436|                         Log.trace('set td text "%s"' % cell)
437|                         self._make_cell('td', cell)
438|                 case _:
439|                     Log.trace('Ignore: %s:%s' % (cmd,txt))
440| 
441|     def do_end_0 (self, props):
442|         '''CMND: END.'''
443|         Log.debug('End Table: %s' % str(props))
444|         self._buffer_check()
445| 
446|     def _buffer_check (self):
447|         '''Flush row buffer to section list.'''
448|         # If row buffer is occupied...
449|         if 0 < len(self.curr_row):
450|             # Write the row to the appropriate section...
451|             match self.curr_section:
452|                 case 'thead':
453|                     self.thead.append(self.curr_row)
454|                 case 'tfoot':
455|                     self.tfoot.append(self.curr_row)
456|                 case _:
457|                     self.tbody.append(self.curr_row)
458|             # Reset the current row buffer...
459|             self.curr_row = []
460| 
461|     def _make_cell (self, tag, txt):
462|         '''Make an element from current properties.'''
463|         tcss = self.row_css + self.cell_css
464|         eid = (' id="%s"' % self.cell_id) if 0<len(self.cell_id) else ''
465|         cls = (' class="%s"' % self.cell_class) if 0<len(self.cell_class) else ''
466|         css = (' style="%s"' % tcss) if 0<len(tcss) else ''
467|         spn = ' '.join(self.cell_span) if 0 < len(self.cell_span) else ''
468|         td = ('<%s%s%s%s%s>%s</%s>' % (tag, eid, cls, spn, css, txt, tag))
469|         self.curr_row.append(td)
470|         self.curr_col += 1
471|         self.cell_id = ''
472|         self.cell_class = ''
473|         self.cell_css = ''
474|         self.cell_span = []
475| 
476|     def _spanner (self, lst):
477|         '''Parse the row/col span code and add to current element.'''
478|         if len(lst) == 0:
479|             return
480|         for txt in lst:
481|             match txt[0].upper():
482|                 case 'R':
483|                     Log.trace('set rowspan %d' % int(txt[1]))
484|                     self.cell_span.append(' rowspan="%d"' % int(txt[1]))
485|                 case 'C':
486|                     Log.trace('set colspan %d' % int(txt[1]))
487|                     self.cell_span.append(' colspan="%d"' % int(txt[1]))
488|                 case '_':
489|                     raise RuntimeError('Illegal span code: "%s"' % txt)
490| 
491|     def __str__ (self):
492|         return self.content()
493| 
494|     def __repr__ (self):
495|         t = (typename(self), self.table_id, id(self))
496|         s = '{%s:{tid:"%s", id:%08x}}'
497|         return s%t
498| 
499| 
500| 
501| ##================================================================================================##
502| def do_make_table (**kwargs):
503|     """CMND: Make an HTML table from shorthand input."""
504|     fpath = KWARG('fpath', BasePath, str, kwargs)
505|     fname = KWARG('fname', 'table.html', str, kwargs)
506|     Log.info('make-table:: %s' % str(list(kwargs.keys())))
507|     Log.debug('fpath="%s"' % fpath)
508|     Log.debug('fname="%s"' % fname)
509|     Log.info()
510| 
511|     # Load text from file...
512|     fn = path.join(fpath, fname)
513|     fo = textfile(fn)
514|     fo.load()
515| 
516|     tm = tablemaker(fo.data)
517|     Log.info()
518|     for cmd in tm.cmds:
519|         Log.debug(cmd)
520|     Log.debug()
521| 
522|     html = tm.content()
523|     for line in html.splitlines():
524|         Log.info(line)
525|     Log.info()
526| 
527|     fn = path.join(fpath, '%s.html' % path.splitext(fname)[0])
528|     fo = textfile(fn)
529|     fo.data = tm.content()
530|     fo.save()
531| 
532|     Log.info()
533|     return 'Done'
534| 
535| ##================================================================================================##
536| def do_test (**kwargs):
537|     """Do a test."""
538|     fpath = KWARG('fpath', BasePath, str, kwargs)
539|     fname = KWARG('fname', 'test.out', str, kwargs)
540|     Log.info('test:: %s' % str(list(kwargs.keys())))
541|     Log.debug('fpath="%s"' % fpath)
542|     Log.debug('fname="%s"' % fname)
543|     Log.info()
544|     Log.info()
545|     return 'Done'
546| ####################################################################################################
547| def dispatch (cmd, **kwargs):
548|     """Dispatch to a module function based on CMD."""
549|     Log.info(f'CMD: {cmd}')
550|     for kw in kwargs:
551|         Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
552|     Log.info()
553|     if cmd == 'make': return do_make_table(**kwargs)
554|     if cmd == 'test': return do_test(**kwargs)
555|     return 'Nothing to do!'
556| ####################################################################################################
557| if __name__ == '__main__':
558|     print(f'autorun: {argv[0]}')
559|     Log.start(path.join(BasePath,'tmake.log'))
560|     Log.level(trace())
561|     Log.info(argv[0])
562|     Log.info()
563|     cmd = argv[1] if 1 < len(argv) else CMND
564|     kwargs = ARGS
565|     for a in argv[2:]:
566|         nv = a.split('=', 1)
567|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
568|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
569|     try:
570|         print(f'CMD: {cmd}')
571|         print()
572|         obj = dispatch(cmd, **kwargs)
573|         print()
574|         print(obj)
575|         Log.info()
576|         Log.info(obj)
577|     except:
578|         etype, evalue, tb = exc_info()
579|         ts = extract_tb(tb)
580|         Log.error()
581|         Log.error(f'{etype.__name__}: {evalue!s}')
582|         Log.error()
583|         for t in ts[-5:]:
584|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
585|             Log.error(f' {t[3]}')
586|             Log.error()
587|         raise
588|     finally:
589|         Log.end()
590| ####################################################################################################
591| '''eof'''
592|