Skip to content

Go CLI: add response output - #16263

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
myf-bee:maoyifeng-go-cli
Jun 23, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
myf-bee:maoyifeng-go-cli

Conversation

@myf-bee

@myf-bee myf-bee commented Jun 23, 2026

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Go CLI: add response output

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 23, 2026
@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds three new CLI response types (UserStorageResponse, UserQuotaResponse, rewritten UserIndexResponse) with ordered-metric table rendering. It adds PrintTableSimpleByFormatWithOrder to table.go and fixes bordered-mode cell padding. A new GetIndexStats method is added to the Elasticsearch client. Admin command handlers are updated to use the new types and the correct /storage endpoint.

Changes

Admin User Stats Response Types and Table Rendering

Layer / File(s) Summary
Table rendering: padCell fix and PrintTableSimpleByFormatWithOrder
internal/cli/table.go
Fixes bordered-mode cell padding to use padCell (display-width-aware) instead of manual len-based padding. Adds PrintTableSimpleByFormatWithOrder, which renders JSON, plain, or bordered tables using a caller-supplied column order with capped widths and consistent cell truncation.
Elasticsearch GetIndexStats method
internal/engine/elasticsearch/client.go
Adds GetIndexStats to elasticsearchEngine, calling _cat/indices in JSON format. Returns an empty slice for empty input or HTTP 404, and propagates other errors. Successful responses are decoded into []map[string]interface{}.
CommonDataResponse helper and new user response types
internal/cli/response.go
Removes the old UserIndexResponse wrapper and replaces it with a version embedding CommonDataResponse. Adds orderedMetricTable() to CommonDataResponse for deterministic metric rows. Adds UserStorageResponse (summary + files table) and UserQuotaResponse (rows table), each with Type() and PrintOut() supporting both JSON and bordered formatted output.
Admin command handlers wired to new response types
internal/cli/admin_command.go
Updates AdminShowUserStorageCommand to call /admin/users/{user}/storage and deserialize into UserStorageResponse. Updates AdminShowUserQuotaCommand and AdminShowUserIndexCommand to deserialize into UserQuotaResponse and UserIndexResponse respectively, with matching error messages.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as AdminShow* Command
    participant API as RAGFlow API
    participant ResponseType as UserStorage/Quota/IndexResponse
    participant Table as PrintTableSimpleByFormatWithOrder

    CLI->>API: GET /admin/users/{user}/storage|quota|index
    API-->>CLI: JSON response body
    CLI->>ResponseType: json.Unmarshal(body)
    ResponseType->>ResponseType: PrintOut()
    alt Code != 0
        ResponseType-->>CLI: print error, return
    end
    alt OutputFormatJSON
        ResponseType-->>CLI: print raw JSON
    else formatted
        ResponseType->>ResponseType: orderedMetricTable()
        ResponseType->>Table: PrintTableSimpleByFormatWithOrder(summary rows, columns, format)
        Table-->>CLI: render summary table
        ResponseType->>Table: PrintTableSimpleByFormatWithOrder(data rows, columns, format)
        Table-->>CLI: render data table (files/indices/rows)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#16119: Adds the admin CLI commands for showing user storage, quota, and index—this PR updates those same command handlers to use the correct endpoints and newly typed response structs.

Suggested labels

size:XL

🐇 A rabbit hops through the terminal's glow,
Three new responses in a tidy row—
Storage and quota and index aligned,
With ordered metric tables, neatly designed!
padCell now pads with display-width care,
And GetIndexStats floats through the Elastic air. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is incomplete, providing only a restatement of the title without addressing the required template sections or explaining the problem being solved. Fill in all required template sections: expand 'What problem does this PR solve' with detailed context, and properly select the 'Type of change' checkbox (New Feature is already marked but not selected).
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Go CLI: add response output' is vague and generic, describing the general category of change without conveying specific details about what response output functionality is being added. Consider a more specific title that indicates what aspect of response output is being enhanced, such as 'Add formatted table output for user storage and quota queries' or similar.
✅ Passed checks (2 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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


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.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 2082-2084: The error messages in the quota and index handler
functions contain generic "user storage" context strings that don't accurately
reflect the specific operation being performed. Update all error messages at
lines 2075, 2079, 2111, 2115, and 2118-2120 to use operation-specific context
instead of the copied generic text. For quota-related operations, use "get user
quota failed" as the error prefix (matching the pattern shown in the JSON
unmarshal error at line 2083), and for index-related operations, use appropriate
index-specific error context. This ensures error messages clearly indicate which
operation failed during troubleshooting.

