-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
791 lines (719 loc) · 36.8 KB
/
main.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
# coding=utf-8
"""
crud-code-generator-for-springboot
"""
import argparse
import os
import platform
import shutil
import string
import subprocess
import inflection
CURRENT_PATH = os.getcwd() # 当前目录
TEMPLATE_PATH = os.path.join(CURRENT_PATH, "templates") # 模板目录
ARCHETYPE_RESOURCE_PATH = os.path.join(CURRENT_PATH, "archetype-resources") # 原型资源目录
project_info = {
"project_path": None,
"package_name": None,
"group_id": None,
"artifact_id": None,
"version": None,
"description": None,
"port": None,
"payment": False,
"debug": False,
}
file_info = {}
def substitute(template_str, **vars):
merged_vars = {**project_info, **file_info, **vars}
template = string.Template(template_str)
return template.substitute(merged_vars)
def init_project():
print("初始化项目,复制 .sql 文件")
g = os.walk(ARCHETYPE_RESOURCE_PATH)
for path, _, file_list in g:
for file_name in file_list:
if file_name == ".DS_Store" or (not project_info["payment"] and file_name == "t_payment.sql"):
continue
sub_path = path[len(ARCHETYPE_RESOURCE_PATH) + 1 :]
with open(os.path.join(path, file_name), "r", encoding="utf-8") as file_read:
if "src/main/resources/sql" in path or "src\\main\\resources\\sql" in path:
directory_path = os.path.join(project_info["project_path"], sub_path)
if not os.path.exists(directory_path):
os.makedirs(directory_path)
file_path = os.path.join(directory_path, file_name)
if project_info["debug"]:
print(file_path)
content = file_read.read()
with open(file_path, "w", encoding="utf-8") as file_write:
file_write.write(content)
def get_column_type_property_name(column):
column_type = "String"
property_name = column["name"]
if column["type"] == "bigint":
column_type = "Long"
elif column["type"] == "double":
column_type = "Double"
elif column["type"] == "decimal":
column_type = "BigDecimal"
elif column["type"] == "tinyint" and column["name"].startswith("is_"):
column_type = "Boolean"
elif column["type"] == "tinyint" or column["type"] == "int":
column_type = "Int"
elif column["type"] == "datetime" or column["type"] == "time" or column["type"] == "date":
column_type = "Date"
return column_type, property_name
def copy_archetype_resources():
if project_info["debug"]:
print("复制骨架资源文件")
g = os.walk(ARCHETYPE_RESOURCE_PATH)
for path, _, file_list in g:
for file_name in file_list:
if file_name == ".DS_Store":
continue
sub_path = path[len(ARCHETYPE_RESOURCE_PATH) + 1 :]
with open(os.path.join(path, file_name), "r", encoding="utf-8") as file_read:
directory_path = os.path.join(project_info["project_path"], sub_path)
if "src/main/kotlin" in path or "src\\main\\kotlin" in path:
directory_path = os.path.join(project_info["project_path"], "src/main/kotlin", *project_info["package_name"].split("."), sub_path[len("src/main/kotlin") + 1 :])
if not os.path.exists(directory_path):
os.makedirs(directory_path)
file_path = os.path.join(directory_path, file_name)
if os.path.exists(file_path) and os.path.splitext(file_name)[-1] == ".sql":
if project_info["debug"]:
print("跳过:" + file_path)
continue
if not project_info["payment"] and file_name in [
"t_payment.sql",
"PaymentController.kt",
"PaymentService.kt",
"PaymentMapper.kt",
"PaymentStatus.kt",
"PaymentMapper.xml",
"WxPrepayResponse.kt",
]:
continue
if project_info["debug"]:
print("准备复制:" + file_path)
content = substitute(file_read.read())
with open(file_path, "w", encoding="utf-8") as file_write:
file_write.write(content)
if project_info["debug"]:
print("已复制:" + file_path)
if file_name == "generator.sh" and platform.system() != "Windows":
subprocess.run(["chmod", "+x", file_path])
def run_package():
global file_info
if project_info["debug"]:
print("执行 CRUD")
input_path = os.path.join(project_info["project_path"], "src/main/resources/sql")
# kotlin 输出目录
kotlin_output_path = os.path.join(project_info["project_path"], "src", "main", "kotlin", *project_info["package_name"].split("."))
# mapper 输出目录
mapper_output_path = os.path.join(project_info["project_path"], "src", "main", "resources", "mapper")
if os.path.exists(kotlin_output_path):
shutil.rmtree(kotlin_output_path)
if os.path.exists(mapper_output_path):
shutil.rmtree(mapper_output_path)
for input_file_name in os.listdir(input_path):
file_info = {}
input_file_path = os.path.join(input_path, input_file_name)
if not os.path.isdir(input_file_path):
if not input_file_name.endswith(".sql"):
if project_info["debug"]:
print("跳过: " + input_file_name)
continue
if project_info["debug"]:
print("处理: " + input_file_name)
file_info["table_name"] = os.path.splitext(input_file_name)[0].strip() # 文件名
if not project_info["payment"] and file_info["table_name"] == "t_payment":
continue
if file_info["table_name"] == "t_flyway_history":
continue
file_info["model_name"] = file_info["table_name"][2:] if file_info["table_name"].startswith("t_") else file_info["table_name"]
file_info["model_name_pascal_case"] = inflection.camelize(file_info["model_name"], True) # PascalCase
file_info["model_name_pascal_case_plural"] = inflection.pluralize(file_info["model_name_pascal_case"]) # PascalCases 复数形式
file_info["model_name_camel_case"] = inflection.camelize(file_info["model_name"], False) # camelCase
file_info["model_name_snake_case"] = inflection.underscore(file_info["model_name"]) # snake_case
file_info["model_name_kebab_case"] = inflection.dasherize(file_info["model_name_snake_case"]) # kebab-case
table_description = file_info["model_name"] # 表注释
file_read = open(input_file_path, "r", encoding="UTF-8")
columns = [] # 字段数组
for line in file_read:
if line.find("CREATE TABLE ") >= 0:
if line.strip().split()[2].split(".")[-1].strip("`") != file_info["table_name"]:
print("表名与文件名不一致!")
return
continue
if line.find(" KEY ") >= 0:
continue # 跳过索引
if line.find("CHARSET=") >= 0:
table_description = line[line.find("COMMENT") + 8 :].split("'")[1] # 读取表注释
continue
if len(line.strip().split()) < 2:
continue
column = {
"name": line.strip().split()[0].strip("`"),
"type": line.strip().split()[1].split("(")[0].lower(),
}
if line.find("NOT NULL ") > 0:
column["nullable"] = False # 字段是否可空
column["default"] = None
else:
column["nullable"] = True
column["default"] = "null"
if line.find("DEFAULT ") > 0:
column["default"] = line[line.find("DEFAULT ") + 8 :].split()[0].replace("'", '"') # 字段默认值
if column["default"] == "NULL" or column["default"] == "CURRENT_TIMESTAMP":
column["default"] = "null"
if column["type"].find("decimal") >= 0:
column["default"] = "BigDecimal(%s)" % column["default"].replace('"', "")
if (column["type"].find("int") >= 0 or column["type"].find("double") >= 0 or column["type"].find("decimal") >= 0) and column["default"].find('"') >= 0:
column["default"] = column["default"].replace('"', "")
if column["type"] == "tinyint" and column["name"].startswith("is_"):
if column["default"] == "0":
column["default"] = "false"
else:
column["default"] = "true"
column["comment"] = line[line.find("COMMENT") + 8 :].split("'")[1] # 字段注释
columns.append(column)
file_read.close()
# [Model]Mapper.xml
lines = []
for column in columns:
property_name = column["name"]
if column["name"] == "is_delete":
continue
if file_info["model_name"] == "user" and (column["name"] == "password" or column["name"] == "salt"):
continue
lines.append(" `%s`.`%s`" % (file_info["model_name_snake_case"], column["name"]))
column_list = ",\n".join(lines)
lines = []
for column in columns:
if column["name"] == "id" or column["name"] == "sort_weight" or (file_info["model_name"] == "user" and (column["name"] == "password" or column["name"] == "salt")):
continue
if column["type"] == "datetime" or column["type"] == "time" or column["type"] == "date":
lines.append(' <if test="request.%sFrom != null">' % (inflection.camelize(column["name"], False)))
lines.append(
" AND `%s`.`%s` >= #{request.%sFrom}"
% (
file_info["model_name_snake_case"],
column["name"],
inflection.camelize(column["name"], False),
)
)
lines.append(" </if>")
lines.append(' <if test="request.%sTo != null">' % (inflection.camelize(column["name"], False)))
lines.append(
" AND `%s`.`%s` <= #{request.%sTo}"
% (
file_info["model_name_snake_case"],
column["name"],
inflection.camelize(column["name"], False),
)
)
lines.append(" </if>")
continue
if column["name"] == "is_delete":
lines.append(" AND `%s`.`%s` = 0" % (file_info["model_name_snake_case"], column["name"]))
continue
if column["type"] == "varchar" or column["type"] == "text":
lines.append(
" <if test=\"request.%s != null and request.%s !=''\">"
% (
inflection.camelize(column["name"], False),
inflection.camelize(column["name"], False),
)
)
else:
lines.append(' <if test="request.%s != null">' % (inflection.camelize(column["name"], False)))
lines.append(
" AND `%s`.`%s` = #{request.%s}"
% (
file_info["model_name_snake_case"],
column["name"],
inflection.camelize(column["name"], False),
)
)
lines.append(" </if>")
search_where = "\n".join(lines)
lines = []
for column in columns:
if column["name"] == "id" or column["name"] == "is_delete":
continue
lines.append(" `%s`" % (column["name"]))
name_list = ",\n".join(lines)
lines = []
for column in columns:
if column["name"] == "id" or column["name"] == "is_delete":
continue
elif column["name"] == "create_time" or column["name"] == "update_time" or column["name"] == "created_time" or column["name"] == "updated_time":
lines.append(" NOW()")
else:
lines.append(" #{%s.%s}" % (file_info["model_name_camel_case"], inflection.camelize(column["name"], False)))
value_list = ",\n".join(lines)
lines = []
for column in columns:
if column["name"] == "id" or column["name"] == "create_time" or column["name"] == "created_time" or column["name"] == "is_delete":
continue
elif column["name"] == "update_time" or column["name"] == "updated_time":
lines.append(" `%s` = NOW()" % (column["name"]))
else:
lines.append(
" `%s` = #{%s.%s}"
% (
column["name"],
file_info["model_name_camel_case"],
inflection.camelize(column["name"], False),
)
)
update_list = ",\n".join(lines)
lines = []
for column in columns:
if column["name"] == "id" or column["name"] == "create_time" or column["name"] == "created_time" or column["name"] == "is_delete":
continue
elif column["name"] == "update_time" or column["name"] == "updated_time":
lines.append(" `%s` = NOW()" % (column["name"]))
else:
if column["type"] == "varchar" or column["type"] == "text":
lines.append(
" <if test=\"request.%s != null and request.%s !=''\">"
% (inflection.camelize(column["name"], False), inflection.camelize(column["name"], False))
)
else:
lines.append(' <if test="request.%s != null">' % (inflection.camelize(column["name"], False)))
lines.append(" `%s` = #{request.%s}," % (column["name"], inflection.camelize(column["name"], False)))
lines.append(" </if>")
update_partly_list = "\n".join(lines)
lines = []
for column in columns:
if column["name"] == "sort_weight":
lines.append("`%s`.`sort_weight` DESC" % (file_info["model_name_snake_case"]))
if not lines:
lines.append("`%s`.`id` DESC" % (file_info["model_name_snake_case"]))
orders = ", ".join(lines)
if file_info["model_name"] == "user":
file_read = open(os.path.join(TEMPLATE_PATH, "UserMapper.xml"), "r", encoding="UTF-8")
else:
file_read = open(os.path.join(TEMPLATE_PATH, "Mapper.xml"), "r", encoding="UTF-8")
content = substitute(
file_read.read(),
column_list=column_list,
name_list=name_list,
orders=orders,
search_where=search_where,
update_list=update_list,
update_partly_list=update_partly_list,
value_list=value_list,
)
if not os.path.exists(mapper_output_path):
os.makedirs(mapper_output_path)
file_write = open(
os.path.join(mapper_output_path, file_info["model_name_pascal_case"] + "Mapper.xml"),
"w",
encoding="UTF-8",
)
file_write.write(content)
file_write.close()
# [Model].kt
content = "package %s.models\n\n" % project_info["package_name"]
content += "import io.swagger.v3.oas.annotations.media.Schema\n"
content += "import %s.annotations.NoArg\n" % project_info["package_name"]
content += "import java.math.BigDecimal\n"
content += "import java.util.*\n\n"
content += "@NoArg\n"
content += "data class %s(\n" % (file_info["model_name_pascal_case"])
lines = []
swagger_index = 0
for column in columns:
if column["name"] == "is_delete":
continue
else:
column_type, property_name = get_column_type_property_name(column)
if column["nullable"]:
column_type += "?"
if column["default"]:
column_type += " = " + column["default"]
if column["name"] == "id":
column_type += " = 0"
line_text = ' @Schema(description = "%s")\n' % (column["comment"])
# 特殊处理 for Payment.kt
if file_info["model_name"] == "payment" and (
property_name == "status"
or property_name == "wx_transaction_id"
or property_name == "wx_payment_open_id"
or property_name == "message"
or property_name == "payment_time"
):
line_text += " var %s: %s" % (
inflection.camelize(property_name, False),
column_type,
)
# 特殊处理 for User.kt
elif file_info["model_name"] == "user" and (property_name != "id" and property_name != "create_time" and property_name != "update_time"):
line_text += " var %s: %s" % (inflection.camelize(property_name, False), column_type)
else:
line_text += " val %s: %s" % (inflection.camelize(property_name, False), column_type)
lines.append(line_text)
swagger_index += 1
content += "%s,\n" % (",\n\n".join(lines))
content += ")\n"
output_models_path = os.path.join(kotlin_output_path, "models")
if not os.path.exists(output_models_path):
os.makedirs(output_models_path)
file_write = open(os.path.join(output_models_path, file_info["model_name_pascal_case"] + ".kt"), "w", encoding="UTF-8")
file_write.write(content)
file_write.close()
# [Model]EditRequest.kt
content = "package %s.viewmodels.%s\n\n" % (
project_info["package_name"],
file_info["model_name_camel_case"],
)
content += "import io.swagger.v3.oas.annotations.media.Schema\nimport java.math.BigDecimal\nimport java.util.*\nimport jakarta.validation.constraints.NotNull\n\n"
content += "data class %sEditRequest(\n" % (file_info["model_name_pascal_case"])
lines = []
swagger_index = 0
for column in columns:
define = "val"
required = True
hidden = False
line_text = ""
column_type, property_name = get_column_type_property_name(column)
if column["nullable"]:
column_type += "?"
required = False
if column["default"]:
column_type += " = " + column["default"]
if column["name"] == "id":
define = "var"
required = False
hidden = True
if (
column["name"] == "create_time"
or column["name"] == "update_time"
or column["name"] == "created_time"
or column["name"] == "updated_time"
or column["name"] == "is_delete"
):
continue
if column["name"] == "id":
column_type += " = 0"
if required:
line_text += ' @NotNull(message = "%s 不能为空")\n' % (inflection.camelize(property_name, False))
line_text += ' @Schema(description = "%s", required = %s, hidden = %s)\n' % (
column["comment"],
"true" if required else "false",
"true" if hidden else "false",
)
line_text += " %s %s: %s" % (define, inflection.camelize(property_name, False), column_type)
lines.append(line_text)
swagger_index += 1
content += "%s,\n" % (",\n\n".join(lines))
content += ")\n"
output_viewmodels_path = os.path.join(kotlin_output_path, "viewmodels", file_info["model_name_camel_case"])
if not os.path.exists(output_viewmodels_path):
os.makedirs(output_viewmodels_path)
file_write = open(
os.path.join(output_viewmodels_path, file_info["model_name_pascal_case"] + "EditRequest.kt"),
"w",
encoding="UTF-8",
)
file_write.write(content)
file_write.close()
# [Model]PartlyEditRequest.kt
content = "package %s.viewmodels.%s\n\n" % (
project_info["package_name"],
file_info["model_name_camel_case"],
)
content += "import io.swagger.v3.oas.annotations.media.Schema\n"
content += "import java.math.BigDecimal\n"
content += "import java.util.*\n"
content += "import jakarta.validation.constraints.NotNull\n"
content += "\n"
content += "data class %sPartlyEditRequest(\n" % (file_info["model_name_pascal_case"])
lines = []
swagger_index = 0
for column in columns:
define = "var"
hidden = "true"
if (
column["name"] == "create_time"
or column["name"] == "update_time"
or column["name"] == "created_time"
or column["name"] == "updated_time"
or column["name"] == "is_delete"
):
continue
column_type, property_name = get_column_type_property_name(column)
if column["name"] != "id":
define = "val"
hidden = "false"
column_type += "? = null"
# 特殊处理 for UserPartlyEditRequest.kt
if file_info["model_name"] == "user" and (column["name"] == "password" or column["name"] == "salt"):
define = "var"
line_text = ' @Schema(description = "%s", required = false, hidden = %s)\n' % (
column["comment"],
hidden,
)
line_text += " %s %s: %s" % (define, inflection.camelize(property_name, False), column_type)
lines.append(line_text)
swagger_index += 1
content += "%s,\n" % (",\n\n".join(lines))
content += ")\n"
output_viewmodels_path = os.path.join(kotlin_output_path, "viewmodels", file_info["model_name_camel_case"])
if not os.path.exists(output_viewmodels_path):
os.makedirs(output_viewmodels_path)
file_write = open(
os.path.join(output_viewmodels_path, file_info["model_name_pascal_case"] + "PartlyEditRequest.kt"),
"w",
encoding="UTF-8",
)
file_write.write(content)
file_write.close()
# [Model]SearchRequest.kt
content = "package %s.viewmodels.%s\n\n" % (
project_info["package_name"],
file_info["model_name_camel_case"],
)
content += (
"import io.swagger.v3.oas.annotations.media.Schema\nimport %s.models.Paging\nimport %s.viewmodels.common.SortOrder\nimport java.math.BigDecimal\nimport java.util.*\n\n"
% (project_info["package_name"], project_info["package_name"])
)
content += "data class %sSearchRequest(\n" % (file_info["model_name_pascal_case"])
lines = []
swagger_index = 0
for column in columns:
if column["name"] == "id" or column["name"] == "sort_weight" or column["name"] == "is_delete":
continue
column_type, property_name = get_column_type_property_name(column)
column_type += "? = null"
define = "val"
if column["type"] == "datetime" or column["type"] == "time" or column["type"] == "date":
line_text = ' @Schema(description = "%s From")\n' % (column["comment"])
line_text += " %s %s: %s" % (
define,
inflection.camelize(column["name"] + "From", False),
column_type,
)
lines.append(line_text)
swagger_index += 1
line_text = ' @Schema(description = "%s To")\n' % (column["comment"])
line_text += " %s %s: %s" % (
define,
inflection.camelize(column["name"] + "To", False),
column_type,
)
lines.append(line_text)
swagger_index += 1
continue
line_text = ' @Schema(description = "%s")\n' % (column["comment"])
line_text += " %s %s: %s" % (
define,
inflection.camelize(property_name, False),
column_type,
)
lines.append(line_text)
swagger_index += 1
line_text = ' @Schema(description = "排序条件")\n'
line_text += " val sortOrders: List<SortOrder>? = null"
lines.append(line_text)
swagger_index += 1
line_text = ' @Schema(description = "分页(默认第1页,每页显示10条)")\n'
line_text += " val paging: Paging = Paging(1, 10)"
lines.append(line_text)
content += "%s,\n" % (",\n\n".join(lines))
content += ")\n"
output_viewmodels_path = os.path.join(kotlin_output_path, "viewmodels", file_info["model_name_camel_case"])
if not os.path.exists(output_viewmodels_path):
os.makedirs(output_viewmodels_path)
file_write = open(
os.path.join(output_viewmodels_path, file_info["model_name_pascal_case"] + "SearchRequest.kt"),
"w",
encoding="UTF-8",
)
file_write.write(content)
file_write.close()
# [Model]Mapper.kt
file_read = open(os.path.join(TEMPLATE_PATH, "Mapper.kt"), "r", encoding="UTF-8")
content = substitute(file_read.read())
output_mappers_path = os.path.join(kotlin_output_path, "mappers")
if not os.path.exists(output_mappers_path):
os.makedirs(output_mappers_path)
file_write = open(
os.path.join(output_mappers_path, file_info["model_name_pascal_case"] + "Mapper.kt"),
"w",
encoding="UTF-8",
)
file_write.write(content)
file_write.close()
# [Model]Service.kt
if file_info["model_name"] == "user":
file_read = open(os.path.join(TEMPLATE_PATH, "UserService.kt"), "r", encoding="UTF-8")
columns_data = []
add_user_with_password_columns_data = []
bind_mobile_columns_data = []
for column in columns:
property_name = column["name"]
if (
column["name"] == "create_time"
or column["name"] == "update_time"
or column["name"] == "created_time"
or column["name"] == "updated_time"
or column["name"] == "is_delete"
):
continue
columns_data.append(
" %s = request.%s"
% (
inflection.camelize(property_name, False),
inflection.camelize(property_name, False),
)
)
if column["name"] != "password" and column["name"] != "salt":
add_user_with_password_columns_data.append(
" %s = request.%s"
% (
inflection.camelize(property_name, False),
inflection.camelize(property_name, False),
)
)
else:
add_user_with_password_columns_data.append(
" %s = %s"
% (
inflection.camelize(property_name, False),
inflection.camelize(property_name, False),
)
)
if column["name"] != "mobile" and column["name"] != "id":
bind_mobile_columns_data.append(
" mobileUser.%s = currentUser.%s"
% (
inflection.camelize(property_name, False),
inflection.camelize(property_name, False),
)
)
content = substitute(
file_read.read(),
columns_data=",\n".join(columns_data),
add_user_with_password_columns_data=",\n".join(add_user_with_password_columns_data),
bind_mobile_columns_data="\n".join(bind_mobile_columns_data),
)
else:
file_read = open(os.path.join(TEMPLATE_PATH, "Service.kt"), "r", encoding="UTF-8")
columns_data = []
for column in columns:
property_name = column["name"]
if (
column["name"] == "create_time"
or column["name"] == "update_time"
or column["name"] == "created_time"
or column["name"] == "updated_time"
or column["name"] == "is_delete"
):
continue
columns_data.append(
" %s = request.%s"
% (
inflection.camelize(property_name, False),
inflection.camelize(property_name, False),
)
)
content = substitute(file_read.read(), columns_data=",\n".join(columns_data))
output_services_path = os.path.join(kotlin_output_path, "services")
if not os.path.exists(output_services_path):
os.makedirs(output_services_path)
file_write = open(
os.path.join(output_services_path, file_info["model_name_pascal_case"] + "Service.kt"),
"w",
encoding="UTF-8",
)
file_write.write(content)
file_write.close()
# [Model]Controller.kt
file_read = open(os.path.join(TEMPLATE_PATH, "Controller.kt"), "r", encoding="UTF-8")
content = substitute(file_read.read(), model_description=table_description)
output_controllers_path = os.path.join(kotlin_output_path, "controllers")
if not os.path.exists(output_controllers_path):
os.makedirs(output_controllers_path)
file_write = open(
os.path.join(output_controllers_path, file_info["model_name_pascal_case"] + "Controller.kt"),
"w",
encoding="UTF-8",
)
file_write.write(content)
file_write.close()
def str_input(prompt, required=False, default=None):
required_str = " (必填)" if required else ""
default_str = f" [{default}]" if default is not None else ""
user_input = input(f"{prompt}{required_str}{default_str}: ").strip()
result = user_input or default
if required and not result:
print("该项输入为必填项")
return str_input(prompt, required, default)
return result
def bool_input(prompt, default):
user_input = input(f"{prompt} [{'Y/n' if default else 'y/N'}]: ").strip().lower()
if user_input in ["y", "yes"]:
return True
elif user_input in ["n", "no"]:
return False
elif user_input == "":
return default
else:
print("请输入 y 或 n,或者直接回车使用默认值")
return bool_input(prompt, default)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Code Generator for Spring Boot")
parser.add_argument("command", choices=["init", "run"], help="Command to execute (init for interactive mode, run for non-interactive mode)")
parser.add_argument("--group_id", help="项目 Group ID")
parser.add_argument("--artifact_id", help="项目 Artifact ID")
parser.add_argument("--version", help="项目版本号", default="1.0.0")
parser.add_argument("--port", help="端口号", default=8000)
parser.add_argument("--package_name", help="项目包名")
parser.add_argument("--project_path", help="项目路径")
parser.add_argument("--description", help="项目描述")
parser.add_argument("--payment", action="store_true", help="是否包含支付模块", default=False)
parser.add_argument("--debug", action="store_true", help="是否开启调试模式", default=False)
args = parser.parse_args()
if args.command == "init":
project_info["group_id"] = str_input("请输入项目 Group ID", required=True)
project_info["artifact_id"] = str_input("请输入项目 Artifact ID", required=True)
default_package_name = f"{project_info['group_id']}.{project_info['artifact_id']}".replace("-", "_")
project_info["package_name"] = str_input("请输入项目包名", required=False, default=default_package_name)
project_info["version"] = str_input("请输入项目版本号", required=True, default=args.version)
project_info["port"] = str_input("请输入端口号", required=True, default=args.port)
project_info["project_path"] = str_input("请输入项目路径", required=True)
project_info["description"] = str_input("请输入项目描述")
project_info["payment"] = bool_input("是否包含支付模块", args.payment)
project_info["debug"] = bool_input("是否开启调试模式", args.debug)
elif args.command == "run":
project_info["group_id"] = args.group_id
project_info["artifact_id"] = args.artifact_id
default_package_name = f"{project_info['group_id']}.{project_info['artifact_id']}".replace("-", "_")
project_info["package_name"] = args.package_name or default_package_name
project_info["version"] = args.version
project_info["port"] = args.port
project_info["project_path"] = args.project_path
project_info["description"] = args.description
project_info["payment"] = args.payment
project_info["debug"] = args.debug
if project_info["debug"]:
print("debug mode")
print(project_info)
if not os.path.exists(project_info["project_path"]):
os.makedirs(project_info["project_path"])
if not os.path.exists(os.path.join(project_info["project_path"], "pom.xml")):
# 初始化项目(复制 .sql 文件)
init_project()
run_package()
copy_archetype_resources()
if args.command == "init":
# 提交 commit
os.chdir(project_info["project_path"])
subprocess.run(["git", "init"])
subprocess.run(["git", "checkout", "-b", "generator"])
subprocess.run(["git", "add", "."])
subprocess.run(["git", "commit", "-m", "gen: init project"])
print("generator 执行完成")