summaryrefslogtreecommitdiff
path: root/tools/hdoc.py
blob: 3a32eb39a6887a10f0b093d201a0f1abc3d706eb (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env python3

import sys
import re
from subprocess import Popen, PIPE
from argparse import ArgumentParser

__version__ = "0.1"

RE_FN = re.compile("[^\s]+\s+([^\(]+)\(")
RE_STRUCT = re.compile("(struct\s+[^{]+)\s*{")
RE_DEFINE = re.compile("#define\s+([^(]+)\(")
RE_DOC = re.compile("\s+\*\s?(.*\n)")
RE_SEC = re.compile("//\s+@(.*)\n")
RE_SECDOC = re.compile("//\s?(.*\n)")


def main():

    parser = ArgumentParser(description="Include docs to markdown",
                            epilog="Copyright (C) 2020 Juan J Martinez <jjm@usebox.net>",
                            )

    parser.add_argument("--version", action="version",
                        version="%(prog)s " + __version__)
    parser.add_argument("--doc-version", dest="docver", default=None,
                        help="Use this as version instead of git tag/commit")
    parser.add_argument("--header", dest="header", default=None,
                        help="Add this file at the begining of the document")
    parser.add_argument("--footer", dest="footer", default=None,
                        help="Add this file at the end of the document")
    parser.add_argument("title", help="Title of the resulting document")

    args = parser.parse_args()

    if args.docver is None:
        proc = Popen(["git", "describe", "--abbrev=0", "--tags"],
                     stdout=PIPE, stderr=PIPE)
        out, err = proc.communicate()
        if proc.returncode != 0:
            proc = Popen(["git", "rev-parse", "--short", "HEAD"],
                         stdout=PIPE, stderr=PIPE)
            out, err = proc.communicate()
            out = b"git-" + out

        docver = out.decode("utf-8").strip()
    else:
        docver = args.docver

    data = sys.stdin.readlines()
    ref = {}
    section = None
    sections = {}
    while data:
        line = data.pop(0)

        # section comment
        if line.strip().startswith("//"):
            g = RE_SEC.search(line)
            if g:
                section = g.group(1)
                doclines = []
                while True:
                    line = data.pop(0)
                    if not line.strip():
                        break
                    doclines.append(line)

                doc = ""
                for l in doclines:
                    g = RE_SECDOC.match(l)
                    if g:
                        doc += g.group(1)

                sections[section] = doc

        # begin fn/struct comment
        if line.strip() == "/**":
            doclines = []
            while True:
                line = data.pop(0)
                if line.strip() == "*/":
                    break
                doclines.append(line)

            line = data.pop(0)
            g = RE_DEFINE.search(line)
            if g is None:
                g = RE_STRUCT.search(line)
                if g is None:
                    g = RE_FN.search(line)
                    if g is None:
                        continue
                    else:
                        fn = line.strip()
                else:
                    fn = line
                    while True:
                        line = data.pop(0)
                        fn += line
                        if line.strip() == "};":
                            break
            else:
                fn = line
                while True:
                    line = data.pop(0)
                    fn += line
                    if not line.strip().endswith("\\"):
                        fn = fn.rstrip()
                        break

            name = g.group(1).strip()
            anchor = name.replace(" ", "-")

            doc = ""
            for l in doclines:
                g = RE_DOC.match(l)
                if g:
                    doc += g.group(1)
            ref[name] = {"name": name, "anchor": anchor,
                         "fn": fn, "doc": doc, "section": section}

    print("""\
---
title: '{title}'
subtitle: 'Version {version}'
...""".format(title=args.title, version=docver))

    if args.header:
        with open(args.header, "rt") as fd:
            print(fd.read())

    csec = None
    for k in sorted(ref.keys(), key=lambda k: (ref[k]["section"], k)):
        v = ref[k]
        if csec != v["section"]:
            csec = v["section"]
            print("## %s\n" % csec)
            if csec in sections:
                print(sections[csec])

        print("""\
### {name}
```c
{fn}
```

{doc}
""".format(**v))

    if args.footer:
        with open(args.footer, "rt") as fd:
            print(fd.read())


if __name__ == "__main__":
    main()