-
Notifications
You must be signed in to change notification settings - Fork 1
/
tabtotext.py
executable file
·3670 lines (3571 loc) · 159 KB
/
tabtotext.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
"""
This script allows to format table-like data (list of dicts).
The various output formats can be read back. The file extension will
usally define the format. ==> ".md" is Github Flavourd Markdown.
".txt" is compressed markdown table, ".wide" is space-only markdown,
".html" is Html Table, ".htm" without table borders, ".xhtml" with xmlns block,
".xlsx" as Excel if openpyxl is available (or tabxlsx fallback),
".tab" is tab-seperated csv, ".tabs" with markdown alignment,
".csv" is semicolon csv, ".list" without headers,
and ".dat" files use $IFS as tabulator (like bash 'read').
"""
__copyright__ = "(C) 2017-2024 Guido Draheim, licensed under the Apache License 2.0"""
__version__ = "1.6.3361"
from typing import Optional, Union, Dict, List, Any, Sequence, Callable, Type, cast, Tuple, Iterable, Iterator, TextIO, NamedTuple
from collections import OrderedDict
from html import escape
from datetime import date as Date
from datetime import datetime as Time
from datetime import timezone as TimeZone
from datetime import timedelta as Plus
from abc import abstractmethod
import os
import sys
import re
import logging
import json
from io import StringIO, TextIOWrapper
logg = logging.getLogger("TABTOTEXT")
try:
from tabtools import Frac4, fracfloat, float_with_frac, float_with_hours
except ImportError as e: # pragma: no cover
logg.warning("can not import tabtools, fallback to Frac4 with {.2f}, %s", e)
class Frac4: # type: ignore[no-redef]
def __init__(self, value: float) -> None:
self.value = value
def __format__(self, fmt: str) -> str:
value = self.value
if fmt and fmt[-1] in "HhqQMR$":
fmt = ".2f"
num = "{:" + fmt + "}"
return fmt.format(value)
def fracfloat(value: str) -> float:
return float(value)
SECTION = "data"
DATEFMT = "%Y-%m-%d"
TIMEFMT = "%Y-%m-%d.%H%M"
FLOATFMT = "%4.2f"
NORIGHT = False
MINWIDTH = 5
NIX = ""
STRLIST: List[str] = []
COL_SEP = "|"
TABXLSX = False
JSONData = Union[str, int, float, bool, Date, Time, None]
JSONBase = Union[str, int, float, bool]
JSONItem = Union[str, int, float, bool, Date, Time, None, Dict[str, Any], List[Any]]
JSONDict = Dict[str, JSONItem]
JSONList = List[JSONDict]
JSONDictList = Dict[str, JSONList]
JSONDictDict = Dict[str, JSONDict]
# dataclass support
class DataItem:
""" Use this as the base class for dataclass types """
def __getitem__(self, name: str) -> JSONItem:
return cast(JSONItem, getattr(self, name))
def replace(self, **values: str) -> JSONDict:
return _dataitem_replace(self, values) # type: ignore[arg-type]
DataList = List[DataItem]
def _is_dataitem(obj: Any) -> bool:
if isinstance(obj, DataItem):
return True
if hasattr(obj, '__dataclass_fields__'):
return True
return False
def _dataitem_asdict(obj: DataItem, dict_factory: Type[Dict[str, Any]] = dict) -> JSONDict:
if hasattr(obj, "keys"):
return cast(JSONDict, obj)
result: JSONDict = dict_factory()
annotations: Dict[str, str] = obj.__class__.__dict__.get('__annotations__', {})
for name in annotations:
result[name] = cast(JSONItem, getattr(obj, name))
return result
def _dataitem_replace(obj: DataItem, values: JSONDict, dict_factory: Type[Dict[str, Any]] = dict) -> JSONDict:
result: JSONDict = dict_factory()
annotations: Dict[str, str] = obj.__class__.__dict__.get('__annotations__', {})
for name in annotations:
if name in values:
result[name] = values[name]
else:
result[name] = cast(JSONItem, getattr(obj, name))
return result
# Files can contain multiple tables which get represented as a list of sheets where
# each sheet remembers the title and the order columns in the original table. This allows
# to convert file formats with the order of tables, columns (and rows) being preserved.
class TabSheet(NamedTuple):
data: List[JSONDict]
headers: List[str]
title: str
def tablistfor(tabdata: Dict[str, List[JSONDict]]) -> List[TabSheet]:
tablist: List[TabSheet] = []
for name, data in tabdata.items():
tablist += [TabSheet(data, [], name)]
return tablist
def tablistitems(tablist: List[TabSheet]) -> Iterator[Tuple[str, List[JSONDict]]]:
for tabsheet in tablist:
yield tabsheet.title, tabsheet.data
def tablistmap(tablist: List[TabSheet]) -> Dict[str, List[JSONDict]]:
tabdata: Dict[str, List[JSONDict]] = OrderedDict()
for name, data in tablistitems(tablist):
tabdata[name] = data
return tabdata
# helper functions
_None_String = "~"
_False_String = "(no)"
_True_String = "(yes)"
def setNoRight(value: bool) -> None:
global NORIGHT
NORIGHT = value
def str77(value: JSONItem, maxlength: int = 77) -> str:
assert maxlength > 10
if value is None:
return _None_String
val = str(value)
if len(val) > maxlength:
return val[:(maxlength - 10)] + "..." + val[-7:]
return val
def str40(value: JSONItem) -> str:
return str77(value, 40)
def str27(value: JSONItem) -> str:
return str77(value, 27)
def str18(value: JSONItem) -> str:
return str77(value, 18)
def strNone(value: Any, datedelim: str = '-', datefmt: Optional[str] = None) -> str:
return strJSONItem(value, datedelim, datefmt)
def strJSONItem(value: JSONItem, datedelim: str = '-', datefmt: Optional[str] = None) -> str:
if value is None:
return _None_String
if value is False:
return _False_String
if value is True:
return _True_String
if isinstance(value, Time):
datefmt1 = datefmt if datefmt else DATEFMT
datefmt2 = datefmt1.replace('-', datedelim)
if "Z" in DATEFMT:
return value.astimezone(TimeZone.utc).strftime(datefmt2)
else:
return value.strftime(datefmt2)
if isinstance(value, Date):
datefmt1 = datefmt if datefmt else DATEFMT
datefmt2 = datefmt1.replace('-', datedelim)
return value.strftime(datefmt2)
return str(value)
def unmatched(value: JSONItem, cond: str) -> bool:
try:
if value is None or value is False or value is True:
if len(cond) >= 2 and cond[:2] in ["==", "=~", "<=", ">="]:
if cond[2:] in ["1", "True", "true", "yes", "(yes)", "*", "+"]:
cond = cond[:2] + "1"
if cond[2:] in ["0", "False", "false", "no", "(no)", "", "-", "~"]:
cond = cond[:2] + "0"
elif len(cond) >= 1 and cond[:1] in ["<", ">"]:
if cond[1:] in ["1", "True", "true", "yes", "(yes)", "*", "+"]:
cond = cond[:1] + "1"
if cond[1:] in ["0", "False", "false", "no", "(no)", "", "-", "~"]:
cond = cond[:1] + "0"
if value is True:
value = 1
else:
value = 0
if isinstance(value, Time) or isinstance(value, Date):
value = value.strftime(DATEFMT)
if isinstance(value, int) or isinstance(value, float):
eps = 0.005 # adding epsilon converts int-value to float-value
if cond.startswith("=~"):
return value - eps > float(cond[2:]) or float(cond[2:]) > value + eps
if cond.startswith("<>"):
return value - eps < float(cond[2:]) and float(cond[2:]) < value + eps
if cond.startswith("==") or cond.startswith("=~"):
return float(value) != float(cond[2:]) # not recommended
if cond.startswith("<="):
return value - eps > float(cond[2:])
if cond.startswith("<"):
return value + eps >= float(cond[1:])
if cond.startswith(">="):
return value + eps < float(cond[2:])
if cond.startswith(">"):
return value - eps <= float(cond[1:])
else:
if cond.startswith("=~"):
return str(value) != cond[2:]
if cond.startswith("=="):
return str(value) != cond[2:]
if cond.startswith("<>"):
return str(value) == cond[2:]
if cond.startswith("<="):
return str(value) > cond[2:]
if cond.startswith("<"):
return str(value) >= cond[1:]
if cond.startswith(">="):
return str(value) < cond[2:]
if cond.startswith(">"):
return str(value) <= cond[1:]
except Exception as e:
logg.warning("unmatched value %s does not work for cond (*%s)", type(value), cond)
return False
############################################################
def sec_usec(sec: Optional[str]) -> Tuple[int, int]:
""" split float value to seconds and microsecond integers"""
if not sec:
return 0, 0
if "." in sec:
x = float(sec)
s = int(x)
u = int((x - s) * 1000000)
return s, u
return int(sec), 0
class StrToDate:
""" parsing iso8601 day formats"""
def __init__(self, datedelim: str = "-") -> None:
self.delim = datedelim
self.is_date = re.compile(r"(\d\d\d\d)-(\d\d)-(\d\d)[.]?$".replace('-', datedelim))
self.is_part = re.compile(r"(\d\d\d\d)-(\d\d)-(\d\d)[^\d].*".replace('-', datedelim))
def date(self, value: str) -> Optional[Date]:
got = self.is_date.match(value)
if got:
y, m, d = got.group(1), got.group(2), got.group(3)
return Date(int(y), int(m), int(d))
return None
def datepart(self, value: str) -> Optional[Date]:
got = self.is_part.match(value)
if got:
y, m, d = got.group(1), got.group(2), got.group(3)
return Date(int(y), int(m), int(d))
return None
def __call__(self, value: str) -> Union[str, Date, Time]:
d = self.date(value)
if d: return d
p = self.datepart(value)
if p: return p
return value
class StrToTime(StrToDate):
""" parsing iso8601 day or day-and-time formats with zone offsets"""
def __init__(self, datedelim: str = "-") -> None:
StrToDate.__init__(self, datedelim)
self.is_localtime = re.compile(
r"(\d\d\d\d)-(\d\d)-(\d\d)[.T ](\d\d)[:]?(\d\d)(?:[:](\d\d(?:[.]\d*)?))?$".replace('-', datedelim))
self.is_zonetime = re.compile(
r"(\d\d\d\d)-(\d\d)-(\d\d)[.T ](\d\d)[:]?(\d\d)(?:[:](\d\d(?:[.]\d*)?))?[ ]*(Z|UTC|[+-][0-9][0-9])(?:[:]?([0-9][0-9]))?$".replace('-', datedelim))
def time(self, value: str) -> Optional[Time]:
got = self.is_localtime.match(value)
if got:
y, m, d, H, M, S = got.group(1), got.group(2), got.group(3), got.group(4), got.group(5), got.group(6)
return Time(int(y), int(m), int(d), int(H), int(M), *sec_usec(S))
got = self.is_zonetime.match(value)
if got:
hh, mm = got.group(7), got.group(8)
if hh in ["Z", "UTC"]:
plus = TimeZone.utc
else:
plus = TimeZone(Plus(hours=int(hh), minutes=int(mm or 0)))
y, m, d, H, M, S = got.group(1), got.group(2), got.group(3), got.group(4), got.group(5), got.group(6)
return Time(int(y), int(m), int(d), int(H), int(M), *sec_usec(S), tzinfo=plus)
return None
def __call__(self, value: str) -> Union[str, Date, Time]:
d = self.date(value)
if d: return d
t = self.time(value)
if t: return t
return value
class DictParser:
@abstractmethod
def load(self, filename: str) -> Iterator[JSONDict]:
while False:
yield {}
@abstractmethod
def scan(self, text: str) -> Iterator[JSONDict]:
while False:
yield {}
class TabListParser:
@abstractmethod
def load(self, filename: str) -> Iterator[TabSheet]:
while False:
yield {}
@abstractmethod
def scan(self, text: str) -> Iterator[TabSheet]:
while False:
yield {}
class FormatJSONItem:
@abstractmethod
def __call__(self, col: str, val: JSONItem) -> str:
return ""
def right(self, col: str) -> bool:
return False
FormatsDict = Union[FormatJSONItem, Dict[str, str]]
class BaseFormatJSONItem(FormatJSONItem):
def __init__(self, formats: Dict[str, str], **kwargs: Any) -> None:
self.formats = formats
self.datedelim = '-'
self.datefmt = DATEFMT
self.kwargs = kwargs
self.formatleft = re.compile("[{]:[^{}]*<[^{}]*[}]")
self.formatright = re.compile("[{]:[^{}]*>[^{}]*[}]")
self.formatnumber = re.compile("[{]:[^{}]*[defghDEFGHMQR$%][}]")
def right(self, col: str) -> bool:
if col in self.formats and not NORIGHT:
if self.formats[col].startswith(" "):
return True
if self.formats[col].startswith("{: "):
return True
if self.formatleft.search(self.formats[col]):
return False
if self.formatright.search(self.formats[col]):
return True
if self.formatnumber.search(self.formats[col]):
return True
return False
def __call__(self, col: str, val: JSONItem) -> str:
return self.item(val)
def item(self, val: JSONItem) -> str:
return strJSONItem(val, self.datedelim, self.datefmt)
class ParseJSONItem:
def __init__(self, datedelim: str = '-') -> None:
self.is_int = re.compile(r"([+-]?\d+)$")
self.is_float = re.compile(r"([+-]?\d+)(?:[.]\d*)?(?:e[+-]?\d+)?$")
self.is_float_with_frac = re.compile(float_with_frac)
self.is_float_with_hours = re.compile(float_with_hours)
self.datedelim = datedelim
self.None_String = _None_String
self.False_String = _False_String
self.True_String = _True_String
self.toDate = StrToTime(datedelim)
def toJSONItem(self, val: str) -> JSONItem:
""" generic conversion of string to data types - it may do too much """
if val == self.None_String:
return None
if val == self.False_String:
return False
if val == self.True_String:
return True
if self.is_int.match(val):
return int(val)
if self.is_float.match(val):
return float(val)
if self.is_float_with_frac.match(val):
return fracfloat(val)
if self.is_float_with_hours.match(val):
return fracfloat(val)
return self.toDate(val)
def tabWithDateTime() -> None:
global DATEFMT
DATEFMT = "%Y-%m-%dT%H:%M:%S"
def tabWithDateHour() -> None:
global DATEFMT
DATEFMT = "%Y-%m-%d.%H%M"
def tabWithDateZulu() -> None:
global DATEFMT
DATEFMT = "%Y-%m-%dZ%H%M"
def tabWithDateOnly() -> None:
global DATEFMT
DATEFMT = "%Y-%m-%d"
# ================================= sorting
RowSortList = Union[Sequence[str], Dict[str, str], Callable[[JSONDict], str]]
class RowSortCallable:
""" The column names in the sorts-list are used here for one of their
functions as sorting the rows of the table by returning a sort-string
from the record. You can override that with a callable but then it
can not be used anymore with its double function to also move the
sort-columns to the left of the table. See 'reorder' below."""
def __init__(self, sorts: RowSortList, datedelim: str = '-') -> None:
""" only a few tabto-functions have a local datedelim to pass"""
self.sorts = sorts
self.datedelim = datedelim
def __call__(self, item: JSONDict) -> str:
""" makes the class to be of type Callable[[JSONDict], str] """
sorts = self.sorts
if callable(sorts):
return sorts(item)
else:
sortvalue = ""
for sort in sorts:
# numbers before empty before strings
if "@" in sort:
col, rename = sort.split("@", 1)
else:
col = sort
if col in item:
value = item[col]
if value is None:
sortvalue += "\n?"
elif value is False:
sortvalue += "\n"
elif value is True:
sortvalue += "\n!"
elif isinstance(value, int):
val = "%i" % value
sortvalue += "\n" + (":" * len(val)) + val
elif isinstance(value, float):
val = "%.6f" % value
sortvalue += "\n" + (":" * val.index(".")) + val
elif isinstance(value, Time):
sortvalue += "\n" + value.strftime("%Y%m%d.%H%MS")
elif isinstance(value, Date):
sortvalue += "\n" + value.strftime("%Y%m%d")
else:
sortvalue += "\n" + str(value)
else:
sortvalue += "\n?"
return sortvalue
ColSortList = Union[Sequence[str], Dict[str, str], Callable[[str], str]]
class ColSortCallable:
""" The column names in the sorts-list always had a double function: sorting
the rows, and the sorting columns are reordered to the left of the table.
The latter can be overridden by specifying a reorder-list of colum names,
plus that one can be a function that returns the reordering key. """
def __init__(self, sorts: RowSortList, reorder: ColSortList = []) -> None:
self.sorts = sorts
self.reorder = reorder
def __call__(self, header: str) -> str:
""" makes the class to be of type Callable[[str], str] """
reorder = self.reorder
if callable(reorder):
return reorder(header)
else:
sortheaders = reorder
sorts = self.sorts
if not sortheaders and not callable(sorts):
sortheaders = sorts
if isinstance(sortheaders, dict):
if header in sortheaders:
return sortheaders[header]
else:
if header in sortheaders:
num = sortheaders.index(header)
return ("@" * len(str(num)) + str(num))
return header
LegendList = Union[Dict[str, str], Sequence[str]]
# ================================= #### GFM
class NumFormatJSONItem(BaseFormatJSONItem):
def __init__(self, formats: Dict[str, str] = {}, tab: str = '|'):
BaseFormatJSONItem.__init__(self, formats)
self.floatfmt = FLOATFMT
def __call__(self, col: str, val: JSONItem) -> str:
if col in self.formats:
fmt = self.formats[col]
if fmt.startswith("{:") and fmt[-1] == "}" and "%s" in fmt:
fmt = fmt[2:-1].replace("%s", "{:s}")
if fmt.startswith("{:%") and fmt[-1] == "}" and fmt[-2] in "sf":
fmt = fmt.replace("{:%", "{:")
if "{:" in fmt:
for fmt4 in fmt.split("|"):
val4 = val
q = fmt4.rindex("}")
if q > 0 and fmt4[q - 1] in "hHqQM$":
val4 = Frac4(val) # type: ignore[assignment,arg-type]
try:
return fmt4.format(val4)
except Exception as e:
logg.debug("format <%s> does not apply: %s", fmt, e)
# only a few percent-formatting variants are supported
if isinstance(val, float):
m = re.search(r"%\d(?:[.]\d)f", fmt)
if m:
try:
return fmt % val
except Exception as e:
logg.debug("format <%s> does not apply: %e", fmt, e)
logg.debug("unknown format '%s' for col '%s'", fmt, col)
if isinstance(val, float):
return self.floatfmt % val
return self.item(val)
class FormatGFM(NumFormatJSONItem):
def __init__(self, formats: Dict[str, str] = {}, tab: str = '|'):
NumFormatJSONItem.__init__(self, formats)
self.tab = tab
def __call__(self, col: str, val: JSONItem) -> str:
if not self.tab:
return NumFormatJSONItem.__call__(self, col, val)
tab = self.tab
esc1 = "\\"
esc2 = "\\\\"
esc3 = tab[0] if tab else "\\"
esc4 = "\\" + tab[0] if tab else "\\"
esc7 = "\n"
esc8 = "\\\n"
return NumFormatJSONItem.__call__(self, col, val).replace(esc1, esc2).replace(esc3, esc4).replace(esc7, esc8)
def tabToGFMx(result: Union[JSONList, JSONDict, DataList, DataItem], # ..
sorts: Sequence[str] = [], formats: FormatsDict = {}, selected: List[str] = [], # ..
*, noheaders: bool = False, legend: LegendList = [], tab: str = "|", padding: str = " ",
section: str = NIX) -> str:
if isinstance(result, Dict):
results = [result]
elif _is_dataitem(result):
results = [_dataitem_asdict(cast(DataItem, result))]
elif hasattr(result, "__len__") and len(cast(List[Any], result)) and (_is_dataitem(cast(List[Any], result)[0])):
results = list(_dataitem_asdict(cast(DataItem, item)) for item in cast(List[Any], result))
else:
results = cast(JSONList, result)
return tabToGFM(results, sorts, formats, selected, noheaders=noheaders, legend=legend, tab=tab, padding=padding, section=section)
def tabToGFM(result: Iterable[JSONDict], # ..
sorts: RowSortList = [], formats: FormatsDict = {}, selected: List[str] = [], # ..
*, noheaders: bool = False, legend: LegendList = [], tab: str = "|", padding: str = " ",
section: str = NIX, reorder: ColSortList = []) -> str:
""" old-style RowSortList and FormatsDict assembled into headers with microsyntax """
headers: List[str] = []
sorting: RowSortList = []
formatter: FormatsDict = {}
if isinstance(sorts, Sequence) and isinstance(formats, dict):
sortheaders: List[str] = []
for header in sorts:
cols: List[str] = []
for headercol in header.split("|"):
if "@" in headercol:
name, suffix = headercol.split("@", 1)
if suffix:
renames = "@" + suffix
else:
name, renames = headercol, ""
sortheaders += [name]
if name in formats:
cols += [name + ":" + formats[name] + renames]
else:
cols += [name + renames]
headers += ["|".join(cols)]
logg.info("headers = %s", headers)
logg.info("sorting = %s", sortheaders)
sorting = sortheaders
else:
sorting = sorts
formatter = formats
return tabtoGFM(result, headers, selected, legend=legend, # ..
noheaders=noheaders, tab=tab, padding=padding, # ..
section=section, reorder=reorder, sorts=sorting, formatter=formatter)
def tabtoGFM(data: Iterable[JSONDict], headers: List[str] = [], selected: List[str] = [], # ..
*, legend: LegendList = [], minwidth: int = 0, noheaders: bool = False, unique: bool = False,
tab: str = "|", padding: str = " ", section: str = NIX,
reorder: ColSortList = [], sorts: RowSortList = [], formatter: FormatsDict = {}) -> str:
logg.debug("tabtoGFM:")
minwidth = minwidth or MINWIDTH
renameheaders: Dict[str, str] = {}
showheaders: List[str] = []
sortheaders: List[str] = []
formats: Dict[str, str] = {}
combine: Dict[str, List[str]] = {}
freehdrs: Dict[str, str] = {}
for header in headers:
combines = ""
for headercol in header.split("|"):
if "@" in headercol:
selcol, rename = headercol.split("@", 1)
else:
selcol, rename = headercol, ""
if "{" in selcol and "{:" not in selcol:
names3: List[str] = []
freeparts = selcol.split("{")
for freepart in freeparts[1:]:
colon3, brace3 = freepart.find(":"), freepart.find("}")
if brace3 == -1:
logg.error("no closing '}' for '{%s' in %s", freepart, selcol)
continue
end3 = brace3 if colon3 == -1 else min(colon3, brace3)
name3 = freepart[:end3]
names3.append(name3)
name = " ".join(names3)
freehdrs[name] = selcol
elif ":" in selcol:
name, form = selcol.split(":", 1)
if isinstance(formats, dict):
fmts = form if "{" in form else ("{:" + form + "}")
formats[name] = fmts.replace("i}", "n}").replace("u}", "n}").replace("r}", "s}").replace("a}", "s}")
else:
name = selcol
showheaders += [name] # headers make a default column order
if rename:
sortheaders += [name] # headers does not sort anymore
if not combines:
combines = name
elif combines not in combine:
combine[combines] = [name]
elif name not in combine[combines]:
combine[combines] += [name]
if rename:
renameheaders[name] = rename
logg.debug("renameheaders = %s", renameheaders)
logg.debug("sortheaders = %s", sortheaders)
logg.debug("formats = %s", formats)
logg.debug("combine = %s", combine)
logg.debug("freehdrs = %s", freehdrs)
combined: Dict[str, List[str]] = {}
renaming: Dict[str, str] = {}
filtered: Dict[str, str] = {}
selcols: List[str] = []
freecols: Dict[str, str] = {}
for selecheader in selected:
combines = ""
for selec in selecheader.split("|"):
if "@" in selec:
selcol, rename = selec.split("@", 1)
else:
selcol, rename = selec, ""
if "{" in selcol and "{:" not in selcol:
names4: List[str] = []
freeparts = selcol.split("{")
for freepart in freeparts[1:]:
colon4, brace4 = freepart.find(":"), freepart.find("}")
if brace4 == -1:
logg.error("no closing '}' for '{%s' in %s", freepart, selcol)
continue
end4 = brace4 if colon4 == -1 else min(colon4, brace4)
name4 = freepart[:end4]
names4.append(name4)
name = " ".join(names4)
freecols[name] = selcol
elif ":" in selcol:
name, form = selcol.split(":", 1)
fmts = form if "{" in form else ("{:" + form + "}")
formats[name] = fmts.replace("i}", "n}").replace("u}", "n}").replace("r}", "s}").replace("a}", "s}")
else:
name = selcol
if "<" in name:
name, cond = name.split("<", 1)
filtered[name] = "<" + cond
elif ">" in name:
name, cond = name.split(">", 1)
filtered[name] = ">" + cond
elif "=" in name:
name, cond = name.split("=", 1)
filtered[name] = "=" + cond
selcols.append(name)
if rename:
renaming[name] = rename
if not combines:
combines = name
elif combines not in combined:
combined[combines] = [name]
elif combines not in combined[combines]:
combined[combines] += [name]
logg.debug("combined = %s", combined)
logg.debug("renaming = %s", renaming)
logg.debug("filtered = %s", filtered)
logg.debug("selcols = %s", selcols)
logg.debug("freecols = %s", freecols)
if not selected:
combined = combine # argument
freecols = freehdrs
renaming = renameheaders
logg.debug("combined : %s", combined)
logg.debug("freecols : %s", freecols)
logg.debug("renaming : %s", renaming)
newsorts: Dict[str, str] = {}
colnames: Dict[str, str] = {}
for name, rename in renaming.items():
if "@" in rename:
newname, newsort = rename.split("@", 1)
elif rename and rename[0].isalpha():
newname, newsort = rename, ""
else:
newname, newsort = "", rename
if newname:
colnames[name] = newname
if name in formats:
formats[newname] = formats[name]
if newsort:
newsorts[name] = newsort
logg.debug("newsorts = %s", newsorts)
logg.debug("colnames = %s", colnames)
if sorts:
sortcolumns = sorts
else:
sortcolumns = [(name if name not in colnames else colnames[name]) for name in (selcols or sortheaders)]
if newsorts:
for num, name in enumerate(sortcolumns):
if name not in newsorts:
newsorts[name] = ("@" * len(str(num)) + str(num))
sortcolumns = sorted(newsorts, key=lambda x: newsorts[x])
logg.debug("sortcolumns : %s", sortcolumns)
else:
logg.debug("sortcolumns = %s", sortcolumns)
format: FormatJSONItem
if formatter and isinstance(formatter, FormatJSONItem):
format = formatter
else:
logg.debug("formats = %s | tab=%s", formats, tab)
format = FormatGFM(formats, tab=tab)
selcolumns = [(name if name not in colnames else colnames[name]) for name in (selcols)]
selheaders = [(name if name not in colnames else colnames[name]) for name in (showheaders)]
sortkey = ColSortCallable(selcolumns or sorts or selheaders, reorder)
sortrow = RowSortCallable(sortcolumns)
rows: List[JSONDict] = []
cols: Dict[str, int] = {}
for num, item in enumerate(data):
row: JSONDict = {}
if "#" in selcols:
row["#"] = num + 1
cols["#"] = len(str(num + 1))
skip = False
for name, value in item.items():
selname = name
if name in renameheaders and renameheaders[name] in selcols:
selname = renameheaders[name]
if selcols and selname not in selcols and "*" not in selcols:
continue
try:
if name in filtered:
skip = skip or unmatched(value, filtered[name])
except: pass
colname = selname if selname not in colnames else colnames[selname]
row[colname] = value
oldlen = cols[colname] if colname in cols else max(minwidth, len(colname))
cols[colname] = max(oldlen, len(format(colname, value)))
for freecol, freeformat in freecols.items():
try:
freenames = freecol.split(" ")
freeitem: JSONDict = dict([(freename, _None_String) for freename in freenames])
for name, value in item.items():
itemname = name
if name in renameheaders and renameheaders[name] in freenames:
itemname = renameheaders[name]
if itemname in freenames:
freeitem[itemname] = format(name, value)
value = freeformat.format(**freeitem)
colname = freecol if freecol not in colnames else colnames[freecol]
row[colname] = value
oldlen = cols[colname] if colname in cols else max(minwidth, len(colname))
cols[colname] = max(oldlen, len(value))
except Exception as e:
logg.info("formatting '%s' at %s bad for:\n\t%s", freeformat, e, item)
if not skip:
rows.append(row)
ws = ("", " ", " ", " ", " ", " ", " ", " ", " ") # " "*(0...8)
colo = tuple(sorted(cols.keys(), key=sortkey)) # ordered column names
colw = tuple((cols[col] for col in colo)) # widths of cols ordered
colr = tuple((format.right(col) for col in colo)) # rightalign of cols ordered
tab2 = tab[0] + padding if tab else ""
rtab = padding + tab[1] if len(tab) > 1 else ""
lines: List[str] = []
if section:
lines += [F"\n## {section}"]
if not noheaders:
hpad = [(ws[w] if w < 9 else (" " * w)) for w in ((colw[m] - len(col)) for m, col in enumerate(colo))]
line = [tab2 + (hpad[m] + col if colr[m] else col + hpad[m]) for m, col in enumerate(colo)]
if rtab:
lines += [(padding.join(line)) + rtab]
else:
lines += [(padding.join(line)).rstrip()]
if tab and padding:
seps = ["-" * colw[m] for m, col in enumerate(colo)]
seperators = [tab2 + (seps[m][:-1] + ":" if colr[m] else seps[m]) for m, col in enumerate(colo)]
lines += [padding.join(seperators) + rtab]
old: Dict[str, str] = {}
same: List[str] = []
for item in sorted(rows, key=sortrow):
values: Dict[str, str] = {}
for name, value in item.items():
values[name] = format(name, value)
vals = [values.get(col, _None_String) for col in colo]
vpad = [(ws[w] if w < 9 else (" " * w)) for w in ((colw[m] - len(vals[m])) for m, col in enumerate(colo))]
line = [tab2 + (vpad[m] + vals[m] if colr[m] else vals[m] + vpad[m]) for m, col in enumerate(colo)]
if unique:
same = [sel for sel in selcols if sel in values and sel in old and values[sel] == old[sel]]
if not selcols or same != selcols:
if rtab:
lines.append((padding.join(line)) + rtab)
else:
lines.append((padding.join(line)).rstrip())
old = values
return "\n".join(lines) + "\n" + legendToGFM(legend, sorts, reorder)
def legendToGFM(legend: LegendList, sorts: RowSortList = [], reorder: ColSortList = []) -> str:
sortkey = ColSortCallable(sorts, reorder)
if isinstance(legend, dict):
lines = []
for key in sorted(legend.keys(), key=sortkey):
line = "%s: %s" % (key, legend[key])
lines.append(line)
return listToGFM(lines)
elif isinstance(legend, str):
return listToGFM([legend])
else:
return listToGFM(legend)
def listToGFM(lines: Sequence[str]) -> str:
if not lines: return ""
return "\n" + "".join(["- %s\n" % line.strip() for line in lines if line and line.strip()])
def loadGFM(text: str, datedelim: str = '-', tab: str = '|', section: str = NIX) -> JSONList:
parser = DictParserGFM(datedelim=datedelim, tab=tab, section=section)
return list(parser.scan(text))
def readFromGFM(filename: str, datedelim: str = '-', tab: str = '|', section: str = NIX) -> JSONList:
parser = DictParserGFM(datedelim=datedelim, tab=tab, section=section)
return list(parser.load(filename))
def tablistfileGFM(filename: str, datedelim: str = '-', tab: str = '|', section: str = NIX) -> List[TabSheet]:
parser = TabListParserGFM(datedelim=datedelim, tab=tab, section=section)
return list(parser.load(filename))
def tablistscanGFM(text: str, datedelim: str = '-', tab: str = '|', section: str = NIX) -> List[TabSheet]:
parser = TabListParserGFM(datedelim=datedelim, tab=tab, section=section)
return list(parser.scan(text))
class DictParserGFM(DictParser):
def __init__(self, section: str = NIX, *, datedelim: str = '-', tab: str = '|') -> None:
self.convert = ParseJSONItem(datedelim)
if tab in ["", "\n"]:
raise AssertionError("Markdown Parser needs tab delimiter")
self.tab = tab or '|'
self.section = section
self.headers = STRLIST
def load(self, filename: str, *, tab: Optional[str] = None) -> Iterator[JSONDict]:
return self.read(open(filename))
def scan(self, text: str, *, tab: Optional[str] = None) -> Iterator[JSONDict]:
return self.read(text.splitlines())
def read(self, rows: Iterable[str], *, tab: Optional[str] = None) -> Iterator[JSONDict]:
if tab in ["", "\n"]:
raise AssertionError("Markdown Parser needs tab delimiter")
tab = tab[0] if tab else self.tab[0] # field seperator
igs = chr(0x1D) # ascii/ebcdic group seperator
at = "start"
pre = ""
for row in rows:
line = row.rstrip().replace(igs, tab)
if "\\" in line:
esc = line.split("\\")
if esc[-1] == "":
pre = line # line continuation
continue
if pre:
line = pre + "\n" + line
pre = ""
if "\\" in line:
groups = [("\\" if not g else igs + g[1:] if g.startswith(tab) else g) for g in ("\n" + line).split("\\")]
line = ("".join(groups))[1:]
# check decoded row
logg.debug("line = %s", line.replace(igs, "{tab}").replace("\n", "{br}"))
if not line or line.startswith("#"):
continue
if not line or line.startswith("- "):
continue
if line.startswith(tab) or (tab in "\t" and tab in line):
if at == "start":
cols = [name.strip().replace(igs, tab) for name in line.split(tab)]
at = "header"
self.headers = cols
continue
if at == "header":
newcols = [name.strip().replace(igs, tab) for name in line.split(tab)]
if len(newcols) != len(cols):
logg.error("header divider has not the same length")
at = "data" # promote anyway
continue
at = "divider"
# fallthrough
if at == "divider":
ok = True
for col in newcols:
if not col: continue
if not re.match(r"^ *:*--*:* *$", col):
logg.warning("no header divider: %s", col)
ok = False
if not ok:
at = "data"
# fallthrough
else:
at = "data"
continue
if at == "data":
values = [field.strip().replace(igs, tab) for field in line.split(tab)]
record = []
for value in values:
record.append(self.convert.toJSONItem(value.strip()))
newrow = dict(zip(cols, record))
if "" in newrow:
del newrow[""]
yield newrow
else:
logg.warning("unrecognized line: %s", line.replace(tab, "|"))
class TabListParserGFM(TabListParser):
def __init__(self, section: str = NIX, *, datedelim: str = '-', tab: str = '|') -> None:
self.convert = ParseJSONItem(datedelim)
if tab in ["", "\n"]:
raise AssertionError("Markdown Parser needs tab delimiter")
self.tab = tab or "|"
self.section = section
self.headers = STRLIST
def load(self, filename: str, *, tab: Optional[str] = None) -> Iterator[TabSheet]:
return self.read(open(filename), tab=tab)
def scan(self, text: str, *, tab: Optional[str] = None) -> Iterator[TabSheet]:
return self.read(text.splitlines(), tab=tab)
def read(self, lines: Iterable[str], *, tab: Optional[str] = None) -> Iterator[TabSheet]:
if tab in ["", "\n"]:
raise AssertionError("Markdown Parser needs tab delimiter")
tab = tab[0] if tab else self.tab[0] # field seperator
igs = chr(0x1D) # ascii/ebcdic group seperator
tabs: List[TabSheet] = []
data: List[JSONDict] = []
# must have headers
lookingfor = "headers"
headers: List[str] = []
title = ""
pre = ""
for line in lines:
if "\\" in line:
esc = line.rstrip().split("\\")
if esc[-1] == "":
pre = line.rstrip() # line continuation
continue
if pre:
line = pre + "\n" + line
pre = ""
if "\\" in line:
groups = [("\\" if not g else igs + g[1:] if g.startswith(tab) else g) for g in ("\n" + line).split("\\")]
line = ("".join(groups))[1:]
# check decoded row
logg.info("line = %s", line.replace(igs, "{tab}").replace("\n", "{br}"))
if not line.rstrip() or (tab and not line.startswith(tab)):
if headers:
if not title:
title = "-%s" % (len(tabs) + 1)
yield TabSheet(data, headers, title)
title = ""
headers = []
data = []
lookingfor = "headers"
if line.startswith("## "):
title = line[3:].strip().replace(igs, tab)
continue
vals = [tad.strip().replace(igs, tab) for tad in line.split(tab)]
if tab:
del vals[0]
if lookingfor == "headers":
headers = [header.strip() for header in vals]
lookingfor = "divider"
continue
elif lookingfor == "divider":
lookingfor = "data"
if re.match(r"^ *:*--*:* *$", vals[0]):
continue
record: JSONDict = {}
for col, val in enumerate(vals):
v = val.strip()
if v == _None_String:
record[headers[col]] = None
elif v == _False_String:
record[headers[col]] = False
elif v == _True_String:
record[headers[col]] = True
else:
try:
record[headers[col]] = int(v)
except:
record[headers[col]] = self.convert.toDate(v)
data.append(record)
if headers:
if not title:
title = "-%s" % (len(tabs) + 1)
yield TabSheet(data, headers, title)
# ================================= #### HTML
class FormatHTML(NumFormatJSONItem):
def __init__(self, formats: Dict[str, str] = {}):
NumFormatJSONItem.__init__(self, formats)