-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcfg2c.py
More file actions
153 lines (128 loc) · 5.16 KB
/
cfg2c.py
File metadata and controls
153 lines (128 loc) · 5.16 KB
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
import csv
import sys
import argparse
HDLR_HEADER_IDX = "#define CFG_IDX_{}(i, ...){{switch(i){{ \\\n{} default:break;}}}}\n"
HDLR_SWITCH_IDX = "case {}: cfg_{}_{}(&{}, {}, {}, __VA_ARGS__);break;\\ \n"
HDLR_HEADER_NAME = "#define CFG_NAME_{}(n, ...){{ \\\n{} }}\n"
HDLR_SWITCH_NAME = "if(strcmp(n, \"{}\") == 0)\\\n cfg_{}_{}(&{}, {}, {}, __VA_ARGS__);\\\n"
CFG_STRUCT = "typedef struct {0} {{\n{1}}} {0}_t;\nextern {0}_t {0};\n"
CFG_STRUCT_ENTRY = " {} {}; //!> {}\n"
def csv2lists(cfg):
ids = []
names = []
descriptions = []
setdefaults = []
for c in cfg:
ids.append(c['id'])
names.append(c['name'])
descriptions.append(c['description'])
setdefaults.append(c['name'] + ' = ' + c['default'] + ';')
return {'ids' : ids, 'names' : names, 'descriptions' : descriptions,
'setdefaults' : setdefaults}
def handler_id_gen(args, cfg, cfg_l, handler):
yield "#define CFGH_ID_{}(_c, _i, ...) {{switch((_i)){{ \\".format(
handler.upper())
i = 0
for c in cfg:
yield ("\tcase {}: cfg_{}_{}(&(_c)->{}, {}, {}, {}, __VA_ARGS__); break;\\"
"".format(c['id'], handler, c['type'].replace(' ', '_'), c['name'],
c['min'], c['max'], i))
i = i +1
yield "\tdefault: cfg_{}_notfound(__VA_ARGS__);}}\\".format(handler)
yield "}\n"
def handler_name_gen(args, cfg, cfg_l, handler):
yield "#define CFGH_NAME_{}(_c, _n, ...) {{\\".format(handler.upper())
i = 0
for c in cfg:
yield "if(strcmp(_n, {}_names[{}]) == 0){{\\".format(args.out, i)
yield "\tcfg_{}_{}(&(_c)->{}, {}, {}, {}, __VA_ARGS__);}}\\".format(handler,
c['type'].replace(' ', '_'), c['name'], c['min'], c['max'], i)
i = i +1
yield "}\n"
def header_gen(args, cfg, cfg_l):
yield "// this file is automatically generated by " + sys.argv[0]
yield "// arguments: `{}`\n".format(' '.join(sys.argv))
yield "#if !defined({0}_H)\n#define {0}_H".format(args.out.upper())
yield "#include \"ch.h\"\n\n"
# genreate structure
yield "typedef struct {} {{".format(args.out)
for c in cfg:
yield '\t' + c['type'] + ' ' + c['name'] + '; //!> ' + c['description']
yield '}} {}_t;'.format(args.out)
yield ""
yield "extern void {0}_setdefaults({0}_t *cfg);".format(args.out)
yield "#define {}_CNT {}".format(args.out.upper(), len(cfg_l['names']))
if(args.wid):
yield "extern int {}_ids[];".format(args.out)
if(args.wname):
yield "extern char *{}_names[];".format(args.out)
if(args.wdescriptions):
yield "extern char *{}_descriptions[];".format(args.out)
yield ""
# generate all the handlers
for h in args.handlers:
if(args.wid):
yield '\n'.join(handler_id_gen(args, cfg, cfg_l, h))
if(args.wname):
yield '\n'.join(handler_name_gen(args, cfg, cfg_l, h))
yield "#endif"
def source_gen(args, cfg, cfg_l):
yield "// this file is automatically generated by " + sys.argv[0]
yield "// arguments: `{}`\n".format(' '.join(sys.argv))
yield "#include \"{0}.h\"\n\n".format(args.out)
if(args.wid):
yield "int {}_ids[] = {{ {} }};".format(args.out,
', '.join(cfg_l['ids']))
if(args.wname):
yield "char *{}_names[] = {{ \"{}\" }};".format(args.out,
'", "'.join(cfg_l['names']))
if(args.wdescriptions):
yield "char *{}_descriptions[] = {{ \"{}\" }};".format(args.out,
'", "'.join(cfg_l['descriptions']))
yield "void {0}_setdefaults({0}_t *cfg) {{".format(args.out)
for c in cfg:
yield "\tcfg->{0} = {1};".format(c["name"], c["default"])
yield "}"
yield ""
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Generate .c/.h files for handling a specific configuration file')
parser.add_argument('configfile', metavar='cfg', type=str,
help='csv file describing the configuration')
# parser.add_argument('--sum', dest='accumulate', action='store_const',
# const=sum, default=max,
# help='sum the integers (default: find the max)')
parser.add_argument('--instances', metavar='H', type=str, nargs='+', default='',
help='generate configuration instances')
parser.add_argument('--c', metavar='O', type=bool, default=True,
help="Generate C source file")
parser.add_argument('--h', metavar='O', type=bool, default=True,
help="Generate C Header file")
parser.add_argument('--wid', metavar='O', type=bool, default=True,
help="Generate 'by id' handlers")
parser.add_argument('--wname', metavar='O', type=bool, default=True,
help="Generate 'by name' handlers")
parser.add_argument('--wdescriptions', metavar='O', type=bool, default=True,
help="Generate description strings")
parser.add_argument('--out', type=str, default='cfg',
help="c/h structure & hadlers to generate")
parser.add_argument('--handlers', metavar='H', type=str, nargs='+',
help='Handler class for manipulating the configuration')
args = parser.parse_args()
print(args)
with open(args.configfile, 'r') as f:
config = csv.DictReader(f, delimiter=',', quotechar='"')
config = list(config)
cfg_l = csv2lists(config)
header = '\n'.join(header_gen(args, config, cfg_l))
source = '\n'.join(source_gen(args, config, cfg_l))
if args.h:
with open(args.out + '.h', 'w') as h_f:
h_f.write(header)
else:
print(header)
if args.c:
with open(args.out + '.c', 'w') as c_f:
c_f.write(source)
else:
print(source)