feat(codegen): --module-only selective export + fixUnresolvedVelocityVars
New --module-only flag for selective module export (all/entity/biz/controller).
Auto-adjusts --multi-module-pom to only generate selected module poms.
fixUnresolvedVelocityVars() post-processes JNPF .java templates that emit
literal ${...} placeholders when Velocity vars are undefined. Three paths:
1. method calls - capitalize last .method() name (Java getter convention)
2. private declaration - use curJsonProp snake_case to camelCase
3. simple variable - keep original case (avoid afterVModel becoming afterVmodel)
End-to-end verified: --module-only=entity compiles 0 errors, 6 .class files.
Full 3-module compile still has 43 ServiceImpl errors (undefined ${search.*} getters
are inherent JNPF template bug, dacli can only make syntax valid not runtime).
This commit is contained in:
1 parent
6d7fb68f2c
commit
3e024ac111
1 file changed
+148
-11
+148
-11
@@ -70,6 +70,11 @@ interface CodegenOpts {
|
||||
* 与 --flat 互斥 (pom 必须配合多模块结构才有意义)
|
||||
*/
|
||||
multiModulePom?: boolean
|
||||
/**
|
||||
* 只导出指定模块 (默认 all). 用于单模块测试/编译验证
|
||||
* 值: all | entity | biz | controller | entity,biz 逗号分隔
|
||||
*/
|
||||
moduleOnly?: string
|
||||
autoMenu?: boolean
|
||||
json?: boolean
|
||||
}
|
||||
@@ -190,6 +195,68 @@ function detectOldPrefixFromContent(content: string): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* JNPF 模板 bug 后处理: 修复 Velocity 未替换的字面 ${...} 占位符 (含方法调用)
|
||||
*
|
||||
* 根因 (多个模板): Form.java.vm / Pagination.java.vm / ServiceImpl.java.vm 用了
|
||||
* `#set($x = "${y}")` 但 $y 为 undefined, Velocity 把字面字符串赋给 $x, 导致输出
|
||||
* `private XXX ${y};` 或 `form.get${Field.fieldAlias.substring(...)}()` 这种非法 Java 代码
|
||||
*
|
||||
* 修复策略: 对 .java 文件中所有 ${xxx.yyy[.method(args)]} 字面占位符:
|
||||
* - 简单 ${xxx}: 用 @JsonProperty 推 camelCase (Form 字段) 或通用占位符
|
||||
* - 含方法调用 ${xxx.method()}: 整个表达式替换为通用驼峰名 (ServiceImpl getter 等)
|
||||
*
|
||||
* 例: Form.java 原始 → 修复后
|
||||
* @JsonProperty("f_team_name")
|
||||
* @JSONField(name = "f_team_name")
|
||||
* private String ${html.fieldAlias}; private String fteamName;
|
||||
*
|
||||
* ServiceImpl.java 原始 → 修复后
|
||||
* form.get${Field.fieldAlias.substring(0,1).toUpperCase()}${Field.fieldAlias.substring(1)}()
|
||||
* → form.getFieldAlias() // 占位符, 编译过但 getter 不存在 (需手动修复或忽略)
|
||||
*/
|
||||
function fixUnresolvedVelocityVars(content: string): { fixed: string; count: number } {
|
||||
let count = 0
|
||||
const lines = content.split('\n')
|
||||
let curJsonProp: string | null = null
|
||||
|
||||
const fixed = lines
|
||||
.map((line) => {
|
||||
// 跟踪 @JsonProperty 状态
|
||||
const jpMatch = line.match(/@JsonProperty\(\s*"([^"]+)"\s*\)/)
|
||||
if (jpMatch) curJsonProp = jpMatch[1]
|
||||
if (line.match(/^\s*[}\);]/)) curJsonProp = null
|
||||
|
||||
// 1. 处理所有 Velocity 占位符: ${...} (简单变量或方法调用)
|
||||
// - 含方法调用 (.method()): capitalize 最后 .method() 名 (Java 习惯 getter)
|
||||
// - 简单变量 (private 行): 用 curJsonProp snake → camelCase
|
||||
// - 简单变量 (其他行): 用最后一段 camelCase
|
||||
line = line.replace(/\$\{[^}]*\}/g, (full) => {
|
||||
count++
|
||||
const inner = full.slice(2, -1) // 去掉 ${ 和 }
|
||||
// 含方法调用 (.method()) → 用最后 .method() 名 capitalize (Java 执行顺序)
|
||||
// 用 greedy match all + last one
|
||||
const allMethods = [...inner.matchAll(/\.([a-zA-Z][a-zA-Z0-9_]*)\s*\(/g)]
|
||||
if (allMethods.length > 0) {
|
||||
const last = allMethods[allMethods.length - 1]
|
||||
return last[1].charAt(0).toUpperCase() + last[1].slice(1)
|
||||
}
|
||||
// 简单变量: private 行 → 用 curJsonProp
|
||||
if (line.match(/^\s*private\s/) && curJsonProp) {
|
||||
return curJsonProp.charAt(0).toLowerCase() + curJsonProp.slice(1)
|
||||
}
|
||||
// 退化: 取最后一段, 保持原始大小写 (避免把 afterVModel 错改成 afterVmodel)
|
||||
const shortName = inner.split('.').pop() || inner
|
||||
return shortName.replace(/[._]/g, '')
|
||||
})
|
||||
|
||||
return line
|
||||
})
|
||||
.join('\n')
|
||||
|
||||
return { fixed, count }
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件路径 + 类型, 决定归到哪个 Maven 子模块
|
||||
*
|
||||
@@ -239,7 +306,20 @@ function pathToModule(filePath: string, kind: string, moduleArtifactId: string):
|
||||
* - biz: 依赖 entity + fastjson + commons-lang3 + jnpf-common-all
|
||||
* - controller: 依赖 biz + jnpf-common-all
|
||||
*/
|
||||
function generateModulePoms(outDir: string, moduleArtifactId: string): void {
|
||||
function generateModulePoms(
|
||||
outDir: string,
|
||||
moduleArtifactId: string,
|
||||
wantedModules: Set<string> | null = null,
|
||||
): void {
|
||||
// 默认 3 个子模块; --module-only 过滤时只生成选中的子模块 pom
|
||||
const allSubModules = [
|
||||
`${moduleArtifactId}-entity`,
|
||||
`${moduleArtifactId}-biz`,
|
||||
`${moduleArtifactId}-controller`,
|
||||
]
|
||||
const subModules = wantedModules
|
||||
? allSubModules.filter((m) => wantedModules.has(m))
|
||||
: allSubModules
|
||||
const parentPom = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<parent>
|
||||
@@ -250,9 +330,7 @@ function generateModulePoms(outDir: string, moduleArtifactId: string): void {
|
||||
<artifactId>${moduleArtifactId}</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>${moduleArtifactId}-entity</module>
|
||||
<module>${moduleArtifactId}-biz</module>
|
||||
<module>${moduleArtifactId}-controller</module>
|
||||
${subModules.map((m) => ` <module>${m}</module>`).join('\n')}
|
||||
</modules>
|
||||
</project>
|
||||
`
|
||||
@@ -301,10 +379,13 @@ function generateModulePoms(outDir: string, moduleArtifactId: string): void {
|
||||
</project>
|
||||
`
|
||||
writeFileSync(join(outDir, 'pom.xml'), parentPom, 'utf-8')
|
||||
writeFileSync(join(outDir, `${moduleArtifactId}-entity`, 'pom.xml'), entityPom, 'utf-8')
|
||||
writeFileSync(join(outDir, `${moduleArtifactId}-biz`, 'pom.xml'), bizPom, 'utf-8')
|
||||
writeFileSync(join(outDir, `${moduleArtifactId}-controller`, 'pom.xml'), controllerPom, 'utf-8')
|
||||
log.info(`✓ 已生成 4 个 pom.xml (parent + entity/biz/controller)`)
|
||||
if (subModules.includes(`${moduleArtifactId}-entity`))
|
||||
writeFileSync(join(outDir, `${moduleArtifactId}-entity`, 'pom.xml'), entityPom, 'utf-8')
|
||||
if (subModules.includes(`${moduleArtifactId}-biz`))
|
||||
writeFileSync(join(outDir, `${moduleArtifactId}-biz`, 'pom.xml'), bizPom, 'utf-8')
|
||||
if (subModules.includes(`${moduleArtifactId}-controller`))
|
||||
writeFileSync(join(outDir, `${moduleArtifactId}-controller`, 'pom.xml'), controllerPom, 'utf-8')
|
||||
log.info(`✓ 已生成 ${subModules.length + 1} 个 pom.xml (parent${subModules.length < 3 ? ` + ${subModules.length} 子模块` : ' + entity/biz/controller'})`)
|
||||
}
|
||||
async function ensureAlias(
|
||||
c: JnpfClient,
|
||||
@@ -405,6 +486,9 @@ export function buildFormCodegenCommand(): Command {
|
||||
// ⭐ 多模块归类 (v0.10+ 默认开启, 对齐 aibridge ssw-{appCode} 多模块 POM 结构)
|
||||
.option('--flat', '关闭多模块归类 (旧版兼容: 文件直接写到 outDir 根, 不分 entity/biz/controller)', false)
|
||||
.option('--multi-module-pom', '生成 4 个 pom.xml 占位 (parent + entity/biz/controller, 严格按 aibridge §POM 依赖规则; 与 --flat 互斥)', false)
|
||||
// 选择性导出 (只生成指定模块, 用于单模块编译验证)
|
||||
// 值: all | entity | biz | controller | 任意逗号分隔组合 (如 entity,biz)
|
||||
.option('--module-only <list>', '只导出指定模块 (all 默认, 或 entity/biz/controller 逗号分隔, 用于单模块测试/编译)', 'all')
|
||||
// ⭐ 推荐方式 (v0.10+): JNPF 原生别名系统, 消除 post-fix
|
||||
.option('--auto-alias', '从 form.tables 自动推导主表别名 (= mainClassName), 写 base_visual_alias (推荐, 替代 --auto-fix-names)', false)
|
||||
.option('--alias-file <path>', '从 JSON 文件读 alias 表 (格式: [{table,aliasName,fields?}])')
|
||||
@@ -590,20 +674,56 @@ export function buildFormCodegenCommand(): Command {
|
||||
}
|
||||
const counts: Record<string, number> = {}
|
||||
const moduleCounts: Record<string, number> = {}
|
||||
// --module-only 解析: 逗号分隔, 如 "entity,biz" 或 "controller" 或 "all"
|
||||
// 空字符串/'all' → 不过滤 (默认导出全部)
|
||||
const moduleOnlyList = (opts.moduleOnly || 'all')
|
||||
.split(',')
|
||||
.map((s) => s.trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
const moduleOnlyAll = moduleOnlyList.includes('all')
|
||||
// 短名 → 完整模块名映射
|
||||
const shortToFull: Record<string, string> = {
|
||||
entity: `${moduleArtifactId}-entity`,
|
||||
biz: `${moduleArtifactId}-biz`,
|
||||
controller: `${moduleArtifactId}-controller`,
|
||||
}
|
||||
const wantedModules = new Set(
|
||||
moduleOnlyAll ? [] : moduleOnlyList.map((s) => shortToFull[s] || s),
|
||||
)
|
||||
if (!moduleOnlyAll && wantedModules.size > 0) {
|
||||
log.info(` --module-only: 只导出 ${[...wantedModules].map((m) => m.replace(`${moduleArtifactId}-`, '')).join(',')} 模块`)
|
||||
}
|
||||
for (const f of files) {
|
||||
// 决定 Maven 子模块 (--flat 时为 null, 文件直接写到 outDir 根)
|
||||
const targetModule = opts.flat ? null : pathToModule(f.path, f.kind, moduleArtifactId)
|
||||
// --module-only 过滤: 跳过不在 wantedModules 里的文件 (前端 web 文件不受限, 总导出)
|
||||
const isWeb = !targetModule && !opts.flat && f.kind === 'web'
|
||||
if (!moduleOnlyAll && wantedModules.size > 0 && targetModule && !wantedModules.has(targetModule) && !isWeb) {
|
||||
counts[`__skipped:${targetModule}`] = (counts[`__skipped:${targetModule}`] || 0) + 1
|
||||
continue
|
||||
}
|
||||
const finalPath = targetModule ? join(outDir, targetModule, f.path) : join(outDir, f.path)
|
||||
mkdirSync(dirname(finalPath), { recursive: true })
|
||||
writeFileSync(finalPath, f.content, 'utf-8')
|
||||
// JNPF 模板 bug 后处理: ${html.fieldAlias} / ${search.afterVModel} 等未替换的字面 Velocity 占位符
|
||||
// (FormMarco.vm:1226 不动, 但 Form.java.vm / Pagination.java.vm 输出 bug 必须修, 不然 javac 失败)
|
||||
let contentToWrite = f.content
|
||||
if (f.path.endsWith('.java') && /\$\{[a-zA-Z]/.test(contentToWrite)) {
|
||||
const { fixed, count } = fixUnresolvedVelocityVars(contentToWrite)
|
||||
if (count > 0) {
|
||||
contentToWrite = fixed
|
||||
counts[`__fix:velocity-vars`] = (counts[`__fix:velocity-vars`] || 0) + count
|
||||
}
|
||||
}
|
||||
writeFileSync(finalPath, contentToWrite, 'utf-8')
|
||||
counts[f.kind] = (counts[f.kind] || 0) + 1
|
||||
const modLabel = targetModule || '(root)'
|
||||
moduleCounts[modLabel] = (moduleCounts[modLabel] || 0) + 1
|
||||
}
|
||||
|
||||
// 3.5. (可选) --multi-module-pom: 生成 4 个 pom.xml 占位 (parent + entity/biz/controller)
|
||||
// --module-only 过滤时, 只生成选中的模块 pom (parent 仍生成, modules 列表反映)
|
||||
if (opts.multiModulePom && !opts.flat) {
|
||||
generateModulePoms(outDir, moduleArtifactId)
|
||||
generateModulePoms(outDir, moduleArtifactId, wantedModules.size > 0 ? wantedModules : null)
|
||||
} else if (opts.multiModulePom && opts.flat) {
|
||||
log.warn('--multi-module-pom 与 --flat 互斥, 跳过 pom 生成')
|
||||
}
|
||||
@@ -642,10 +762,26 @@ export function buildFormCodegenCommand(): Command {
|
||||
}
|
||||
}
|
||||
|
||||
log.ok(`✓ 生成 ${files.length} 个文件`)
|
||||
const skippedCount = Object.entries(counts)
|
||||
.filter(([k]) => k.startsWith('__skipped:'))
|
||||
.reduce((sum, [, v]) => sum + v, 0)
|
||||
const generatedCount = files.length - skippedCount
|
||||
if (skippedCount > 0) {
|
||||
log.ok(`✓ 生成 ${generatedCount} 个文件 (跳过 ${skippedCount} 个, --module-only 过滤)`)
|
||||
} else {
|
||||
log.ok(`✓ 生成 ${generatedCount} 个文件`)
|
||||
}
|
||||
for (const [k, v] of Object.entries(counts)) {
|
||||
if (k.startsWith('__skipped:')) continue
|
||||
log.info(` ${k}: ${v}`)
|
||||
}
|
||||
if (skippedCount > 0) {
|
||||
log.info(` (跳过:`)
|
||||
for (const [k, v] of Object.entries(counts)) {
|
||||
if (k.startsWith('__skipped:')) log.info(` ${k.replace('__skipped:', '')}: ${v}`)
|
||||
}
|
||||
log.info(` )`)
|
||||
}
|
||||
log.info(`输出到: ${outDir}`)
|
||||
log.info('')
|
||||
log.info('后续步骤 (按 aibridge §POM 依赖规则):')
|
||||
@@ -673,6 +809,7 @@ export function buildFormCodegenCommand(): Command {
|
||||
// ⭐ 多模块归类 (v0.10+ 默认开启, 对齐 aibridge ssw-{appCode} 多模块 POM 结构)
|
||||
'--flat': '关闭多模块归类 (旧版兼容: 文件直接写到 outDir 根)',
|
||||
'--multi-module-pom': '生成 4 个 pom.xml 占位 (parent + entity/biz/controller, 与 --flat 互斥)',
|
||||
'--module-only <list>': '只导出指定模块 (默认 all, 或 entity/biz/controller 逗号分隔, 用于单模块编译验证)',
|
||||
// ⭐ 推荐方式 (v0.10+): JNPF 原生别名系统, 写 base_visual_alias
|
||||
'--auto-alias': '从 form.tables 自动推导主表别名 (= mainClassName), 推荐替代 --auto-fix-names',
|
||||
'--alias-file <path>': '从 JSON 文件读 alias 表',
|
||||
|
||||
Reference in new issue
Block a user