feat(codegen): 新增 dacli form codegen 表单代码生成 (白皮书 5.5, 参考 aibridge)
白皮书 5.5 — mybatis-plus-generator 自动生成前后端代码, Java 版 dacli 有,
TS 版 v0.8 没继承, 这次补上。
参考 aibridge CodeGenerator (docs/aibridge/code/utils/code_generator.py)
的接口形状, 但 v1 实现做了简化:
aibridge 风格:
CodeGenerator(func_id, module_name, enable_flow, tables, form_type,
description, auto_fix_names).generate()
dacli 实现:
dacli form codegen <formId> [options]
v1 选项 (8 个):
--module 业务模块名 (例 tds), 目录名
--modulePackage 包名 (例 ssw.tds)
--description 功能描述
--dbLinkId 数据源 id
--mainClassName 主类名 PascalCase
--enableFlow 0/1
--out 输出目录 (默认 ./generated/<formId>/)
--auto-fix-names 改 Ais_xxx → PascalCase (aibridge 风格的简化版)
--auto-menu 生成完直接挂菜单 (TODO, 暂未实现)
API 流程:
1. GET /api/visualdev/Base/{id} 拿 enCode/fullName
2. POST /api/visualdev/Generater/{id}/Actions/CodePreview
body = DownloadCodeForm { module, modulePackageName, description,
dataSourceId, mainClassName, enableFlow, contrast }
3. 遍历返回的 list[] 文件树, 按 folderName (vue/ts/xml/java/json) 分类
4. 按 kind (web/entity/model/service/mapper/controller) 写到 --out
5. --auto-fix-names 时扫 java 文件, 检测 Ais_xxx 前缀, 替换成 mainClassName
限制:
- 必须先 release (state=1), 否则 CodePreview 返空
- --auto-fix-names 是简化版, 深度修复 (包名/import/前端 import 路径) 需另写
- --auto-menu 待实现, 计划调 menu create 自动挂菜单
参考:
- aibridge code/utils/code_generator.py (Python, 500+ 行)
- aibridge code/utils/run-codegen.py (CLI 入口)
- jnpf/后端/.../VisualdevGenController.java (CodePreview 端点)
Co-Authored-By: Claude <[email protected]>
This commit is contained in:
1 parent
233cf81876
commit
087a26d408
2 files changed
+207
-1
No files matched your search
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* commands/form/codegen.ts — 表单代码生成器 (白皮书 5.5)
|
||||
*
|
||||
* 参考 aibridge CodeGenerator:
|
||||
* /home/ubuntu/ccWorkDir/docs/aibridge/code/utils/code_generator.py
|
||||
*
|
||||
* 流程:
|
||||
* 1. POST /api/visualdev/Generater/{id}/Actions/CodePreview 拿文件树
|
||||
* 2. 遍历 tree, 按 fileName 后缀分类 (vue/ts → frontend, java/xml/json → backend)
|
||||
* 3. 写到 --out 目录
|
||||
* 4. (可选) --auto-fix-names: 把 JNPF 生成的 Ais_xxx → PascalCase (aibridge 风格)
|
||||
* 5. (可选) --auto-menu: 生成完直接调 dacli menu create 挂菜单
|
||||
*
|
||||
* 注意: 该功能白皮书 5.5 提到, Java 版 dacli 也有, TS 版 v0.8 没继承。
|
||||
* v1 实现是"直写", 不做 aibridge 那种深度类名修复 (那是大工程)。
|
||||
*/
|
||||
import { Command } from 'commander'
|
||||
import { writeFileSync, mkdirSync, existsSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installAiHelpHook } from '../../core/help.ts'
|
||||
import { log, printJson } from '../../core/log.ts'
|
||||
|
||||
interface CodegenOpts {
|
||||
module?: string
|
||||
modulePackage?: string
|
||||
description?: string
|
||||
dbLinkId?: string
|
||||
mainClassName?: string
|
||||
enableFlow?: string
|
||||
out?: string
|
||||
autoFixNames?: boolean
|
||||
autoMenu?: boolean
|
||||
json?: boolean
|
||||
}
|
||||
|
||||
interface CodeTreeItem {
|
||||
fileName: string
|
||||
fileContent: string
|
||||
folderName: string
|
||||
children?: CodeTreeItem[]
|
||||
}
|
||||
|
||||
/** 分类文件: 前端 vs 后端, 后端再细分 */
|
||||
function classifyFile(item: CodeTreeItem): 'web' | 'entity' | 'model' | 'service' | 'mapper' | 'controller' | null {
|
||||
const folder = (item.folderName || '').toLowerCase()
|
||||
const name = item.fileName
|
||||
if (!item.fileContent) return null
|
||||
if (folder === 'vue' || folder === 'ts' || folder === 'js') return 'web'
|
||||
if (folder === 'xml') return 'mapper'
|
||||
if (folder === 'json') return 'model'
|
||||
if (folder === 'java') {
|
||||
if (name.includes('Controller')) return 'controller'
|
||||
if (name.includes('ServiceImpl')) return 'service'
|
||||
if (name.includes('Service')) return 'service'
|
||||
if (name.includes('Mapper')) return 'mapper'
|
||||
if (name.includes('Entity')) return 'entity'
|
||||
if (name.includes('Excel') || name.includes('Form') || name.includes('Pagination') || name.includes('Constant') || name.includes('Json')) return 'model'
|
||||
return 'model'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 从 aibridge 的 _detect_old_prefix 学来的: 找 JNPF 生成的 Ais_xxx 风格前缀 */
|
||||
function detectOldPrefix(content: string): string | null {
|
||||
// 形如 `public class Ais_aisprojectInfo` 的前缀
|
||||
const m = content.match(/public\s+class\s+([A-Z][a-z]?)_([A-Z]?[a-z]+\w*)/)
|
||||
if (m) return `${m[1]}_`
|
||||
return null
|
||||
}
|
||||
|
||||
export function buildFormCodegenCommand(): Command {
|
||||
const cmd = new Command('codegen')
|
||||
.description('表单代码生成 (白皮书 5.5, 参考 aibridge CodeGenerator)')
|
||||
.argument('<formId>', 'form id (要先 release, state=1)')
|
||||
.option('--module <name>', '业务模块名 (例 tds) — 用于目录名, 不影响类名')
|
||||
.option('--modulePackage <pkg>', '模块包名 (例 ssw.tds) — 写到 Java package 行')
|
||||
.option('--description <desc>', '功能描述 (写到类注释)')
|
||||
.option('--dbLinkId <id>', '数据源 id (走业务库, 默认从 token.dbLinkId)')
|
||||
.option('--mainClassName <name>', '主表类名 (PascalCase, 默认取 enCode)')
|
||||
.option('--enableFlow <0|1>', '是否启用流程 0/1', '0')
|
||||
.option('--out <path>', '输出目录 (默认 ./generated/<formId>/)')
|
||||
.option('--auto-fix-names', '自动改类名前缀 Ais_xxx → PascalCase (aibridge 风格, 简化版)', false)
|
||||
.option('--auto-menu', '生成完直接调 menu create 挂菜单', false)
|
||||
.option('--json', '原始 JSON 输出 (file tree)', false)
|
||||
.action(async (formId: string, opts: CodegenOpts) => {
|
||||
const c = await JnpfClient.fromToken()
|
||||
const dbLinkId = opts.dbLinkId || c.dbLinkId || '0'
|
||||
|
||||
// 1. 拿 form 概要 (拿 enCode 当默认 mainClassName)
|
||||
const info = await c.get<{ enCode?: string; fullName?: string }>(`/visualdev/Base/${formId}`)
|
||||
const enCode = info.data?.enCode || formId
|
||||
const fullName = info.data?.fullName || enCode
|
||||
const mainClassName = opts.mainClassName || enCode
|
||||
const modulePackage = opts.modulePackage || `ssw.${opts.module || enCode}`
|
||||
|
||||
const body = {
|
||||
module: opts.module || enCode,
|
||||
modulePackageName: modulePackage,
|
||||
description: opts.description || fullName,
|
||||
dataSourceId: dbLinkId,
|
||||
mainClassName,
|
||||
enableFlow: Number(opts.enableFlow || '0'),
|
||||
contrast: false,
|
||||
}
|
||||
|
||||
log.info(`POST /visualdev/Generater/${formId}/Actions/CodePreview`)
|
||||
const r = await c.postJson<unknown>(`/visualdev/Generater/${formId}/Actions/CodePreview`, body)
|
||||
if (r.code !== 200) {
|
||||
log.error(`CodePreview 失败 (code=${r.code}): ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
const data = r.data as { list?: CodeTreeItem[] } | undefined
|
||||
const tree = data?.list || []
|
||||
if (tree.length === 0) {
|
||||
log.warn('CodePreview 返回空 list, 没文件可生成 (确认 form 已发布 state=1)')
|
||||
return
|
||||
}
|
||||
if (opts.json) {
|
||||
printJson({ formId, enCode, fullName, body, tree })
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 展开 tree, 分类
|
||||
const files: { kind: string; path: string; content: string }[] = []
|
||||
const traverse = (items: CodeTreeItem[], parent = '') => {
|
||||
for (const it of items) {
|
||||
const path = parent ? `${parent}/${it.fileName}` : it.fileName
|
||||
if (it.children?.length) {
|
||||
traverse(it.children, path)
|
||||
} else {
|
||||
const kind = classifyFile(it)
|
||||
if (kind) files.push({ kind, path, content: it.fileContent })
|
||||
}
|
||||
}
|
||||
}
|
||||
traverse(tree)
|
||||
|
||||
// 3. 写到 --out
|
||||
const outDir = opts.out || join(process.cwd(), 'generated', enCode)
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
log.info(`输出目录: ${outDir}`)
|
||||
const counts: Record<string, number> = {}
|
||||
for (const f of files) {
|
||||
const fullPath = join(outDir, f.path)
|
||||
mkdirSync(dirname(fullPath), { recursive: true })
|
||||
let content = f.content
|
||||
if (opts.autoFixNames && (f.kind === 'controller' || f.kind === 'service' || f.kind === 'entity')) {
|
||||
const oldPrefix = detectOldPrefix(content)
|
||||
if (oldPrefix) {
|
||||
content = content.replace(new RegExp(`\\b${oldPrefix}`, 'g'), mainClassName)
|
||||
log.debug(`fix prefix: ${oldPrefix} → ${mainClassName} in ${f.path}`)
|
||||
}
|
||||
}
|
||||
writeFileSync(fullPath, content, 'utf-8')
|
||||
counts[f.kind] = (counts[f.kind] || 0) + 1
|
||||
}
|
||||
log.ok(`✓ 生成 ${files.length} 个文件`)
|
||||
for (const [k, v] of Object.entries(counts)) {
|
||||
log.info(` ${k}: ${v}`)
|
||||
}
|
||||
log.info(`输出到: ${outDir}`)
|
||||
log.info('')
|
||||
log.info('后续步骤:')
|
||||
log.info(' 1. 在 IDE 打开生成的 Java 文件, 检查 import 和 @RestController 路径')
|
||||
log.info(' 2. mvn package 编译 (boot/ssw-<module>-controller)')
|
||||
log.info(' 3. 部署到 jnpf-admin')
|
||||
log.info(' 4. 重启 JNPF 后浏览器访问 /api/<module>/... 验')
|
||||
if (opts.autoMenu) {
|
||||
log.info('--auto-menu 暂未实现 (TODO: 调 menu create 自动挂菜单)')
|
||||
}
|
||||
})
|
||||
installAiHelpHook(cmd, {
|
||||
purpose: '表单代码生成 (白皮书 5.5) — 调平台 CodePreview, 写到本地目录, 参考 aibridge CodeGenerator',
|
||||
required: { '<formId>': 'form id (要先 release, state=1)' },
|
||||
optional: {
|
||||
'--module': '业务模块名 (例 tds), 目录名',
|
||||
'--modulePackage': '包名 (例 ssw.tds)',
|
||||
'--description': '功能描述 (类注释)',
|
||||
'--dbLinkId': '数据源 id',
|
||||
'--mainClassName': '主类名 PascalCase',
|
||||
'--enableFlow': '0/1',
|
||||
'--out': '输出目录 (默认 ./generated/<formId>/)',
|
||||
'--auto-fix-names': '自动改 Ais_xxx → PascalCase (简化版, 不如 aibridge 完整)',
|
||||
'--auto-menu': '生成完直接挂菜单 (TODO)',
|
||||
},
|
||||
example: [
|
||||
'dacli form codegen 808986025610185477 --module=tds --out=./generated/',
|
||||
'dacli form codegen 808986025610185477 --module=tds --enable-flow=1 --auto-fix-names',
|
||||
],
|
||||
source: {
|
||||
web: 'web/.../formDesign/CodeGen.vue',
|
||||
api: 'POST /api/visualdev/Generater/{id}/Actions/CodePreview',
|
||||
ref: 'aibridge code/utils/code_generator.py (Python 参考实现)',
|
||||
},
|
||||
notes: [
|
||||
'form 必须先 release (state=1), 否则 CodePreview 返空',
|
||||
'生成的是 JNPF 默认包名 Ais_xxx, --auto-fix-names 做简化版改名',
|
||||
'深度类名修复 (aibridge 风格) 需另写, v1 暂不覆盖',
|
||||
'白皮书 5.5 提到 mybatis-plus-generator 是该能力底层',
|
||||
],
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
@@ -12,9 +12,10 @@ import { buildFormImportCommand } from './import.ts'
|
||||
import { buildFormCloneCommand } from './clone.ts'
|
||||
import { buildFormValidateCommand } from './validate.ts'
|
||||
import { buildFormFixColumnDataCommand } from './fix-columndata.ts'
|
||||
import { buildFormCodegenCommand } from './codegen.ts'
|
||||
|
||||
export function buildFormCommand(): Command {
|
||||
const cmd = new Command('form').description('表单 CRUD (list/info/create/release/delete/export/import/clone/validate/fix-columndata)')
|
||||
const cmd = new Command('form').description('表单 CRUD (list/info/create/release/delete/export/import/clone/validate/fix-columndata/codegen)')
|
||||
cmd.addCommand(buildFormListCommand())
|
||||
cmd.addCommand(buildFormInfoCommand())
|
||||
cmd.addCommand(buildFormCreateCommand())
|
||||
@@ -25,5 +26,6 @@ export function buildFormCommand(): Command {
|
||||
cmd.addCommand(buildFormCloneCommand())
|
||||
cmd.addCommand(buildFormValidateCommand())
|
||||
cmd.addCommand(buildFormFixColumnDataCommand())
|
||||
cmd.addCommand(buildFormCodegenCommand())
|
||||
return cmd
|
||||
}
|
||||
Reference in new issue
Block a user