初始提交

This commit is contained in:
焦龙言
2026-07-24 09:43:10 +08:00
commit b5b4721456
793 changed files with 116305 additions and 0 deletions
@@ -0,0 +1,3 @@
from .command import app
__all__ = ['app']
@@ -0,0 +1,273 @@
from typing import Annotated, Literal
import typer
from cli.completion.providers import COMPLETION_PROVIDER_GATEWAY
from cli.context import AllowProdOption, DryRunOption, EnvOption, OutputOption, YesOption
from .controller import GenCommandController
app = typer.Typer(
help='代码生成相关命令',
no_args_is_help=True,
context_settings={'help_option_names': ['-h', '--help']},
)
_GEN_COMMAND_CONTROLLER = GenCommandController()
@app.command('import-table', help='导入数据库表到代码生成业务表')
def import_table(
table_names: Annotated[
list[str],
typer.Argument(
help='待导入的数据库表名,可传多个',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_gen_db_table_names,
),
],
env: EnvOption = 'dev',
output: OutputOption = 'text',
allow_prod: AllowProdOption = False,
yes: YesOption = False,
dry_run: DryRunOption = False,
) -> None:
"""
导入数据库表到代码生成业务表。
:param table_names: 待导入表名列表
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:return: None
"""
_GEN_COMMAND_CONTROLLER.import_table(
table_names,
env,
output,
allow_prod,
yes,
dry_run,
)
@app.command('list', help='查看代码生成业务表列表')
def list_command(
env: EnvOption = 'dev',
output: OutputOption = 'text',
table_name: str = typer.Option(
'',
'--table-name',
help='按表名称过滤',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_gen_table_names,
),
table_comment: str = typer.Option('', '--table-comment', help='按表描述过滤'),
paged: bool = typer.Option(False, '--paged/--no-paged', help='是否启用分页结果'),
page_num: int = typer.Option(1, '--page-num', min=1, help='分页页码'),
page_size: int = typer.Option(20, '--page-size', min=1, help='分页每页数量'),
) -> None:
"""
查看代码生成业务表列表。
:param env: 当前命令运行环境
:param output: 输出格式
:param table_name: 表名称过滤条件
:param table_comment: 表描述过滤条件
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
:return: None
"""
_GEN_COMMAND_CONTROLLER.list_tables(
env,
output,
table_name=table_name,
table_comment=table_comment,
paged=paged,
page_num=page_num,
page_size=page_size,
)
@app.command('db-list', help='查看数据库中可导入的物理表列表')
def db_list(
env: EnvOption = 'dev',
output: OutputOption = 'text',
table_name: str = typer.Option(
'',
'--table-name',
help='按表名称过滤',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_gen_db_table_names,
),
table_comment: str = typer.Option('', '--table-comment', help='按表描述过滤'),
paged: bool = typer.Option(False, '--paged/--no-paged', help='是否启用分页结果'),
page_num: int = typer.Option(1, '--page-num', min=1, help='分页页码'),
page_size: int = typer.Option(20, '--page-size', min=1, help='分页每页数量'),
) -> None:
"""
查看数据库中可导入的物理表列表。
:param env: 当前命令运行环境
:param output: 输出格式
:param table_name: 表名称过滤条件
:param table_comment: 表描述过滤条件
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
:return: None
"""
_GEN_COMMAND_CONTROLLER.list_db_tables(
env,
output,
table_name=table_name,
table_comment=table_comment,
paged=paged,
page_num=page_num,
page_size=page_size,
)
@app.command('detail', help='查看单个代码生成业务表详情')
def detail(
table_id: Annotated[int, typer.Argument(help='业务表 ID')],
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
查看单个代码生成业务表详情。
:param table_id: 业务表 ID
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_GEN_COMMAND_CONTROLLER.show_detail(table_id, env, output)
@app.command('create-table', help='根据建表 SQL 创建表结构并导入代码生成业务表')
def create_table(
env: EnvOption = 'dev',
output: OutputOption = 'text',
allow_prod: AllowProdOption = False,
yes: YesOption = False,
dry_run: DryRunOption = False,
sql: str = typer.Option('', '--sql', help='直接传入建表 SQL 文本'),
sql_file: str = typer.Option(
'',
'--sql-file',
help='从文件读取建表 SQL',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_sql_files,
),
) -> None:
"""
根据建表 SQL 创建表结构并导入代码生成业务表。
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param sql: 直接传入的 SQL 文本
:param sql_file: SQL 文件路径
:return: None
"""
_GEN_COMMAND_CONTROLLER.create_table(
env,
output,
allow_prod,
yes,
dry_run,
sql=sql,
sql_file=sql_file,
)
@app.command('preview', help='查看指定业务表的代码生成结果预览')
def preview(
table_id: Annotated[int, typer.Argument(help='业务表 ID')],
env: EnvOption = 'dev',
output: OutputOption = 'text',
) -> None:
"""
预览指定业务表的代码生成结果。
:param table_id: 业务表 ID
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
_GEN_COMMAND_CONTROLLER.preview(table_id, env, output)
@app.command('export', help='导出代码生成结果')
def export(
table_names: Annotated[
list[str],
typer.Argument(
help='待导出的业务表名,可传多个',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_gen_table_names,
),
],
env: EnvOption = 'dev',
output: OutputOption = 'text',
allow_prod: AllowProdOption = False,
yes: YesOption = False,
dry_run: DryRunOption = False,
mode: Annotated[Literal['zip', 'local'], typer.Option('--mode', help='导出模式')] = 'zip',
output_file: str = typer.Option(
'',
'--output-file',
help='zip 导出目标文件路径',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_output_paths,
),
) -> None:
"""
导出代码生成结果。
:param table_names: 业务表名称列表
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param mode: 导出模式
:param output_file: zip 导出目标文件路径
:return: None
"""
_GEN_COMMAND_CONTROLLER.export(
table_names,
env,
output,
allow_prod,
yes,
dry_run,
mode=mode,
output_file=output_file,
)
@app.command('sync-db', help='同步指定业务表的数据库表结构')
def sync_db(
table_name: Annotated[
str,
typer.Argument(
help='业务表名称',
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_gen_table_names,
),
],
env: EnvOption = 'dev',
output: OutputOption = 'text',
allow_prod: AllowProdOption = False,
yes: YesOption = False,
) -> None:
"""
同步指定业务表的数据库表结构。
:param table_name: 业务表名称
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:return: None
"""
_GEN_COMMAND_CONTROLLER.sync_db(table_name, env, output, allow_prod, yes)
@@ -0,0 +1,304 @@
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
CliExecutionService,
)
from cli.runtime.gen import GEN_RUNTIME, GenRuntimeService
from .presenter import GenCommandPresenter
class GenCommandController:
"""
代码生成命令控制器。
该控制器负责组织 `gen` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
:param context_factory: CLI 上下文工厂
:param execution_service: CLI 执行服务
:param presenter: 代码生成命令文本渲染器
"""
def __init__(
self,
*,
context_factory: CliContextFactory | None = None,
execution_service: CliExecutionService | None = None,
presenter: GenCommandPresenter | None = None,
runtime_service: GenRuntimeService | None = None,
) -> None:
"""
初始化代码生成命令控制器。
:param context_factory: CLI 上下文工厂
:param execution_service: CLI 执行服务
:param presenter: 代码生成命令文本渲染器
:param runtime_service: 代码生成运行时服务
:return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
self.presenter = presenter or GenCommandPresenter()
self.runtime_service = runtime_service or GEN_RUNTIME
def import_table(
self,
table_names: list[str],
env: str,
output: str,
allow_prod: bool,
yes: bool,
dry_run: bool,
) -> None:
"""
导入数据库表到代码生成业务表。
:param table_names: 待导入表名列表
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:return: None
"""
ctx = self.context_factory.build_dangerous(
env,
output,
allow_prod,
yes,
dry_run,
command_name='gen import-table',
)
payload = self.execution_service.run_async(self.runtime_service.import_tables(table_names, dry_run=dry_run))
payload['env'] = ctx.env
self.execution_service.complete_payload(ctx, payload)
def list_tables(
self,
env: str,
output: str,
*,
table_name: str,
table_comment: str,
paged: bool,
page_num: int,
page_size: int,
) -> None:
"""
查看代码生成业务表列表。
:param env: 当前命令运行环境
:param output: 输出格式
:param table_name: 表名称过滤条件
:param table_comment: 表描述过滤条件
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(
self.runtime_service.list_gen_tables(
table_name=table_name,
table_comment=table_comment,
paged=paged,
page_num=page_num,
page_size=page_size,
)
)
payload['env'] = ctx.env
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=lambda data: self.presenter.build_gen_table_list_text(data, db_mode=False),
text_condition=lambda data: data.get('ok', False),
)
def list_db_tables(
self,
env: str,
output: str,
*,
table_name: str,
table_comment: str,
paged: bool,
page_num: int,
page_size: int,
) -> None:
"""
查看数据库中可导入的物理表列表。
:param env: 当前命令运行环境
:param output: 输出格式
:param table_name: 表名称过滤条件
:param table_comment: 表描述过滤条件
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(
self.runtime_service.list_gen_db_tables(
table_name=table_name,
table_comment=table_comment,
paged=paged,
page_num=page_num,
page_size=page_size,
)
)
payload['env'] = ctx.env
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=lambda data: self.presenter.build_gen_table_list_text(data, db_mode=True),
text_condition=lambda data: data.get('ok', False),
)
def show_detail(self, table_id: int, env: str, output: str) -> None:
"""
查看单个代码生成业务表详情。
:param table_id: 业务表 ID
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.get_gen_table_detail(table_id))
payload['env'] = ctx.env
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_gen_detail_text,
text_condition=lambda data: 'error' not in data,
)
def create_table(
self,
env: str,
output: str,
allow_prod: bool,
yes: bool,
dry_run: bool,
*,
sql: str,
sql_file: str,
) -> None:
"""
根据建表 SQL 创建表结构并导入代码生成业务表。
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param sql: 直接传入的 SQL 文本
:param sql_file: SQL 文件路径
:return: None
"""
ctx = self.context_factory.build_dangerous(
env,
output,
allow_prod,
yes,
dry_run,
command_name='gen create-table',
)
payload = self.execution_service.run_async(self.runtime_service.create_tables(sql, sql_file, dry_run=dry_run))
payload['env'] = ctx.env
self.execution_service.complete_payload(ctx, payload)
def preview(self, table_id: int, env: str, output: str) -> None:
"""
预览指定业务表的代码生成结果。
:param table_id: 业务表 ID
:param env: 当前命令运行环境
:param output: 输出格式
:return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.preview_code(table_id))
payload['env'] = ctx.env
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_gen_preview_text,
text_condition=lambda data: data.get('ok', False),
)
def export(
self,
table_names: list[str],
env: str,
output: str,
allow_prod: bool,
yes: bool,
dry_run: bool,
*,
mode: str,
output_file: str,
) -> None:
"""
导出代码生成结果。
:param table_names: 业务表名称列表
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param mode: 导出模式
:param output_file: zip 导出目标文件路径
:return: None
"""
ctx = self.context_factory.build_dangerous(
env,
output,
allow_prod,
yes,
dry_run,
command_name='gen export',
)
payload = self.execution_service.run_async(
self.runtime_service.export_code(table_names, mode=mode, output_file=output_file, dry_run=dry_run)
)
payload['env'] = ctx.env
self.execution_service.complete_payload_with_text(
ctx,
payload,
text_builder=self.presenter.build_gen_export_text,
text_condition=lambda data: data.get('ok', False),
)
def sync_db(
self,
table_name: str,
env: str,
output: str,
allow_prod: bool,
yes: bool,
) -> None:
"""
同步指定业务表的数据库表结构。
:param table_name: 业务表名称
:param env: 当前命令运行环境
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:return: None
"""
ctx = self.context_factory.build_dangerous(
env,
output,
allow_prod,
yes,
False,
command_name='gen sync-db',
)
payload = self.execution_service.run_async(self.runtime_service.sync_gen_table_from_db(table_name))
payload['env'] = ctx.env
self.execution_service.complete_payload(ctx, payload)
@@ -0,0 +1,231 @@
from cli.utils import SHELL_TEXT_FORMATTER
class GenCommandPresenter:
"""
代码生成命令文本渲染器。
该渲染器负责将 `gen` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
def build_gen_preview_text(self, payload: dict[str, object]) -> str:
"""
将代码预览结果渲染为文本摘要。
:param payload: 代码预览结果字典
:return: 文本摘要
"""
preview_payload = payload.get('preview')
lines = [
f'ok: {str(payload.get("ok", False)).lower()}',
f'env: {payload.get("env", "")}',
f'table_id: {payload.get("tableId", "-")}',
f'template_count: {payload.get("templateCount", 0)}',
]
if not isinstance(preview_payload, dict) or not preview_payload:
lines.append('templates: none')
return '\n'.join(lines)
lines.append('templates:')
for template_name, template_content in preview_payload.items():
lines.extend([f' {line}' for line in self._build_text_block(str(template_name), template_content)])
return '\n'.join(lines)
def build_gen_export_text(self, payload: dict[str, object]) -> str:
"""
将代码导出结果渲染为文本摘要。
:param payload: 代码导出结果字典
:return: 文本摘要
"""
table_names = payload.get('tableNames')
results = payload.get('results')
lines = [
f'ok: {str(payload.get("ok", False)).lower()}',
f'env: {payload.get("env", "")}',
f'mode: {payload.get("mode", "-")}',
f'dry_run: {str(payload.get("dryRun", False)).lower()}',
f'message: {payload.get("message", "-")}',
]
if isinstance(table_names, list) and table_names:
lines.append('table_names:')
lines.extend(f' - {table_name}' for table_name in table_names)
else:
lines.append('table_names: none')
if payload.get('outputFile'):
lines.append(f'output_file: {payload.get("outputFile")}')
if payload.get('genPath'):
lines.append(f'gen_path: {payload.get("genPath")}')
if payload.get('size') is not None:
lines.append(f'size: {payload.get("size")}')
if isinstance(results, list) and results:
lines.append('results:')
lines.extend(
f' - {item.get("tableName", "-")}: {str(item.get("ok", False)).lower()} | {item.get("message", "-")}'
for item in results
if isinstance(item, dict)
)
return '\n'.join(lines)
def build_gen_table_list_text(self, payload: dict[str, object], *, db_mode: bool = False) -> str:
"""
将代码生成表列表或数据库表列表渲染为文本摘要。
:param payload: 列表结果字典
:param db_mode: 是否为数据库物理表列表模式
:return: 文本摘要
"""
lines = [f'ok: {str(payload.get("ok", False)).lower()}']
filters = payload.get('filters')
if isinstance(filters, dict):
lines.extend(self._build_gen_filter_lines(filters))
page_payload = payload.get('page')
if isinstance(page_payload, dict):
rows = page_payload.get('rows', [])
lines.append(
'page: '
f'{page_payload.get("pageNum", "-")}/{page_payload.get("pages", "-")} '
f'(page_size={page_payload.get("pageSize", "-")}, total={page_payload.get("total", "-")})'
)
lines.append(f'count: {len(rows) if isinstance(rows, list) else 0}')
if not isinstance(rows, list) or not rows:
lines.append('items: none')
return '\n'.join(lines)
lines.append('items:')
for row in rows:
if isinstance(row, dict):
item_lines = (
self._build_gen_db_table_item_lines(row) if db_mode else self._build_gen_table_item_lines(row)
)
lines.extend([f' {item}' for item in item_lines])
return '\n'.join(lines)
items = payload.get('items')
lines.append(f'count: {payload.get("count", 0)}')
if not isinstance(items, list) or not items:
lines.append('items: none')
return '\n'.join(lines)
lines.append('items:')
for item in items:
if isinstance(item, dict):
item_lines = (
self._build_gen_db_table_item_lines(item) if db_mode else self._build_gen_table_item_lines(item)
)
lines.extend([f' {line}' for line in item_lines])
return '\n'.join(lines)
def build_gen_detail_text(self, payload: dict[str, object]) -> str:
"""
将代码生成业务表详情渲染为文本摘要。
:param payload: 详情结果字典
:return: 文本摘要
"""
detail = payload.get('detail')
if not isinstance(detail, dict):
return '\n'.join(
[
f'ok: {str(payload.get("ok", False)).lower()}',
f'table_id: {payload.get("tableId", "-")}',
'detail: none',
]
)
info = detail.get('info')
if not isinstance(info, dict):
return '\n'.join(
[
f'ok: {str(payload.get("ok", False)).lower()}',
f'table_id: {payload.get("tableId", "-")}',
'info: none',
]
)
return '\n'.join(
[
f'ok: {str(payload.get("ok", False)).lower()}',
f'table_id: {payload.get("tableId", "-")}',
f'table_name: {payload.get("tableName", "-")}',
f'column_count: {payload.get("columnCount", 0)}',
f'table_count: {payload.get("tableCount", 0)}',
f'table_comment: {SHELL_TEXT_FORMATTER.truncate_text(info.get("tableComment", ""), 80) or "-"}',
f'class_name: {info.get("className", "-")}',
f'tpl_category: {info.get("tplCategory", "-")}',
f'tpl_web_type: {info.get("tplWebType", "-")}',
f'package_name: {SHELL_TEXT_FORMATTER.truncate_text(info.get("packageName", ""), 80) or "-"}',
f'module_name: {info.get("moduleName", "-")}',
f'business_name: {info.get("businessName", "-")}',
f'function_name: {info.get("functionName", "-")}',
f'function_author: {info.get("functionAuthor", "-")}',
f'gen_type: {info.get("genType", "-")}',
f'gen_path: {SHELL_TEXT_FORMATTER.truncate_text(info.get("genPath", ""), 120) or "-"}',
f'remark: {SHELL_TEXT_FORMATTER.truncate_text(info.get("remark", ""), 160) or "-"}',
]
)
@staticmethod
def _build_text_block(title: str, value: object) -> list[str]:
"""
将多行文本构建为带标题的块级文本。
:param title: 块标题
:param value: 原始文本值
:return: 文本行列表
"""
text = '' if value is None else str(value)
if not text.strip():
return [f'{title}: -']
return [f'{title}:', ' |', *[f' {line}' for line in text.splitlines()]]
@staticmethod
def _build_gen_filter_lines(filters: dict[str, object]) -> list[str]:
"""
构建代码生成表过滤条件文本行。
:param filters: 过滤条件字典
:return: 过滤条件文本行列表
"""
active_filters = []
for key, value in filters.items():
if value in (None, '', False):
continue
active_filters.append(f'{SHELL_TEXT_FORMATTER.to_snake_case(key)}={value}')
if not active_filters:
return ['filters: none']
return ['filters:', *[f' - {item}' for item in active_filters]]
@staticmethod
def _build_gen_table_item_lines(table_item: dict[str, object]) -> list[str]:
"""
构建单条代码生成表记录的文本行。
:param table_item: 代码生成表记录
:return: 文本行列表
"""
return [
f'- [{table_item.get("tableId", "-")}] {SHELL_TEXT_FORMATTER.truncate_text(table_item.get("tableName", ""), 40) or "-"}',
f' comment: {SHELL_TEXT_FORMATTER.truncate_text(table_item.get("tableComment", ""), 60) or "-"}',
f' class_name: {table_item.get("className", "-")}',
f' tpl_category: {table_item.get("tplCategory", "-")} | module_name: {table_item.get("moduleName", "-")}',
f' business_name: {table_item.get("businessName", "-")} | function_name: {table_item.get("functionName", "-")}',
]
@staticmethod
def _build_gen_db_table_item_lines(table_item: dict[str, object]) -> list[str]:
"""
构建单条数据库物理表记录的文本行。
:param table_item: 数据库物理表记录
:return: 文本行列表
"""
return [
f'- {SHELL_TEXT_FORMATTER.truncate_text(table_item.get("tableName", ""), 48) or "-"}',
f' comment: {SHELL_TEXT_FORMATTER.truncate_text(table_item.get("tableComment", ""), 80) or "-"}',
f' create_time: {table_item.get("createTime", "-")}',
f' update_time: {table_item.get("updateTime", "-")}',
]