xref: /btstack/doc/manual/html_postprocess_code_blocks.py (revision 0f7fd6c19b44e3fae3aaf3caf2c11dd07533fe4c)
1#!/usr/bin/env python3
2
3import os, sys, shutil, re, pickle, getopt
4from pathlib import Path
5
6def writeCodeBlock(aout, code, references):
7    for function_name, url in references.items():
8        html_link = '<a href="' + url + '">' + function_name + '</a>'
9        #print "before:" + code + "\n\n"
10        code = code.replace(function_name, html_link)
11    aout.write(code)
12
13
14def main(argv):
15    htmlfolder = "btstack/"
16
17    cmd = 'html_postprocess_code_blocks.py [-o <htmlkfolder>]'
18
19    try:
20        opts, args = getopt.getopt(argv,"o:",["ofolder="])
21    except getopt.GetoptError:
22        print (cmd)
23        sys.exit(2)
24    for opt, arg in opts:
25        if opt == '-h':
26            print (cmd)
27            sys.exit()
28        elif opt in ("-o", "--ofolder"):
29            htmlfolder = arg
30
31    html_path = htmlfolder + "examples/"
32    html_tmppath = htmlfolder + "examples/tmp/"
33
34    html_in  = html_path + "examples/index.html"
35    html_tmp = html_tmppath + "index.html"
36    references = pickle.load(open( "references.p", "rb" ))
37
38    Path(html_tmppath).mkdir(parents=True, exist_ok=True)
39
40    codeblock = 0
41    codeblock_end = 0
42
43    with open(html_in, 'r') as fin:
44        with open(html_tmp, 'w') as fout:
45            for line in fin:
46                if not codeblock:
47                    fout.write(line)
48                    if re.match('.*<pre><code>.*',line):
49                        codeblock = 1
50                    continue
51
52                writeCodeBlock(fout,line, references)
53                # check if codeblock ended
54                if re.match('.*</code></pre>.*',line):
55                    codeblock = 0
56
57
58    shutil.copyfile(html_tmp, html_in)
59    shutil.rmtree(html_tmppath)
60
61if __name__ == "__main__":
62   main(sys.argv[1:])
63