aboutsummaryrefslogtreecommitdiff
path: root/doc/doc_extract.py
blob: ce192cbf8da5eb1679a19695d46fdc5063ebb003 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python3

import sys
import os

def get_source_files_recursive(path):
    source_files = []
    for dirpath, _, filenames in os.walk(path):
        for filename in filenames:
            ext = os.path.splitext(filename)[1]
            if ext == ".c" or ext == ".h":
                full_path = os.path.join(dirpath, filename)
                source_files.append(full_path)
    return source_files

def lstrip_lines(string):
    result = []
    for line in string.splitlines():
        result.append(line.lstrip())

    if len(result) > 0:
        if len(result[0].strip()) == 0:
            del result[0]
        if len(result[-1].strip()) == 0:
            del result[-1]
    return "\n".join(result)

def extract_docs(filepath):
    file_content = ""
    with open(filepath, "r") as file:
        file_content = file.read()

    docs = []
    search_index = 0
    while True:
        index = file_content.find("/*doc(", search_index)
        if index == -1:
            break
        index += 6

        doc_name_end = len(file_content)
        for i, c in enumerate(file_content[index:]):
            if c == ')':
                doc_name_end = index + i
                break
        doc_name = file_content[index:doc_name_end]

        doc_name_end += 1
        end = file_content.find("*/", doc_name_end)
        if end == -1:
            break
        doc = file_content[doc_name_end:end]

        search_index = end + 2
        docs.append((doc_name, lstrip_lines(doc)))
    return docs

def convert_to_subsections(doc_str):
    lines = []
    for line in doc_str.splitlines():
        if len(line) != 0 and line[0] == "#":
            line = "##" + line[1:]
        lines.append(line)
    return "\n".join(lines)

def main():
    script_path = os.path.realpath(sys.argv[0])
    script_dir = os.path.dirname(script_path)
    amalgam_base = os.path.dirname(script_dir)
    amalgam_includes = os.path.join(amalgam_base, "include")
    amalgam_sources = os.path.join(amalgam_base, "src")

    source_files = get_source_files_recursive(amalgam_includes)
    source_files += get_source_files_recursive(amalgam_sources)
    doc_data = []
    for filepath in source_files:
        docs = extract_docs(filepath)
        for doc in docs:
            section = "# {}\n{}".format(doc[0], convert_to_subsections(doc[1]))
            doc_data.append(section)
            print("Added section %s to the documentation" % doc[0])

    doc_path = os.path.join(script_dir, "Documentation.md")
    with open(doc_path, "w") as file:
        file.write("\n\n".join(doc_data))

if __name__ == "__main__":
    main()