Add support for Jira-style tables
dblume

dblume commited on 2024-03-01 23:04:44
Showing 1 changed files, with 13 additions and 6 deletions.

... ...
@@ -1,5 +1,5 @@
1 1
 #!/usr/bin/env python3
2
-from typing import Sequence
2
+from typing import Sequence, Optional
3 3
 
4 4
 __author__ = "David Blume"
5 5
 __copyright__ = "Copyright 2016-2023, David Blume"
... ...
@@ -10,6 +10,7 @@ __status__ = "Development"
10 10
 def print_table(rows: Sequence[Sequence[str]],
11 11
                 underline_header: str='-',
12 12
                 col_delimiter: str="\t",
13
+                header_delimiter: Optional[str]=None,
13 14
                 outside_delimiters: bool=False):
14 15
     """Prints rows with consistent column widths."""
15 16
     cols = zip(*rows)
... ...
@@ -23,7 +24,14 @@ def print_table(rows: Sequence[Sequence[str]],
23 24
         fmt = f"{col_delimiter.lstrip()}{fmt}{col_delimiter.rstrip()}"
24 25
 
25 26
     # Print each row using the computed format
26
-    print(fmt.format(*rows[0]))
27
+    if header_delimiter is not None:
28
+        width_diff = len(header_delimiter) - len(col_delimiter)
29
+        header_fmt = header_delimiter.join(["{:<%d}" % (i - width_diff) for i in col_widths])
30
+        if outside_delimiters:
31
+            header_fmt = f"{header_delimiter.lstrip()}{header_fmt}{header_delimiter.rstrip()}"
32
+    else:
33
+        header_fmt = fmt
34
+    print(header_fmt.format(*rows[0]))
27 35
     if underline_header:
28 36
         if outside_delimiters:
29 37
             print(col_delimiter.lstrip() + col_delimiter.join([(underline_header * i) for i in col_widths]) + col_delimiter.rstrip())
... ...
@@ -41,8 +49,7 @@ if __name__ == '__main__':
41 49
     print()
42 50
     print_table(t)
43 51
     print()
44
-    print_table(t, underline_header='=', col_delimiter="  ")
45
-    print()
46
-    print_table(t, None, col_delimiter=" | ", outside_delimiters=True)
47
-    print()
48 52
     print_table(t, col_delimiter=" | ", outside_delimiters=True)
53
+    print()
54
+    print_table(t, None, col_delimiter=" | ", header_delimiter=" || ",
55
+                outside_delimiters=True)
49 56