Skip to content

Conversation

@ZStack-Robot
Copy link
Collaborator

Add complete Go SDK generator that automatically generates
type-safe client code from ZStack Java API definitions.

Resolves: ZCF-22

Change-Id: I6162766579786f756d7466697976687163767276
Signed-off-by: AlanJager ye.zou@zstack.io

sync from gitlab !9036

@coderabbitai
Copy link

coderabbitai bot commented Jan 19, 2026

遍历

该拉取请求引入完整的 Go SDK 生成框架:新增 GoApiTemplate.groovy 与扩展的 GoInventory.groovy,多项 Go 模板与示例、两份开发/规范文档,以及参数/客户端/会话相关模板,实现 API 预解析、类型映射、视图/参数/操作文件分阶段生成与异步长任务支持。(不超过 50 字)

变更

合并 / 文件 变更摘要
核心生成器 - API 模板
rest/src/main/resources/scripts/GoApiTemplate.groovy
新增 GoApiTemplate 类,实现 SdkTemplate。增加大量状态与访问器、RestRequest/RestResponse 解析、action/resource 抽取、query vs action 区分、inventory 寻找、异步(长作业)支持、路径占位符与 spec 处理、以及生成不同 API 方法(create/query/page/get/update/delete/expunge/generic)之逻辑与辅助方法。
核心生成器 - 清单/视图/参数
rest/src/main/resources/scripts/GoInventory.groovy
扩展视图/参数/生成状态缓存(viewStructNameMap、generatedViewStructs、paramNestedTypes 等)、新增 LongJob 映射扫描、预解析 API 模板(prepareApiTemplates)、多阶段 generate 流程、生成额外引用类型的迭代逻辑、基础视图文件生成与生成结果验证。
开发指南
rest/src/main/resources/scripts/SDK生成器开发指南.md
新增全面的 Go SDK 生成器开发文档,包含架构说明、端到端流程、Java→Go 类型映射规则、递归类型处理策略、命名与导入约定及示例伪代码。
规范文档
rest/src/main/resources/scripts/ZStack SDK Go 开发规范与标准.md
新增 Go SDK 实现规范与标准文档,覆盖代码风格、struct/JSON 约定、时间处理、异步长任务支持、生成器约束与资源新增流程等。
参数基础类型模板
rest/src/main/resources/scripts/templates/base_param_types.go.template
新增 DeleteMode 枚举及常量,新增 BaseParamHqlParamVariablesConditionPageVar 等基础参数类型定义。
参数工具模板
rest/src/main/resources/scripts/templates/base_params.go.template
新增 param.QueryParam 及构造器与流式 setter,新增 ConvertStruct2UrlValues() 用于将结构体转 url.Values 的反射函数。
客户端模板
rest/src/main/resources/scripts/templates/client.go.template
新增 client.ZSClient 与构造器 NewZSClient(),包含登录/登出/会话验证、hql/Zql、作业状态视图与轮询常量等客户端能力。
登录参数模板
rest/src/main/resources/scripts/templates/login_params.go.template
新增多种登录参数结构(Account、User、IAM/LDAP、Platform 等)及对应 detail struct。
会话视图模板
rest/src/main/resources/scripts/templates/session_additional_views.go.template, .../session_views.go.template
新增 SessionInventoryViewWebUISessionView 视图结构定义(时间字段、JSON 标签等)。
示例程序
rest/src/main/resources/scripts/templates/example_main.go
新增示例 main,演示客户端初始化、登录、查询 VM/镜像/卷、会话验证与登出流程。

序列图

sequenceDiagram
    participant User as 代码生成器用户
    participant GoInventory as GoInventory
    participant GoApiTemplate as GoApiTemplate
    participant RestAPI as RestRequest/RestResponse
    participant TypeMapper as Java→Go 类型映射
    participant FileGen as 文件写入器

    User->>GoInventory: generate()
    GoInventory->>GoInventory: scanLongJobMappings()
    GoInventory->>GoInventory: 加载 inventories
    GoInventory->>GoApiTemplate: prepareApiTemplates()
    loop 遍历 API 列表
        GoApiTemplate->>RestAPI: 读取注解并解析路径/方法/响应
        RestAPI-->>GoApiTemplate: 元数据
        GoApiTemplate->>TypeMapper: 请求类型映射
        TypeMapper-->>GoApiTemplate: Go 类型信息
        GoApiTemplate->>GoInventory: 返回解析后的 API 模板
    end
    GoInventory->>GoInventory: 生成视图/参数/操作 AST
    GoInventory->>FileGen: 渲染并写入 view/param/action 文件
    FileGen-->>User: 生成的 Go SDK 源文件
Loading

预估代码审查工作量

🎯 4 (Complex) | ⏱️ ~60 分钟

🐰 兔兔来报喜,生成器新枝丫,
模板成行列,视图参数一并发,
路径占位理清楚,异步长作业接续下,
文档规范齐备,示例演示把门闩,
代码生成欢腾处,开发者笑开花。

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed 标题完全相关,清晰概括了PR的核心变更 - 引入完整的Go SDK生成器,格式正确,字符数符合要求。
Description check ✅ Passed 描述充分相关,明确说明了PR的目的是添加自动生成类型安全客户端代码的Go SDK生成器,与变更内容相符。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 17

