Debian Codegraph @

util/constants-tool

raw
1 #!/usr/bin/env python3
2
3 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
4
5 from importlib import import_module
6 import os
7 import sys
8
9 enum_names = [
10 'dns.dnssec.Algorithm',
11 'dns.edns.OptionType',
12 'dns.flags.Flag',
13 'dns.flags.EDNSFlag',
14 'dns.message.MessageSection',
15 'dns.opcode.Opcode',
16 'dns.rcode.Rcode',
17 'dns.rdataclass.RdataClass',
18 'dns.rdatatype.RdataType',
19 'dns.rdtypes.dnskeybase.Flag',
20 'dns.update.UpdateSection',
21 ]
22
23 def generate():
24 for enum_name in enum_names:
25 dot = enum_name.rindex('.')
26 module_name = enum_name[:dot]
27 type_name = enum_name[dot + 1:]
28 lname = type_name.lower()
29 mod = import_module(module_name)
30 enum = getattr(mod, type_name)
31 filename = module_name.replace('.', '/') + '.py'
32 new_filename = filename + '.new'
33 with open(filename) as f:
34 with open(new_filename, 'w') as nf:
35 lines = f.readlines()
36 found = False
37 i = 0
38 length = len(lines)
39 while i < length:
40 l = lines[i].rstrip()
41 i += 1
42 if l.startswith(f'### BEGIN generated {type_name} ' +
43 'constants') or \
44 l.startswith(f'### BEGIN generated {lname} constants'):
45 found = True
46 break
47 else:
48 print(l, file=nf)
49 if found:
50 found = False
51 while i < length:
52 l = lines[i].rstrip()
53 i += 1
54 if l.startswith(f'### END generated {type_name} ' +
55 'constants') or \
56 l.startswith(f'### END generated {lname} constants'):
57 found = True
58 break
59 if not found:
60 print(f'Found begin marker for {type_name} but did ' +
61 'not find end marker!', file=sys.stderr)
62 sys.exit(1)
63 if not found:
64 print('', file=nf)
65 print(f'### BEGIN generated {type_name} constants', file=nf)
66 print('', file=nf)
67 # We have to use __members__.items() and not "in enum" because
68 # otherwise we miss values that have multiple names (e.g. NONE
69 # and TYPE0 for rdatatypes).
70 for name, value in enum.__members__.items():
71 print(f'{name} = {type_name}.{name}', file=nf)
72 print('', file=nf)
73 print(f'### END generated {type_name} constants', file=nf)
74 # Copy remaining lines (if any)
75 while i < length:
76 l = lines[i].rstrip()
77 i += 1
78 print(l, file=nf)
79 os.rename(new_filename, filename)
80
81 def main():
82 generate()
83
84 if __name__ == '__main__':
85 main()