Repository navigation
Go CLI: add admin_command response table funtion - #16454
Conversation
|
Caution Review failedAn error occurred during the review process. Please try again later. 📝 WalkthroughWalkthroughAdds Admin CLI Response Type Updates
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/response.go`:
- Around line 1143-1195: QuotaSummaryResponse.PrintOut mixes plain text headers
and “No data” messages into the output even when r.OutputFormat is JSON, which
breaks valid JSON serialization. Update PrintOut to branch on OutputFormatJSON
and emit a single JSON document for the full quota summary instead of calling
fmt.Println/PrintTableSimpleByFormatWithOrder per section; keep the existing
section loop for non-JSON formats and preserve the current behavior for Code !=
0.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 679658fb-116a-4b06-9d89-19145af6f515
📒 Files selected for processing (3)
internal/cli/admin_command.gointernal/cli/response.gointernal/cli/table.go
| func (r *QuotaSummaryResponse) PrintOut() { | ||
| if r.Code != 0 { | ||
| fmt.Println("ERROR") | ||
| fmt.Printf("%d, %s\n", r.Code, r.Message) | ||
| return | ||
| } | ||
|
|
||
| sections := []struct { | ||
| key string | ||
| title string | ||
| columns []string | ||
| }{ | ||
| {"storage", "Storage", []string{"Plan", "Users", "Avg Used", "Limit", "Avg Usage"}}, | ||
| {"apps", "Apps", []string{"Plan", "Avg Used", "Limit", "Avg Usage"}}, | ||
| {"api", "API Requests", []string{"Plan", "Tokens", "Limit/min"}}, | ||
| } | ||
|
|
||
| for i, section := range sections { | ||
| if i > 0 { | ||
| fmt.Println() | ||
| } | ||
| fmt.Printf("--- %s ---\n", section.title) | ||
|
|
||
| rowsRaw, ok := r.Data[section.key] | ||
| if !ok { | ||
| fmt.Println("No data") | ||
| continue | ||
| } | ||
|
|
||
| rows, ok := rowsRaw.([]interface{}) | ||
| if !ok || len(rows) == 0 { | ||
| fmt.Println("No data") | ||
| continue | ||
| } | ||
|
|
||
| table := make([]map[string]interface{}, 0, len(rows)) | ||
| for _, row := range rows { | ||
| if m, ok := row.(map[string]interface{}); ok { | ||
| orderedRow := make(map[string]interface{}) | ||
| for _, col := range section.columns { | ||
| if v, exists := m[col]; exists { | ||
| orderedRow[col] = v | ||
| } else { | ||
| orderedRow[col] = "" | ||
| } | ||
| } | ||
| table = append(table, orderedRow) | ||
| } | ||
| } | ||
|
|
||
| PrintTableSimpleByFormatWithOrder(table, section.columns, r.OutputFormat) | ||
| } | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Preserve valid JSON output for quota summaries.
Lines 1164-1193 always print section headers and No data, so OutputFormatJSON produces a mix of plain text plus multiple JSON arrays instead of one valid JSON document. AdminShowQuotaSummaryCommand now routes this endpoint through QuotaSummaryResponse, so --output json becomes unparsable.
Proposed fix
func (r *QuotaSummaryResponse) PrintOut() {
if r.Code != 0 {
fmt.Println("ERROR")
fmt.Printf("%d, %s\n", r.Code, r.Message)
return
}
+
+ if r.OutputFormat == OutputFormatJSON {
+ jsonData, err := json.MarshalIndent(r.Data, "", " ")
+ if err != nil {
+ fmt.Printf("Error marshaling JSON: %v\n", err)
+ return
+ }
+ fmt.Println(string(jsonData))
+ return
+ }
sections := []struct {
key string
title string
columns []string📝 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.
| func (r *QuotaSummaryResponse) PrintOut() { | |
| if r.Code != 0 { | |
| fmt.Println("ERROR") | |
| fmt.Printf("%d, %s\n", r.Code, r.Message) | |
| return | |
| } | |
| sections := []struct { | |
| key string | |
| title string | |
| columns []string | |
| }{ | |
| {"storage", "Storage", []string{"Plan", "Users", "Avg Used", "Limit", "Avg Usage"}}, | |
| {"apps", "Apps", []string{"Plan", "Avg Used", "Limit", "Avg Usage"}}, | |
| {"api", "API Requests", []string{"Plan", "Tokens", "Limit/min"}}, | |
| } | |
| for i, section := range sections { | |
| if i > 0 { | |
| fmt.Println() | |
| } | |
| fmt.Printf("--- %s ---\n", section.title) | |
| rowsRaw, ok := r.Data[section.key] | |
| if !ok { | |
| fmt.Println("No data") | |
| continue | |
| } | |
| rows, ok := rowsRaw.([]interface{}) | |
| if !ok || len(rows) == 0 { | |
| fmt.Println("No data") | |
| continue | |
| } | |
| table := make([]map[string]interface{}, 0, len(rows)) | |
| for _, row := range rows { | |
| if m, ok := row.(map[string]interface{}); ok { | |
| orderedRow := make(map[string]interface{}) | |
| for _, col := range section.columns { | |
| if v, exists := m[col]; exists { | |
| orderedRow[col] = v | |
| } else { | |
| orderedRow[col] = "" | |
| } | |
| } | |
| table = append(table, orderedRow) | |
| } | |
| } | |
| PrintTableSimpleByFormatWithOrder(table, section.columns, r.OutputFormat) | |
| } | |
| } | |
| func (r *QuotaSummaryResponse) PrintOut() { | |
| if r.Code != 0 { | |
| fmt.Println("ERROR") | |
| fmt.Printf("%d, %s\n", r.Code, r.Message) | |
| return | |
| } | |
| if r.OutputFormat == OutputFormatJSON { | |
| jsonData, err := json.MarshalIndent(r.Data, "", " ") | |
| if err != nil { | |
| fmt.Printf("Error marshaling JSON: %v\n", err) | |
| return | |
| } | |
| fmt.Println(string(jsonData)) | |
| return | |
| } | |
| sections := []struct { | |
| key string | |
| title string | |
| columns []string | |
| }{ | |
| {"storage", "Storage", []string{"Plan", "Users", "Avg Used", "Limit", "Avg Usage"}}, | |
| {"apps", "Apps", []string{"Plan", "Avg Used", "Limit", "Avg Usage"}}, | |
| {"api", "API Requests", []string{"Plan", "Tokens", "Limit/min"}}, | |
| } | |
| for i, section := range sections { | |
| if i > 0 { | |
| fmt.Println() | |
| } | |
| fmt.Printf("--- %s ---\n", section.title) | |
| rowsRaw, ok := r.Data[section.key] | |
| if !ok { | |
| fmt.Println("No data") | |
| continue | |
| } | |
| rows, ok := rowsRaw.([]interface{}) | |
| if !ok || len(rows) == 0 { | |
| fmt.Println("No data") | |
| continue | |
| } | |
| table := make([]map[string]interface{}, 0, len(rows)) | |
| for _, row := range rows { | |
| if m, ok := row.(map[string]interface{}); ok { | |
| orderedRow := make(map[string]interface{}) | |
| for _, col := range section.columns { | |
| if v, exists := m[col]; exists { | |
| orderedRow[col] = v | |
| } else { | |
| orderedRow[col] = "" | |
| } | |
| } | |
| table = append(table, orderedRow) | |
| } | |
| } | |
| PrintTableSimpleByFormatWithOrder(table, section.columns, r.OutputFormat) | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/cli/response.go` around lines 1143 - 1195,
QuotaSummaryResponse.PrintOut mixes plain text headers and “No data” messages
into the output even when r.OutputFormat is JSON, which breaks valid JSON
serialization. Update PrintOut to branch on OutputFormatJSON and emit a single
JSON document for the full quota summary instead of calling
fmt.Println/PrintTableSimpleByFormatWithOrder per section; keep the existing
section loop for non-JSON formats and preserve the current behavior for Code !=
0.
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/admin_command.go`:
- Around line 1178-1180: The new admin log-level handlers are bypassing the same
auth gate used by the rest of admin commands. Update the admin command flow
around the log-level getters/setters to require the existing `LoginToken == nil`
guard and follow the same `AdminMode`/login check pattern as the other handlers
in `admin_command.go`. Also change the `/admin/...` getter path to use the same
admin request scope as the other admin APIs instead of `Request(..., "web",
...)`, so the new commands stay consistent with the established admin auth
contract.
- Around line 1196-1198: The non-200 response handling in the log-level update
flow still reports the wrong operation name. Update the error text in the
response check within the admin command logic (the branch that handles the HTTP
status on the log-level update request) so it refers to the log-level update
action instead of “failed to register user,” and keep the status/body details
intact for debugging.
- Around line 1200-1205: Do not overwrite the backend response status in the
change-log-level flow: in the admin command’s JSON handling for the response
unmarshalling, keep the `SimpleResponse.Code` returned by the server instead of
forcing it to `0`. Update the logic around the response parsing in
`admin_command.go` so `result.Code` reflects the actual application-level
outcome, and only treat the command as successful when the parsed response
indicates success.
In `@internal/cli/response.go`:
- Around line 311-320: `ListMemoriesResponse.PrintOut` is writing the `Total:`
prefix unconditionally, which breaks `--output json` by mixing plain text with
JSON output. Update `PrintOut()` to branch on `r.OutputFormat` before printing,
and only emit the human-readable total/table when not in JSON mode; keep the
`r.Data["total_count"]`, `r.Data["memory_list"]`, and `PrintTableSimpleByFormat`
handling intact for the non-JSON path, and ensure the JSON path returns clean
machine-readable output with no extra text.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f33bd9da-8e05-4c58-aba8-53c8152e83d7
📒 Files selected for processing (2)
internal/cli/admin_command.gointernal/cli/response.go
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/admin_command.go`:
- Around line 1178-1180: The new admin log-level handlers are bypassing the same
auth gate used by the rest of admin commands. Update the admin command flow
around the log-level getters/setters to require the existing `LoginToken == nil`
guard and follow the same `AdminMode`/login check pattern as the other handlers
in `admin_command.go`. Also change the `/admin/...` getter path to use the same
admin request scope as the other admin APIs instead of `Request(..., "web",
...)`, so the new commands stay consistent with the established admin auth
contract.
- Around line 1196-1198: The non-200 response handling in the log-level update
flow still reports the wrong operation name. Update the error text in the
response check within the admin command logic (the branch that handles the HTTP
status on the log-level update request) so it refers to the log-level update
action instead of “failed to register user,” and keep the status/body details
intact for debugging.
- Around line 1200-1205: Do not overwrite the backend response status in the
change-log-level flow: in the admin command’s JSON handling for the response
unmarshalling, keep the `SimpleResponse.Code` returned by the server instead of
forcing it to `0`. Update the logic around the response parsing in
`admin_command.go` so `result.Code` reflects the actual application-level
outcome, and only treat the command as successful when the parsed response
indicates success.
In `@internal/cli/response.go`:
- Around line 311-320: `ListMemoriesResponse.PrintOut` is writing the `Total:`
prefix unconditionally, which breaks `--output json` by mixing plain text with
JSON output. Update `PrintOut()` to branch on `r.OutputFormat` before printing,
and only emit the human-readable total/table when not in JSON mode; keep the
`r.Data["total_count"]`, `r.Data["memory_list"]`, and `PrintTableSimpleByFormat`
handling intact for the non-JSON path, and ensure the JSON path returns clean
machine-readable output with no extra text.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f33bd9da-8e05-4c58-aba8-53c8152e83d7
📒 Files selected for processing (2)
internal/cli/admin_command.gointernal/cli/response.go
🛑 Comments failed to post (4)
internal/cli/admin_command.go (3)
1178-1180: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Use the same admin auth contract as the other admin handlers.
These two commands skip the
LoginToken == nilguard used throughout this file, and the getter additionally callsRequest(..., "web", ...)for an/admin/...endpoint. That makes the new log-level commands diverge from the rest of the admin surface and can turn a valid admin flow into an auth/scope failure.Proposed fix
func (c *CLI) AdminSetLogLevelCommand(cmd *Command) (ResponseIf, error) { - if c.Config.CLIMode != AdminMode { + if c.Config.CLIMode != AdminMode || c.AdminServerClient.LoginToken == nil { return nil, fmt.Errorf("this command is only allowed in ADMIN mode or already login") } @@ func (c *CLI) AdminShowLogLevelCommand(cmd *Command) (ResponseIf, error) { - if c.Config.CLIMode != AdminMode { + if c.Config.CLIMode != AdminMode || c.AdminServerClient.LoginToken == nil { return nil, fmt.Errorf("this command is only allowed in ADMIN mode or already login") } - resp, err := c.AdminServerClient.Request("GET", "/admin/config/log", "web", nil, nil) + resp, err := c.AdminServerClient.Request("GET", "/admin/config/log", "admin", nil, nil)Also applies to: 3545-3549
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/admin_command.go` around lines 1178 - 1180, The new admin log-level handlers are bypassing the same auth gate used by the rest of admin commands. Update the admin command flow around the log-level getters/setters to require the existing `LoginToken == nil` guard and follow the same `AdminMode`/login check pattern as the other handlers in `admin_command.go`. Also change the `/admin/...` getter path to use the same admin request scope as the other admin APIs instead of `Request(..., "web", ...)`, so the new commands stay consistent with the established admin auth contract.
1196-1198: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Fix the non-200 error text here.
This branch is handling log-level updates, but the message still says
failed to register user, which will mislead anyone debugging server-side failures.Proposed fix
if resp.StatusCode != 200 { - return nil, fmt.Errorf("failed to register user: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) + return nil, fmt.Errorf("failed to change log level: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) }📝 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.if resp.StatusCode != 200 { return nil, fmt.Errorf("failed to change log level: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/admin_command.go` around lines 1196 - 1198, The non-200 response handling in the log-level update flow still reports the wrong operation name. Update the error text in the response check within the admin command logic (the branch that handles the HTTP status on the log-level update request) so it refers to the log-level update action instead of “failed to register user,” and keep the status/body details intact for debugging.
1200-1205: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not force success after unmarshalling the response.
Overwriting
result.Codewith0discards application-level failures returned in a 200 response, so this command can report success even when the backend rejected the change.Proposed fix
var result SimpleResponse if err = json.Unmarshal(resp.Body, &result); err != nil { return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err) } - result.Code = 0 + if result.Code != 0 { + return nil, fmt.Errorf("%s", result.Message) + } result.Duration = resp.Duration return &result, nil📝 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.var result SimpleResponse if err = json.Unmarshal(resp.Body, &result); err != nil { return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err) } if result.Code != 0 { return nil, fmt.Errorf("%s", result.Message) } result.Duration = resp.Duration🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/admin_command.go` around lines 1200 - 1205, Do not overwrite the backend response status in the change-log-level flow: in the admin command’s JSON handling for the response unmarshalling, keep the `SimpleResponse.Code` returned by the server instead of forcing it to `0`. Update the logic around the response parsing in `admin_command.go` so `result.Code` reflects the actual application-level outcome, and only treat the command as successful when the parsed response indicates success.internal/cli/response.go (1)
311-320: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Keep
--output jsonvalid forlist_memories.
PrintOut()always emitsTotal: ...before the table. In JSON mode that prepends plain text to the response, so the command no longer returns machine-readable JSON.Proposed fix
func (r *ListMemoriesResponse) PrintOut() { if r.Code == 0 { + if r.OutputFormat == OutputFormatJSON { + jsonData, err := json.MarshalIndent(r.Data, "", " ") + if err != nil { + fmt.Printf("Error marshaling JSON: %v\n", err) + return + } + fmt.Println(string(jsonData)) + return + } + total := r.Data["total_count"].(float64) fmt.Printf("Total: %0.0f\n", total) docs := r.Data["memory_list"].([]interface{}) table := make([]map[string]interface{}, 0)📝 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.func (r *ListMemoriesResponse) PrintOut() { if r.Code == 0 { if r.OutputFormat == OutputFormatJSON { jsonData, err := json.MarshalIndent(r.Data, "", " ") if err != nil { fmt.Printf("Error marshaling JSON: %v\n", err) return } fmt.Println(string(jsonData)) return } total := r.Data["total_count"].(float64) fmt.Printf("Total: %0.0f\n", total) docs := r.Data["memory_list"].([]interface{}) table := make([]map[string]interface{}, 0) for _, doc := range docs { table = append(table, doc.(map[string]interface{})) } PrintTableSimpleByFormat(table, r.OutputFormat)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/response.go` around lines 311 - 320, `ListMemoriesResponse.PrintOut` is writing the `Total:` prefix unconditionally, which breaks `--output json` by mixing plain text with JSON output. Update `PrintOut()` to branch on `r.OutputFormat` before printing, and only emit the human-readable total/table when not in JSON mode; keep the `r.Data["total_count"]`, `r.Data["memory_list"]`, and `PrintTableSimpleByFormat` handling intact for the non-JSON path, and ensure the JSON path returns clean machine-readable output with no extra text.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16454 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
### Summary Go CLI: add admin_command response table funtion --------- Co-authored-by: Jin Hai <[email protected]>
Summary
Go CLI: add admin_command response table funtion