-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmkpp
executable file
·202 lines (145 loc) · 4.71 KB
/
mkpp
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env python3
"""
mkpp == make python class property functions
- - - -
Auto create property methods (and optionally setters) for variables
of an internal python class.
"""
# TODOS:
# - check for existing properties and setters
# bugs and hints: [email protected]
import argparse
import logging
import logging.config
import re
import sys
from typing import Any, Dict # , List, Tuple, Callable
__log_level_default = logging.INFO
def main() -> None:
setup = get_prog_setup_or_exit_with_usage()
init_logging(setup)
logger = logging.getLogger(__name__)
try:
sys.exit(run(setup))
except Exception:
logger.critical("Abort, rc=3", exc_info=True)
sys.exit(3)
def get_prog_setup_or_exit_with_usage() -> Dict[str, Any]:
parser = argparse.ArgumentParser(
description=get_prog_doc(),
formatter_class=argparse.RawTextHelpFormatter,
)
log_group = parser.add_mutually_exclusive_group()
parser.add_argument(
'INFILE', help='specify the input python file',
)
parser.add_argument(
'OUTFILE', help=(
'specify the (modified) output python file (use "-" for stdout)'
),
)
parser.add_argument(
'insert_at', type=int, help='line number to insert the new code',
)
parser.add_argument(
'--range', default=':',
help=(
'specify which lines to parse, syntax: [line_from]:[line_to] '
'(default: all)'
),
)
parser.add_argument(
'--with_setters', action='store_true',
help='create setters too',
)
parser.add_argument(
'--pattern',
help=(
'specify regex, which lines (within the range) '
'should be taken (default: all)'
),
default=r'.+',
)
log_group.add_argument(
'--debug', action='store_true',
help='enable debug log level',
)
log_group.add_argument(
'--log_cfg', dest='log_cfg',
help='optional logging cfg in ini format',
)
args = vars(parser.parse_args())
args = {k: '' if v is None else v for k, v in args.items()}
args['pattern'] = re.compile(args['pattern'])
return args
def get_prog_doc() -> str:
doc_str = sys.modules['__main__'].__doc__
if doc_str is not None:
return doc_str.strip()
else:
return '<???>'
def init_logging(setup: Dict[str, Any]) -> None:
"""Creates either a logger by cfg file or a default instance
with given log level by arg --log_level (otherwise irgnored)
"""
if setup['log_cfg'] == '':
if setup['debug']:
level = logging.DEBUG
format = '%(levelname)s - %(message)s'
else:
level = __log_level_default
format = '%(message)s'
logging.basicConfig(level=level, format=format)
else:
logging.config.fileConfig(setup['log_cfg'])
def run(setup: Dict[str, Any]) -> int:
logger = logging.getLogger(__name__)
with open(setup['INFILE']) as f_in:
lines = [l.rstrip() for l in f_in.readlines()]
auto_generated_code = get_autogenerated_code(setup, lines)
extended_code = ''
for line_num, line in enumerate(lines, start=1):
if line_num == setup['insert_at']:
extended_code += auto_generated_code
extended_code += line + '\n'
if setup['OUTFILE'] == '-':
print(extended_code)
else:
with open(setup['OUTFILE'], 'wt') as f_out:
print(extended_code, file=f_out)
return 0
def get_autogenerated_code(setup: Dict[any,any], lines: int) -> str:
rf, rt = setup['range'].split(':')
rf = 1 if rf == '' else int(rf)
rt = len(lines) if rt == '' else int(rt)
ag_code = ''
for n, line in enumerate(lines, start=1):
if rf <= n <= rt:
ag_code += gen_code_for_line(setup, n, line)
return ag_code
def gen_code_for_line(setup: dict[any, any], n: int, line: str) -> str:
pattern_priv_var = re.compile(r'\s+self._+(?P<k>\S+)\s=\s*(?P<v>\S+)')
self_match = pattern_priv_var.match(line)
code = ''
if self_match:
k = self_match.group('k')
if not setup['pattern'].match(k):
return ''
code += make_property_for(k)
if setup['with_setters']:
code += make_setter_for(k)
return code
def make_property_for(value: str) -> str:
return (
f' @property\n'
f' def {value}(self):\n'
f' return self.__{value}\n\n'
)
def make_setter_for(value: str) -> str:
return (
f' @{value}.setter\n'
f' def {value}(self, value):\n'
f' self.__{value} = value\n\n'
)
if __name__ == '__main__':
main()