Skip to content

Prompt feature leftover items #804

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
May 15, 2025
Merged

Prompt feature leftover items #804

merged 18 commits into from
May 15, 2025

Conversation

lazysegtree
Copy link
Collaborator

@lazysegtree lazysegtree commented May 10, 2025

PRs

Relevant Issues

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added support for a chooser file to write selected file paths and exit, configurable via CLI flag.
    • Introduced quit state machine for improved quit confirmation flow.
    • Added dynamic prompt modal sizing with explicit width and height parameters.
    • Enhanced CLI with new flags for hotkey and chooser file paths.
  • Refactor

    • Improved path resolution with centralized handling of tilde and relative paths.
    • Encapsulated first-use state within the model struct.
    • Simplified key input handling and prompt modal rendering.
    • Updated prompt modal to manage shell mode state via setter methods.
    • Removed deprecated utilities and unused imports.
    • Reorganized chooser file handling to conditionally write and quit before opening editors.
    • Refactored tests for clearer setup, detailed scenarios, and platform-specific adjustments.
    • Enhanced global config loading to determine file locations dynamically.
  • Bug Fixes

    • Improved error handling when resolving directories, defaulting to home directory if invalid.
    • Fixed platform-specific issues in shell substitution tests on Windows.
  • Tests

    • Added extensive tests for path resolution, prompt modal behavior, file operations, and quitting scenarios.
    • Provided shared test utilities for consistent environment setup.
    • Added chooser file integration tests verifying file writing and process exit.
    • Added detailed prompt rendering tests validating output under various inputs and modes.
  • Chores

    • Updated documentation to reflect improved test coverage.
    • Added comments and TODOs for future improvements.
    • Cleaned up codebase by removing unused code and improving logging clarity.

Copy link

coderabbitai bot commented May 10, 2025

Warning

Rate limit exceeded

@lazysegtree has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 26 minutes and 51 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1b565ba and 8c98741.

📒 Files selected for processing (3)
  • src/cmd/main.go (2 hunks)
  • src/internal/model_test.go (1 hunks)
  • testsuite/core/fs_manager.py (1 hunks)

Walkthrough

This update centralizes and refactors path resolution logic by introducing a new utility function, ResolveAbsPath, which handles tilde expansion and relative paths. The function is adopted across configuration and panel navigation code, with related methods refactored for clarity and consistency. Corresponding tests for the new utility are also added. Additionally, the model's firstUse state is encapsulated as a struct field, prompt modal dimension handling is enhanced, and comprehensive prompt modal tests are introduced.

Changes

Files/Paths Change Summary
src/internal/config_function.go Refactored to use utils.ResolveAbsPath for directory path handling, improved error checking, removed unused imports.
src/internal/model.go Refactored panel path handling to use utils.ResolveAbsPath, extracted new method for relative panel creation, updated error messages, replaced global firstUse with model field, added prompt modal size management, and quit state machine.
src/internal/handle_panel_navigation.go Added comments and TODO for error definition; no logic changes.
src/internal/utils/file_utils.go Added ResolveAbsPath utility function for centralized, robust path resolution.
src/internal/utils/file_utils_test.go Added new tests for ResolveAbsPath, covering tilde expansion, absolute/relative paths, and path cleaning.
src/internal/default_config.go Updated defaultModelConfig to accept firstUse parameter and initialize model field, set prompt modal default size, and initialize quit state.
src/internal/function.go Removed TeaUpdate function, added getFocusedFilePanel method to model.
src/internal/model_file_operations_test.go Added TestCopy to verify copy-paste functionality with file panels and clipboard.
src/internal/model_prompt_test.go Replaced minimal prompt tests with comprehensive TestModel_Update_Prompt covering prompt modal and shell commands.
src/internal/model_test.go Added global test setup, cleanup, and basic model initialization test.
src/internal/test_utils.go Added test utilities for model setup, directory/file creation, and model update helper.
src/internal/type.go Added firstUse boolean field and modelQuitState enum field to model struct with comment on possible pointer receiver usage.
src/internal/ui/prompt/model.go Added getter/setter methods for prompt model flags and dimensions; centralized shell mode state management; removed parameterized render method.
src/internal/ui/prompt/model_test.go Updated tests to use new getter methods instead of direct field access for prompt model state assertions; added comprehensive render tests.
src/internal/model_render.go Modified prompt modal rendering call to no longer pass explicit dimensions.
src/internal/ui/prompt/consts.go Added constants for minimum prompt width and height and default test width and max height.
src/internal/ui/prompt/tokenize_test.go Enhanced shell substitution tests for platform-specific behavior and timeouts, especially on Windows.
src/internal/common/load_config.go Changed PopulateGlobalConfigs to parameterless; dynamically resolves config file paths relative to source.
src/cmd/main.go Added lastdir-file boolean flag to path-list command; added chooser-file string flag with alias to root CLI flags.
src/config/fixed_variable.go Added global ChooserFile variable and setter; updated CLI argument handling to set chooser file path.
src/internal/handle_file_operations.go Added chooserFileWriteAndQuit method; modified file and directory open methods to write chooser file and quit if set.
src/internal/handle_panel_movement.go Refactored enterPanel to handle chooser file writing and quit logic conditionally after symlink directory handling.
src/internal/key_function.go Simplified mainKey method signature; replaced quit confirmation boolean with quit state enum.
testsuite/core/fs_manager.py Added read_file method to read file contents with error handling.
testsuite/core/pyautogui_manager.py Updated start_spf method to accept optional argument list appended to command.
testsuite/core/runner.py Added blank lines for visual separation; no logic changes.
testsuite/core/spf_manager.py Updated abstract start_spf method signature to accept optional argument list.
testsuite/core/tmux_manager.py Updated start_spf method to accept optional argument list and modify tmux window command accordingly.
testsuite/tests/chooser_file_test.py Added ChooserFileTest class to validate chooser file writing and content during superfile execution.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Model
    participant Utils

    User->>Model: Request to open new panel with path
    Model->>Utils: ResolveAbsPath(currentDir, path)
    Utils-->>Model: Absolute, cleaned path
    Model->>Model: Create new panel at resolved path
Loading

Possibly related PRs

  • Model unit tests #803: The main PR and the retrieved PR Model unit tests #803 both modify the defaultModelConfig function to add a firstUse boolean parameter and move the firstUse state from a global variable to a field inside the model struct, indicating a direct and strong code-level relationship in how the model's initial state is handled.
  • feat: Render unit tests for prompt model #809: The main PR includes changes that add and improve prompt model rendering tests and refactor prompt model sizing and state management, which directly relates to the retrieved PR that also adds comprehensive render unit tests for the prompt model and updates test logic accordingly.
  • Prompt dynamic dimensions and unit tests fix #805: The main PR and the retrieved PR Prompt dynamic dimensions and unit tests fix #805 both refactor the handling of initial directory paths in initialConfig by replacing manual tilde expansion and filepath.Abs calls with the centralized utils.ResolveAbsPath function, and both encapsulate the firstUse boolean into the model struct while adding prompt modal size management and updating prompt modal rendering to use stored dimensions instead of parameters, indicating a direct and strong code-level relationship.

Suggested labels

refactoring

Poem

In a warren of folders, a rabbit did hop,
With tilde and slashes, it never would stop.
Now, with ResolveAbsPath, the journey’s a breeze—
No more lost tunnels, just directories with ease!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 1

🧹 Nitpick comments (2)
src/internal/utils/file_utils.go (1)

102-115: Well-designed path resolution utility.

The new ResolveAbsPath function is a good abstraction that centralizes path resolution logic. The documentation clearly states that currentDir should be an absolute path, and the implementation correctly handles tilde expansion and relative paths.

However, consider adding validation for the currentDir parameter to ensure it's actually an absolute path.

