-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcreate-embedded-app.py
427 lines (363 loc) · 15.5 KB
/
create-embedded-app.py
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import subprocess
from os import path
import shutil
import argparse
import sys
INPUT_INVALID = ["''", '""', "", "undefined"]
POSSIBLE_ROLES = ["PUBLIC", "USER", "ADMIN"] # the first value should be the default
# Create the parser
parser = argparse.ArgumentParser(prog="create-embedded-app",
description="Creates an embedded app in the Teiler-Dashboard.")
parser.add_argument("-n",
dest="NAME",
type=str,
default=None,
help="Name of the embedded app (required)")
parser.add_argument("-t",
dest="TITLE",
type=str,
default=None,
help="Title of the embedded app (default: '')")
parser.add_argument("-r",
dest="ROLES",
type=str,
nargs="+",
default=None,
choices=POSSIBLE_ROLES,
help=f"Roles of the embedded app (default: {POSSIBLE_ROLES[0]})")
parser.add_argument("-d",
dest="DESCRIPTION",
type=str,
default=None,
help="Description of the embedded app (default: '')")
group_icon = parser.add_mutually_exclusive_group()
group_icon.add_argument("-ic",
dest="ICON_CLASS",
type=str,
default="undefined",
help="Icon class of the embedded app (default: undefined)")
group_icon.add_argument("-is",
dest="ICON_SOURCE_URL",
type=str,
default="undefined",
help="URL of the icon for the embedded app (default: undefined)")
parser.add_argument("-i",
dest="INTERACTIVE",
action="store_false",
help="If specified, no interactive prompt will open if one "
"of the inputs was not specified in the command (this "
"may lead to a failure).")
args = parser.parse_args()
args._get_args()
def getRoles(role_input):
while 1:
if role_input is None:
role_input = input(f"ROLES [{', '.join(POSSIBLE_ROLES)}] (comma separated): ")
if isinstance(role_input, str):
role_input = set(role_input.replace(" ", "").upper().split(","))
else:
sys.exit(f"{role_input} is not a valid input.")
for role in role_input:
if role not in POSSIBLE_ROLES:
print(f"'{role}' is not a valid role, please repeat.")
role_input = None
break # if a role is not valid, repeat input
else:
break # if all roles are valid, break out of the while loop
return role_input
# if interactive mode is activated, ask the user for all unspecified arguments
if args.INTERACTIVE:
if args.NAME is None:
args.NAME = ""
while not args.NAME.isalpha():
args.NAME = input("NAME: ")
if args.TITLE is None:
args.TITLE = input("TITLE: ")
if args.ROLES is None:
args.ROLES = getRoles(args.ROLES)
if args.DESCRIPTION is None:
args.DESCRIPTION = input("DESCRIPTION: ")
# if one of icon_class and icon_source_url is specified, we can continue
if args.ICON_CLASS == "undefined" and args.ICON_SOURCE_URL == "undefined":
while 1:
icon_input = "undefined"
while icon_input == "undefined":
icon_input = input("ICON_CLASS (leave empty if you don't want to"
" specify): ")
if icon_input == "undefined":
print("undefined is not a valid input!")
if icon_input not in ["", "''", '""']:
args.ICON_CLASS = icon_input
args.ICON_SOURCE_URL = "undefined"
break
else:
icon_input = 'undefined'
# args.ICON_CLASS = "undefined"
while icon_input == "undefined":
icon_input = input("ICON_SOURCE_URL: ")
if icon_input == "undefined":
print("undefined is not a valid input!")
if icon_input not in ["", "''", '""']:
args.ICON_SOURCE_URL = icon_input
args.ICON_CLASS = 'undefined'
break
print("Neither ICON_CLASS or ICON_SOURCE_URL were specified!")
else:
# due to the interactive parameter, we cant make the icon_group required
# anymore, so we have to check it manually
if args.NAME is None:
sys.exit("NAME is required!")
if args.ICON_CLASS in INPUT_INVALID and args.ICON_SOURCE_URL in INPUT_INVALID:
sys.exit("Specify ICON_CLASS or ICON_SOURCE_URL.")
if args.TITLE is None:
args.TITLE = ""
if args.DESCRIPTION is None:
args.DESCRIPTION = ""
if args.ROLES is None: # no other cases needed here, argparse guarantees correct input if given
args.ROLES = [POSSIBLE_ROLES[0]]
# add quotation marks to the icon parameters, if they are defined
if args.ICON_CLASS != "undefined":
args.ICON_CLASS = f"'{args.ICON_CLASS}'"
if args.ICON_SOURCE_URL != "undefined":
args.ICON_SOURCE_URL = f"'{args.ICON_SOURCE_URL}'"
root = path.dirname(path.abspath(__file__))
# definition of all needed paths
APP = path.join(root, "src", "app")
APP_MODULES = path.join(APP, "app.module.ts")
APP_ROUTING_MODULES = path.join(APP, "route", "app-routing.module.ts")
TEILER = path.join(APP, "teiler")
TEILER_MODULES = path.join(TEILER, "teiler.module.ts")
TEILER_APP = path.join(TEILER, "teiler-app.ts")
TEILER_SERVICE = path.join(TEILER, "teiler.service.ts")
SERVICE_FILE = path.join(APP, f"{args.NAME}.service.ts")
SERVICE_SPEC_FILE = path.join(APP, f"{args.NAME}.service.spec.ts")
COMPONENT_FILE = path.join(APP, args.NAME, f"{args.NAME}.component.ts")
ROUTE_MANAGER = path.join(APP, 'route', "route-manager.service.ts")
# different variations of the NAME, that will be used later
# component and service name will be extracted from the generated files
COMPONENT_NAME = ""
SERVICE_NAME = ""
NAME_ENUM = args.NAME.replace("-", "_").upper()
"""------------------------------
1. Generate service and component
------------------------------"""
print(f"\nGenerate new service {args.NAME}...")
rt = subprocess.call(['npm', 'run', 'ng', 'g', 's', args.NAME], cwd=root,
shell=True)
if rt:
raise RuntimeError("Generating the service failed...")
print(f"\nGenerate new component {args.NAME}...")
rt = subprocess.call(['npm', 'run', 'ng', 'g', 'c', args.NAME], cwd=root,
shell=True)
if rt:
raise RuntimeError("Generating the component failed...")
"""-------------------------------------
1.5. Remove Samply from XXX.component.ts
-------------------------------------"""
print(f"\nRemove Samply from {args.NAME}.component.ts")
with open(COMPONENT_FILE, "r") as file:
lines = file.readlines()
for i, line in enumerate(lines):
if line.find("selector:") != -1:
lines[i] = line.replace("samply-", "")
break
else:
raise RuntimeError("Could not find the needed lines.")
with open(COMPONENT_FILE, "w") as file:
file.writelines(lines)
"""----------------------------------------------
2. Move component directory to embedded directory
----------------------------------------------"""
print(f"\nMoving component directory to embedded directory...")
dest_dir = path.join(APP, "embedded", args.NAME)
if path.isdir(dest_dir):
shutil.rmtree(dest_dir)
shutil.move(path.join(APP, args.NAME), path.join(APP, "embedded"))
"""---------------------------------
3. Remove component in app.module.ts
---------------------------------"""
print(f"\nRemoving component in app.module.ts...")
delete_lines = []
found_section = False
import_string = ""
with open(APP_MODULES, "r") as file:
lines = file.readlines()
for i, line in enumerate(lines):
if not found_section and line.find(args.NAME) != -1:
COMPONENT_NAME = line[line.find("{ ") + 2: line.find(" }")]
SERVICE_NAME = COMPONENT_NAME.replace("Component", "Service")
delete_lines.append(i)
found_section = True
continue
if found_section and line.find(COMPONENT_NAME) != -1:
delete_lines.append(i)
lines[i - 1] = lines[i - 1].replace(",", "")
break
else:
raise RuntimeError("Could not find the needed lines.")
for i in delete_lines[::-1]:
import_string = lines.pop(i)
with open(APP_MODULES, "w") as file:
file.writelines(lines)
"""--------------------------------------
4. Add component to app-routing.module.ts
--------------------------------------"""
print(f"\nAdding component to app-routing.module.ts...")
import_string = import_string.replace("from '.", "from '../embedded")
with open(APP_ROUTING_MODULES, "r") as file:
lines = file.readlines()
last_import_line = 0
for i, line in enumerate(lines):
if line.find("import") != -1:
last_import_line = i
continue
if line.find("]") != -1:
lines[i - 1] = lines[i - 1].replace("\n", ",\n")
lines.insert(i, f"\t{COMPONENT_NAME}\n")
lines.insert(last_import_line + 1, import_string)
break
else:
raise RuntimeError("Could not find the needed lines.")
with open(APP_ROUTING_MODULES, "w") as file:
file.writelines(lines)
"""---------------------------------------
5. Move service files to teiler directory
---------------------------------------"""
print(f"\nMoving Service Files...")
SERVICE_FILE = shutil.move(SERVICE_FILE, path.join(APP, "teiler"))
SERVICE_SPEC_FILE = shutil.move(SERVICE_SPEC_FILE, path.join(APP, "teiler"))
"""--------------------------------------------
6. Add service to providers in teiler.module.ts
--------------------------------------------"""
print(f"\nAdding service to providers in teiler.module.ts...")
import_string = f'import {{{SERVICE_NAME}}} from "./{args.NAME}.service";\n'
with open(TEILER_MODULES, "r") as file:
lines = file.readlines()
last_import_line = 0
found_section = False
for i, line in enumerate(lines):
if not found_section and line.find("import {") != -1:
last_import_line = i
continue
if not found_section and line.find("providers:") != -1:
found_section = True
if found_section and line.find("]") != -1:
lines[i] = line.replace("]", f",\n\t\t{SERVICE_NAME}]")
lines.insert(last_import_line + 1, import_string)
break
else:
raise RuntimeError("Could not find the needed lines.")
with open(TEILER_MODULES, "w") as file:
file.writelines(lines)
"""---------------------------------------
7. Add EmbeddedTeilerApps in teiler-app.ts
---------------------------------------"""
print(f"\nAdding EmbeddedTeilerApps in teiler-app.ts...")
with open(TEILER_APP, "r") as file:
lines = file.readlines()
found_section = False
for i, line in enumerate(lines):
if not found_section and line.find(
"export enum EmbeddedTeilerApps") != -1:
found_section = True
continue
if found_section and line.find("}") != -1:
lines[i - 1] = lines[i - 1].replace("\n", ",\n")
lines.insert(i, f"\t{NAME_ENUM} = '{args.NAME}'\n")
break
else:
raise RuntimeError("Could not find the needed lines.")
with open(TEILER_APP, "w") as file:
file.writelines(lines)
"""----------------------------------------------------
8. Extend Service to EbeddedTeilerApp in XXX.service.ts
8.1 Implement properties
8.2 Add EmbeddedTeilerApps to constructor
----------------------------------------------------"""
print(f"\nExtending Service to EbeddedTeilerApp in XXX.service.ts...")
template = \
f'''\tdescription: string = "{args.DESCRIPTION}";
\ticonClass: string | undefined = {args.ICON_CLASS};
\ticonSourceUrl: string | undefined = {args.ICON_SOURCE_URL};
\ttitle: string = "{args.TITLE}";
\troles: TeilerRole[] = [{",".join(["TeilerRole.TEILER_" + role for role in args.ROLES])}];
\tconstructor(router: Router) {{
super(EmbeddedTeilerApps.{NAME_ENUM}, router);
\t}}\n'''
import_string = \
'''import {EmbeddedTeilerApp, EmbeddedTeilerApps, TeilerRole} from "./teiler-app";
import {Router} from "@angular/router";\n'''
with open(SERVICE_FILE, "r") as file:
lines = file.readlines()
found_section = False
for i, line in enumerate(lines):
if not found_section and line.find("export class") != -1:
lines[i] = line.replace("{", "extends EmbeddedTeilerApp {")
found_section = True
continue
if found_section and line.find("constructor") != -1:
lines[i] = template
lines.insert(1, import_string)
break
else:
raise RuntimeError("Could not find the needed lines.")
with open(SERVICE_FILE, "w") as file:
file.writelines(lines)
"""--------------------------------
9. Add service to teiler.service.ts
--------------------------------"""
print(f"\nAdding service to teiler.service.ts...")
import_string = f'import {{{SERVICE_NAME}}} from "./{args.NAME}.service";\n'
with open(TEILER_SERVICE, "r") as file:
lines = file.readlines()
found_section1 = False
edited_section1 = False
found_section2 = False
last_import_line = 0
SERVICE_NAME_lower = SERVICE_NAME[0].lower() + SERVICE_NAME[1:]
for i, line in enumerate(lines):
if not found_section1 and line.find("import {") != -1:
last_import_line = i
if not found_section1 and line.find("constructor") != -1:
found_section1 = True
continue
if found_section1 and line.find(")") != -1:
lines[i - 1] = lines[i - 1].replace("\n", f",\n\t\t{SERVICE_NAME_lower}: {SERVICE_NAME}\n")
edited_section1 = True
continue
if found_section1 and edited_section1 and line.find("let embeddedTeilerApps") != -1:
found_section2 = True
if found_section2 and line.find("]") != -1:
lines[i] = line.replace("]", f",\n\t\t\t{SERVICE_NAME_lower}]")
lines.insert(last_import_line + 1, import_string)
break
else:
raise RuntimeError("Could not find the needed lines.")
with open(TEILER_SERVICE, "w") as file:
file.writelines(lines)
"""------------------------------------------
10. Add component to route-manager.service.ts
------------------------------------------"""
print(f"\nAdding component to route-manager.service.ts...")
import_string = f'import {{{COMPONENT_NAME}}} from "../embedded/{args.NAME}/{args.NAME}.component";\n'
template = f'\t\t{{name: EmbeddedTeilerApps.{NAME_ENUM}, component: {COMPONENT_NAME}}}\n'
with open(ROUTE_MANAGER, "r") as file:
lines = file.readlines()
found_section = False
last_import_line = 0
for i, line in enumerate(lines):
if not found_section and line.find("import {") != -1:
last_import_line = i
if not found_section and line.find("RouteManagerService") != -1:
found_section = True
continue
if found_section and line.find("].map") != -1:
lines[i - 1] = lines[i - 1].replace("\n", ",\n")
lines.insert(i, template)
lines.insert(last_import_line + 1, import_string)
break
else:
raise RuntimeError("Could not find the needed lines.")
with open(ROUTE_MANAGER, "w") as file:
file.writelines(lines)
print("\nSuccess!")