whitespace
[libreriscv.git] / openpower / mdwn_inline.py
1 #!/usr/bin/env python3
2 import sys
3 import os.path
4 from io import StringIO
5
6 deps_only = sys.argv[1] == '--deps'
7
8 if deps_only:
9 del sys.argv[1]
10
11 opened_files = []
12
13 def open_tracked(name, mode='r'):
14 opened_files.append(name)
15 try:
16 return open(name, mode)
17 except FileNotFoundError:
18 if deps_only:
19 return StringIO("")
20 raise
21
22 output_file = sys.argv[2]
23 try:
24 os.remove(output_file)
25 except FileNotFoundError:
26 pass
27 temp_output_file = output_file + '.tmp'
28 file_path = os.path.abspath(__file__)
29 openpower_path = os.path.split(file_path)[0]
30 wiki_path = os.path.split(openpower_path)[0]
31
32
33 def recursive_inline(f, input_name, depth):
34 assert depth < 10, "probably found an [[!inline]]-loop"
35 skip = False # found the pattern <!-- hide -->
36 for line in f.readlines():
37 # skip hide/show
38 if skip:
39 if line.startswith("<!-- show -->"):
40 skip = False
41 continue
42 elif line.startswith("<!-- hide -->"):
43 skip = True
44 continue
45 # fix separation in comparison table
46 if input_name.endswith("comparison_table.tex") and \
47 line.startswith("\begin{itemize}"):
48 o.write(line)
49 o.write("\\itemsep -0.3em\n")
50 continue
51 # find actual inlines
52 if not line.startswith("[[!inline"):
53 o.write(line)
54 continue
55 print(line.strip())
56 # assume first thing is pagename
57 line = line.split('"')
58 fname = line[1]
59 print(f"\tdepth={depth}: {fname}")
60 if fname.endswith(".py"):
61 if fname.startswith("gf_reference"):
62 with open_tracked(
63 wiki_path + "/../nmigen-gf/" + fname) as inc:
64 recursive_inline(inc, fname, depth + 1)
65 else:
66 with open_tracked(wiki_path + "/" + fname) as inc:
67 recursive_inline(inc, fname, depth + 1)
68 else:
69 if fname.endswith(".mdwn"):
70 with open_tracked(wiki_path + "/" + fname) as inc:
71 recursive_inline(inc, fname, depth + 1)
72 elif fname == 'openpower/isatables/fields.text':
73 with open_tracked(
74 wiki_path + "/../openpower-isa/" + fname) as inc:
75 recursive_inline(inc, fname, depth + 1)
76 else:
77 with open_tracked(wiki_path + "/" + fname + ".mdwn") as inc:
78 recursive_inline(inc, fname, depth + 1)
79
80
81 def body(o, print=print):
82 with open_tracked(sys.argv[1], "r") as f:
83 recursive_inline(f, sys.argv[1], 0)
84
85 if deps_only:
86 with StringIO() as o:
87 body(o, print=lambda *_: None)
88 deps_file = output_file + '.d'
89 with open(deps_file, "w") as o:
90 deps = " ".join(opened_files)
91 o.write(f"{output_file} {deps_file}: {deps}\n")
92 else:
93 with open(temp_output_file, "w") as o:
94 body(o)
95 os.rename(temp_output_file, output_file)
96