Skip to content

Go: refactor CLI - #15898

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix450
Jun 10, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix450

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

  1. remove unused code
  2. fix login issue

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • Refactoring

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 10, 2026
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR consolidates the CLI structure by eliminating the newMain() wrapper function, refactoring credential handling from stored arguments to parameter-based verification, removing the client.go abstraction layer while relocating its auth types and adapter to http_client.go, and consistently migrating output format configuration to use c.Config.OutputFormat.

Changes

CLI Structure and Auth Refactoring

Layer / File(s) Summary
CLI entrypoint and error handling consolidation
cmd/ragflow_cli.go
func main() is consolidated to contain full CLI initialization, logger setup, CLI creation, signal cleanup, and command execution directly instead of delegating to newMain(). Error message for single-command failures is updated from generic "Error: %v" to "Command execution failed: %v".
Authentication signature and password prompting refactor
internal/cli/cli.go
CLI struct removes outputFormat and args fields. VerifyAuth() signature changes to VerifyAuth(username, password string) accepting credentials as parameters instead of reading from stored args. NewRun reworks password prompting with generic "Please input your password" message for both API and admin modes, with validation retry logic.
Execution flow and command parsing updates
internal/cli/cli.go
execute() method is replaced with executeNew dispatch that parses commands via NewParser, handles meta commands, and dispatches via ExecuteCommand. executeFilesystemInner now always parses filesystem arguments from interactive input using parseFilesystemArgs instead of reusing pre-parsed c.args.CommandArgs.
Output format configuration migration
internal/cli/cli.go, internal/cli/common_command.go
All references to removed c.outputFormat field are migrated to c.Config.OutputFormat. Changes apply to NewCLIWithConfig initialization, skill-search result printing, filesystem result formatting, and LoginUserByCommand response format and success message.
Auth types and adapter relocation to http_client
internal/cli/http_client.go
Adds filesystem package import as ce alias. Introduces PasswordPromptFunc callback type and CurrentModel struct with Provider, Instance, Model fields. Implements httpClientAdapter with auto-detecting Request method that selects auth kind based on token availability and converts responses to ce.HTTPResponse, plus UploadMultipart delegation. Replaces removed client.go abstractions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

size:L


🐇 Hops through the CLI refactor with glee—
No more wrapper calls, credentials flow free,
Types find new homes, configs align clean,
Auth adapts smartly to every scene,
The code path is clearer, simpler to see!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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: refactor CLI' is vague and generic; it describes refactoring activity without clarifying the specific nature of the changes or their purpose. Provide a more specific title that describes the main objective, such as 'Refactor CLI authentication and consolidate main entry point' or 'Remove unused CLI client and streamline auth handling'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The description includes required sections (problem statement and type of change) but lacks detail; it briefly mentions removing unused code and fixing a login issue without explaining what was removed, how the login issue was fixed, or providing context.
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 and usage tips.

@JinHai-CN
JinHai-CN marked this pull request as ready for review June 10, 2026 06:53
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 🐞 bug Something isn't working, pull request that fix bug. labels Jun 10, 2026

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/cli/cli.go (1)

589-611: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

ReadPassword error silently dropped in both API and admin password prompts.

Both password prompting loops (API mode at lines 589-611 and admin mode at lines 616-648) capture err from ReadPassword() but only check password == "". If ReadPassword returns an I/O error, that error is silently overwritten when VerifyAuth is called. The fix is the same for both: check err != nil immediately after the ReadPassword() call.

🤖 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/cli.go` around lines 589 - 611, ReadPassword's returned error is
ignored; after calling ReadPassword() in both password prompts check err != nil
immediately and handle/return it instead of letting it be overwritten by later
logic. Specifically, in the API prompt block that sets apiConfig.UserPassword
and calls c.VerifyAuth(*apiConfig.UserName, *apiConfig.UserPassword), and in the
admin prompt block that mirrors this flow, add an immediate error check for the
local err from ReadPassword() and return or surface that error before inspecting
password == "" or calling VerifyAuth(), so I/O errors aren't silently dropped.
cmd/ragflow_cli.go (1)

31-34: ⚠️ Potential issue | 🟡 Minor

Inconsistent CLI error handling for ParseArgs failures

When cli.ParseArgs returns an error, main() just returns (no message, implicit exit code 0), unlike other error paths in this file that print the error and call os.Exit(1).

🐛 Suggested fix
 	parseArgs, err := cli.ParseArgs(os.Args[1:])
 	if err != nil {
+		fmt.Printf("Argument parsing failed: %v\n", err)
+		os.Exit(1)
 		return
 	}
🤖 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 `@cmd/ragflow_cli.go` around lines 31 - 34, The ParseArgs error path in main
silently returns; change it to mirror other error handling by printing the error
and exiting with non-zero status: capture the error returned from
cli.ParseArgs(os.Args[1:]), log or fmt.Fprintln(os.Stderr, err) (or use the
existing logger), and call os.Exit(1) instead of returning so failures in
ParseArgs result in an error message and exit code 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.

Outside diff comments:
In `@cmd/ragflow_cli.go`:
- Around line 31-34: The ParseArgs error path in main silently returns; change
it to mirror other error handling by printing the error and exiting with
non-zero status: capture the error returned from cli.ParseArgs(os.Args[1:]), log
or fmt.Fprintln(os.Stderr, err) (or use the existing logger), and call
os.Exit(1) instead of returning so failures in ParseArgs result in an error
message and exit code 1.

In `@internal/cli/cli.go`:
- Around line 589-611: ReadPassword's returned error is ignored; after calling
ReadPassword() in both password prompts check err != nil immediately and
handle/return it instead of letting it be overwritten by later logic.
Specifically, in the API prompt block that sets apiConfig.UserPassword and calls
c.VerifyAuth(*apiConfig.UserName, *apiConfig.UserPassword), and in the admin
prompt block that mirrors this flow, add an immediate error check for the local
err from ReadPassword() and return or surface that error before inspecting
password == "" or calling VerifyAuth(), so I/O errors aren't silently dropped.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 37f2a973-722b-4b9d-84d5-33e1d1f8a81d

📥 Commits

Reviewing files that changed from the base of the PR and between f632bb4 and e278b5a.

📒 Files selected for processing (5)
  • cmd/ragflow_cli.go
  • internal/cli/cli.go
  • internal/cli/client.go
  • internal/cli/common_command.go
  • internal/cli/http_client.go
💤 Files with no reviewable changes (1)
  • internal/cli/client.go

@codecov

codecov Bot commented Jun 10, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15898   +/-   ##
=======================================
  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 139f451 into infiniflow:main Jun 10, 2026
2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jul 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant