Repository navigation
Go: add API mode check in file system command - #16022
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThe PR renames the CLI interactive entrypoint from ChangesCLI execution refactor and filesystem command extraction
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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/filesystem_command.go`:
- Around line 307-310: The plain format output loop (lines 307-310)
unconditionally formats node.CreatedAt, which displays "0001-01-01 00:00" for
unset timestamps, whereas the table format (lines 318-320) checks
node.CreatedAt.IsZero() and displays "-" instead. Apply the same zero-check
pattern to the plain format: before formatting node.CreatedAt in the fmt.Printf
call, check if node.CreatedAt.IsZero() is true and if so, use "-" as the
timestamp value, otherwise use the normal formatted timestamp.
- Around line 182-189: The code flows through after printing "(empty file)" when
content is empty or nil, causing the subsequent fmt.Println(string(content)) to
also execute and print an extra empty line. Add a return nil statement after the
fmt.Println("(empty file)") line, or restructure the conditions using else-if
chains to ensure that when content is empty or nil, the function returns
immediately and does not reach the final fmt.Println(string(content)) call.
- Around line 43-49: The global stdout redirect in the defer block of
ExecuteFilesystemCommand is not thread-safe for concurrent calls. Refactor
ExecuteFilesystemCommand to accept an io.Writer parameter instead of redirecting
os.Stdout globally. Pass this writer down to executeFilesystemInner and any
helper functions that currently write output, allowing them to write directly to
the provided writer instead of relying on stdout capture. This eliminates the
race condition that occurs when multiple goroutines call
ExecuteFilesystemCommand concurrently.
🪄 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: 1992f0dc-cdc0-4051-a0ca-dde158265bcd
📒 Files selected for processing (4)
cmd/ragflow_cli.gointernal/cli/cli.gointernal/cli/cli_http.gointernal/cli/filesystem_command.go
| old := os.Stdout | ||
| os.Stdout = w | ||
| defer func() { | ||
| os.Stdout = old | ||
| _ = w.Close() | ||
| _ = r.Close() | ||
| }() |
There was a problem hiding this comment.
Global stdout redirect is not thread-safe.
Redirecting os.Stdout affects all goroutines in the process. If ExecuteFilesystemCommand is called concurrently (e.g., from multiple HTTP handlers or parallel command execution), the stdout capture will corrupt output from other calls.
Consider using a writer interface pattern where the inner function writes to a provided io.Writer instead of relying on stdout capture:
♻️ Suggested approach
-func (c *CLI) ExecuteFilesystemCommand(cmd *Command) (ResponseIf, error) {
+func (c *CLI) ExecuteFilesystemCommand(cmd *Command) (ResponseIf, error) {
if c.Config.CLIMode != APIMode {
return nil, fmt.Errorf("this command is only allowed in USER mode")
}
rawInput, _ := cmd.Params["command"].(string)
-
- r, w, err := os.Pipe()
- if err != nil {
- return nil, fmt.Errorf("create stdout pipe: %w", err)
- }
- old := os.Stdout
- os.Stdout = w
- defer func() {
- os.Stdout = old
- _ = w.Close()
- _ = r.Close()
- }()
-
- var buf strings.Builder
- copyErrCh := make(chan error, 1)
- go func() {
- _, copyErr := io.Copy(&buf, r)
- copyErrCh <- copyErr
- }()
-
- execErr := c.executeFilesystemInner(rawInput)
- _ = w.Close() // signal EOF to reader goroutine
- copyErr := <-copyErrCh
- if copyErr != nil {
- return nil, fmt.Errorf("capture filesystem output: %w", copyErr)
- }
- return &FileSystemResponse{Output: buf.String()}, execErr
+ var buf strings.Builder
+ execErr := c.executeFilesystemInner(rawInput, &buf)
+ return &FileSystemResponse{Output: buf.String()}, execErr
}Then modify executeFilesystemInner and helper functions to accept an io.Writer parameter.
🤖 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/filesystem_command.go` around lines 43 - 49, The global stdout
redirect in the defer block of ExecuteFilesystemCommand is not thread-safe for
concurrent calls. Refactor ExecuteFilesystemCommand to accept an io.Writer
parameter instead of redirecting os.Stdout globally. Pass this writer down to
executeFilesystemInner and any helper functions that currently write output,
allowing them to write directly to the provided writer instead of relying on
stdout capture. This eliminates the race condition that occurs when multiple
goroutines call ExecuteFilesystemCommand concurrently.
| if content == nil || len(content) == 0 { | ||
| fmt.Println("(empty file)") | ||
| } else if isBinaryContent(content) { | ||
| return fmt.Errorf("cannot display binary file content") | ||
| } | ||
|
|
||
| fmt.Println(string(content)) | ||
| return nil |
There was a problem hiding this comment.
Cat command prints empty file message then prints content anyway.
The control flow falls through after printing "(empty file)", causing an extra empty line to be printed. Add return nil or use else-if chain:
if content == nil || len(content) == 0 {
fmt.Println("(empty file)")
+ return nil
} else if isBinaryContent(content) {
return fmt.Errorf("cannot display binary file content")
+} else {
+ fmt.Println(string(content))
}
-
-fmt.Println(string(content))
return nil🤖 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/filesystem_command.go` around lines 182 - 189, The code flows
through after printing "(empty file)" when content is empty or nil, causing the
subsequent fmt.Println(string(content)) to also execute and print an extra empty
line. Add a return nil statement after the fmt.Println("(empty file)") line, or
restructure the conditions using else-if chains to ensure that when content is
empty or nil, the function returns immediately and does not reach the final
fmt.Println(string(content)) call.
| for i := 0; i < displayCount; i++ { | ||
| node := result.Nodes[i] | ||
| fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, node.CreatedAt.Format("2006-01-02 15:04")) | ||
| } |
There was a problem hiding this comment.
Plain format doesn't handle zero CreatedAt like table format does.
Table format (line 318-320) checks node.CreatedAt.IsZero() and displays "-", but plain format unconditionally formats the time, which would show "0001-01-01 00:00" for unset timestamps.
for i := 0; i < displayCount; i++ {
node := result.Nodes[i]
- fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, node.CreatedAt.Format("2006-01-02 15:04"))
+ created := node.CreatedAt.Format("2006-01-02 15:04")
+ if node.CreatedAt.IsZero() {
+ created = "-"
+ }
+ fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, created)
}📝 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.
| for i := 0; i < displayCount; i++ { | |
| node := result.Nodes[i] | |
| fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, node.CreatedAt.Format("2006-01-02 15:04")) | |
| } | |
| for i := 0; i < displayCount; i++ { | |
| node := result.Nodes[i] | |
| created := node.CreatedAt.Format("2006-01-02 15:04") | |
| if node.CreatedAt.IsZero() { | |
| created = "-" | |
| } | |
| fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, created) | |
| } |
🤖 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/filesystem_command.go` around lines 307 - 310, The plain format
output loop (lines 307-310) unconditionally formats node.CreatedAt, which
displays "0001-01-01 00:00" for unset timestamps, whereas the table format
(lines 318-320) checks node.CreatedAt.IsZero() and displays "-" instead. Apply
the same zero-check pattern to the plain format: before formatting
node.CreatedAt in the fmt.Printf call, check if node.CreatedAt.IsZero() is true
and if so, use "-" as the timestamp value, otherwise use the normal formatted
timestamp.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16022 +/- ##
=======================================
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:
|
What problem does this PR solve?
As title.
Type of change