func ResolveAbsPath(currentDir string, path string) string {
+	// Validate that currentDir is absolute as required by function contract
+	if !filepath.IsAbs(currentDir) {
+		// Log a warning but continue with best effort
+		// We don't return an error to maintain the simple function signature
+		currentDir = filepath.Clean(currentDir)
+	}
	if strings.HasPrefix(path, "~") {
		// We dont use variable.HomeDir here, as the util package cannot have dependency
		// on variable package
		path = strings.Replace(path, "~", xdg.Home, 1)
	}
	if !filepath.IsAbs(path) {
		path = filepath.Join(currentDir, path)
	}
	return filepath.Clean(path)
}
src/internal/utils/file_utils_test.go (1)

10-60: Comprehensive test coverage for the new utility.

The test cases are thorough and cover important scenarios including path cleaning, absolute vs. relative paths, tilde expansion, and edge cases. This ensures the reliability of the centralized path resolution logic.

A few suggestions to enhance the tests further:

  1. Consider adding a test case with a path that includes ~ in the middle (e.g., foo/~/bar)
  2. Add a test for paths with parent directory references (e.g., ../foo)
  3. Test with invalid currentDir values to verify graceful handling
func TestResolveAbsPath(t *testing.T) {
	testdata := []struct {
		name        string
		cwd         string
		path        string
		expectedRes string
	}{
		// Existing test cases...
+		{
+			name:        "Path with parent directory reference",
+			cwd:         "/abc/def",
+			path:        "../ghi",
+			expectedRes: "/abc/ghi",
+		},
+		{
+			name:        "Tilde in the middle of path",
+			cwd:         "/abc",
+			path:        "def/~/ghi",
+			expectedRes: "/abc/def/~/ghi",
+		},
+		{
+			name:        "Relative currentDir",
+			cwd:         "relative/path", // Not absolute as required
+			path:        "file.txt",
+			expectedRes: "relative/path/file.txt", // Should still work with best effort
+		},
	}

	// Rest of the function remains the same
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 54aee46 and ac7914a.

📒 Files selected for processing (5)
  • src/internal/config_function.go (1 hunks)
  • src/internal/handle_panel_navigation.go (1 hunks)
  • src/internal/model.go (2 hunks)
  • src/internal/utils/file_utils.go (2 hunks)
  • src/internal/utils/file_utils_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/internal/config_function.go (3)
src/internal/common/default_config.go (1)
  • Config (11-11)
src/internal/utils/file_utils.go (1)
  • ResolveAbsPath (105-115)
src/config/fixed_variable.go (1)
  • HomeDir (27-27)
src/internal/utils/file_utils_test.go (1)
src/internal/utils/file_utils.go (1)
  • ResolveAbsPath (105-115)
src/internal/model.go (1)
src/internal/utils/file_utils.go (1)
  • ResolveAbsPath (105-115)
🔇 Additional comments (6)
src/internal/handle_panel_navigation.go (1)

28-28: Good addition of a TODO for error standardization.

Adding this TODO comment is a good step towards better error handling practices. Centralizing error definitions in a dedicated errors.go file will improve consistency and maintainability throughout the codebase.

src/internal/config_function.go (2)

63-68: Good refactoring using the new ResolveAbsPath utility.

Using the centralized path resolution utility improves code maintainability and ensures consistent path handling throughout the codebase. The error handling for invalid paths is also appropriate.


72-72: Enhanced debugging information.

Adding the current working directory to the debug log provides valuable context for troubleshooting path resolution issues.

src/internal/model.go (3)

316-317: Improved path handling with dedicated method

This change correctly leverages the new dedicated method for resolving paths relative to the current panel, making the code more readable and maintainable.


348-351: Well-structured extraction of path resolution logic

This new method nicely encapsulates the path resolution logic using the centralized ResolveAbsPath utility, following the Single Responsibility Principle. It properly obtains the current directory from the focused panel and resolves the path relative to it.


353-366: Good refactoring of path handling in directory update

The refactored method now leverages the new utils.ResolveAbsPath utility function to handle path resolution consistently, including tilde expansion and relative paths. Error messages have been properly updated to reflect the resolved path. This change improves code maintainability by centralizing path resolution logic.

@lazysegtree lazysegtree changed the title Updates Prompt feature leftover items May 11, 2025
@lazysegtree lazysegtree added test related PR / Issue related to testcases or testing in general. new feature high priority Issue/PR/Feature/bug that is considered high priority. bug fixes labels May 11, 2025
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: 3

🧹 Nitpick comments (12)
src/internal/default_config.go (1)

13-14: Consider implementing the suggestion in the comment.

The comment suggests using variadic arguments instead of a slice for the file panel directories, which would provide a more flexible API.

-// Maybe we can replace slice of strings with var args - Should we ?
-func defaultModelConfig(toggleDotFile bool, toggleFooter bool, firstUse bool, firstFilePanelDirs []string) model {
+// Use variadic arguments for more flexible API
+func defaultModelConfig(toggleDotFile bool, toggleFooter bool, firstUse bool, dirs ...string) model {
src/internal/model_file_operations_test.go (4)

16-19: Consider addressing TODOs before merging

There are multiple TODO comments indicating incomplete test coverage. Consider implementing these test cases before merging, or create specific follow-up issues for them if they'll be addressed separately.


34-36: Use appropriate file permissions

File permissions of 0755 (executable) are unusual for regular text files. Consider using more appropriate permissions like 0644 for regular files:

-		err = os.WriteFile(file1, SampleDataBytes, 0755)
+		err = os.WriteFile(file1, SampleDataBytes, 0644)

55-55: Remove debug print statements

These fmt.Println statements will pollute test output. Consider removing them or replacing with conditional logging that only appears in verbose mode:

-		fmt.Println(m.fileModel.filePanels[m.filePanelFocusIndex].location)
+		// Use t.Logf for debugging which only appears when tests are run with -v
+		t.Logf("location: %s", m.fileModel.filePanels[m.filePanelFocusIndex].location)

Also applies to: 68-68


84-89: Remove redundant assertion

The assert.FileExists call on line 88 is redundant since the assert.Eventually block already checks for the file's existence. Consider removing it:

		assert.Eventually(t, func() bool {
			_, err := os.Lstat(filepath.Join(dir2, "file1(1).txt"))
			return err == nil
		}, time.Second, 10*time.Millisecond)
-		assert.FileExists(t, filepath.Join(dir2, "file1(1).txt"))
src/internal/test_utils.go (2)

13-13: Consider more descriptive sample data

The sample data is quite minimal. For more thorough testing, consider making it longer or more varied to better test file operations with different content types.


15-19: Well-structured test model helper

This helper function provides a clean way to create test models. Consider adding an optional parameter to override window dimensions for tests that need different sizes:

-func defaultTestModel(dirs ...string) model {
+func defaultTestModel(dirs ...string, opts ...modelTestOption) model {
 	m := defaultModelConfig(false, false, false, dirs)
-	_, _ = TeaUpdate(&m, tea.WindowSizeMsg{Width: 2 * common.MinimumWidth, Height: 2 * common.MinimumHeight})
+	width, height := 2 * common.MinimumWidth, 2 * common.MinimumHeight
+	// Apply options if provided
+	for _, opt := range opts {
+		opt(&width, &height)
+	}
+	_, _ = TeaUpdate(&m, tea.WindowSizeMsg{Width: width, Height: height})
 	return m
}

+// modelTestOption is a function type for configuring test model options
+type modelTestOption func(*int, *int)
+
+// WithDimensions returns an option to set custom window dimensions
+func WithDimensions(width, height int) modelTestOption {
+	return func(w, h *int) {
+		*w, *h = width, height
+	}
+}
src/internal/model_test.go (2)

30-36: Consider returning errors instead of exiting

In the cleanupTestDir function, consider returning an error instead of calling os.Exit(1). This would allow the caller to decide how to handle the error.

-func cleanupTestDir() {
+func cleanupTestDir() error {
 	err := os.RemoveAll(testDir)
 	if err != nil {
-		fmt.Printf("error while cleaning up test directory, err : %v", err)
-		os.Exit(1)
+		return fmt.Errorf("error while cleaning up test directory: %w", err)
 	}
+	return nil
}

Then in TestMain, handle the error:

defer func() {
    if err := cleanupTestDir(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}()

56-59: Use setupDirectories helper

For consistency, consider using the setupDirectories helper function from test_utils.go instead of directly calling os.Mkdir:

-	if err := os.Mkdir(testDir, 0755); err != nil {
-		fmt.Printf("error while creating test directory, err : %v", err)
-		os.Exit(1)
-	}
+	t := &testing.T{}
+	setupDirectories(t, testDir)
+	// Handle case where setupDirectories fails (calls t.FailNow())
+	if t.Failed() {
+		os.Exit(1)
+	}

Alternatively, refactor setupDirectories to return errors so it can be used in both contexts.

src/internal/model_prompt_test.go (3)

16-24: Add t.Parallel() and a cleanup hook for test isolation

The test creates a dedicated directory tree but never removes it and runs every sub-test sequentially.
Running the test (and its sub-tests) in parallel while relying on t.TempDir() or an explicit t.Cleanup(os.RemoveAll) will:

  1. Avoid polluting the workspace.
  2. Prevent state leakage between future tests.
  3. Shorten overall test-suite runtime.
func TestModel_Update_Prompt(t *testing.T) {
-	curTestDir := filepath.Join(testDir, "TestPrompt")
+	t.Parallel()
+
+	curTestDir := t.TempDir()                   // uses Go’s built-in tmp directory
+	curTestDir = filepath.Join(curTestDir, "TestPrompt")
 ...
-	setupDirectories(t, curTestDir, dir1, dir2)
-	setupFiles(t, file1)
+	setupDirectories(t, curTestDir, dir1, dir2)
+	setupFiles(t, file1)
+
+	// Ensure the artefacts are removed even if the test fails
+	t.Cleanup(func() { _ = os.RemoveAll(curTestDir) })

108-118: Guard the splitting loop to avoid accidental infinite iteration

for len(m.fileModel.filePanels) < m.fileModel.maxFilePanel { … } relies on the implementation detail that every SplitCommand must succeed until the panel count matches maxFilePanel.
If a future change prevents a panel from being added (e.g., layout validation) the loop will never terminate and the test will hang.

-for len(m.fileModel.filePanels) < m.fileModel.maxFilePanel {
+for i := 0; i < m.fileModel.maxFilePanel-len(m.fileModel.filePanels); i++ {

This makes the upper bound explicit and guarantees loop termination.


209-218: Apply the same bounded-loop pattern to the “open” panel stress test

Similar to the split test, opening panels until the limit should be bounded by an explicit counter to eliminate the risk of an endless loop if an intermediate open fails.

-for len(m.fileModel.filePanels) < m.fileModel.maxFilePanel {
+for i := 0; i < m.fileModel.maxFilePanel-len(m.fileModel.filePanels); i++ {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac7914a and 3e857c2.

📒 Files selected for processing (11)
  • src/internal/default_config.go (2 hunks)
  • src/internal/function.go (1 hunks)
  • src/internal/handle_panel_navigation.go (1 hunks)
  • src/internal/model.go (5 hunks)
  • src/internal/model_file_operations_test.go (1 hunks)
  • src/internal/model_prompt_test.go (3 hunks)
  • src/internal/model_test.go (1 hunks)
  • src/internal/test_utils.go (1 hunks)
  • src/internal/type.go (2 hunks)
  • src/internal/ui/prompt/model.go (1 hunks)
  • src/internal/ui/prompt/model_test.go (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/internal/handle_panel_navigation.go
  • src/internal/model.go
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/internal/ui/prompt/model_test.go (2)
src/internal/utils/tea_utils.go (1)
  • TeaRuneKeyMsg (5-10)
src/internal/common/type.go (1)
  • NoAction (9-10)
src/internal/test_utils.go (1)
src/internal/common/predefined_variable.go (2)
  • MinimumWidth (15-15)
  • MinimumHeight (14-14)
src/internal/model_test.go (4)
src/internal/ui/prompt/model_test.go (1)
  • TestMain (24-41)
src/internal/common/load_config.go (1)
  • PopulateGlobalConfigs (237-251)
src/internal/utils/log_utils.go (2)
  • SetRootLoggerToStdout (26-33)
  • SetRootLoggerToDiscarded (36-38)
src/internal/test_utils.go (2)
  • SampleDataBytes (13-13)
  • TeaUpdate (42-51)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (11)
src/internal/ui/prompt/model.go (2)

171-173: Good addition of accessor method for shellMode.

This new getter method improves encapsulation by providing controlled access to the internal state flag without exposing the field directly. This is a good practice for maintaining the integrity of the model's state.


175-177: Good addition of accessor method for actionSuccess.

This getter method provides read-only access to the action success state and follows the same encapsulation pattern as IsShellMode(). Both methods support better testing and cleaner interface design.

src/internal/type.go (2)

78-81: Good documentation of potential optimization.

This comment provides valuable insight for future developers about potential optimization opportunities and explains the tradeoffs involved with using pointer receivers vs. value receivers for the tea.Model interface.


99-99: Good encapsulation of previously global state.

Adding the firstUse field to the model struct improves state management by moving what was previously a global variable into the model itself. This makes state tracking more predictable and testable.

src/internal/function.go (1)

384-386: Good helper method for accessing the focused file panel.

This method centralizes the logic for accessing the currently focused file panel, which helps reduce code duplication and improves readability. By returning a pointer, it also allows callers to modify the panel directly when needed.

src/internal/default_config.go (1)

40-40: Good assignment of the new parameter.

The firstUse parameter is correctly assigned to the model's new field, completing the encapsulation of this previously global state.

src/internal/ui/prompt/model_test.go (1)

64-64: Great encapsulation improvement!

Replacing direct field access with getter methods (LastActionSucceeded() and IsShellMode()) improves the code's maintainability and follows good encapsulation practices. This change makes the test code more resilient to internal implementation changes in the model struct.

Also applies to: 85-85, 115-120, 125-127, 131-133, 170-171, 176-177, 183-184, 194-195

src/internal/model_file_operations_test.go (1)

51-53: Investigate model initialization requirement

The comment suggests a workaround is needed to initialize the model. This might indicate a design issue where the model should initialize properly without requiring a keypress event.

Consider revising the model initialization to avoid this workaround, or document why this approach is necessary.

src/internal/test_utils.go (1)

37-51: Good utility function for model updates

The TeaUpdate function is well-designed and properly documented. The TODO comment suggests a good future improvement for integrating error assertions.

src/internal/model_test.go (2)

28-28: Descriptive comment for global variable

Good practice adding a clear comment and nolint directive explaining why this global variable is justified.


96-104: Implement planned validations or convert to explicit TODOs

Currently, the validation plans are just comments. Consider either implementing these validations or converting them to explicit TODO markers that can be tracked:

-		// Validate the most of the data stored in model object
-		// Inspect model struct to see what more can be validated.
-		// 1 - File panel location, cursor, render index, etc.
-		// 2 - Directory Items are listed
-		// 3 - sidebar items pinned items are listed
-		// 4 - process panel is empty
-		// 5 - clipboard is empty
-		// 6 - model's dimenstion
+		// TODO: Implement validations:
+		// - Validate file panel location, cursor, render index
+		// - Verify directory items are listed correctly
+		// - Verify sidebar items and pinned items
+		// - Verify process panel is empty
+		// - Verify clipboard is empty
+		// - Verify model dimensions

Better yet, implement at least some basic validations to make this test meaningful.

lazysegtree and others added 3 commits May 11, 2025 09:56
fix: Unit test fix for windows 2
Prompt dynamic dimensions and unit tests fix
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: 0

♻️ Duplicate comments (2)
src/internal/model_prompt_test.go (2)

85-102: 🛠️ Refactor suggestion

Shell command execution needs assertion improvements

Several calls to TeaUpdate discard the error return value, which could mask potential issues in the test.

-_, _ = TeaUpdate(&m, utils.TeaRuneKeyMsg(common.Hotkeys.OpenCommandLine[0]))
-// Prefer cross platform command
-_, _ = TeaUpdate(&m, utils.TeaRuneKeyMsg("mkdir test_dir"))
-_, _ = TeaUpdate(&m, tea.KeyMsg{Type: tea.KeyEnter})
+_, err := TeaUpdate(&m, utils.TeaRuneKeyMsg(common.Hotkeys.OpenCommandLine[0]))
+require.NoError(t, err)
+// Prefer cross platform command
+_, err = TeaUpdate(&m, utils.TeaRuneKeyMsg("mkdir test_dir"))
+require.NoError(t, err)
+_, err = TeaUpdate(&m, tea.KeyMsg{Type: tea.KeyEnter})
+require.NoError(t, err)

88-94: 🛠️ Refactor suggestion

Replace shell-exec with cross-platform alternative

The test uses a shell command to create a directory, which can behave differently across platforms.

-_, _ = TeaUpdate(&m, utils.TeaRuneKeyMsg("mkdir test_dir"))
+// Use os.MkdirAll directly or a cross-platform helper
+_, err = TeaUpdate(&m, utils.TeaRuneKeyMsg("cd ."))
+require.NoError(t, err)
+
+// Create directory directly using Go
+err = os.MkdirAll(filepath.Join(dir1, "test_dir"), 0755)
+require.NoError(t, err)
🧹 Nitpick comments (1)
src/internal/ui/prompt/tokenize_test.go (1)

187-199: Consider adding timeout adjustments for test stability

Shell command and environment variable substitution tests can be flaky on Windows. Consider adding additional timeout or retry logic for these specific test cases to improve reliability.

 // Note : resolving shell subsitution is flaky in windows.
 _, _ = TeaUpdate(&m, utils.TeaRuneKeyMsg(prompt.OpenCommand+" $(echo \"~\")"))
 _, _ = TeaUpdate(&m, tea.KeyMsg{Type: tea.KeyEnter})
-assert.True(t, m.promptModal.LastActionSucceeded(), "open using command substitution should work")
+// Use require.Eventually to allow for occasional slowness on Windows
+require.Eventually(t, func() bool {
+    return m.promptModal.LastActionSucceeded()
+}, 5*time.Second, 100*time.Millisecond, "open using command substitution should work")
 assert.Equal(t, xdg.Home, m.getFocussedFilePanel().location)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3e857c2 and e4676c7.

📒 Files selected for processing (10)
  • src/internal/default_config.go (2 hunks)
  • src/internal/model.go (8 hunks)
  • src/internal/model_prompt_test.go (3 hunks)
  • src/internal/model_render.go (1 hunks)
  • src/internal/ui/prompt/consts.go (1 hunks)
  • src/internal/ui/prompt/model.go (5 hunks)
  • src/internal/ui/prompt/model_test.go (6 hunks)
  • src/internal/ui/prompt/tokenize_test.go (6 hunks)
  • src/internal/ui/prompt/type.go (1 hunks)
  • src/internal/utils/file_utils_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • src/internal/ui/prompt/consts.go
  • src/internal/ui/prompt/type.go
  • src/internal/utils/file_utils_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/internal/default_config.go
  • src/internal/ui/prompt/model_test.go
  • src/internal/model.go
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/internal/model_prompt_test.go (4)
src/internal/test_utils.go (1)
  • TeaUpdate (42-51)
src/internal/utils/tea_utils.go (1)
  • TeaRuneKeyMsg (5-10)
src/internal/common/default_config.go (1)
  • Hotkeys (12-12)
src/internal/ui/prompt/consts.go (3)
  • SplitCommand (11-11)
  • CdCommand (12-12)
  • OpenCommand (10-10)
src/internal/ui/prompt/model.go (3)
src/internal/ui/prompt/type.go (1)
  • Model (6-30)
src/internal/common/default_config.go (2)
  • Hotkeys (12-12)
  • Config (11-11)
src/internal/ui/spf_renderers.go (1)
  • PromptRenderer (55-73)
🔇 Additional comments (16)
src/internal/model_render.go (1)

432-434: Clean parameter removal from prompt modal rendering

The removal of height and width parameters from the promptModal.Render() call aligns with the refactoring to store dimensions within the prompt modal itself rather than passing them with each render call. This improves encapsulation and consistency.

src/internal/ui/prompt/tokenize_test.go (3)

86-87: Good platform-specific issue documentation

Clear documentation about Windows-specific flakiness issues with shell substitution helps other developers understand potential test failures.


89-98: Excellent platform-specific test improvements

The addition of platform-specific variables for timeout duration, newline suffix, and no-op command makes the tests more robust across different operating systems, particularly Windows.


141-142: Properly handling platform-specific output in test expectations

Using the platform-aware newline suffix in expected command output ensures tests will pass correctly on both Windows (\r\n) and Unix (\n) systems.

Also applies to: 149-157

src/internal/ui/prompt/model.go (6)

16-35: Good dimension management in model constructors

The updated constructor functions now accept and store dimensions, improving the encapsulation of the prompt modal by making it responsible for its own size.


91-103: Refactored shell mode switching with central method call

Replacing direct shell mode assignments with calls to the new setShellMode method centralizes the logic and ensures the prompt prefix is consistently updated.


124-166: Improved render method with better organization

The refactored Render method now uses stored dimensions and has improved hint section handling with the hintSectionAdded flag to prevent duplicate sections.


174-177: Well-designed shell mode encapsulation

The new setShellMode method properly centralizes both the mode flag setting and prompt prefix update, ensuring they stay in sync.


189-214: Good addition of accessor methods

The new getter and setter methods provide a clean interface for accessing and modifying model properties, improving encapsulation. The SetWidth method correctly updates the text input width to account for borders and padding.


205-210: Well-documented width calculation

The comments explaining the width calculation for the text input field are helpful for future maintenance, clearly showing how the borders, padding, and prompt affect the available space.

src/internal/model_prompt_test.go (6)

16-24: Well-organized test setup

The test setup code creates a consistent environment with predefined directories and files, making the tests more reliable and easier to understand.


25-49: Clear test plan with organized comments

The comprehensive list of test scenarios provides a good roadmap for test implementation and helps ensure all important functionality is covered.


62-83: Verify prompt mode opening and switching behavior

The test thoroughly checks opening the prompt in different modes and switching between them, a critical part of the user interface.


125-158: Comprehensive directory navigation tests

The tests thoroughly verify changing directories with absolute paths, relative paths, home directory, and handling of invalid paths.


160-221: Comprehensive panel opening tests

Tests for opening panels cover multiple scenarios including different path formats, environment variables, command substitution, and handling of maximum panel limits.


223-231: Effective modal closing verification

The test ensures that all cancellation hotkeys properly close the prompt modal.

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: 1

♻️ Duplicate comments (1)
src/internal/model_prompt_test.go (1)

92-96: 🛠️ Refactor suggestion

Replace shell-exec mkdir with an internal helper for true cross-platform testing

The comment states "Prefer cross platform command", yet the test still shells out to mkdir, which:

  • Relies on the host shell being available
  • Behaves differently on Windows (cmd /c) vs Unix (sh -c)
  • Introduces timing & quoting issues that unit tests should avoid

Use the model's own command execution abstraction (or a simple os.MkdirAll) to create the directory and assert the prompt's success flag directly:

-TeaUpdateWithErrCheck(t, &m, utils.TeaRuneKeyMsg("mkdir test_dir"))
-TeaUpdateWithErrCheck(t, &m, tea.KeyMsg{Type: tea.KeyEnter})
+// Create directory directly using Go's cross-platform API
+err := os.MkdirAll(filepath.Join(dir1, "test_dir"), 0755)
+require.NoError(t, err)
+
+// Verify that a simple command succeeds
+TeaUpdateWithErrCheck(t, &m, utils.TeaRuneKeyMsg("echo success"))
+TeaUpdateWithErrCheck(t, &m, tea.KeyMsg{Type: tea.KeyEnter})
🧹 Nitpick comments (2)
src/internal/ui/prompt/ReadMe.md (1)

20-22: Enhance to-do list clarity and consistency.

The new to-dos are valuable, but the phrasing and capitalization could be more uniform:

  • Use uppercase “PR” instead of “pr” in “Dimension fix pr comments.”
  • Apply consistent sentence casing (e.g., “Prompt’s rendering tests”).
  • Optionally clarify what dimensions need fixing in the PR comments.

Proposed refinement:

- - Prompt's Rendering tests
- - Dimension fix pr comments
+ - Prompt’s rendering tests
+ - Dimension fix PR comments (specify which modal dimensions require adjustment)
🧰 Tools
🪛 LanguageTool

[duplication] ~20-~20: Possible typo: you repeated a word.
Context: ...ut Model's .prompt field for '>' or ':' prompt - Prompt's Rendering tests - Dimension fix pr co...

(ENGLISH_WORD_REPEAT_RULE)

src/internal/model_prompt_test.go (1)

48-49: Inconsistency between comment and implementation

The comment states "Don't test shell command substitution here," but the test does include shell command substitution tests on lines 197-200 with $(echo \"~\").

Either remove this comment or clarify its meaning to avoid confusion for future maintainers:

-// Dont test shell command substitution here.
+// TODO: Consider moving complex shell command substitution tests to a separate test function
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e4676c7 and 9fbf622.

📒 Files selected for processing (11)
  • src/internal/config_function.go (1 hunks)
  • src/internal/default_config.go (2 hunks)
  • src/internal/function.go (1 hunks)
  • src/internal/model_file_operations_test.go (1 hunks)
  • src/internal/model_prompt_test.go (3 hunks)
  • src/internal/model_test.go (1 hunks)
  • src/internal/test_utils.go (1 hunks)
  • src/internal/ui/prompt/ReadMe.md (1 hunks)
  • src/internal/ui/prompt/consts.go (1 hunks)
  • src/internal/ui/prompt/model.go (5 hunks)
  • src/internal/utils/file_utils.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (9)
  • src/internal/model_file_operations_test.go
  • src/internal/default_config.go
  • src/internal/utils/file_utils.go
  • src/internal/config_function.go
  • src/internal/ui/prompt/consts.go
  • src/internal/function.go
  • src/internal/test_utils.go
  • src/internal/ui/prompt/model.go
  • src/internal/model_test.go
🧰 Additional context used
🪛 LanguageTool
src/internal/ui/prompt/ReadMe.md

[duplication] ~20-~20: Possible typo: you repeated a word.
Context: ...ut Model's .prompt field for '>' or ':' prompt - Prompt's Rendering tests - Dimension fix pr co...

(ENGLISH_WORD_REPEAT_RULE)

🔇 Additional comments (6)
src/internal/model_prompt_test.go (6)

17-27: Good test structure with clear setup and cleanup

The test follows best practices with explicit setup and teardown. Creating dedicated directories for each test and cleaning them up afterward ensures test isolation and prevents test pollution.


29-65: Well-organized test plan with clear comments

The test plan comments provide a clear roadmap of what's being tested. This helps maintainers understand the purpose and scope of each test case.


69-85: Good testing of prompt mode switching and state management

The test case effectively verifies that the prompt modal can be opened in different modes, switched between modes, and closed properly. It tests all the key aspects of basic prompt interaction.


105-124: Well-structured test for panel splitting limits

This test correctly verifies both successful panel splitting and the failure case when the maximum panel limit is reached.


126-159: Comprehensive path handling tests for cd command

The test thoroughly verifies all important path handling scenarios including absolute paths, relative paths, and tilde expansion, which aligns with the new ResolveAbsPath utility function mentioned in the summary.


223-232: Good verification of modal closing with multiple cancel keys

This test properly verifies that all configured cancel keys correctly close the prompt modal, which is important for user experience.

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: 1

♻️ Duplicate comments (1)
src/internal/model_prompt_test.go (1)

188-200: Address Windows platform-specific shell substitution issues

The comments acknowledge that shell substitution is flaky in Windows, but the test still relies on it. This could lead to inconsistent test results across platforms.

As mentioned in past review comments, consider addressing these platform-specific issues by mocking the path resolution function or isolating these tests from platform-specific shell behavior.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9fbf622 and ec16805.

📒 Files selected for processing (11)
  • src/internal/config_function.go (1 hunks)
  • src/internal/default_config.go (2 hunks)
  • src/internal/function.go (1 hunks)
  • src/internal/model_file_operations_test.go (1 hunks)
  • src/internal/model_prompt_test.go (3 hunks)
  • src/internal/model_test.go (1 hunks)
  • src/internal/test_utils.go (1 hunks)
  • src/internal/ui/prompt/ReadMe.md (1 hunks)
  • src/internal/ui/prompt/consts.go (1 hunks)
  • src/internal/ui/prompt/model.go (5 hunks)
  • src/internal/utils/file_utils.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/internal/ui/prompt/ReadMe.md
🚧 Files skipped from review as they are similar to previous changes (9)
  • src/internal/config_function.go
  • src/internal/ui/prompt/consts.go
  • src/internal/default_config.go
  • src/internal/utils/file_utils.go
  • src/internal/function.go
  • src/internal/model_file_operations_test.go
  • src/internal/test_utils.go
  • src/internal/model_test.go
  • src/internal/ui/prompt/model.go
🔇 Additional comments (6)
src/internal/model_prompt_test.go (6)

17-27: Clear, well-structured test setup with proper cleanup

The test setup is well-organized with dedicated functions for directory and file creation, and a proper cleanup function to remove test resources after execution. This approach ensures tests start with a clean state and don't leave artifacts behind.


66-86: Good implementation of mode switching test cases

The basic prompt opening test covers all important aspects: initial state verification, mode switching, and proper closing. The assertions clearly validate the expected state transitions between shell and prompt modes.


105-124: Comprehensive panel splitting test with proper limit handling

The test properly validates both successful panel creation and the failure condition when maximum panel count is reached. Good use of loop to test the edge case.


126-159: Well-structured directory navigation test covering multiple path formats

This test thoroughly covers all path formats (absolute, relative, filename-only, and home directory) along with proper error handling for invalid paths. The assertions clearly validate both the success/failure flags and the actual location changes.


212-222: Good handling of maximum panel limit in open command tests

The test properly validates both successful panel opening and the failure condition when the maximum panel count is reached. The approach of filling panels until the limit and then testing the failure case is effective.


224-232: Comprehensive modal closing test with key iteration

The test effectively validates that all configured cancel keys properly close the prompt modal. The loop over CancelTyping keys ensures that all configured hotkeys work as expected.

@lazysegtree
Copy link
Collaborator Author

image

Current layout.

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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec16805 and da01d2e.

📒 Files selected for processing (3)
  • src/internal/common/load_config.go (2 hunks)
  • src/internal/model_test.go (1 hunks)
  • src/internal/ui/prompt/model_test.go (9 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/internal/ui/prompt/model_test.go
  • src/internal/model_test.go

lazysegtree and others added 2 commits May 15, 2025 13:50
Chooser file option, --lastdir-file option, and improvements in quit, and bug fixes.
@@ -87,9 +87,17 @@ func (m *model) enterPanel() {

if targetInfo.IsDir() {
m.fileModel.filePanels[m.filePanelFocusIndex].location = targetPath
return
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Bug fix for #811

Tested with a symlink file

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: 2

♻️ Duplicate comments (1)
src/internal/model_test.go (1)

68-94: Duplicate test-fixture setup – see earlier review

The directory/file setup here is identical to code in other test files.
Previous reviews suggested extracting a helper (e.g., setupTestEnvironment).
Refactoring would cut ~15 duplicated lines per test.

🧹 Nitpick comments (9)
src/internal/ui/prompt/model.go (1)

204-213: Consider adding clearer documentation for width calculation

The width calculation logic for the text input contains complex offsets that might be difficult to understand for future developers. Consider adding more detailed comments explaining each offset value in the calculation.

 func (m *Model) SetWidth(width int) {
 	if width < PromptMinWidth {
 		slog.Warn("Prompt initialized with too less width", "width", width)
 		width = PromptMinWidth
 	}
 	m.width = width
-	// Excluding borders(2), SpacePadding(1), Prompt(2), and one extra character that is appended
-	// by textInput.View()
+	// Calculate the width available for text input by subtracting:
+	// - Left and right borders (2 characters)
+	// - Left space padding (1 character)
+	// - Prompt prefix width (2 characters)
+	// - Extra character appended by textInput.View() (1 character)
 	m.textInput.Width = width - 2 - 1 - 2 - 1
 }
testsuite/core/fs_manager.py (1)

22-31: Method implementation looks good, minor suggestion for consistency

The read_file method provides a well-implemented utility with proper exception handling and appropriate error logging.

For consistency with other methods like check_exists, consider using self.abspath(relative_path) instead of self.temp_dir / relative_path:

-            with open(self.temp_dir / relative_path, 'r', encoding="utf-8") as f:
+            with open(self.abspath(relative_path), 'r', encoding="utf-8") as f:
testsuite/core/tmux_manager.py (1)

27-37: Implementation correctly supports command-line arguments

The updated method properly handles the additional args parameter and correctly constructs the command string for the tmux session.

Two small suggestions for improvement:

  1. Remove the extra blank line at line 34
  2. Consider adding a security comment about potential command injection risks from string concatenation, or use a safer approach for complex arguments
        self.logger.debug("windows_command : %s", spf_command)
-        
testsuite/tests/chooser_file_test.py (3)

8-13: Use a unique, temporary test root to avoid cross-test collisions

TESTROOT is a constant folder under the repo.
If tests run in parallel or the same suite is executed twice without cleanup, files created here may clash with previous executions or leak into the working tree.

-TESTROOT = Path("chooser_file_ops")
+TESTROOT = Path(os.getenv("PYTEST_TMPDIR", "/tmp")) / "chooser_file_ops"

(Or use tempfile.TemporaryDirectory in __init__.)


37-40: Replace fixed sleep with polling to cut test time & flakiness

A hard-coded time.sleep(3) may be too short on CI or unnecessarily long on a fast laptop.
Poll for the chooser file to appear (or the process to exit) with a timeout instead.


42-55: Clean up the chooser file after validation

The chooser file is left on disk which can affect later tests.
Add a t.Cleanup (or explicit remove) after assertions succeed.

if self.env.fs_mgr.check_exists(CHOOSER_FILE):
    self.env.fs_mgr.remove(CHOOSER_FILE)
src/cmd/main.go (2)

44-49: Minor: expose lastdir-file via a short alias

Most flags already have a two-letter alias (-cf, -hf, …). Consider adding one here for consistency, e.g. -lf.


56-63: Flag description could clarify relation to --print-last-dir

Both flags deal with last dir but live in different command scopes; users might confuse them.
A short note such as “(sub-command only)” or cross-referencing the root flag would help.

src/internal/model_test.go (1)

177-178: Typo: “direcotory” → “directory”

Tiny spelling error in the test case name.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 639fa69 and 1b565ba.

📒 Files selected for processing (18)
  • src/cmd/main.go (2 hunks)
  • src/config/fixed_variable.go (3 hunks)
  • src/internal/default_config.go (2 hunks)
  • src/internal/handle_file_operations.go (4 hunks)
  • src/internal/handle_panel_movement.go (1 hunks)
  • src/internal/key_function.go (3 hunks)
  • src/internal/model.go (14 hunks)
  • src/internal/model_file_operations_test.go (1 hunks)
  • src/internal/model_test.go (1 hunks)
  • src/internal/test_utils.go (1 hunks)
  • src/internal/type.go (2 hunks)
  • src/internal/ui/prompt/model.go (5 hunks)
  • testsuite/core/fs_manager.py (1 hunks)
  • testsuite/core/pyautogui_manager.py (1 hunks)
  • testsuite/core/runner.py (2 hunks)
  • testsuite/core/spf_manager.py (1 hunks)
  • testsuite/core/tmux_manager.py (1 hunks)
  • testsuite/tests/chooser_file_test.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • testsuite/core/runner.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/internal/default_config.go
  • src/internal/type.go
  • src/internal/model_file_operations_test.go
  • src/internal/test_utils.go
  • src/internal/model.go
🧰 Additional context used
🧬 Code Graph Analysis (7)
src/internal/handle_file_operations.go (1)
src/config/fixed_variable.go (1)
  • ChooserFile (62-62)
testsuite/core/spf_manager.py (4)
testsuite/tests/chooser_file_test.py (1)
  • start_spf (31-34)
testsuite/core/pyautogui_manager.py (1)
  • start_spf (18-29)
testsuite/core/tmux_manager.py (1)
  • start_spf (27-42)
testsuite/core/base_test.py (1)
  • start_spf (78-80)
src/internal/handle_panel_movement.go (1)
src/config/fixed_variable.go (1)
  • ChooserFile (62-62)
testsuite/core/tmux_manager.py (3)
testsuite/tests/chooser_file_test.py (1)
  • start_spf (31-34)
testsuite/core/pyautogui_manager.py (1)
  • start_spf (18-29)
testsuite/core/spf_manager.py (1)
  • start_spf (12-13)
testsuite/core/pyautogui_manager.py (3)
testsuite/tests/chooser_file_test.py (1)
  • start_spf (31-34)
testsuite/core/spf_manager.py (1)
  • start_spf (12-13)
testsuite/core/tmux_manager.py (1)
  • start_spf (27-42)
src/cmd/main.go (1)
src/config/fixed_variable.go (6)
  • LastDirFile (46-46)
  • ConfigFile (57-57)
  • HotkeysFile (58-58)
  • LogFile (45-45)
  • SuperFileMainDir (28-28)
  • SuperFileDataDir (30-30)
src/internal/ui/prompt/model.go (5)
src/internal/ui/prompt/type.go (1)
  • Model (6-30)
src/internal/common/default_config.go (2)
  • Hotkeys (12-12)
  • Config (11-11)
src/internal/ui/spf_renderers.go (1)
  • PromptRenderer (55-73)
src/internal/ui/prompt/consts.go (2)
  • PromptMinWidth (34-34)
  • PromptMinHeight (35-35)
src/config/icon/icon.go (1)
  • Warn (35-35)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (24)
src/internal/ui/prompt/model.go (8)

16-19: Good API extension for dynamic sizing

The prompt model now properly accepts and validates dimensions, which improves layout flexibility and component reusability. This is a good architecture improvement that makes the prompt component more self-contained regarding its dimensions.

Also applies to: 21-36


95-97: Good encapsulation of shell mode changes

Replacing direct state manipulation with calls to the setShellMode method improves encapsulation and ensures that all side effects (like updating the prompt prefix) happen consistently.


124-127: Improved render method signature

The render method now uses the model's stored dimensions rather than accepting parameters, which is more consistent with the component's self-contained architecture.


130-146: Better UI rendering logic

The addition of the hintSectionAdded flag prevents duplicate rendering of hint sections, resulting in a cleaner user interface. This kind of careful attention to rendering details improves the overall user experience.


173-176: Well-implemented method for shell mode encapsulation

The setShellMode method properly centralizes all logic related to changing shell mode, including updating the UI prompt. This improves code maintainability and reduces the chance of bugs from inconsistent state updates.


188-194: Useful accessor methods

These getter methods provide a clean API for accessing the model's internal state, following good encapsulation practices while enabling necessary querying of model state.


196-202: Proper dimension accessor methods

These methods complete the dimension management API by providing access to the stored dimensions. This is consistent with proper encapsulation principles.


215-221: Good validation in height setter

The height setter properly validates against minimum values and logs warnings when necessary. This helps maintain a usable UI even when the component is initialized with insufficient dimensions.

testsuite/core/spf_manager.py (1)

12-12: Interface enhancement LGTM

The addition of the optional args parameter to the abstract method allows SPF manager implementations to support additional command-line arguments. This is a clean API extension that maintains backward compatibility.

testsuite/core/pyautogui_manager.py (1)

18-24: Good implementation of argument handling

The method correctly builds an argument list with the provided parameters and safely passes it to subprocess.Popen. This approach is properly aligned with the abstract method signature and avoids shell injection risks by using a list rather than string concatenation.

src/config/fixed_variable.go (3)

60-62: Well-documented global variable for the chooser file feature

The new ChooserFile variable is nicely documented with clear comments explaining its purpose and behavior.


77-79: Clean setter implementation that follows the module's convention

This setter function follows the same pattern as the other setters in this file, maintaining consistency with the codebase.


102-103: Good approach to CLI argument handling for the chooser file

The comment correctly explains why there's no existence check for this file (unlike the config and hotkey files) since you're writing to it rather than reading from it.

src/internal/handle_panel_movement.go (2)

90-91: Preserved early exit behavior for symlink directories

The explicit return statement preserves the existing behavior when encountering a symlink pointing to a directory.


94-101: Well-implemented chooser file functionality with proper error handling

This implementation properly integrates the chooser file feature with appropriate error handling. If writing to the chooser file fails, the code logs the error and falls back to the standard behavior of opening the file with the default application.

src/internal/handle_file_operations.go (3)

557-565: Well-structured utility method for the chooser file feature

This method encapsulates the write-and-quit functionality in a clean, reusable way. It handles errors appropriately and updates the model state correctly.


576-583: Good integration of chooser file feature with file opening

The chooser file functionality is properly integrated into the file opening workflow with appropriate error handling and fallback behavior.


615-622: Consistent implementation of chooser file feature for directory opening

This implementation mirrors the approach used in openFileWithEditor, maintaining consistency in the codebase while properly integrating the chooser file feature for directories.

src/internal/key_function.go (4)

131-132: Simplified return pattern for better flow control

This change directly returns the result of openFileWithEditor, eliminating the need for an intermediate variable and simplifying the control flow.


134-135: Consistent implementation of the simplified return pattern

The same pattern is applied here for openDirectoryWithEditor, maintaining consistency.


140-141: Simplified function with explicit nil return

This explicit nil return completes the refactoring of the function to directly return commands when appropriate.


261-262: Updated to use model state machine instead of direct flag manipulation

This change replaces direct manipulation of a boolean flag with setting the model's quit state, which is more maintainable and aligns with the state machine approach used elsewhere in the codebase.

testsuite/tests/chooser_file_test.py (1)

31-35:

❌ Incorrect review comment

Return the start_spf error to the framework

start_spf ignores the return value (error / exit-code) of start_spf(...).
Bubble-up the error so a failed spawn fails the test instead of hanging.

-        self.env.spf_mgr.start_spf(...)
-        assert self.env.spf_mgr.is_spf_running(), "Superfile is not running"
+        ok = self.env.spf_mgr.start_spf(
+            self.env.fs_mgr.abspath(self.start_dir),
+            ["--chooser-file", str(self.env.fs_mgr.abspath(CHOOSER_FILE))],
+        )
+        assert ok and self.env.spf_mgr.is_spf_running(), "Superfile failed to start"

Here’s a quick lookup of the start_spf implementation to see what it actually returns:


🏁 Script executed:

#!/bin/bash
set -e
# Locate and show the definition (plus context) of start_spf
rg -n "def start_spf" -n . -A 20

Length of output: 7971


Ignore return-value suggestion for start_spf

The various start_spf implementations in tmux_manager.py, pyautogui_manager.py and the abstract spf_manager.py all return None—so assigning their result to a boolean (ok = …) would always be None (falsey) and immediately break the assertion. In practice, failures in start_spf (e.g. session creation errors) already raise exceptions, and the existing assert self.env.spf_mgr.is_spf_running() correctly verifies startup. The proposed diff would not work without first changing the manager API to return a status.

Likely an incorrect or invalid review comment.

src/cmd/main.go (1)

91-101:

✅ Verification successful

Ensure new CLI flags are wired into config propagation

variable.UpdateVarFromCliArgs(c) must read the new --hotkey-file alias and --chooser-file.
Run the following grep to verify the implementation:


🏁 Script executed:

#!/bin/bash
# Confirm UpdateVarFromCliArgs handles the new flags
rg --line-number --context 2 "chooser-file" | head

Length of output: 755


🏁 Script executed:

#!/bin/bash
set -euxo pipefail

# Locate the UpdateVarFromCliArgs function
rg --context 3 "func UpdateVarFromCliArgs" -n .

# Inspect within that function for handling of the new flags
rg --context 5 "chooser-file" -n .
rg --context 5 "hotkey-file" -n .

Length of output: 6406


New CLI flags are already wired into config propagation

UpdateVarFromCliArgs in src/config/fixed_variable.go correctly reads and applies both flags:

  • Lines 93–98: reads hotkey-file and, if non-empty, validates and assigns to HotkeysFile
  • Line 103: calls SetChooserFile(c.String("chooser-file"))

No further changes required.

@lazysegtree
Copy link
Collaborator Author

Before

➜  ~/Workspace/kuknitin/superfile git:(main) [1:56:14] go test -cover -count=1 ./...
	github.com/yorukot/superfile		coverage: 0.0% of statements
	github.com/yorukot/superfile/src/cmd		coverage: 0.0% of statements
	github.com/yorukot/superfile/src/config		coverage: 0.0% of statements
	github.com/yorukot/superfile/src/config/icon		coverage: 0.0% of statements
ok  	github.com/yorukot/superfile/src/internal	3.905s	coverage: 7.8% of statements
ok  	github.com/yorukot/superfile/src/internal/common	4.289s	coverage: 14.9% of statements
	github.com/yorukot/superfile/src/internal/ui		coverage: 0.0% of statements
ok  	github.com/yorukot/superfile/src/internal/ui/prompt	6.026s	coverage: 76.0% of statements
ok  	github.com/yorukot/superfile/src/internal/ui/rendering	3.862s	coverage: 98.4% of statements
ok  	github.com/yorukot/superfile/src/internal/ui/sidebar	4.104s	coverage: 29.3% of statements
ok  	github.com/yorukot/superfile/src/internal/utils	4.396s	coverage: 10.1% of statements
	github.com/yorukot/superfile/src/pkg/file_preview		coverage: 0.0% of statements
	github.com/yorukot/superfile/src/pkg/string_function		coverage: 0.0% of statements
➜  ~/Workspace/kuknitin/superfile git:(main) [1:56:23]

After

➜  ~/Workspace/kuknitin/superfile git:(chooser_file_options) ✗ [1:50:13] go test -cover -count=1 ./...
	github.com/yorukot/superfile		coverage: 0.0% of statements
	github.com/yorukot/superfile/src/cmd		coverage: 0.0% of statements
	github.com/yorukot/superfile/src/config		coverage: 0.0% of statements
	github.com/yorukot/superfile/src/config/icon		coverage: 0.0% of statements
ok  	github.com/yorukot/superfile/src/internal	1.055s	coverage: 21.5% of statements
ok  	github.com/yorukot/superfile/src/internal/common	1.091s	coverage: 14.7% of statements
	github.com/yorukot/superfile/src/internal/ui		coverage: 0.0% of statements
ok  	github.com/yorukot/superfile/src/internal/ui/prompt	3.105s	coverage: 91.3% of statements
ok  	github.com/yorukot/superfile/src/internal/ui/rendering	0.942s	coverage: 98.4% of statements
ok  	github.com/yorukot/superfile/src/internal/ui/sidebar	1.469s	coverage: 29.3% of statements
ok  	github.com/yorukot/superfile/src/internal/utils	0.983s	coverage: 16.7% of statements
	github.com/yorukot/superfile/src/pkg/file_preview		coverage: 0.0% of statements
	github.com/yorukot/superfile/src/pkg/string_function		coverage: 0.0% of statements
➜  ~/Workspace/kuknitin/superfile git:(chooser_file_options)

@lazysegtree lazysegtree merged commit 0c15880 into main May 15, 2025
8 checks passed
@lazysegtree lazysegtree deleted the lazysegtree_dev branch May 15, 2025 10:22
tmeijn pushed a commit to tmeijn/dotfiles that referenced this pull request May 23, 2025
This MR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [yorukot/superfile](https://github.com/yorukot/superfile) | minor | `v1.2.1` -> `v1.3.0` |

MR created with the help of [el-capitano/tools/renovate-bot](https://gitlab.com/el-capitano/tools/renovate-bot).

**Proposed changes to behavior should be submitted there as MRs.**

---

### Release Notes

<details>
<summary>yorukot/superfile (yorukot/superfile)</summary>

### [`v1.3.0`](https://github.com/yorukot/superfile/releases/tag/v1.3.0)

[Compare Source](yorukot/superfile@v1.2.1...v1.3.0)

We are excited to release v1.3.0 for superfile, with new features, key bug fixes, and lots of polish under the hood.

#### Install:

[**Click me to know how to install**](https://github.com/yorukot/superfile?tab=readme-ov-file#installation)

#### Highlights

-   We have revamped the command prompt and added built-in commands for SuperFile-specific actions. Check out yorukot/superfile#745

-   Multi-panel startup support. You can now open multiple panels right from startup, making your workflow even more efficient.

-   Added new configurations :  --chooser-file option, show_panel_footer_info config flag and many command prompt specific flags.

#### Improvements & Fixes

-   The sidebar code was refactored and separated for better maintainability and various linter fixes and CI/CD improvements were made to keep the codebase clean and robust.

-   A new Rendering package is implemented, centralising border, content, and section rendering logic into reusable renderer components, fixing many layout bugs.

-   Model behaviour, file operations and rendering-related unit tests were added to improve test coverage.

#### Detailed Change Summary

<details><summary>Details</summary>
<p>

#### New Features

-   Added a Command-Prompt for SuperFile specific actions [`#752`](yorukot/superfile#752) by [@&#8203;Rocco-Gossmann](https://github.com/Rocco-Gossmann), [@&#8203;yorukot](https://github.com/yorukot)  and [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Allow specifying multiple panels at startup [`#759`](yorukot/superfile#759) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Initial draft of rendering package [`#775`](yorukot/superfile#775) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Render unit tests for prompt model [`#809`](yorukot/superfile#809) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Chooser file option, --lastdir-file option, and improvements in quit, and bug fixes [`#812`](yorukot/superfile#812) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Prompt feature leftover items [`#804`](yorukot/superfile#804) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   SPF Prompt tutorial and fixes [`#814`](yorukot/superfile#814) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Write prompt tutorial, rename prompt mode to spf mode, add develop branch in GitHub workflow, show_panel_footer_info flag [`#815`](yorukot/superfile#815) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Theme: Add gruvbox-dark-hard [`#828`](yorukot/superfile#828) by [@&#8203;Frost-Phoenix](https://github.com/Frost-Phoenix)

#### Updates & Improvements

-   Sidebar separation [`#767`](yorukot/superfile#767) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Sidebar code separation [`#770`](yorukot/superfile#770) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Rendering package and rendering bug fixes [`#781`](yorukot/superfile#781) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Refactor CheckForUpdates [`#797`](yorukot/superfile#797) by [@&#8203;JassonCordones](https://github.com/JassonCordones)
-   Rename metadata strings [`#731`](yorukot/superfile#731) by [@&#8203;booth-w](https://github.com/booth-w)

#### Bug Fixes

-   Fix crash with opening file with editor on an empty panel [`#730`](yorukot/superfile#730) by [@&#8203;booth-w](https://github.com/booth-w)
-   Fix: Add some of the remaining linter and fix errors [`#756`](yorukot/superfile#756) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Golangci lint fixes [`#757`](yorukot/superfile#757) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Fix: Remove redundant function containsKey [`#765`](yorukot/superfile#765) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Fix: Correctly resolve path in open and cd prompt actions [`#802`](yorukot/superfile#802) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Prompt dynamic dimensions and unit tests fix [`#805`](yorukot/superfile#805) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Fix: Convert unicode space to normal space, use rendered in file preview to fix layout bugs, Release 1.3.0 [`#825`](yorukot/superfile#825) by [@&#8203;lazysegtree](https://github.com/lazysegtree)

#### Optimization & Code Quality

-   Adding linter to CI/CD and fix some lint issues [`#739`](yorukot/superfile#739) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Linter fixes, new feature of allowing multiple directories at startup, other code improvements [`#764`](yorukot/superfile#764) by [@&#8203;lazysegtree](https://github.com/lazysegtree)
-   Model unit tests [`#803`](yorukot/superfile#803) by [@&#8203;lazysegtree](https://github.com/lazysegtree)

#### Dependency Updates

-   fix(deps): update dependency astro to v5.7.7 [`#726`](yorukot/superfile#726) by [@&#8203;renovate](https://github.com/renovate)
-   fix(deps): update module github.com/shirou/gopsutil/v4 to v4.25.3 [`#749`](yorukot/superfile#749) by [@&#8203;renovate](https://github.com/renovate)
-   fix(deps): update module github.com/pelletier/go-toml/v2 to v2.2.4 [`#760`](yorukot/superfile#760) by [@&#8203;renovate](https://github.com/renovate)
-   fix(deps): update module github.com/alecthomas/chroma/v2 to v2.16.0 [`#751`](yorukot/superfile#751) by [@&#8203;renovate](https://github.com/renovate)
-   fix(deps): update dependency sharp to ^0.34.0 [`#755`](yorukot/superfile#755) by [@&#8203;renovate](https://github.com/renovate)
-   fix(deps): update dependency [@&#8203;astrojs/starlight](https://github.com/astrojs/starlight) to ^0.34.0 [`#761`](yorukot/superfile#761) by [@&#8203;renovate](https://github.com/renovate)

</p>
</details> 

#### New Contributors
* @&#8203;Rocco-Gossmann made their first contribution in yorukot/superfile#736
* @&#8203;Frost-Phoenix made their first contribution in yorukot/superfile#828

**Full Changelog**: yorukot/superfile@v1.2.1...v1.3.0

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever MR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this MR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this MR, check this box

---

This MR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC4yMi4wIiwidXBkYXRlZEluVmVyIjoiNDAuMjMuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiUmVub3ZhdGUgQm90Il19-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug fixes high priority Issue/PR/Feature/bug that is considered high priority. new feature refactoring test related PR / Issue related to testcases or testing in general.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants