Debian Codegraph @

src/core/generate-bpf-delegate-configs.py

raw
1 #!/usr/bin/env python3
2
3 # SPDX-License-Identifier: LGPL-2.1-or-later
4
5 # Convert the bpf_{cmd,map_type,prog_type,attach_type} enums into a string
6 # array to be used as configuration options
7
8 import re
9 import sys
10
11
12 def print_usage_and_exit() -> None:
13 print(f'Usage: {sys.argv[0]} <code|doc> <header>')
14 sys.exit(1)
15
16
17 if len(sys.argv) != 3:
18 print_usage_and_exit()
19
20 output = sys.argv[1]
21 header = sys.argv[2]
22
23 if output not in ['code', 'doc']:
24 print(f'Invalid format: {format}')
25 print_usage_and_exit()
26
27 with open(header) as file:
28 inEnum = False
29 enumValues: list[str] = []
30 enumName = ''
31
32 if output == 'doc':
33 print('''\
34 <?xml version="1.0"?>
35 <!DOCTYPE bpf-delegates PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
36 "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
37 <para>
38 ''')
39
40 for line in file:
41 line = line.strip()
42
43 if inEnum:
44 # Inside an enum definition
45 if re.match(r'^\s*}', line):
46 # End of an enum definition
47 inEnum = False
48 # Print the enum values as a static const char* array
49 if output == 'code':
50 print(f'static const char* const {enumName}_table[] = {{')
51 else:
52 print(f'<para id="{enumName}">')
53 for enumValue in enumValues:
54 words = enumValue.split('_')
55 enumValue = words[0] + ''.join(word.capitalize() for word in words[1:])
56 if output == 'code':
57 print(f'\t"{enumValue}",')
58 else:
59 print(f'<constant>{enumValue}</constant>')
60 if output == 'code':
61 print('};')
62 else:
63 print('</para>')
64 enumValues = []
65 else:
66 # Collect enum values
67 match = re.fullmatch(r'(\w+)\b,', line)
68 if match and len(match.groups()) > 0 and not match[1].startswith('__'):
69 enumValues.append(match[1])
70 elif match := re.match(r'^\s*enum\s+bpf_(cmd|map_type|prog_type|attach_type)+\s*{', line):
71 # Start of a new enum
72 inEnum = True
73 enumName = 'bpf_delegate_' + match[1]
74
75 if output == 'doc':
76 print('</para>')