In `@internal/cli/response.go`:
- Around line 972-974: The conditional check `if len(summaryTable) > 0`
suppresses the output of PrintTableSimpleByFormatWithOrder when the summaryTable
is empty, causing inconsistent CLI output contracts (particularly breaking JSON
format output on empty results). Remove the if condition and call
PrintTableSimpleByFormatWithOrder unconditionally with the summaryTable, the
column order array with "Metric", "Used", and "Limit", and r.OutputFormat, so
that output is always emitted regardless of whether summaryTable has rows or
not.
🪄 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: 3464228a-5bb1-4c9e-8f5f-a8bd9a775c87

📥 Commits

Reviewing files that changed from the base of the PR and between 11e14a8 and 9a64c00.

📒 Files selected for processing (4)
  • internal/cli/admin_command.go
  • internal/cli/response.go
  • internal/cli/table.go
  • internal/engine/elasticsearch/client.go

Comment on lines +2082 to +2084
var result UserQuotaResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
return nil, fmt.Errorf("get user storage failed: invalid JSON (%w)", err)
return nil, fmt.Errorf("get user quota failed: invalid JSON (%w)", err)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Fix copied error context in quota/index handlers.

After these type-specific updates, request/status failures in the same handlers still report "user storage" (Line 2075, Line 2079, Line 2111, Line 2115), which is misleading during troubleshooting.

Proposed fix
 func (c *CLI) AdminShowUserQuotaCommand(cmd *Command) (ResponseIf, error) {
@@
-	if err != nil {
-		return nil, fmt.Errorf("failed to get user storage: %w", err)
-	}
+	if err != nil {
+		return nil, fmt.Errorf("failed to get user quota: %w", err)
+	}
@@
-	if resp.StatusCode != 200 {
-		return nil, fmt.Errorf("failed to get user storage: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
-	}
+	if resp.StatusCode != 200 {
+		return nil, fmt.Errorf("failed to get user quota: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+	}
@@
 func (c *CLI) AdminShowUserIndexCommand(cmd *Command) (ResponseIf, error) {
@@
-	if err != nil {
-		return nil, fmt.Errorf("failed to get user storage: %w", err)
-	}
+	if err != nil {
+		return nil, fmt.Errorf("failed to get user index: %w", err)
+	}
@@
-	if resp.StatusCode != 200 {
-		return nil, fmt.Errorf("failed to get user storage: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
-	}
+	if resp.StatusCode != 200 {
+		return nil, fmt.Errorf("failed to get user index: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+	}

Also applies to: 2118-2120

🤖 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 2082 - 2084, The error messages
in the quota and index handler functions contain generic "user storage" context
strings that don't accurately reflect the specific operation being performed.
Update all error messages at lines 2075, 2079, 2111, 2115, and 2118-2120 to use
operation-specific context instead of the copied generic text. For quota-related
operations, use "get user quota failed" as the error prefix (matching the
pattern shown in the JSON unmarshal error at line 2083), and for index-related
operations, use appropriate index-specific error context. This ensures error
messages clearly indicate which operation failed during troubleshooting.

Comment thread internal/cli/response.go
Comment on lines +972 to +974
if len(summaryTable) > 0 {
PrintTableSimpleByFormatWithOrder(summaryTable, []string{"Metric", "Used", "Limit"}, r.OutputFormat)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Always emit quota output, even when rows are empty.

Line 972 suppresses output entirely for empty rows, so OutputFormatJSON returns no JSON at all on a successful empty result. Prefer printing via the table helper unconditionally to preserve consistent CLI output contracts.

Proposed fix
-	if len(summaryTable) > 0 {
-		PrintTableSimpleByFormatWithOrder(summaryTable, []string{"Metric", "Used", "Limit"}, r.OutputFormat)
-	}
+	PrintTableSimpleByFormatWithOrder(summaryTable, []string{"Metric", "Used", "Limit"}, r.OutputFormat)
📝 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
if len(summaryTable) > 0 {
PrintTableSimpleByFormatWithOrder(summaryTable, []string{"Metric", "Used", "Limit"}, r.OutputFormat)
}
PrintTableSimpleByFormatWithOrder(summaryTable, []string{"Metric", "Used", "Limit"}, 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 972 - 974, The conditional check `if
len(summaryTable) > 0` suppresses the output of
PrintTableSimpleByFormatWithOrder when the summaryTable is empty, causing
inconsistent CLI output contracts (particularly breaking JSON format output on
empty results). Remove the if condition and call
PrintTableSimpleByFormatWithOrder unconditionally with the summaryTable, the
column order array with "Metric", "Used", and "Limit", and r.OutputFormat, so
that output is always emitted regardless of whether summaryTable has rows or
not.

@6ba3i 6ba3i added the ci Continue Integration label Jun 23, 2026
@codecov

codecov Bot commented Jun 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (9f9433e) to head (9a64c00).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16263   +/-   ##
=======================================
  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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 643cb47 into infiniflow:main Jun 23, 2026
21 checks passed
@myf-bee
myf-bee deleted the maoyifeng-go-cli branch August 5, 2026 05:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants