bug 1034: update spec page on bin/tern lut2/lut3
[libreriscv.git] / openpower / mdwn_inline.py
index cea39fe21d3958bc977e03d7e9a629d6c94e8cc9..6dec26a8b14052c1a2012116b53016b6d43fe432 100755 (executable)
 #!/usr/bin/env python3
-
 import sys
+import os.path
+from io import StringIO
+
+deps_only = sys.argv[1] == '--deps'
+
+if deps_only:
+    del sys.argv[1]
+
+opened_files = []
+
+def open_tracked(name, mode='r'):
+    opened_files.append(name)
+    try:
+        return open(name, mode)
+    except FileNotFoundError:
+        if deps_only:
+            return StringIO("")
+        raise
+
+output_file = sys.argv[2]
+try:
+    os.remove(output_file)
+except FileNotFoundError:
+    pass
+temp_output_file = output_file + '.tmp'
+file_path = os.path.abspath(__file__)
+openpower_path = os.path.split(file_path)[0]
+wiki_path = os.path.split(openpower_path)[0]
 
-with open(sys.argv[2], "w") as o:
-    with open(sys.argv[1], "r") as f:
-        for line in f.readlines():
-            if not line.startswith("[[!inline"):
-                o.write(line)
-                continue
-            print (line.strip())
-            # assume first thing is pagename
-            line = line.split('"')
-            fname = line[1]
-            print ("\t", fname)
-            if fname.endswith(".py"):
-                if fname.startswith("gf_reference"):
-                    with open("../../nmigen-gf/"+fname) as inc:
-                        o.write(inc.read())
-                else:
-                    with open("../%s" % fname) as inc:
-                        o.write(inc.read())
+
+def recursive_inline(f, input_name, depth):
+    assert depth < 10, "probably found an [[!inline]]-loop"
+    skip = False # found the pattern <!-- hide -->
+    for line in f.readlines():
+        # skip hide/show
+        if skip:
+            if line.startswith("<!-- show -->"):
+                skip = False
+            continue
+        elif line.startswith("<!-- hide -->"):
+            skip = True
+            continue
+        # fix separation in comparison table
+        if input_name.endswith("comparison_table.tex") and \
+            line.startswith("\begin{itemize}"):
+            o.write(line)
+            o.write("\\itemsep -0.3em\n")
+            continue
+        # find headings and create name-refs, including filename
+        if line.startswith("#"):
+            iname = input_name.split("/")
+            if iname[0] == 'openpower': iname.pop(0)
+            l = line.strip().split(" ")[1:3]
+            l = map(lambda x: ''.join(filter(str.isalnum, x)), l)
+            l = map(str.lower, l)
+            l = filter(lambda x:x, l)
+            l = list(dict.fromkeys(iname + list(l)))
+            l = '_'.join(l)
+            line = '%s <a name="%s"> </>\n' % (line.strip(), l)
+        # find actual inlines
+        if not line.startswith("[[!inline"):
+            o.write(line)
+            continue
+        print(line.strip())
+        # assume first thing is pagename
+        line = line.split('"')
+        fname = line[1]
+        print(f"\tdepth={depth}: {fname}")
+        if fname.endswith(".py"):
+            if fname.startswith("gf_reference"):
+                with open_tracked(
+                        wiki_path + "/../nmigen-gf/" + fname) as inc:
+                    recursive_inline(inc, fname, depth + 1)
+            else:
+                with open_tracked(wiki_path + "/" + fname) as inc:
+                    recursive_inline(inc, fname, depth + 1)
+        else:
+            if fname.endswith(".mdwn"):
+                with open_tracked(wiki_path + "/" + fname) as inc:
+                    recursive_inline(inc, fname, depth + 1)
+            elif fname.startswith('openpower/isatables'):
+                pth = wiki_path + "/../openpower-isa/" + fname
+                with open_tracked(pth) as inc:
+                    recursive_inline(inc, fname, depth + 1)
+            elif fname.startswith('openpower/isa'):
+                pth = wiki_path + "/../openpower-isa/" + fname + ".mdwn"
+                with open_tracked(pth) as inc:
+                    recursive_inline(inc, fname, depth + 1)
             else:
-                if fname.endswith(".mdwn"):
-                    with open("../%s" % fname) as inc:
-                        o.write(inc.read())
-                elif fname == 'openpower/isatables/fields.text':
-                    with open("../../openpower-isa/%s" % fname) as inc:
-                        o.write(inc.read())
-                else:
-                    with open("../%s.mdwn" % fname) as inc:
-                        o.write(inc.read())
+                with open_tracked(wiki_path + "/" + fname + ".mdwn") as inc:
+                    recursive_inline(inc, fname, depth + 1)
+
+
+def body(o, print=print):
+    with open_tracked(sys.argv[1], "r") as f:
+        recursive_inline(f, sys.argv[1], 0)
+
+if deps_only:
+    with StringIO() as o:
+        body(o, print=lambda *_: None)
+    deps_file = output_file + '.d'
+    with open(deps_file, "w") as o:
+        deps = " ".join(opened_files)
+        o.write(f"{output_file} {deps_file}: {deps}\n")
+else:
+    with open(temp_output_file, "w") as o:
+        body(o)
+    os.rename(temp_output_file, output_file)
+