Add code generation preview mode CLI command (#1036)

This commit is contained in:
Wu Clan
2026-01-25 15:17:04 +08:00
committed by GitHub
parent 19d8a2964f
commit fbdc3f2dc5

View File

@@ -428,7 +428,7 @@ async def import_table(
raise cappa.Exit(e.msg if isinstance(e, BaseExceptionError) else str(e), code=1)
async def generate() -> None:
async def generate(*, preview: bool = False) -> None:
if settings.ENVIRONMENT != 'dev':
raise cappa.Exit('代码生成仅在开发环境可用', code=1)
@@ -461,14 +461,40 @@ async def generate() -> None:
console.print(table)
business = IntPrompt.ask('请从中选择一个业务编号', choices=[str(id_) for id_ in ids])
async with async_db_session.begin() as db:
gen_path = await gen_service.generate(db=db, pk=business)
# 预览
async with async_db_session() as db:
preview_data = await gen_service.preview(db=db, pk=business)
console.print('\n[bold yellow]将要生成以下文件:[/]')
file_table = Table(show_header=True, header_style='bold cyan')
file_table.add_column('文件路径', style='white')
file_table.add_column('大小', style='green', justify='right')
for filepath, content in sorted(preview_data.items()):
size = len(content)
size_str = f'{size} B' if size < 1024 else f'{size / 1024:.1f} KB'
file_table.add_row(filepath, size_str)
console.print(file_table)
if preview:
console.print('\n[bold cyan]预览模式:未执行实际生成操作[/]')
return
# 生成
console.print('\n[bold red]警告:代码生成将进行磁盘文件(覆盖)写入,切勿在生产环境中使用!!![/]')
ok = Prompt.ask('\n确认继续生成代码吗?', choices=['y', 'n'], default='n')
if ok.lower() == 'y':
async with async_db_session.begin() as db:
gen_path = await gen_service.generate(db=db, pk=business)
console.print('\n代码已生成完成', style='bold green')
console.print(Text('\n详情请查看:'), Text(str(gen_path), style='bold white'))
except Exception as e:
raise cappa.Exit(e.msg if isinstance(e, BaseExceptionError) else str(e), code=1)
console.print('\n代码已生成完成', style='bold green')
console.print(Text('\n详情请查看:'), Text(str(gen_path), style='bold magenta'))
@cappa.command(help='初始化 fba 项目', default_long=True)
@dataclass
@@ -617,6 +643,10 @@ class Import:
@cappa.command(name='codegen', help='代码生成(体验完整功能,请自行部署 fba vben 前端工程)', default_long=True)
@dataclass
class CodeGenerator:
preview: Annotated[
bool,
cappa.Arg(short='-p', default=False, help='仅预览将要生成的文件,不执行实际生成操作'),
]
subcmd: cappa.Subcommands[Import | None] = None
def __post_init__(self) -> None:
@@ -626,7 +656,7 @@ class CodeGenerator:
raise cappa.Exit('代码生成插件不存在,请先安装此插件')
async def __call__(self) -> None:
await generate()
await generate(preview=self.preview)
@cappa.command(help='一个高效的 fba 命令行界面', default_long=True)