-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddongen
executable file
·183 lines (169 loc) · 7.93 KB
/
addongen
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
#!/usr/bin/python3
from adjustkeys.arg_defs import configurable_args, op_args
from adjustkeys.log import die
from adjustkeys.util import rem
from adjustkeys.version import version
from adjustkeys.yaml_io import read_yaml
from deps import external_dependencies
from sys import argv, stdin, stderr
def main(progName:str) -> None:
if progName.endswith('.py'):
progName = progName[:-3]
props:str = '\n '.join(list(map(lambda a: a['dest'] + ':' + prop(a), configurable_args)))
ops:[dict] = list(sorted(map(op, op_args), key=lambda op: (op['icon'], op['label'])))
tuple_version:tuple = tuple(version[1:].split('.')) if len(version) != 0 else (0, 0, 1)
deps:[[str, str]] = dependencies(progName)
file:str = stdin.read()
replacements:dict = {
'KCZA_CUSTOM_PROPERTIES': props,
'KCZA_CUSTOM_OPERATORS': '\n\n'.join(list(map(lambda op: op['src'], ops))),
'KCZA_CUSTOM_OPERATOR_HEADERS': ', '.join(list(map(lambda op: str(rem(op, 'src')), ops))),
'KCZA_CUSTOM_OPERATOR_TYPES': ', '.join(list(map(lambda op: op['name'], ops))),
'VERSION': str(tuple_version),
'DEPENDENCY_LIST': ', '.join(list(map(lambda dp: "Dependency(module='%s', package='%s', name=None)" %(dp[0], dp[1]), deps)))
}
for p in replacements.items():
file = file.replace(p[0], p[1])
print("# If this file is difficult to read, that's because it was auto-generated")
print(file, end='')
def prop(a:dict) -> str:
atype:type = a['type']
label:str = '"' + a['label'] + '"'
description:str = '"' + a['help'] + '"'
dest:str = a['dest']
default:object = "arg_dict['%s']['default']" % dest
if 'choices' in a:
choices:[[str, str, str, int]] = []
rawChoices = a['choices']
for i in range(len(rawChoices)):
choice = rawChoices[i]
formattedChoice:[object,str,str,int]
if atype == str:
formattedChoice = (choice.upper().replace('-', '_'), choice.title(), '', i)
else:
formattedChoice = (str(choice), str(choice), '', i)
choices.append(formattedChoice)
if atype == str:
default = default + ".upper().replace('-', '_')"
else:
default = 'str(%s)' % default
return f'EnumProperty(items={choices}, name={label}, default={default}, description={description})'
elif atype == bool:
return f"BoolProperty(name={label}, description={description}, default={default})"
elif atype == float:
soft_min:float = a['soft-min']
soft_max:float = a['soft-max']
precision:str = "min(5, max(1, ceil(-log10(arg_dict['%s']['default'])) + 2 if arg_dict['%s']['default'] != 0 else 0))" % (dest, dest)
return f"FloatProperty(name={label}, description={description}, default={default}, soft_min={soft_min}, soft_max={soft_max}, precision={precision})"
elif atype == int:
minval:float = a['min']
maxval:float = a['max']
return f"IntProperty(name={label}, description={description}, default={default}, min={minval}, max={maxval})"
elif atype == str:
default = "%s if (%s is not None) else 'None'" %(default, default)
if 'str-type' in a:
str_type:str = a['str-type']
if str_type == 'file':
return f"StringProperty(name={label}, description={description}, default={default}, subtype='FILE_PATH')"
elif str_type == 'dir':
return f"StringProperty(name={label}, description={description}, default={default}, subtype='DIR_PATH')"
else:
die('Unknown string property subtype: "%s"' % str_type)
else:
return f"StringProperty(name={label}, description={description}, default={default})"
def op(arg:dict) -> dict:
opName:str = op_name(arg['dest'])
opIdName:str = 'object.' + opName.lower()
opIdLabel:str = arg['label']
return {
'name': opName,
'icon': arg['icon'] if 'icon' in arg else 'CONSOLE',
'idname': opIdName,
'label': arg['label'],
'src': '\n'.join([
'class %s(Operator):' % opName,
' ' + '\n '.join([
"bl_idname = '%s'" % opIdName,
"bl_label = '%s'" % arg['label'],
"bl_description = '%s'" % arg['help'],
'',
'def execute(self, context):',
' ' + '\n '.join([
"self.report({'INFO'}, 'Adjustkeys: See system console for output')",
'push_dependency_path()',
'from .adjustkeys.adjustkeys import main as adjustkeys',
'from .adjustkeys.exceptions import AdjustKeysException',
'from .adjustkeys.log import printe',
'from .adjustkeys.util import safe_get',
'from traceback import format_exc',
'pop_dependency_path()',
"print('=' * 80)",
'akargs = get_args_from_ui(context)',
'try:',
' ' + '\n '.join([
"inf = adjustkeys(akargs, { '%s': True })" % arg['dest'],
"num_warnings = safe_get(inf, 'num_warnings')",
'if num_warnings is not None and num_warnings > 0:',
' ' + '\n '.join([
"self.report({'WARNING'}, 'There %s %d warning%s produced by adjustkeys, see system console for more information.' %('were' if num_warnings > 1 else 'was', num_warnings, 's' if num_warnings > 1 else ''))",
]),
"return {'FINISHED'}"
]),
'except AdjustKeysException as akex:',
' ' + '\n '.join([
"self.report({'ERROR'}, str(akex))",
'printe(str(akex))',
"if int(akargs['verbosity']) >= 2:",
' ' + '\n '.join([
'printe(format_exc())',
]),
"return {'CANCELLED'}",
]),
'finally:',
' ' + '\n '.join([
"print('=' * 80)",
])
])
])
])
}
def op_name(dest:str) -> str:
return 'akminiop' + dest.title().replace('_', '')
def dependencies(insertion_file:str) -> [[str, str]]:
python_native_deps:[str] = [ # there must be a better way of doing this...
'argparse',
'bpy',
'bmesh',
'collections',
'copy',
'decimal',
'functools',
'futures', # futures is included in the Python3 standard library, but not that of Python2 (it can be ignored)
'importlib',
'math',
'mathutils',
'multiprocessing',
'os',
're',
'statistics',
'sys',
'tempfile',
'types',
'typing',
'xml',
]
ext_deps:[str] = external_dependencies(insertion_file)
dep_origin_map:[str] = { v:k for k,v in read_yaml('pipreqs_module_map.yml').items() }
deps:[[str,str]] = [ (pkg, dep_origin_map[pkg]) if pkg in dep_origin_map else (pkg, pkg) for pkg in ext_deps if not pkg.startswith('adjustkeys') and pkg not in python_native_deps ]
pipreqs_deps:[str]
with open('requirements.txt', 'r') as f:
pipreqs_deps = list(map(lambda l: l.split('==')[0], f.readlines()))
missing_deps:[str] = [ pkg for _,pkg in deps if pkg not in pipreqs_deps and pkg not in python_native_deps ]
if missing_deps != []:
print('WARNING: Some dependencies are missing from the mapping file:\n\t%s' % '\n\t'.join(missing_deps), file=stderr)
exit(1)
return deps
if __name__ == '__main__':
if len(argv) < 2:
die('Please enter the name of the main file for %s to search for dependencies' % argv[0])
main(argv[1])