]> git.sesse.net Git - bcachefs-tools-debian/blob - doc/macro2rst.py
Disable pristine-tar option in gbp.conf, since there is no pristine-tar branch.
[bcachefs-tools-debian] / doc / macro2rst.py
1 #!/usr/bin/env python3
2 '''
3 A utility script for generating documentation.
4
5 Preprocessor macro output from opts_macro.h is parsed and combined with
6 bcachefs.5.rst.tmpl to generate bcachefs.5.rst.
7
8 >=python3.6
9 '''
10
11 import sys
12 import re
13
14 INDENT = '       '
15 TEMPLATE = './doc/bcachefs.5.rst.tmpl'
16 RST_FILE= './doc/bcachefs.5.rst'
17 SANITIZE_CHARS = [
18             '\\\\n',
19             '\\n',
20             '  ',
21             '"',
22             '\\',
23         ]
24
25 def sanitize(text):
26     '''
27     Parses opts_macro.h preprocessor output
28     :param text: text to sanitize
29     :type text: str
30     :returns: a list of options
31     :rtype: list
32     '''
33
34     args = []
35     reg = re.search('FMT_START_SECTION(.*)FMT_END_SECTION', text,
36             flags=re.DOTALL)
37     if not reg:
38         raise re.error('no text found')
39
40     # decoding would probably be better, but this works
41     for char in SANITIZE_CHARS:
42         text = text.replace(char, '')
43
44     text = re.split(r'FMT_END_LINE', text)
45
46     # this seemed easier than getting preprocessor macros to play nice
47     # with python's builtin csv module
48     for line in text:
49         vals = line.split(';')
50         if not vals:
51             continue
52         if len(vals) != 4:
53             continue
54         vals = list(map(str.strip, vals))
55         name, is_bool, desc, arg_name = vals
56
57         # this macro value from opts.h indicates that no values are passed
58         if is_bool == 'OPT_BOOL()':
59             args.append(f'--{name}\n{INDENT}{desc}')
60         else:
61             args.append(f'--{name} <{arg_name}>\n{INDENT}{desc}')
62     if not args:
63         raise re.error('no args found, likely parsing error')
64
65     return args
66
67
68 def main():
69     ''' Transform stdin to option list and write templated output to new file '''
70     out = ''
71
72     stdin = sys.stdin.read()
73     opts = sanitize(stdin)
74     opts = '\n'.join(opts)
75
76     # Insert into template
77     with open(TEMPLATE, 'r') as in_handle:
78         in_handle = in_handle.read()
79     out = in_handle.replace('OPTIONS_TABLE', opts)
80     with open(RST_FILE, 'w') as out_handle:
81         out_handle.write(out)
82
83
84 if __name__ == '__main__':
85     main()