🤖 Fix all issues with AI agents
In `@rest/src/main/resources/scripts/GoApiTemplate.groovy`:
- Around line 136-143: The comment above the isQueryMessage() block contains
Chinese and must be replaced with English; change the comment to a concise
English sentence such as "Query APIs always generate Get and Page methods" and
keep the surrounding logic intact (references: isQueryMessage(), clzName,
getMethodName, pageMethodName, names) so only the comment text is modified, not
the code behavior.
- Around line 192-197: The method getSkippedApis() references a missing static
variable skippedApis causing compilation failure; fix by either adding a
matching static field (e.g., define skippedApis as a Set<String> initialized
appropriately and populated where APIs should be skipped) or remove
getSkippedApis() if unused. Update the class-level declaration to something like
a static Set<String> skippedApis = new LinkedHashSet<>() (or the preferred Set
implementation) and ensure any code that should populate it uses that symbol, or
delete the getSkippedApis method to eliminate the dead reference.
- Around line 362-394: Replace all Chinese comments in this snippet with concise
English equivalents: change the comment above builder.append("// ${clzName}
${getMethodDescription()}") and the block explaining http_client unpacking and
when to use Inventory View (lines referencing unwrapForGet, queryInventoryClass,
inventoryFieldName) to English, and convert the comments inside the
isQueryMessage branch that describe generation of query/get/page methods (around
generateQueryMethod, generateGetMethodForQuery, generatePageMethod) to English
as well; keep the same meaning and context (e.g., "http_client automatically
unwraps POST/PUT inventory field, use Inventory View for
Create/Add/Update/Change; only GET needs manual unpacking" and "always generate
Get method for Query APIs to avoid compile errors", etc.), preserving variable
names like unwrapForGet, goInventoryFieldName, clzName and skipNames so
reviewers can locate the changes.

In `@rest/src/main/resources/scripts/GoInventory.groovy`:
- Around line 719-728: The generated Go code contains Chinese comments in
generateBaseViewFile(); update that method so all appended comment strings in
the content.append calls produce English text (e.g., replace "基础信息视图" → "Base
information view", "资源唯一标识" → "Resource unique identifier", "资源名称" → "Resource
name", "创建时间" → "Creation time", "最后操作时间" → "Last operation time", etc.),
ensuring the appended lines for BaseInfoView and BaseTimeView use English
comments and keep tag formatting unchanged.
- Around line 948-971: In generateViewStruct, replace the Chinese comments with
English equivalents: change the comment lines that annotate the struct (e.g.,
"// ${structName} ${getStructDescription(inventoryClazz)}"), the inheritance
note for InventoryView, and the skip-note for fields already included by
BaseInfoView and BaseTimeView to English; update the inline comments near the
InventoryView checks (references: structName, InventoryView, BaseInfoView,
BaseTimeView, and fieldMap loop) so they convey the same meaning in English and
maintain existing positioning and formatting.
- Around line 1429-1465: Replace all Chinese comments inside the
isOptionalField(Field field, Map<String, APIParam> apiParamMap) method with
concise English comments that preserve the original intent: explain the null
check, the special-case rule for "uuid" and "name", the logic for reading
APIParam.required via apiParamMap or field.getAnnotation(APIParam.class), the
special optional fields ("description","lastOpDate","expiredDate"), and the rule
treating non-primitive/String wrapper and date types as optional when APIParam
is absent; keep existing variable names (field, apiParamMap, param, fieldType)
and control flow unchanged.
- Around line 75-100: The method scanLongJobMappings() contains Chinese
comments; replace them with concise English comments preserving their
meaning—e.g., change "获取所有带 `@LongJobFor` 注解的类" to "Retrieve all classes annotated
with `@LongJobFor`", "获取注解中的目标API类" to "Get target API class from the annotation",
"存储映射关系" to "Store mapping relation", and adjust any other Chinese comments
around longJobClasses, longJobMappings, Platform.reflections, and the logger
blocks to English while keeping the surrounding logic unchanged.

In `@rest/src/main/resources/scripts/SDK生成器开发指南.md`:
- Around line 114-130: The markdown table under the "Java 类型 | Go 类型(必填) | Go
类型(可选)" header has inconsistent column counts causing MD056; ensure every data
row has three pipe-separated columns by adding a placeholder for the optional
column (e.g., `-`) or by supplying the appropriate Go optional type for each
entry so all rows match the header; update the rows such as the `String, char,
Character` through `其他复杂类型` and `无法识别的类型` lines to include the third column.
- Around line 19-38: The fenced code block showing the SDK directory tree is
missing a language tag and contains hard tab characters (lint issues MD040 and
MD010); update that block (and the similar one at lines 763-795) to add an
appropriate language marker (e.g., ```text or ```bash) and replace all hard tabs
with spaces (or reformat the tree using spaces) so the markdown linter passes;
target the fenced blocks that include the "sdk/" tree and the files listed
(client.go, {resource}_actions.go, base_params.go, base_views.go, errors.go)
when making the edits.
- Around line 1-4: The document titled "ZStack SDK 生成器开发指南" is entirely in
Chinese which violates the repository rule forbidding Chinese in code/docs;
create an English version (or migrate this file to a location that permits
Chinese) by translating the entire content including the title, headings,
descriptions and examples, and replace the current Chinese file with the English
version (or add a clear README noting the moved Chinese original). Ensure the
new file retains the same structure and examples and use the original file name
or clearly reference "ZStack SDK 生成器开发指南" in the commit message so reviewers can
verify the translation.

In `@rest/src/main/resources/scripts/templates/base_params.go.template`:
- Around line 86-101: ConvertStruct2UrlValues has its nil-check ordering
reversed and naive value stringification: check param == nil before calling
reflect.TypeOf(param).Kind() to avoid reflect.TypeOf(nil) panic, then verify
reflect.TypeOf(param).Kind() == reflect.Ptr; keep use of structs.New(param) and
s.Map() once pointer/non-nil is confirmed. For value conversion, iterate
mappedOpts from s.Map() and for each value v inspect its kind (reflect.Kind) and
if it's a slice, map or struct (or otherwise non-primitive), marshal v to JSON
(encoding/json) and set result via result.Set(key, jsonString); otherwise use
fmt.Sprintf("%v", v) for simple types, ensuring proper error handling from
json.Marshal and returning errors upward.

In `@rest/src/main/resources/scripts/templates/client.go.template`:
- Around line 532-537: The error string currently appends the full Authorization
header (req.Header.Get("Authorization")) which leaks credentials; change the
template so that when resp.StatusCode >= 400 you do NOT include the raw
Authorization header—either omit it entirely or append a masked value (e.g.,
show only scheme and first/last few chars or "REDACTED") and only include full
value under a debug flag; update the block that builds errMsg (the code
referencing resp, req, method, url, resp.StatusCode) to use a sanitized
Authorization value or conditional debug logging instead of directly
concatenating the header.

In `@rest/src/main/resources/scripts/templates/example_main.go`:
- Around line 11-109: The example contains Chinese comments and output strings
(e.g., comments around config creation, and fmt.Println/fmt.Printf calls like
"正在登录...", "登录失败", "查询成功!共找到 %d 台虚拟机", etc.); update all inline comments and
user-facing strings to English to comply with the repo guideline (replace
Chinese comments and all fmt.Println/fmt.Printf/strings in functions such as
Login(), QueryVmInstance(), GetVmInstance(), QueryImage(), QueryVolume(),
ValidateSession(), Logout() usage sites and variables like config and cli in the
template) while keeping behavior identical; ensure messages are clear (e.g.,
"Logging in...", "Login failed:", "Found %d VMs", "Logging out...") and leave
internal identifiers (config, cli, sessionView, vms, vmDetail) unchanged.
- Around line 17-21: Replace all Chinese comments and hardcoded Chinese strings
in this file with English equivalents: update comments like "// 方式2:
使用默认配置(推荐)", "// 初始化客户端", "// 登录" to English, and change user-facing strings
such as "正在登录...", "登录失败: %v\n", "查询成功!" to clear English messages. Keep the
same logic and variable names (e.g., config, DefaultZSConfig, LoginAccount) but
ensure any log/error/output text is English; also validate the method signatures
for DefaultZSConfig and LoginAccount against the upstream
github.com/zstackio/zstack-sdk-go-v2 docs/source and adjust the call chain if
the SDK uses different names or parameter order.

In `@rest/src/main/resources/scripts/templates/session_views.go.template`:
- Around line 7-26: Two templates define the same types (SessionInventoryView
and WebUISessionView) causing duplicate type errors; remove the duplicate type
definitions by deleting these structs from one of the templates (either
session_views.go.template or session_additional_views.go.template) or adjust the
generator to emit these structs only once. Specifically, keep a single canonical
definition of SessionInventoryView and WebUISessionView and remove the other
occurrences, or change the generator deduplication logic so it detects and skips
already-emitted types to prevent duplicate output.

In `@rest/src/main/resources/scripts/ZStack` SDK Go 开发规范与标准.md:
- Around line 133-148: The fenced code block showing the project tree is missing
a language tag and the nested list indentation doesn't follow MD007; add an
appropriate language marker (e.g., ```text or ```bash) to the code fence and
normalize the nested list indentation (use consistent two- or four-space
indentation for child items under the top-level list) so the block and list
comply with MD040/MD007 lint rules; update the specific fenced block that begins
with the triple backticks containing the zstack-sdk-go-v2 tree and adjust its
nested items (pkg/, client/, param/, etc.) to use consistent indentation.
- Around line 11-26: The doc currently points to the community-maintained module
path; update all occurrences of the module path in the examples and imports
(e.g., the go get line and import statements referencing
"github.com/terraform-zstack-modules/zstack-sdk-go-v2") to the official SDK
module path "github.com/zstackio/zstack-sdk-go-v2" so examples (including the go
get command and imports in the sample main using pkg/client and pkg/param) pull
the official, supported SDK.
🧹 Nitpick comments (3)
rest/src/main/resources/scripts/templates/login_params.go.template (1)

5-22: 命名不一致:LoginByAccountParam vs LogInByUserParam

类型命名存在不一致:

  • Line 5: LoginByAccountParam(使用 "Login")
  • Line 19: LogInByUserParam(使用 "LogIn")

建议统一命名风格,保持 SDK 的一致性。如果这是为了匹配 Java API 的命名约定,请忽略此建议。

rest/src/main/resources/scripts/GoApiTemplate.groovy (2)

274-278: 不可达的异常捕获块

Line 274 的 NoSuchFieldException 捕获块不可能被执行,因为在此 try 块中没有可能抛出 NoSuchFieldException 的代码——该异常已在 Line 250 和 271 的内部 try-catch 中被处理。

♻️ 移除不可达的 catch 块
             } catch (NoSuchFieldException e) {
                 // ignore
             }
-        } catch (NoSuchFieldException e) {
-            logger.debug("[GoSDK] No 'inventories' field in " + responseClass?.simpleName)
         } catch (Exception e) {
             logger.warn("[GoSDK] Error finding inventory class for " + clzName + ": " + e.message)
         }

1078-1086: 冗余的字符串操作和中文注释

  1. Line 1080: apiPath.replaceAll(/^v1/, "v1") 是无效操作,将 "v1" 替换为 "v1" 没有任何效果
  2. Line 1083: 注释 "Async" 可以更具描述性
♻️ 修复冗余操作
     private String generateAsyncMethod(String apiPath, String httpMethod, String viewStructName) {
         String asyncMethodName = "${clzName}Async"
-        String resource = apiPath.replaceAll(/^v1/, "v1")
+        String resource = apiPath

         def builder = new StringBuilder()
-        builder.append("\n// ${asyncMethodName} Async\n")
+        builder.append("\n// ${asyncMethodName} executes ${clzName} asynchronously and returns a LongJob UUID\n")

Comment on lines 136 to 143
// Query APIs 总是生成 Get 和 Page 方法
if (isQueryMessage()) {
String getMethodName = clzName.replaceFirst('^Query', 'Get')
names.add(getMethodName)

String pageMethodName = clzName.replaceFirst('^Query', 'Page')
names.add(pageMethodName)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

代码注释使用了中文,违反编码规范

根据编码规范,代码中不应包含中文,包括注释。请将中文注释替换为英文。

📝 将中文注释替换为英文
-        // Query APIs 总是生成 Get 和 Page 方法
+        // Query APIs always generate Get and Page methods
         if (isQueryMessage()) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Query APIs 总是生成 Get Page 方法
if (isQueryMessage()) {
String getMethodName = clzName.replaceFirst('^Query', 'Get')
names.add(getMethodName)
String pageMethodName = clzName.replaceFirst('^Query', 'Page')
names.add(pageMethodName)
}
// Query APIs always generate Get and Page methods
if (isQueryMessage()) {
String getMethodName = clzName.replaceFirst('^Query', 'Get')
names.add(getMethodName)
String pageMethodName = clzName.replaceFirst('^Query', 'Page')
names.add(pageMethodName)
}
🤖 Prompt for AI Agents
In `@rest/src/main/resources/scripts/GoApiTemplate.groovy` around lines 136 - 143,
The comment above the isQueryMessage() block contains Chinese and must be
replaced with English; change the comment to a concise English sentence such as
"Query APIs always generate Get and Page methods" and keep the surrounding logic
intact (references: isQueryMessage(), clzName, getMethodName, pageMethodName,
names) so only the comment text is modified, not the code behavior.

Comment on lines +11 to +109
// 创建客户端配置
// 方式1: 使用完整配置
// config := client.NewZSConfig("YOUR_ZSTACK_API_ENDPOINT", 8080, "/zstack").
// LoginAccount("admin", "password").
// Debug(true)

// 方式2: 使用默认配置(推荐)
config := client.DefaultZSConfig("YOUR_ZSTACK_API_ENDPOINT").
LoginAccount("admin", "password").
Debug(true)

// 初始化客户端
cli := client.NewZSClient(config)

// 登录
fmt.Println("正在登录...")
sessionView, err := cli.Login()
if err != nil {
fmt.Printf("登录失败: %v\n", err)
return
}
fmt.Printf("登录成功!Session UUID: %s\n", sessionView.Uuid)

// 查询虚拟机列表
fmt.Println("\n开始查询虚拟机...")
queryParams := param.NewQueryParam()
queryParams.Limit(10)
vms, err := cli.QueryVmInstance(&queryParams)
if err != nil {
fmt.Printf("查询失败: %v\n", err)
return
}

fmt.Printf("查询成功!共找到 %d 台虚拟机\n", len(vms))
for i, vm := range vms {
fmt.Printf("[%d] VM: %s, UUID: %s, State: %s\n", i+1, vm.Name, vm.Uuid, vm.State)
}

// 获取单个虚拟机详情(如果有虚拟机的话)
if len(vms) > 0 {
fmt.Printf("\n获取第一台虚拟机详情...\n")
vmDetail, err := cli.GetVmInstance(vms[0].Uuid)
if err != nil {
fmt.Printf("获取虚拟机详情失败: %v\n", err)
} else {
fmt.Printf("虚拟机详情: Name=%s, UUID=%s, State=%s, CPUs=%d, Memory=%d\n",
vmDetail.Name, vmDetail.Uuid, vmDetail.State, vmDetail.CpuNum, vmDetail.MemorySize)
}
}

// 查询镜像列表
fmt.Println("\n查询镜像列表...")
imageParams := param.NewQueryParam()
imageParams.Limit(5)
images, err := cli.QueryImage(&imageParams)
if err != nil {
fmt.Printf("查询镜像失败: %v\n", err)
} else {
fmt.Printf("共找到 %d 个镜像\n", len(images))
for i, img := range images {
fmt.Printf("[%d] Image: %s, UUID: %s, Format: %s\n", i+1, img.Name, img.Uuid, img.Format)
}
}

// 查询云盘列表
fmt.Println("\n查询云盘列表...")
volumeParams := param.NewQueryParam()
volumeParams.Limit(5)
volumes, err := cli.QueryVolume(&volumeParams)
if err != nil {
fmt.Printf("查询云盘失败: %v\n", err)
} else {
fmt.Printf("共找到 %d 个云盘\n", len(volumes))
for i, vol := range volumes {
sizeGB := int64(0)
if vol.Size != nil {
sizeGB = *vol.Size / (1024 * 1024 * 1024)
}
fmt.Printf("[%d] Volume: %s, UUID: %s, Size: %d GB\n",
i+1, vol.Name, vol.Uuid, sizeGB)
}
}

// 验证会话是否有效
fmt.Println("\n验证会话...")
valid, err := cli.ValidateSession()
if err != nil {
fmt.Printf("验证会话失败: %v\n", err)
} else {
fmt.Printf("会话有效性: %v\n", valid)
}

// 登出
fmt.Println("\n正在登出...")
if err := cli.Logout(); err != nil {
fmt.Printf("登出失败: %v\n", err)
} else {
fmt.Println("登出成功!")
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

示例含中文注释/输出与仓库规范不符

示例代码包含中文注释与输出字符串,和仓库“代码/注释/报错需使用英文”的规范冲突。建议统一为英文或移至允许中文的文档位置。As per coding guidelines, ...

🤖 Prompt for AI Agents
In `@rest/src/main/resources/scripts/templates/example_main.go` around lines 11 -
109, The example contains Chinese comments and output strings (e.g., comments
around config creation, and fmt.Println/fmt.Printf calls like "正在登录...", "登录失败",
"查询成功!共找到 %d 台虚拟机", etc.); update all inline comments and user-facing strings to
English to comply with the repo guideline (replace Chinese comments and all
fmt.Println/fmt.Printf/strings in functions such as Login(), QueryVmInstance(),
GetVmInstance(), QueryImage(), QueryVolume(), ValidateSession(), Logout() usage
sites and variables like config and cli in the template) while keeping behavior
identical; ensure messages are clear (e.g., "Logging in...", "Login failed:",
"Found %d VMs", "Logging out...") and leave internal identifiers (config, cli,
sessionView, vms, vmDetail) unchanged.

Comment on lines +17 to +21
// 方式2: 使用默认配置(推荐)
config := client.DefaultZSConfig("YOUR_ZSTACK_API_ENDPOINT").
LoginAccount("admin", "password").
Debug(true)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# First, find the file and examine its content
find . -name "example_main.go" -type f

Repository: MatheMatrix/zstack

Length of output: 180


🏁 Script executed:

# Search for method definitions in Go files
rg -n "DefaultZSConfig|LoginAccount|Login\(" -t go -A 3

Repository: MatheMatrix/zstack

Length of output: 1154


🏁 Script executed:

# Check if the file has Chinese characters
file rest/src/main/resources/scripts/templates/example_main.go 2>/dev/null || echo "File not found at that path"
rg "方式|推荐|配置|默认" -t go

Repository: MatheMatrix/zstack

Length of output: 311


🏁 Script executed:

# Search for DefaultZSConfig method definition
rg "func.*DefaultZSConfig" -t go -A 5

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

# Search for LoginAccount and Login method definitions
rg "func.*\(.*\).*LoginAccount|func.*\(.*\).*Login\(" -t go -A 3

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

# Count all Chinese characters in the example file
rg "[\u4e00-\u9fff]" rest/src/main/resources/scripts/templates/example_main.go -o | wc -l

Repository: MatheMatrix/zstack

Length of output: 65


🏁 Script executed:

# Find client package files
find . -name "*.go" -type f | xargs grep -l "DefaultZSConfig" | head -5

Repository: MatheMatrix/zstack

Length of output: 121


🏁 Script executed:

# Look at the client package structure
find . -path "*/client*" -name "*.go" -type f | head -10

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

# Search for type definitions and method receivers
rg "DefaultZSConfig\|LoginAccount" -t go --context=5 | head -60

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

# Read the example_main.go file to understand its structure
wc -l rest/src/main/resources/scripts/templates/example_main.go
cat -n rest/src/main/resources/scripts/templates/example_main.go | head -50

Repository: MatheMatrix/zstack

Length of output: 1566


🏁 Script executed:

# Look for any client package or library in the repository
find . -name "*.go" -type f | head -20

Repository: MatheMatrix/zstack

Length of output: 121


🏁 Script executed:

# Search for the actual zstack-sdk-go-v2 package if it's in this repo
find . -path "*zstack-sdk-go*" -name "*.go" -type f 2>/dev/null | head -10

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

# Look in go.mod or vendor directory for the SDK
find . -name "go.mod" -o -name "go.sum" | xargs cat 2>/dev/null | grep -i zstack | head -10

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

# Check if there's a local client package definition
find . -name "client.go" -o -name "config.go" | xargs grep -l "DefaultZSConfig\|LoginAccount" 2>/dev/null

Repository: MatheMatrix/zstack

Length of output: 46


代码包含中文注释和字符串,违反编码指南

该文件包含大量中文注释和硬编码字符串(第11-46行及以上),包括:

  • 注释:// 方式2: 使用默认配置(推荐)// 初始化客户端// 登录
  • 字符串:"正在登录...", "登录失败: %v\n", "查询成功!"

根据编码指南,所有代码中不应包含中文,包括注释、错误消息和用户输出文本——必须使用正确的英文。请将所有中文转换为英文。

关于 DefaultZSConfigLoginAccount 方法签名的一致性,由于实际 SDK 实现(github.com/zstackio/zstack-sdk-go-v2)未在本仓库中,无法验证具体方法签名。建议验证时参考 SDK 文档或源代码。

🤖 Prompt for AI Agents
In `@rest/src/main/resources/scripts/templates/example_main.go` around lines 17 -
21, Replace all Chinese comments and hardcoded Chinese strings in this file with
English equivalents: update comments like "// 方式2: 使用默认配置(推荐)", "// 初始化客户端", "//
登录" to English, and change user-facing strings such as "正在登录...", "登录失败: %v\n",
"查询成功!" to clear English messages. Keep the same logic and variable names (e.g.,
config, DefaultZSConfig, LoginAccount) but ensure any log/error/output text is
English; also validate the method signatures for DefaultZSConfig and
LoginAccount against the upstream github.com/zstackio/zstack-sdk-go-v2
docs/source and adjust the call chain if the SDK uses different names or
parameter order.

Comment on lines +7 to +26
// SessionInventoryView Session
type SessionInventoryView struct {
Uuid string `json:"uuid"`
AccountUuid string `json:"accountUuid,omitempty"`
UserUuid string `json:"userUuid,omitempty"`
UserType string `json:"userType,omitempty"`
ExpiredDate time.Time `json:"expiredDate,omitempty"`
CreateDate time.Time `json:"createDate,omitempty"`
}

// WebUISessionView Web UI Session
type WebUISessionView struct {
SessionId string `json:"sessionId"` // Session ID
AccountUuid string `json:"accountUuid"` // Account UUID
UserUuid string `json:"userUuid"` // User UUID
UserName string `json:"username"` // Username
LoginType string `json:"loginType"` // Login type
CurrentIdentity string `json:"currentIdentity"` // Current identity
ZSVersion string `json:"zsVersion"` // ZStack Cloud version
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# Find the template files mentioned
fd -type f -name "session_views.go.template" -o -name "session_additional_views.go.template"

Repository: MatheMatrix/zstack

Length of output: 180


🏁 Script executed:

# Search for references to these template files in the codebase (e.g., in generator code)
rg -l "session_views\.go\.template|session_additional_views\.go\.template"

Repository: MatheMatrix/zstack

Length of output: 180


🏁 Script executed:

# Look for the actual template files with cat to examine their content
find . -name "session_views.go.template" -o -name "session_additional_views.go.template" | xargs cat -n

Repository: MatheMatrix/zstack

Length of output: 2339


删除重复的类型定义以解决 Go 编译错误

session_views.go.templatesession_additional_views.go.template 中都定义了相同的 SessionInventoryViewWebUISessionView 类型。若生成器同时将两个模板输出到 pkg/view 目录,将导致 Go 编译失败,错误提示为"duplicate type definition"。

建议:删除其中一个模板文件中的重复定义,或修改生成器逻辑以确保仅输出一次这些类型。

🤖 Prompt for AI Agents
In `@rest/src/main/resources/scripts/templates/session_views.go.template` around
lines 7 - 26, Two templates define the same types (SessionInventoryView and
WebUISessionView) causing duplicate type errors; remove the duplicate type
definitions by deleting these structs from one of the templates (either
session_views.go.template or session_additional_views.go.template) or adjust the
generator to emit these structs only once. Specifically, keep a single canonical
definition of SessionInventoryView and WebUISessionView and remove the other
occurrences, or change the generator deduplication logic so it detects and skips
already-emitted types to prevent duplicate output.

Comment on lines +11 to +26
```bash
go get github.com/terraform-zstack-modules/zstack-sdk-go-v2
```

### 初始化客户端

> **注意**: `DefaultZSConfig` 需要显式传入 context path (如 `"/zstack"`)。
```go
package main

import (
"fmt"
"github.com/terraform-zstack-modules/zstack-sdk-go-v2/pkg/client"
"github.com/terraform-zstack-modules/zstack-sdk-go-v2/pkg/param"
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find and display the go.mod file to check the actual module path
find . -name "go.mod" -type f | head -20

Repository: MatheMatrix/zstack

Length of output: 180


🏁 Script executed:

#!/bin/bash
# Search for module declaration in go.mod files
rg -n "^module " --type txt -g 'go.mod'

Repository: MatheMatrix/zstack

Length of output: 180


🏁 Script executed:

#!/bin/bash
# Search for both module path variants in the codebase
echo "=== Searching for terraform-zstack-modules variant ==="
rg "terraform-zstack-modules/zstack-sdk-go-v2" --max-count 20
echo ""
echo "=== Searching for zstackio variant ==="
rg "zstackio/zstack-sdk-go-v2" --max-count 20

Repository: MatheMatrix/zstack

Length of output: 180


🏁 Script executed:

#!/bin/bash
# Check the documentation file being reviewed
cat -n "rest/src/main/resources/scripts/ZStack SDK Go 开发规范与标准.md" | head -50

Repository: MatheMatrix/zstack

Length of output: 180


🌐 Web query:

zstack-sdk-go-v2 GitHub go.mod module path

💡 Result:

The module path is: github.com/zstackio/zstack-sdk-go-v2. [1][2]

Sources:

  • pkg.go.dev — github.com/zstackio/zstack-sdk-go-v2/pkg/client. [1]
  • pkg.go.dev — github.com/zstackio/zstack-sdk-go-v2/pkg/util/multipart. [2]

🌐 Web query:

github.com/zstackio/zstack-sdk-go-v2 vs github.com/terraform-zstack-modules/zstack-sdk-go-v2

💡 Result:

Summary comparison

  • Official/maintainer: github.com/zstackio/zstack-sdk-go-v2 is the upstream/official SDK from ZStack maintainers. [1]
  • Community/packaged: github.com/terraform-zstack-modules/zstack-sdk-go is a community/terraform-modules organization fork/package (not official). The README explicitly states it is not officially associated with ZStack. [2]
  • Activity & surface:
    • zstackio/zstack-sdk-go-v2 has full API surface, pkg.go.dev documentation, and many generated client methods (large codebase). Use this for direct, up-to-date SDK usage. [1]
    • terraform-zstack-modules/zstack-sdk-go is smaller, fewer stars/forks, and appears targeted to Terraform provider integration or community use. It has tags/releases but is community-maintained. [2]
  • Recommendation: prefer zstackio/zstack-sdk-go-v2 for canonical, comprehensive SDK needs; use terraform-zstack-modules variant only if you specifically need that packaged version for Terraform modules or the community fork’s changes. [1][2]

Sources

  • zstackio/zstack-sdk-go-v2 (official SDK, pkg docs). [1]
  • terraform-zstack-modules/zstack-sdk-go (community/terraform-packaged fork; README note). [2]

🌐 Web query:

"zstack-sdk-go-v2" "go get" correct import path

💡 Result:

Use the module path github.com/zstackio/zstack-sdk-go-v2. Example:

  • go get: go get github.com/zstackio/zstack-sdk-go-v2@latest
  • import (example): import "github.com/zstackio/zstack-sdk-go-v2/pkg/client"

Sources: [pkg.go.dev documentation for github.com/zstackio/zstack-sdk-go-v2][1], [zstack GitHub org / repo][2].


将文档中的模块路径更正为官方版本

文档推荐的模块路径 github.com/terraform-zstack-modules/zstack-sdk-go-v2 是社区维护的非官方版本。正确的官方 SDK 模块路径应为 github.com/zstackio/zstack-sdk-go-v2(由 ZStack 官方维护)。按当前文档操作的用户会安装非官方版本,导致功能不完整或与官方 SDK 存在差异。请将示例代码和文档统一为官方模块路径 github.com/zstackio/zstack-sdk-go-v2

🤖 Prompt for AI Agents
In `@rest/src/main/resources/scripts/ZStack` SDK Go 开发规范与标准.md around lines 11 -
26, The doc currently points to the community-maintained module path; update all
occurrences of the module path in the examples and imports (e.g., the go get
line and import statements referencing
"github.com/terraform-zstack-modules/zstack-sdk-go-v2") to the official SDK
module path "github.com/zstackio/zstack-sdk-go-v2" so examples (including the go
get command and imports in the sample main using pkg/client and pkg/param) pull
the official, supported SDK.

Add complete Go SDK generator that automatically generates
type-safe client code from ZStack Java API definitions.

Resolves: ZCF-22

Change-Id: I6162766579786f756d7466697976687163767276
Signed-off-by: AlanJager <ye.zou@zstack.io>
@MatheMatrix MatheMatrix force-pushed the sync/ye.zou/introduce-go-sdk2 branch from 94bff85 to 4dc0ea0 Compare January 19, 2026 15:10
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In `@rest/src/main/resources/scripts/templates/client.go.template`:
- Around line 199-211: The code references an undefined constant WebZStackPort
in the ZSClient.hql method; fix by either declaring WebZStackPort with the
intended integer value in this package (so hql can use
fmt.Sprintf("http://%s:%d/graphql", cli.hostname, WebZStackPort)) or replace its
usage with the concrete port number you intend to use; ensure the constant is
exported/placed in a shared package if other files need it, and verify
httpPost/jsonMarshal usages remain unchanged.

In `@rest/src/main/resources/scripts/templates/login_params.go.template`:
- Around line 5-22: Rename all login-related structs and fields to use "LogIn"
(capital I) to match ZStack naming: change LoginByAccountParam →
LogInByAccountParam, the field LoginByAccount → LogInByAccount and its JSON tag
`logInByAccount`, and LoginByAccountDetailParam → LogInByAccountDetailParam;
also rename LoginIAM2VirtualIDWithLdapParam → LogInIAM2VirtualIDWithLdapParam,
the field LoginIAM2VirtualIDWithLdap → LogInIAM2VirtualIDWithLdap and its JSON
tag to `logInIAM2VirtualIDWithLdap`, and LoginIAM2PlatformParam →
LogInIAM2PlatformParam, the field LoginIAM2Platform → LogInIAM2Platform and its
JSON tag to `logInIAM2Platform`; update all references/usages, imports and tests
to match the new identifiers.

In `@rest/src/main/resources/scripts/ZStack` SDK Go 开发规范与标准.md:
- Around line 422-434: The document currently mandates Chinese comments for
exported fields which conflicts with the repository rule forbidding Chinese in
code; update the guideline text to require English field comments and change the
example in the VmInstanceInventoryView struct so each exported field (UUID,
ZoneUUID, ClusterUUID, MemorySize, CPUNum) uses English comments (e.g.,
"Resource UUID, unique identifier", "Zone UUID", "Cluster UUID", "Memory size in
bytes", "CPU count") to align the docs with the coding standard.
- Around line 788-796: The example contains a Chinese error string ("查询失败:
%v\n"); update the example to use an English message (e.g., "query failed:
%v\n") wherever that literal appears (likely in the example function that logs
or returns the error), ensure the replacement is applied to any
fmt.Printf/fmt.Errorf/log.* call that uses that message so the code follows the
English-only error-string guideline.
♻️ Duplicate comments (2)
rest/src/main/resources/scripts/SDK生成器开发指南.md (1)

1-935: 文档全中文内容已在之前的审查中标记

此文档通篇为中文,与仓库编码规范冲突(代码/文档不应包含中文)。此问题已在之前的审查中指出,请参考之前的建议进行处理:提供英文版本或迁移到允许中文的文档位置。

rest/src/main/resources/scripts/templates/base_params.go.template (1)

86-102: ConvertStruct2UrlValues 空指针检查顺序错误会导致 panic

此问题已在之前的审查中标记。Line 87 在检查 param 是否为 nil 之前就调用了 reflect.TypeOf(param).Kind()。如果 paramnilreflect.TypeOf(nil) 返回 nil,调用 .Kind() 将导致 panic。

请将 nil 检查移到 reflect 调用之前:

🐛 修复空指针检查顺序
 func ConvertStruct2UrlValues(param interface{}) (url.Values, error) {
+	if param == nil {
+		return nil, errors.New("param is nil")
+	}
 	if reflect.Ptr != reflect.TypeOf(param).Kind() {
 		return nil, errors.New("model should be pointer kind")
 	}
+	if reflect.ValueOf(param).IsNil() {
+		return nil, errors.New("param is nil")
+	}
 	result := url.Values{}
-	if param == nil || reflect.ValueOf(param).IsNil() {
-		return nil, errors.New("param is nil")
-	}
🧹 Nitpick comments (6)
rest/src/main/resources/scripts/templates/client.go.template (2)

113-123: 日志中包含 sessionId 可能存在安全风险

Lines 117 和 121 在日志中直接输出 sessionId。虽然 Debug 级别日志通常不在生产环境启用,但 Error 级别日志(Line 117)可能会记录敏感的会话标识符,建议考虑脱敏处理或仅记录部分字符。

🔒 建议脱敏处理
 func (cli *ZSClient) ValidateSessionId(sessionId string) (map[string]bool, error) {
 	validSession := make(map[string]bool)
 	err := cli.GetWithSpec("v1/accounts/sessions", sessionId, "valid", "", nil, &validSession)
 	if err != nil {
-		golog.Errorf("ZSClient.ValidateSession sessionId[%s] error:%v", sessionId, err)
+		golog.Errorf("ZSClient.ValidateSession sessionId[%s...] error:%v", sessionId[:min(8, len(sessionId))], err)
 		return nil, err
 	}

-	golog.Debugf("ZSClient.ValidateSession sessionId[%s]:%v", sessionId, validSession)
+	golog.Debugf("ZSClient.ValidateSession sessionId[%s...]:%v", sessionId[:min(8, len(sessionId))], validSession)
 	return validSession, nil
 }

229-674: 大量注释掉的代码

Lines 229-674 包含大量被注释掉的代码,包括完整的客户端实现、配置结构和多个方法。如果这些代码是过时的或已被替代,建议删除以保持代码整洁;如果是为了参考保留,建议移到单独的文档或设计说明中。

此外,之前审查中指出的凭据泄露问题(Line 535 Authorization 头被包含在错误消息中)位于这段注释代码中。如果将来取消注释使用,需要先修复该安全问题。

rest/src/main/resources/scripts/GoApiTemplate.groovy (1)

347-349: generate() 方法返回空列表

generate() 方法实现了 SdkTemplate 接口但返回空列表。根据代码结构,实际生成逻辑通过 generateMethodCode()generateResponseViewCode() 方法完成,由 GoInventory 统一调用。

建议添加注释说明此设计意图,避免后续维护者困惑。

📝 添加说明注释
     List<SdkFile> generate() {
+        // Individual file generation is handled by GoInventory.
+        // This template provides generateMethodCode() and generateResponseViewCode()
+        // for consolidated file generation.
         return []
     }
rest/src/main/resources/scripts/GoInventory.groovy (3)

91-93: 异常处理可能掩盖重要错误

在处理 LongJob 类时捕获的异常仅记录警告日志。如果某个 LongJob 类处理失败,可能导致该 API 的 LongJob 映射丢失,进而影响生成的 SDK 功能。

建议考虑在处理完成后汇总失败数量,或在关键场景下将警告提升为错误。


166-219: 步骤编号不一致

generate() 方法中的步骤编号存在不一致:0, 1, 1, 1b, 2, 4, 5, 6, 7, 8(跳过了 3)。建议统一编号以提高代码可读性。

♻️ 建议的修复
-        // 0. Scan LongJob mappings
+        // 1. Scan LongJob mappings
         scanLongJobMappings()
...
-        // 1. Pre-parse all APIs once to avoid O(N*M) processing and redundant logging
+        // 2. Pre-parse all APIs once to avoid O(N*M) processing and redundant logging
         prepareApiTemplates()
...
-        // 1. Generate view files (Resource Grouping)
+        // 3. Generate view files (Resource Grouping)
...
-        // 1b. Generate action and param files (Resource Grouping)
+        // 4. Generate action and param files (Resource Grouping)
...
-        // 2. Generate catch-all other views (for APIs without a matching `@Inventory` class)
+        // 5. Generate catch-all other views
...
-        // 4. Generate other params file
+        // 6. Generate other params file
...
-        // 5. Generate other actions file
+        // 7. Generate other actions file
...
-        // 6. Generate view files for additional referenced classes (iterative discovery)
+        // 8. Generate view files for additional referenced classes
...
-        // 7. Base files
+        // 9. Base files
...
-        // 8. Validate that all referenced response views were generated
+        // 10. Validate that all referenced response views were generated

311-705: 已弃用的方法应考虑移除

generateClientFile() 被标记为 @Deprecated,且注释说明 client.go 是手动维护的。此方法包含近 400 行代码但不应被调用。建议移除此死代码以减少维护负担和代码复杂度。

Comment on lines +199 to +211
func (cli *ZSClient) hql(params param.HqlParam, retVal interface{}, unMarshalKeys ...string) (http.Header, error) {
urlStr := fmt.Sprintf("http://%s:%d/graphql", cli.hostname, WebZStackPort)
_, respHeader, resp, err := cli.httpPost(urlStr, jsonMarshal(params), false)
if err != nil {
return nil, err
}

if retVal == nil {
return nil, nil
}

return respHeader, resp.Unmarshal(retVal, unMarshalKeys...)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

rg -n "WebZStackPort" --type go

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

rg -n "WebZStackPort" --no-type-list

Repository: MatheMatrix/zstack

Length of output: 505


🏁 Script executed:

rg "WebZStackPort"

Repository: MatheMatrix/zstack

Length of output: 198


🏁 Script executed:

rg -B5 -A5 "WebZStackPort\s*="

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

rg "const.*WebZStackPort"

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

cat -n rest/src/main/resources/scripts/templates/client.go.template | head -220 | tail -40

Repository: MatheMatrix/zstack

Length of output: 1520


🏁 Script executed:

head -50 rest/src/main/resources/scripts/templates/client.go.template

Repository: MatheMatrix/zstack

Length of output: 1162


🏁 Script executed:

rg -n "^const" rest/src/main/resources/scripts/templates/client.go.template

Repository: MatheMatrix/zstack

Length of output: 97


🏁 Script executed:

sed -n '232,320p' rest/src/main/resources/scripts/templates/client.go.template

Repository: MatheMatrix/zstack

Length of output: 2011


🏁 Script executed:

wc -l rest/src/main/resources/scripts/templates/client.go.template

Repository: MatheMatrix/zstack

Length of output: 126


🏁 Script executed:

rg -n "WebZStackPort" -B3 -A3 rest/src/main/resources/scripts/templates/client.go.template

Repository: MatheMatrix/zstack

Length of output: 397


🏁 Script executed:

grep -n "WebZStackPort" rest/src/main/resources/scripts/templates/client.go.template

Repository: MatheMatrix/zstack

Length of output: 141


🏁 Script executed:

find rest -name "*.go" -type f -exec grep -l "WebZStackPort" {} \;

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

grep -rn "const.*WebZStackPort\|var.*WebZStackPort" --include="*.go" --include="*.template"

Repository: MatheMatrix/zstack

Length of output: 44


🏁 Script executed:

cat -n rest/src/main/resources/scripts/templates/client.go.template | grep -A10 -B10 "package client"

Repository: MatheMatrix/zstack

Length of output: 409


🏁 Script executed:

find rest -type f \( -name "*.go" -o -name "*.template" \) | head -20

Repository: MatheMatrix/zstack

Length of output: 531


WebZStackPort constant is undefined in the codebase

Line 200 references WebZStackPort, but this constant is not defined anywhere in the repository. This will cause a compilation error. Either define the constant in this file or in an imported package, or use a concrete port number instead.

Additionally, the review comment itself should be written in English, not Chinese, per the coding guidelines.

🤖 Prompt for AI Agents
In `@rest/src/main/resources/scripts/templates/client.go.template` around lines
199 - 211, The code references an undefined constant WebZStackPort in the
ZSClient.hql method; fix by either declaring WebZStackPort with the intended
integer value in this package (so hql can use
fmt.Sprintf("http://%s:%d/graphql", cli.hostname, WebZStackPort)) or replace its
usage with the concrete port number you intend to use; ensure the constant is
exported/placed in a shared package if other files need it, and verify
httpPost/jsonMarshal usages remain unchanged.

Comment on lines +5 to +22
type LoginByAccountParam struct {
BaseParam
LoginByAccount LoginByAccountDetailParam `json:"logInByAccount"`
}

type LoginByAccountDetailParam struct {
AccountName string `json:"accountName"` // Account name
Password string `json:"password"` // Password
AccountType string `json:"accountType"` // Account type
CaptchaUuid string `json:"captchaUuid"` // Captcha UUID
VerifyCode string `json:"verifyCode"` // Verification code
ClientInfo map[string]interface{} `json:"clientInfo"` // Client information
}

type LogInByUserParam struct {
BaseParam
LogInByUser LogInByUserDetailParam `json:"logInByUser"`
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

rg "logInByUser|loginByAccount|LogInByUser|LoginByAccount" --type java -i -l | head -20

Repository: MatheMatrix/zstack

Length of output: 1520


🏁 Script executed:

rg -n "class.*LogIn.*Msg|class.*LoginByAccount" --type java -A 3

Repository: MatheMatrix/zstack

Length of output: 2329


🏁 Script executed:

find . -type f -name "*.java" | xargs grep -l "loginByAccount\|logInByUser" | head -10

Repository: MatheMatrix/zstack

Length of output: 781


🏁 Script executed:

cat -n rest/src/main/resources/scripts/templates/login_params.go.template

Repository: MatheMatrix/zstack

Length of output: 2339


多个结构体命名不符合 ZStack 命名规范,应使用 "LogIn" 而非 "Login"

根据 ZStack API 约定(如 APILogInByAccountMsgAPILogInByUserMsgAPILogInMsg 等),所有登录相关的命名应使用 "LogIn"(大写 I)。当前文件存在以下不符合规范的命名:

  • 第 5 行:LoginByAccountParam → 应为 LogInByAccountParam
  • 第 7 行:字段 LoginByAccount → 应为 LogInByAccount
  • 第 10 行:LoginByAccountDetailParam → 应为 LogInByAccountDetailParam
  • 第 32 行:LoginIAM2VirtualIDWithLdapParam → 应为 LogInIAM2VirtualIDWithLdapParam
  • 第 34 行:字段 LoginIAM2VirtualIDWithLdap → 应为 LogInIAM2VirtualIDWithLdap;JSON 标签 loginIAM2VirtualIDWithLdap → 应为 logInIAM2VirtualIDWithLdap
  • 第 43 行:LoginIAM2PlatformParam → 应为 LogInIAM2PlatformParam
  • 第 45 行:字段 LoginIAM2Platform → 应为 LogInIAM2Platform;JSON 标签 loginIAM2Platform → 应为 logInIAM2Platform
🤖 Prompt for AI Agents
In `@rest/src/main/resources/scripts/templates/login_params.go.template` around
lines 5 - 22, Rename all login-related structs and fields to use "LogIn"
(capital I) to match ZStack naming: change LoginByAccountParam →
LogInByAccountParam, the field LoginByAccount → LogInByAccount and its JSON tag
`logInByAccount`, and LoginByAccountDetailParam → LogInByAccountDetailParam;
also rename LoginIAM2VirtualIDWithLdapParam → LogInIAM2VirtualIDWithLdapParam,
the field LoginIAM2VirtualIDWithLdap → LogInIAM2VirtualIDWithLdap and its JSON
tag to `logInIAM2VirtualIDWithLdap`, and LoginIAM2PlatformParam →
LogInIAM2PlatformParam, the field LoginIAM2Platform → LogInIAM2Platform and its
JSON tag to `logInIAM2Platform`; update all references/usages, imports and tests
to match the new identifiers.

Comment on lines +422 to +434
### 5.2 字段注释

**所有导出字段必须有中文注释说明:**

```go
type VmInstanceInventoryView struct {
UUID string `json:"uuid"` // 资源UUID,唯一标识
ZoneUUID string `json:"zoneUuid"` // 区域UUID
ClusterUUID string `json:"clusterUuid"` // 集群UUID
MemorySize int64 `json:"memorySize"` // 内存大小(字节)
CPUNum int `json:"cpuNum"` // CPU数量
}
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

文档建议与编码规范矛盾

Line 424 建议"所有导出字段必须有中文注释说明",但仓库编码规范明确禁止代码中包含中文(包括注释)。此处建议应改为要求使用英文注释。As per coding guidelines, ...

-**所有导出字段必须有中文注释说明:**
+**All exported fields must have English comments:**

 ```go
 type VmInstanceInventoryView struct {
-    UUID             string `json:"uuid"`             // 资源UUID,唯一标识
-    ZoneUUID         string `json:"zoneUuid"`         // 区域UUID
-    ClusterUUID      string `json:"clusterUuid"`      // 集群UUID
-    MemorySize       int64  `json:"memorySize"`       // 内存大小(字节)
-    CPUNum           int    `json:"cpuNum"`           // CPU数量
+    UUID             string `json:"uuid"`             // Resource UUID, unique identifier
+    ZoneUUID         string `json:"zoneUuid"`         // Zone UUID
+    ClusterUUID      string `json:"clusterUuid"`      // Cluster UUID
+    MemorySize       int64  `json:"memorySize"`       // Memory size in bytes
+    CPUNum           int    `json:"cpuNum"`           // CPU count
 }
🤖 Prompt for AI Agents
In `@rest/src/main/resources/scripts/ZStack` SDK Go 开发规范与标准.md around lines 422 -
434, The document currently mandates Chinese comments for exported fields which
conflicts with the repository rule forbidding Chinese in code; update the
guideline text to require English field comments and change the example in the
VmInstanceInventoryView struct so each exported field (UUID, ZoneUUID,
ClusterUUID, MemorySize, CPUNum) uses English comments (e.g., "Resource UUID,
unique identifier", "Zone UUID", "Cluster UUID", "Memory size in bytes", "CPU
count") to align the docs with the coding standard.

Comment on lines +788 to +796
// 可选字段 - 使用指针
Description *string `json:"description,omitempty"`
ZoneUUID *string `json:"zoneUuid,omitempty"`

// 数值字段 - 使用指针区分 0 和未设置
CPUNum *int `json:"cpuNum,omitempty"`
MemorySize *int64 `json:"memorySize,omitempty"`
}
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

示例代码中包含中文字符串

示例代码中的错误消息使用了中文("查询失败: %v\n"),违反编码规范。应改为英文。

-	fmt.Printf("查询失败: %v\n", err)
+	fmt.Printf("Query failed: %v\n", err)
🤖 Prompt for AI Agents
In `@rest/src/main/resources/scripts/ZStack` SDK Go 开发规范与标准.md around lines 788 -
796, The example contains a Chinese error string ("查询失败: %v\n"); update the
example to use an English message (e.g., "query failed: %v\n") wherever that
literal appears (likely in the example function that logs or returns the error),
ensure the replacement is applied to any fmt.Printf/fmt.Errorf/log.* call that
uses that message so the code follows the English-only error-string guideline.

@MatheMatrix MatheMatrix deleted the sync/ye.zou/introduce-go-sdk2 branch January 20, 2026 02:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants