create tables from optable.csv
[libreriscv.git] / openpower / sv / rfc / ls012_optable.py
1 #!/usr/bin/env python3
2 # generates markdown tables from CSV files, after doing lovely sorting
3 # by different columns, blah blah...
4 from copy import deepcopy
5
6 def write_mdwn_row(f, row):
7 row = "|".join(row)
8 row = "|%s|\n" % row
9 f.write(row)
10
11 def underlines(header):
12 row = []
13 for col in header:
14 row.append("-" * len(col))
15 return row
16
17 def print_table(title, header, areas, sortby):
18 fname = title.lower().replace(" ", "_")
19 with open("ls012/%s.mdwn" % fname, "w") as f:
20 # write out the page header
21 f.write("\\newpage{}\n")
22 f.write("\n")
23 f.write("# %s\n" % title)
24 f.write("\n")
25 # sort everything if required
26 if sortby is not None:
27 areas = sortby(areas)
28 linecount = None
29 # start writing out areas
30 for title, rows in areas.items():
31 # start new page (if not first newpage)
32 if linecount == 0:
33 f.write("\\newpage{}\n")
34 f.write("\n")
35 if linecount is None: # skipped first newpage
36 linecount = 0
37
38 f.write("## %s\n" % title)
39 f.write("\n")
40
41 # work out maximum length of items, and adjust header
42 hdr = deepcopy(header)
43 cols = {}
44 for hd in hdr:
45 cols[hd] = len(hd)
46 for row in rows:
47 for hd, value in row.items():
48 cols[hd] = max(cols[hd], len(value))
49 # adjust header (add spaces)
50 for i, hd in enumerate(hdr):
51 n_spaces = cols[hd] - len(hd)
52 hdr[i] = hdr[i] + " " * n_spaces
53 # write out header
54 write_mdwn_row(f, hdr)
55 write_mdwn_row(f, underlines(hdr))
56 for row in rows:
57 # adjust row (add same spaces as header width)
58 r = []
59 for (value, col_len) in zip(row.values(), cols.values()):
60 value = value.replace("_", "\_") # latex, duh
61 n_spaces = col_len - len(value)
62 r.append(value + " " * n_spaces)
63 # write row
64 write_mdwn_row(f, r)
65 f.write("\n\n")
66
67 # approx 6 lines per header
68 linecount += 6
69
70 # allow 60 rows per page
71 linecount += len(rows)
72 if linecount >= 60:
73 linecount = 0
74
75 if __name__ == '__main__':
76 with open("ls012/optable.csv") as f:
77 l = map(str.strip, f.readlines())
78 areas = {}
79 header = None
80 for line in l:
81 if line.startswith("#"):
82 area = line[1:].strip()
83 areas[area]= []
84 continue
85 # split line by commas, whitespace-strip it
86 line = list(map(str.strip, line.split(',')))
87 # identify header
88 if header is None:
89 header = line
90 continue
91 # create a dictionary by tuple of header+line
92 linedict = dict(zip(header, line))
93 print (area)
94 print (linedict)
95 print ()
96 # store line in area
97 areas[area].append(linedict)
98
99 # exccellent - now have a dictionary of list of dictionaries:
100 # area - list-of-instructions - dictionary-by-heading
101 print_table("Areas", header, areas, None)
102