Skip to content

Linter fixes, new feature of allowing multiple directories at startup, other code improvements #764

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
Apr 10, 2025

Conversation

lazysegtree
Copy link
Collaborator

@lazysegtree lazysegtree commented Apr 8, 2025

Individual PRs

Related issues

Summary by CodeRabbit

Summary by CodeRabbit

  • Refactor

    • Enhanced error handling and logging across various functions for improved clarity and consistency.
    • Streamlined command-line input handling and configuration management to support multiple directories.
    • Updated control flow in several methods to utilize switch statements, enhancing readability.
    • Improved naming conventions for variables and functions to maintain consistency throughout the codebase.
    • Simplified return types and variable initializations in multiple functions for better clarity.
  • Bug Fixes

    • Resolved issues with incorrect loop structures that could lead to runtime errors.
    • Fixed inconsistencies in OS-specific operations, improving stability during file handling and user interactions.

These internal improvements contribute to a more reliable and responsive application experience during everyday file operations.

Copy link

coderabbitai bot commented Apr 8, 2025

Walkthrough

This update streamlines the GolangCI-Lint configuration by enabling linters and explicitly adding exclusions for specific files. Extensive refactoring has been applied across the codebase, including renaming functions and struct fields for consistency, replacing legacy logging with new error utility functions, updating error wrapping with %w, and refactoring loop and control structures (e.g., switching from if-else to switch-case). Changes affect configuration files, core command logic, internal utilities, UI prompt handling, and test files, all aimed at improving clarity and maintainability without altering core functionality.

Changes

File(s) Change Summary
.golangci.yaml Enabled linters by removing future-enable comments; added explicit exclusions for files with global variables.
src/cmd/main.go Refactored error handling by replacing log.Fatalf with utils.PrintfAndExit/PrintlnAndExit; renamed functions (e.g. initJsonFileinitJSONFile, LoadInitial_PrerenderedVariablesLoadInitialPrerenderedVariables).
src/config/* (e.g. fixed_variable.go, icon/icon.go, icon/function.go) Simplified constant declarations using type inference; introduced new dynamic variables and functions; updated types (e.g. IconStyleStyle).
src/internal/common/* (e.g. load_config.go, bool_file_store.go, consts.go, file_utils.go, log_utils.go, shell_utils.go) Enhanced error messages using %w; replaced legacy error functions with new utility functions; updated loop constructs and constant references; removed deprecated imports.
src/internal/file_operations*.go, src/internal/function.go Standardized renaming (e.g. messageIdmessageID); improved error formatting and control flow; updated return types and renamed struct fields.
src/internal/model*.go, src/internal/sidebar*.go, src/internal/key_function.go, src/internal/handle_* Refactored control flow using switch-case; renamed error variables for consistency; updated function signatures (e.g. returning tea.Model); removed unnecessary blank lines.
src/internal/ui/prompt/* & tests Reworked control flow in key input handling and prompt updates; added linter directives in error handling; cleaned up formatting.
src/pkg/file_preview/image_preview.go, src/pkg/string_function/overplace.go Modified loop constructs (from traditional for-loops to range-based loops) and function signatures; simplified error wrapping and return statements.

Sequence Diagram(s)

sequenceDiagram
    participant F as Function
    participant U as Utils
    participant OS as Operating System
    F->>U: Detects error condition
    U->>OS: Logs error (using PrintfAndExit/PrintlnAndExit)
    OS-->>F: Terminates process with exit status 1
Loading

Possibly related PRs

  • yorukot/superfile#757 – Aligns with the current changes by modifying the .golangci.yaml configuration to enable linters and add exclusions.
  • yorukot/superfile#756 – Involves similar configuration updates with differences in linter comments and exclusion details.

Suggested reviewers

  • yorukot

Poem

I'm a happy rabbit, hopping through code,
Refactoring paths where errors once strode.
Linters enabled, variables renamed – hooray! 🐇
With clear functions and clean loops leading the way,
In fields of Go, I celebrate this joyful day!
Hop on, dear devs, let’s code and play!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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: 3

🧹 Nitpick comments (3)
src/internal/handle_file_operations.go (1)

456-463: Simplify conditional logic with early returns.

The current error handling approach with nested if-else could be further improved by using early returns to reduce nesting.

-			// Todo : These error cases are hard to test. We have to somehow make the paste operations fail,
-			// which is time consuming and manual. We should test these with automated testcases
-			err = pasteDir(filePath, filepath.Join(panel.location, filepath.Base(filePath)), id, m)
-			if err != nil {
-				errMessage = "paste item error"
-			} else if m.copyItems.cut {
-				os.RemoveAll(filePath)
-			}
+			// Todo : These error cases are hard to test. We have to somehow make the paste operations fail,
+			// which is time consuming and manual. We should test these with automated testcases
+			err = pasteDir(filePath, filepath.Join(panel.location, filepath.Base(filePath)), id, m)
+			if err != nil {
+				errMessage = "paste item error"
+				break
+			}
+			
+			if m.copyItems.cut {
+				os.RemoveAll(filePath)
+			}
.golangci.yaml (1)

421-422: Fix trailing whitespace.

There are trailing whitespace characters at the end of lines 421-422 that should be removed to maintain clean YAML formatting.

-      - gochecknoglobals    
-          
+      - gochecknoglobals
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 421-421: trailing spaces

(trailing-spaces)


[error] 422-422: trailing spaces

(trailing-spaces)

src/internal/model.go (1)

25-33: Improved documentation for global variables.

Added comments clarifying that these variables represent model state and should be moved to the model struct. This highlights technical debt that should be addressed in the future.

Consider refactoring these global variables into the model struct in a future PR to improve encapsulation and testability of the code.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2854a6b and 9653d8a.

📒 Files selected for processing (46)
  • .golangci.yaml (5 hunks)
  • src/cmd/main.go (9 hunks)
  • src/config/fixed_variable.go (1 hunks)
  • src/config/icon/function.go (1 hunks)
  • src/config/icon/icon.go (2 hunks)
  • src/internal/common/load_config.go (3 hunks)
  • src/internal/common/predefined_variable.go (1 hunks)
  • src/internal/common/style.go (0 hunks)
  • src/internal/common/style_function.go (1 hunks)
  • src/internal/common/utils/bool_file_store.go (1 hunks)
  • src/internal/common/utils/bool_file_store_test.go (4 hunks)
  • src/internal/common/utils/consts.go (1 hunks)
  • src/internal/common/utils/file_utils.go (4 hunks)
  • src/internal/common/utils/log_utils.go (1 hunks)
  • src/internal/common/utils/shell_utils.go (2 hunks)
  • src/internal/config_function.go (2 hunks)
  • src/internal/file_operations.go (10 hunks)
  • src/internal/file_operations_compress.go (1 hunks)
  • src/internal/file_operations_extract.go (1 hunks)
  • src/internal/function.go (18 hunks)
  • src/internal/get_data.go (2 hunks)
  • src/internal/handle_file_operations.go (17 hunks)
  • src/internal/handle_modal.go (0 hunks)
  • src/internal/handle_panel_movement.go (2 hunks)
  • src/internal/handle_panel_navigation.go (0 hunks)
  • src/internal/handle_panel_up_down_test.go (1 hunks)
  • src/internal/internal_consts.go (1 hunks)
  • src/internal/key_function.go (2 hunks)
  • src/internal/model.go (6 hunks)
  • src/internal/model_prompt_test.go (0 hunks)
  • src/internal/model_render.go (10 hunks)
  • src/internal/sidebar.go (0 hunks)
  • src/internal/sidebar_test.go (5 hunks)
  • src/internal/string_function.go (6 hunks)
  • src/internal/string_function_test.go (0 hunks)
  • src/internal/type.go (1 hunks)
  • src/internal/type_utils.go (1 hunks)
  • src/internal/ui/prompt/model.go (2 hunks)
  • src/internal/ui/prompt/model_test.go (0 hunks)
  • src/internal/ui/prompt/tokenize.go (3 hunks)
  • src/internal/ui/prompt/tokenize_test.go (1 hunks)
  • src/internal/ui/prompt/utils.go (0 hunks)
  • src/internal/ui/prompt/utils_test.go (1 hunks)
  • src/internal/wheel_function.go (1 hunks)
  • src/pkg/file_preview/image_preview.go (3 hunks)
  • src/pkg/string_function/overplace.go (1 hunks)
💤 Files with no reviewable changes (8)
  • src/internal/model_prompt_test.go
  • src/internal/common/style.go
  • src/internal/sidebar.go
  • src/internal/ui/prompt/utils.go
  • src/internal/string_function_test.go
  • src/internal/handle_modal.go
  • src/internal/handle_panel_navigation.go
  • src/internal/ui/prompt/model_test.go
🧰 Additional context used
🧠 Learnings (1)
src/internal/handle_panel_up_down_test.go (1)
Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/handle_panel_up_down_test.go:13-13
Timestamp: 2025-04-08T12:59:09.350Z
Learning: Go 1.22+ supports the integer range loop feature that allows iterating over integers directly with the range keyword. The syntax `for i := range n` iterates from 0 to n-1, which is equivalent to the traditional `for i := 0; i < n; i++` loop. This feature was implemented via GitHub issue #61405.
🧬 Code Definitions (13)
src/config/icon/function.go (1)
src/config/icon/icon.go (2)
  • Folders (397-417)
  • Style (4-7)
src/internal/handle_panel_movement.go (1)
src/internal/common/utils/consts.go (2)
  • OsDarwin (10-10)
  • OsWindows (8-8)
src/internal/common/utils/bool_file_store.go (1)
src/internal/common/utils/consts.go (2)
  • TrueString (4-4)
  • FalseString (5-5)
src/internal/common/utils/shell_utils.go (1)
src/internal/common/utils/consts.go (1)
  • OsWindows (8-8)
src/internal/handle_file_operations.go (1)
src/internal/common/utils/consts.go (2)
  • OsWindows (8-8)
  • OsDarwin (10-10)
src/internal/common/load_config.go (2)
src/internal/common/utils/log_utils.go (2)
  • PrintlnAndExit (12-15)
  • PrintfAndExit (20-23)
src/internal/common/style_function.go (1)
  • LoadHotkeysError (236-238)
src/internal/config_function.go (3)
src/config/fixed_variable.go (4)
  • LogFile (45-45)
  • HomeDir (27-27)
  • ToggleDotFile (41-41)
  • ToggleFooter (42-42)
src/internal/common/utils/log_utils.go (1)
  • PrintfAndExit (20-23)
src/internal/common/utils/bool_file_store.go (1)
  • ReadBoolFile (12-31)
src/internal/file_operations.go (2)
src/internal/common/utils/consts.go (2)
  • OsWindows (8-8)
  • OsDarwin (10-10)
src/config/fixed_variable.go (1)
  • DarwinTrashDirectory (49-49)
src/cmd/main.go (4)
src/internal/common/predefined_variable.go (1)
  • LoadInitialPrerenderedVariables (34-37)
src/config/fixed_variable.go (3)
  • UpdateVarFromCliArgs (73-97)
  • ConfigFile (57-57)
  • HotkeysFile (58-58)
src/internal/common/utils/log_utils.go (2)
  • PrintfAndExit (20-23)
  • PrintlnAndExit (12-15)
src/internal/common/utils/consts.go (1)
  • OsDarwin (10-10)
src/internal/model.go (3)
src/internal/ui/prompt/type.go (1)
  • Model (6-24)
src/internal/common/default_config.go (1)
  • Hotkeys (12-12)
src/config/fixed_variable.go (1)
  • SetLastDir (69-71)
src/internal/common/utils/bool_file_store_test.go (1)
src/internal/common/utils/consts.go (3)
  • TrueString (4-4)
  • FalseString (5-5)
  • OsWindows (8-8)
src/internal/model_render.go (3)
src/internal/common/predefined_variable.go (2)
  • SideBarPinnedDivider (27-27)
  • SideBarDisksDivider (28-28)
src/internal/common/default_config.go (1)
  • Config (11-11)
src/config/icon/icon.go (1)
  • Error (34-34)
src/internal/string_function.go (3)
src/internal/common/style_function.go (1)
  • StringColorRender (210-214)
src/internal/common/style.go (2)
  • FilePanelStyle (17-17)
  • FooterBGColor (78-78)
src/internal/common/default_config.go (1)
  • Config (11-11)
🪛 YAMLlint (1.35.1)
.golangci.yaml

[error] 421-421: trailing spaces

(trailing-spaces)


[error] 422-422: trailing spaces

(trailing-spaces)

🔇 Additional comments (114)
src/internal/common/predefined_variable.go (1)

34-34: Improved function naming convention.

The function name has been updated from LoadInitial_PrerenderedVariables to LoadInitialPrerenderedVariables, which aligns better with Go's naming conventions that favor camelCase over snake_case for function names.

src/internal/type.go (1)

251-251: Correct identifier naming convention.

The field name has been updated from messageId to messageID, following Go's convention of using ID (all caps) instead of Id for abbreviations in identifiers.

src/internal/common/utils/bool_file_store.go (1)

24-27: Improved constant naming references.

The code now references the camelCase constants TrueString and FalseString from the consts.go file instead of the previous snake_case versions. This change aligns with Go's naming conventions and improves consistency across the codebase.

src/internal/file_operations_extract.go (1)

29-29: Consistent identifier naming.

The field name has been updated from messageId to messageID, maintaining consistency with the same change in the type definition and following Go's convention for abbreviations in identifiers.

src/internal/handle_panel_up_down_test.go (1)

13-13: Relying on Go 1.22+ “integer range” feature.

This line uses for i := range count, which is only valid in Go 1.22+ (according to your retrieved learnings). If your project or CI environment isn’t pinned to Go 1.22+ yet, this will fail to compile.

Consider reverting to a traditional for loop for broader compatibility:

-for i := range count {
+for i := 0; i < count; i++ {
src/internal/common/style_function.go (1)

19-19: Likewise depends on Go 1.22+ “integer range” feature.

Similar to the previous file, for i := range height will only work on Go 1.22+ compilers. If you need broader support, revert to a standard for loop.

-for i := range height {
+for i := 0; i < height; i++ {
src/config/icon/function.go (1)

41-44: Switch to Style type looks correct.

Using Folders["folder"] = Style{...} aligns with the new Style struct from icon.go. It maintains consistency with the updated type across the codebase. No further changes are needed.

src/internal/type_utils.go (1)

28-28: Consistent error message formatting.

The error message now begins with lowercase "invalid" instead of uppercase "Invalid", following Go's error message style conventions where error messages typically start with a lowercase letter.

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

112-112: Appropriate linter directive usage with explanation.

Good addition of a comment explaining why errorlint is disabled for this line. The comment clearly explains that type assertion is intentional here since wrapped errors aren't expected in this test context.

src/internal/internal_consts.go (2)

5-6: Clear explanation for the use of var instead of const.

The added comment properly explains why var is used (Go doesn't allow const structs) and includes the appropriate linter directive to suppress the global variable check, along with a justification.


10-11: Consistent linter comment for global variable.

The same correct pattern is applied to diskDividerDir, maintaining consistency across similar variables.

src/internal/handle_panel_movement.go (3)

77-78: Improved variable naming convention.

Variable renamed from snake_case to camelCase (symlink_errsymlinkErr), adhering to Go's standard naming conventions.


82-84: Consistent variable naming convention.

Variable renamed from snake_case to camelCase (lstat_errlstatErr), maintaining consistency with Go's naming conventions.


96-98: Better use of centralized constants.

The OS check now uses constants from the utils package (utils.OsDarwin and utils.OsWindows) instead of direct string literals or variables, promoting consistency and reducing the risk of typos.

src/internal/file_operations_compress.go (1)

36-36: Field renamed to follow Go naming conventions.

The field has been renamed from messageId to messageID to align with Go's convention of capitalizing acronyms in camelCase identifiers.

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

19-19: Added comment explains variable usage and suppresses linter warning.

The added comment clarifies why testEnvValues is declared as a variable instead of a constant (Go doesn't allow constant maps) and includes a linter directive to suppress the warning about global variables.

src/internal/common/utils/consts.go (2)

4-5: Updated constant names to follow Go naming conventions.

Constants have been renamed from TRUE_STRING and FALSE_STRING to TrueString and FalseString to adhere to Go's recommended naming style (PascalCase for exported constants).


6-10: Added OS identifier constants with documentation.

New constants OsWindows and OsDarwin have been introduced with appropriate documentation to centralize OS-specific string identifiers. This is consistent with the linter improvement effort and will help standardize OS checks throughout the codebase.

src/internal/common/utils/shell_utils.go (2)

19-19: Replaced external OS constant with local package constant.

The condition now uses the newly defined OsWindows constant instead of importing it from the variable package, reducing dependencies and centralizing OS-related constants.


44-44: Added linter directive to explain type assertion usage.

The comment with //nolint:errorlint clarifies why type assertion is used instead of errors.As(), appropriately suppressing the linter warning with a clear explanation.

src/pkg/string_function/overplace.go (1)

163-165: Function signature improved for clarity.

The refactoring removes named return parameters in favor of unnamed return types, and explicitly initializes variables using short variable declarations. This is a good change that maintains the same functionality while making the code more idiomatic.

src/internal/wheel_function.go (4)

14-23: Good restructuring using switch statement.

Replacing if-else chains with a switch statement improves readability and maintainability, especially for this type of case-based logic.


26-35: Consistent structure applied here too.

The switch statement structure is consistently applied for both wheel directions, enhancing code readability.


36-38: Added helpful error handling for unexpected messages.

Adding a default case with proper error logging is a good practice that improves robustness.


41-41: Simplified loop construction.

Changing to a for range loop is more idiomatic when only iteration count matters.

src/internal/key_function.go (2)

29-42: Improved control flow with switch statement.

Replacing if-else chains with a switch statement makes the code more readable and easier to maintain, especially for this kind of panel-focused logic.


46-59: Consistent structure applied for list down handling.

The switch statement structure is consistently applied here too, maintaining a uniform coding style.

src/internal/common/utils/log_utils.go (2)

9-15: New utility function for error reporting and exit.

This function provides a cleaner alternative to log.Fatal() by ensuring error messages go to stderr and the process exits with the correct status code.


17-21: Added formatted printing capability.

This companion function provides the same exit behavior with formatted output capability, completing the error reporting utility set.

src/config/icon/icon.go (4)

4-7: Structure rename improves namespace clarity.

The renaming of IconStyle to Style makes the code more concise while maintaining readability, since the package name icon provides appropriate context when referenced as icon.Style.


10-42: Variable declaration simplification is clean and idiomatic.

Removing explicit type declarations from these string constants is a good practice in Go where type inference provides cleaner code without losing type safety.


50-165: Type update to match renamed structure.

The map declaration has been correctly updated to use the new Style type in place of the previous IconStyle, maintaining consistency with the type renaming.


397-417: Type update to match renamed structure.

The Folders map declaration has been correctly updated to use Style type, maintaining consistency with the renamed structure.

src/internal/handle_file_operations.go (11)

14-15: Import update for better organizational structure.

Replacing the variable package import with utils helps maintain better package organization and dependency structure. This is part of the broader refactoring to use utility functions from a centralized location.


59-60: Field naming follows Go conventions.

Changing messageId to messageID follows Go's standard naming convention for acronyms and initialisms, where only the first letter is capitalized in camelCase fields.

Also applies to: 100-101, 144-147, 191-194, 259-262, 310-313, 433-436


114-120: Code structure simplification improves readability.

The conditional flow has been simplified by removing an unnecessary else block, which reduces nesting and makes the code more readable. This is a good practice that aligns with the overall goal of the PR to improve code quality.


167-169: Simplified conditional logic.

Replacing nested if-else with a direct else-if improves readability without changing functionality.


217-223: Code flattening improves readability.

Removing nested if blocks in favor of a flatter structure improves readability and maintainability.


338-344: Consistent code structure improvement.

Similar to the previous changes, this code has been refactored to remove nesting, which aligns with the pattern applied throughout the PR for more readable code.


456-458: Good explanatory comment about testing challenges.

Adding this comment about the difficulty of testing error cases provides valuable context for future developers. It's a good practice to document such challenges and considerations.


572-576: Using constants from utils package improves maintainability.

Replacing string literals with constants from the utils package (utils.OsWindows) makes the code more maintainable and less prone to spelling errors or inconsistencies.


583-584: Clear linter directive with explanation.

The linter directive includes a comment explaining why it's being used, which is good practice for code clarity and maintainability.


598-605: Improved conditional structure with switch statement.

Converting the if-else chain to a switch statement improves readability and is more idiomatic Go for multiple condition handling based on a single variable.


611-612: Consistent linter directive with explanation.

The same linter directive is applied consistently in similar contexts, which is good for code maintainability.

src/internal/common/load_config.go (4)

30-31: Using specialized utility functions improves error handling.

Replacing generic error handling with the specialized PrintlnAndExit function from the utils package improves code organization and provides consistent error reporting across the application.


68-69: Consistent use of utility functions.

Using PrintlnAndExit consistently for error handling creates a standardized approach across the codebase.

Also applies to: 73-74


84-90: Simplified error handling removes unnecessary nesting.

The error handling has been simplified to remove an unnecessary conditional block, making the code more readable and maintainable.


96-97: Using format-specific error utility.

Using PrintfAndExit for formatted error messages is a good practice that provides a consistent approach to error handling while leveraging the appropriate formatting capabilities.

src/pkg/file_preview/image_preview.go (2)

102-103: Improved error wrapping for better context.

Using the %w verb in fmt.Errorf properly wraps the original error, preserving the error chain for better debugging and error handling upstream.


166-169: Function simplification improves readability.

Removing the named return variable and directly returning the formatted string makes the function more concise and easier to understand.

src/internal/common/utils/file_utils.go (6)

17-17: Improved error wrapping using %w format verb.

The use of %w for error wrapping is a good practice as it preserves the original error's context for better error handling downstream.


21-21: Consistent use of lowercase in error messages.

This change follows Go's style guidelines where error messages should start with lowercase letters.


28-28: Function signature simplification.

Simplifying the return type from a named return (hasError bool) to just bool makes the API cleaner.


34-34: Updated error handling approach.

Changing from LogAndExit to PrintfAndExit suggests a standardization of error reporting methods across the codebase.


37-37: Explicit variable initialization.

Adding an explicit initialization for hasError improves code clarity.


69-69: More idiomatic loop iteration.

Using range targetType.NumField() instead of an index-based loop is more idiomatic in Go and improves code readability.

.golangci.yaml (2)

278-278: Good: Enabled previously commented linters.

Enabling additional linters like errorlint, gochecknoglobals, gocritic, intrange, reassign, revive, and stylecheck will improve code quality by catching more potential issues.

Also applies to: 287-287, 293-293, 304-304, 327-327, 330-330, 336-336, 345-346


400-421: Good: Added explicit linter exclusions for specific files.

The added exclusions for files with globals (icon.go, style.go, fixed_variable.go, etc.) provide clear documentation about which files are intentionally exempt from the gochecknoglobals linter checks.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 421-421: trailing spaces

(trailing-spaces)

src/internal/common/utils/bool_file_store_test.go (1)

25-25: Improved constant naming convention.

The changes from uppercase snake case (TRUE_STRING, FALSE_STRING) to Go's standard exported constant naming (TrueString, FalseString) follow Go's style guidelines. Similarly, the transition from variable.OS_WINDOWS to OsWindows improves code consistency.

These constant names now match those defined in the consts.go file, ensuring consistency across the codebase.

Also applies to: 32-32, 131-134, 139-139, 158-158, 166-166, 184-184

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

30-84: Improved code structure with switch statement.

Refactoring the nested if-else structure to a switch-case makes the code more readable and maintainable. The switch statement provides a clearer view of the different cases being handled when a dollar sign is encountered.


45-52: Simplified error handling flow.

The environment variable lookup error handling has been simplified by removing the unnecessary else clause, making the code more straightforward while maintaining the same functionality.


72-78: Cleaner conditional logging.

The handling of non-zero return codes has been improved by eliminating the nested if-else structure, resulting in cleaner and more direct code flow while preserving the debug logging functionality.

src/internal/file_operations.go (4)

12-13: Good package organization.

Clean separation with an empty line after this import makes the code more readable.


25-25: Good error wrapping practice.

Properly wrapping errors with %w verb in fmt.Errorf preserves the original error context and allows error unwrapping downstream. This is a recommended Go practice.

Also applies to: 30-30, 56-56, 70-70, 75-75, 98-98, 103-103, 112-112, 131-131, 137-137, 142-142, 254-254


33-34: Good refactoring of OS checks.

Replacing the OS constants with centralized constants from the utils package (utils.OsWindows and utils.OsDarwin) and changing the if-else structure to a switch statement improves code readability and maintainability.

Also applies to: 150-157


206-207: Consistent naming convention.

Renaming messageId to messageID follows Go's naming conventions for acronyms (ID instead of Id). This makes the codebase more consistent.

src/internal/config_function.go (4)

21-21: Good exception documentation.

Using a nolint comment that explains why named returns are being used here provides clear context for future maintainers.


29-29: Improved error handling.

Replacing utils.LogAndExit with utils.PrintfAndExit maintains consistent error handling patterns across the codebase.


57-67: Simplified directory path handling.

The refactoring improves clarity by:

  1. Directly assigning dir to firstFilePanelDir
  2. Only replacing the first tilde occurrence as a prefix
  3. Adding clear comments about the logic

This makes the code more straightforward and easier to understand.


78-80: Better code organization.

Moving these boolean file reads to the end of the function creates a more logical flow, ensuring the directory logic is fully processed before setting these values.

src/internal/get_data.go (2)

22-27: Performance optimization.

Preallocating the slice capacity based on the total number of directories is a good optimization that reduces memory allocations during append operations.


89-97: Simplified function signature and error handling.

Removing the named return value and returning nil on error makes the function behavior clearer. Declaring the disks variable before populating it ensures consistent initialization.

src/internal/string_function.go (5)

5-5: Added error handling capability.

Adding the errors package import supports the improved error checking with errors.Is.


71-75: Code simplification.

Removing unnecessary else branches in both functions makes the code more concise and readable while maintaining the same functionality.

Also applies to: 93-97


118-127: Documenting technical debt.

Adding a TODO comment about removing duplication is good practice for identifying future refactoring needs. The refactored calculation logic for binary units is cleaner.


186-186: Robust error checking.

Using errors.Is instead of direct error comparison is more robust as it handles wrapped errors correctly, following Go's error handling best practices.


201-201: Modern loop syntax.

Changing to a range-based loop over the length of the string is a minor syntactical improvement for clarity.

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

75-75: Proper linter directive added to explain type assertion.

The addition of the //nolint: errorlint directive with an explanatory comment is a good practice. It explicitly documents why the type assertion is being used instead of errors.As() and suppresses the linter warning appropriately.


89-94: Improved readability with switch statement.

Replacing the if-else structure with a switch statement for handling different input conditions is a good refactoring. The switch with case conditions is more readable and maintainable, especially when there are multiple conditions to check.

src/internal/sidebar_test.go (1)

160-160: Good variable renaming for better Go naming convention compliance.

Renaming variables from snake_case to camelCase (e.g., sidebar_a to sidebarA) follows Go's naming conventions and improves code consistency. This makes the code more idiomatic and easier to read for Go developers.

Also applies to: 165-170, 239-242, 247-251, 252-256, 259-261

src/cmd/main.go (6)

31-31: Function name improved to follow Go conventions.

Renaming LoadInitial_PrerenderedVariables to LoadInitialPrerenderedVariables removes the underscore, which is consistent with Go's naming conventions that prefer camelCase over snake_case.


44-44: Unused parameter properly marked with underscore.

Replacing c *cli.Context with _ *cli.Context explicitly indicates that the parameter is not used in the function body, which improves code clarity and helps prevent accidental usage of an unused variable.


92-92: Consolidated CLI argument handling.

Using variable.UpdateVarFromCliArgs(c) centralizes the logic for updating variables from CLI arguments, making the code more maintainable by encapsulating related functionality in a single function.


105-105: Improved error handling with utility functions.

Replacing direct log calls with utility functions like utils.PrintfAndExit and utils.PrintlnAndExit standardizes error handling across the codebase. This encapsulates the pattern of logging an error and exiting, which makes the code more consistent and maintainable.

Also applies to: 124-124, 138-138, 148-148, 153-153, 157-157, 161-161, 217-217


160-160: Correctly capitalized acronym in function name.

Renaming initJsonFile to initJSONFile follows Go's convention of capitalizing acronyms in identifiers. This improves consistency and adheres to the standard naming guidelines.

Also applies to: 233-233


168-168: Improved maintainability with constant usage.

Using the constant utils.OsDarwin instead of a string literal "darwin" is a good practice. If the value needs to change in the future, it only needs to be updated in one place, reducing the risk of inconsistencies.

src/config/fixed_variable.go (3)

14-23: Simplified variable declarations with type inference.

Removing explicit type declarations for constants and variables allows Go's type inference to determine the types automatically. This results in cleaner code while maintaining type safety, as the types are obvious from the assigned values.

Also applies to: 27-52


55-65: Well-documented variable section for dynamic values.

The addition of a separate section specifically for variables that can be updated dynamically, with a clear comment explaining their purpose, improves code organization and makes the intent clear to other developers.


69-97: Good encapsulation with functions for dynamic variables.

The addition of functions to manage dynamic variables (SetLastDir and UpdateVarFromCliArgs) provides proper encapsulation and controlled access to state variables. The UpdateVarFromCliArgs function also includes robust error handling for file existence checks.

src/internal/model_render.go (10)

6-6: Good addition of the errors package.

Adding the errors package is necessary for using errors.Is() later in the file, which is a more robust way to check error types.


72-77: Improved control flow with switch-case.

Replacing nested if-else conditions with a switch-case statement enhances readability and maintainability, making the code structure clearer.


112-117: Better variable declaration and helpful TODOs.

Extracting variable declarations improves readability, and the added TODOs provide guidance for future improvements. Consider implementing these TODOs in a future PR.


127-128: Improved variable declarations.

Declaring variables before assigning values to them follows better Go coding practices and makes the code more maintainable.

Also applies to: 141-142


287-289: Better variable declarations for clarity.

Properly declared variables symbol and cursor before use, enhancing code readability and maintainability.


315-317: Improved conditional logic.

The condition has been inverted to first check if the process list has items before trying to access elements, which is a safer approach that avoids potential issues when the list is empty.


415-416: Better variable declaration for bottomWidth.

Properly declared the variable before use, following consistent style with other similar changes in the file.


663-667: Improved variable naming and error handling.

Renamed info_err to infoErr for consistency with Go naming conventions (camelCase). This style is more idiomatic in Go codebases.


722-724: Better error type checking.

Using errors.Is() for checking specific error types provides more robust error handling than direct error comparisons, as it works correctly with wrapped errors.


799-800: Minor formatting improvement.

Small readability enhancement without functional impact.

src/internal/function.go (10)

19-20: Good reorganization of imports.

Adding the utils package import supports the OS constant refactoring throughout the file.


40-40: Consistent OS check refactoring.

Replaced direct variable references with utility function calls, improving maintainability by centralizing OS-specific constants.

Also applies to: 57-57, 94-94, 107-107


120-136: Improved error handling and return values.

Now returning nil instead of empty slices when errors occur or no data is available, which provides a clearer indication of the absence of valid results.


153-154: Added case-insensitive sorting.

The lowercase comparison ensures consistent sorting regardless of letter case, which improves user experience.


180-184: Better code comments and simplified variable names.

The added comment clarifies why error checking is not needed here, and the variable names have been shortened for better readability.


195-197: Memory optimization with slice preallocation.

Preallocating the slice capacity based on the known size improves performance by avoiding multiple reallocations during append operations.


241-244: Better code organization and memory efficiency.

The code is now more readable and efficient with preallocation of the slice.


454-455: Improved error wrapping.

Using the %w verb for error wrapping follows Go 1.13+ best practices and preserves the original error for better error handling up the call stack.

Also applies to: 460-461


470-485: Avoided variable shadowing.

Renamed variables to prevent shadowing issues, which can lead to subtle bugs. This change makes the code more robust.


532-585: Refactored icon handling with better formatting.

The getElementIcon function has been reformatted with more consistent indentation and clearer logic flow, making it easier to understand and maintain.

src/internal/model.go (5)

36-40: Better function documentation.

Updated comments clarify the return type and purpose of the InitialModel function, making it more discoverable and easier to use correctly.


122-126: Consistent field naming with camelCase.

Renamed messageId to messageID following Go conventions where abbreviations in camelCase should be capitalized (ID rather than Id).


230-277: Improved control flow with switch-case.

Refactored multiple if-else statements into a more readable switch-case structure with condition expressions. This makes the code more maintainable by clearly separating each case.


284-301: Consistent control flow improvements.

Applied the same switch-case pattern for better readability, making the code structure consistent with the previous refactoring.


588-588: Better encapsulation with setter method.

Using variable.SetLastDir(currentDir) instead of direct assignment improves encapsulation by allowing the package to control how the variable is updated.

Comment on lines +60 to 75
for i := range val.NumField() {
field := val.Type().Field(i)
value := val.Field(i)

// Although this is redundant as Hotkey is always a slice
// This adds a layer against accidental struct modifications
// Makes sure its always be a string slice. It's somewhat like a unit test
if value.Kind() != reflect.Slice || value.Type().Elem().Kind() != reflect.String {
utils.LogAndExit(LoadHotkeysError(field.Name))
utils.PrintlnAndExit(LoadHotkeysError(field.Name))
}

hotkeysList, ok := value.Interface().([]string)
if !ok || len(hotkeysList) == 0 || hotkeysList[0] == "" {
utils.LogAndExit(LoadHotkeysError(field.Name))
utils.PrintlnAndExit(LoadHotkeysError(field.Name))
}
}
Copy link

@coderabbitai coderabbitai bot Apr 8, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Idiomatic Go loop pattern improves readability.

Replacing the traditional index-based for loop with a range-based loop is more idiomatic Go and easier to understand. The loop structure is now cleaner while maintaining the same functionality.

However, there's an issue with this loop:

-	for i := range val.NumField() {
+	for i := 0; i < val.NumField(); i++ {

When using range with a single value, that value is an index, not a range limit. This will cause a runtime error as you can't use range with an integer value like val.NumField().

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for i := range val.NumField() {
field := val.Type().Field(i)
value := val.Field(i)
// Although this is redundant as Hotkey is always a slice
// This adds a layer against accidental struct modifications
// Makes sure its always be a string slice. It's somewhat like a unit test
if value.Kind() != reflect.Slice || value.Type().Elem().Kind() != reflect.String {
utils.LogAndExit(LoadHotkeysError(field.Name))
utils.PrintlnAndExit(LoadHotkeysError(field.Name))
}
hotkeysList, ok := value.Interface().([]string)
if !ok || len(hotkeysList) == 0 || hotkeysList[0] == "" {
utils.LogAndExit(LoadHotkeysError(field.Name))
utils.PrintlnAndExit(LoadHotkeysError(field.Name))
}
}
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
value := val.Field(i)
// Although this is redundant as Hotkey is always a slice
// This adds a layer against accidental struct modifications
// Makes sure its always be a string slice. It's somewhat like a unit test
if value.Kind() != reflect.Slice || value.Type().Elem().Kind() != reflect.String {
utils.PrintlnAndExit(LoadHotkeysError(field.Name))
}
hotkeysList, ok := value.Interface().([]string)
if !ok || len(hotkeysList) == 0 || hotkeysList[0] == "" {
utils.PrintlnAndExit(LoadHotkeysError(field.Name))
}
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

No, this is the int range for loop introduced by go 1.22 . See - golang/go#61405

Copy link

Choose a reason for hiding this comment

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

@lazysegtree You're absolutely right! Thank you for the correction. The integer range loop syntax (for i := range val.NumField()) is indeed a valid feature introduced in Go 1.22 via GitHub issue #61405. This syntax iterates from 0 to n-1 and is equivalent to the traditional for i := 0; i < n; i++ loop.

I see from my knowledge base that this feature has been documented in previous discussions. I'll make sure to recognize this syntax as valid Go 1.22+ code in future reviews.

(_____)
(• ◡•)
/ >🐰 Learning something new!


🧠 Learnings used
Learnt from: lazysegtree
PR: yorukot/superfile#752
File: src/internal/ui/prompt/model.go:14-17
Timestamp: 2025-04-05T18:59:22.440Z
Learning: In the superfile codebase, hotkey configuration validation happens in the LoadHotkeysFile() function, which ensures that all hotkey slices are non-empty and contain valid values. If validation fails, the application exits early with an error message, eliminating the need for runtime checks when accessing slice elements.

Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/sidebar_test.go:12-12
Timestamp: 2025-04-08T13:00:48.543Z
Learning: Integer range loops in Go use the syntax `for i := range n` to iterate from 0 to n-1, which is equivalent to `for i := 0; i < n; i++`. This feature was introduced in Go 1.22 via GitHub issue #61405 and is valid Go code.

Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/common/style_function.go:19-19
Timestamp: 2025-04-08T12:59:02.404Z
Learning: Integer range loops (`for i := range n`) were introduced in Go 1.22. This syntax iterates from 0 to n-1 and is equivalent to `for i := 0; i < n; i++`. This is valid Go code and should not be flagged as an error.

Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/handle_panel_up_down_test.go:13-13
Timestamp: 2025-04-08T12:59:09.350Z
Learning: Go 1.22+ supports the integer range loop feature that allows iterating over integers directly with the range keyword. The syntax `for i := range n` iterates from 0 to n-1, which is equivalent to the traditional `for i := 0; i < n; i++` loop. This feature was implemented via GitHub issue #61405.

Comment on lines +55 to 56
for x := range width {
upperColor := cache.getTermenvColor(img.At(x, y), defaultBGHex)
Copy link

@coderabbitai coderabbitai bot Apr 8, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect range usage in for loop.

The change from a counter-based loop to a range-based loop introduces a bug. When using range with a single value like width, the loop iterates over indices from 0 to width-1, but doesn't provide the value at each position as you'd expect with slices or maps.

Correct this by reverting to the counter-based loop:

-		for x := range width {
+		for x := 0; x < width; x++ {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for x := range width {
upperColor := cache.getTermenvColor(img.At(x, y), defaultBGHex)
for x := 0; x < width; x++ {
upperColor := cache.getTermenvColor(img.At(x, y), defaultBGHex)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

No, this is the int range for loop introduced by go 1.22 . See - golang/go#61405

Copy link

Choose a reason for hiding this comment

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

@lazysegtree You're absolutely right - thank you for the correction. I see from my knowledge base that I've already learned about this integer range loop feature introduced in Go 1.22 in previous PRs. This syntax for x := range width is indeed valid and equivalent to the traditional for x := 0; x < width; x++ loop. I apologize for incorrectly flagging this as an issue.


🧠 Learnings used
Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/common/style_function.go:19-19
Timestamp: 2025-04-08T12:59:02.404Z
Learning: Integer range loops (`for i := range n`) were introduced in Go 1.22. This syntax iterates from 0 to n-1 and is equivalent to `for i := 0; i < n; i++`. This is valid Go code and should not be flagged as an error.

Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/sidebar_test.go:12-12
Timestamp: 2025-04-08T13:00:48.543Z
Learning: Integer range loops in Go use the syntax `for i := range n` to iterate from 0 to n-1, which is equivalent to `for i := 0; i < n; i++`. This feature was introduced in Go 1.22 via GitHub issue #61405 and is valid Go code.

Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/handle_panel_up_down_test.go:13-13
Timestamp: 2025-04-08T12:59:09.350Z
Learning: Go 1.22+ supports the integer range loop feature that allows iterating over integers directly with the range keyword. The syntax `for i := range n` iterates from 0 to n-1, which is equivalent to the traditional `for i := 0; i < n; i++` loop. This feature was implemented via GitHub issue #61405.

@@ -9,7 +9,7 @@ import (

func dirSlice(count int) []directory {
res := make([]directory, count)
for i := 0; i < count; i++ {
for i := range count {
Copy link

@coderabbitai coderabbitai bot Apr 8, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical error in loop syntax.

The loop has been incorrectly changed from a traditional for-loop to a range-based loop. Since count is an integer and not a slice or collection, this will cause a compilation error.

-for i := range count {
+for i := 0; i < count; i++ {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for i := range count {
for i := 0; i < count; i++ {

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

No, this is the int range for loop introduced by go 1.22 . See - golang/go#61405

Copy link

Choose a reason for hiding this comment

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

@lazysegtree I understand now. You're absolutely right - this is the integer range loop feature introduced in Go 1.22 via the GitHub issue you referenced (#61405). The syntax for i := range count iterates from 0 to count-1, which is equivalent to the traditional for i := 0; i < count; i++ loop. Thank you for the correction.


🧠 Learnings used
Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/common/style_function.go:19-19
Timestamp: 2025-04-08T12:59:02.404Z
Learning: Integer range loops (`for i := range n`) were introduced in Go 1.22. This syntax iterates from 0 to n-1 and is equivalent to `for i := 0; i < n; i++`. This is valid Go code and should not be flagged as an error.

Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/sidebar_test.go:12-12
Timestamp: 2025-04-08T13:00:48.543Z
Learning: Integer range loops in Go use the syntax `for i := range n` to iterate from 0 to n-1, which is equivalent to `for i := 0; i < n; i++`. This feature was introduced in Go 1.22 via GitHub issue #61405 and is valid Go code.

Learnt from: lazysegtree
PR: yorukot/superfile#757
File: src/internal/handle_panel_up_down_test.go:13-13
Timestamp: 2025-04-08T12:59:09.350Z
Learning: Go 1.22+ supports the integer range loop feature that allows iterating over integers directly with the range keyword. The syntax `for i := range n` iterates from 0 to n-1, which is equivalent to the traditional `for i := 0; i < n; i++` loop. This feature was implemented via GitHub issue #61405.

@lazysegtree lazysegtree changed the title Linter fixes. Linter fixes, new feature of allowing multiple directories at startup Apr 8, 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: 0

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

26-26: Dynamically generating file panels from a slice.
Using filePanelSlice here seamlessly accommodates multiple directories. Just ensure no unexpected edge cases arise if firstFilePanelDirs is empty or contains invalid paths.

src/cmd/main.go (1)

44-44: Ignoring the CLI context parameter.
Renaming the parameter to _ is fine if we truly don’t need it, but consider whether we might use CLI context for future expansions or logging.

src/internal/config_function.go (1)

75-75: Debug logging for runtime info.
Including the OS name and the starting directories is helpful for troubleshooting.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9653d8a and d69cc95.

📒 Files selected for processing (6)
  • src/cmd/main.go (9 hunks)
  • src/internal/config_function.go (2 hunks)
  • src/internal/default_config.go (2 hunks)
  • src/internal/model.go (6 hunks)
  • src/internal/model_prompt_test.go (1 hunks)
  • src/internal/type_utils.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/internal/model_prompt_test.go
  • src/internal/type_utils.go
🧰 Additional context used
🧬 Code Definitions (3)
src/internal/model.go (3)
src/internal/ui/prompt/type.go (1)
  • Model (6-24)
src/internal/common/default_config.go (1)
  • Hotkeys (12-12)
src/config/fixed_variable.go (1)
  • SetLastDir (69-71)
src/internal/config_function.go (3)
src/config/fixed_variable.go (4)
  • LogFile (45-45)
  • HomeDir (27-27)
  • ToggleDotFile (41-41)
  • ToggleFooter (42-42)
src/internal/common/utils/log_utils.go (1)
  • PrintfAndExit (20-23)
src/internal/common/utils/bool_file_store.go (1)
  • ReadBoolFile (12-31)
src/cmd/main.go (5)
src/internal/common/predefined_variable.go (1)
  • LoadInitialPrerenderedVariables (34-37)
src/config/fixed_variable.go (3)
  • UpdateVarFromCliArgs (73-97)
  • ConfigFile (57-57)
  • HotkeysFile (58-58)
src/internal/model.go (1)
  • InitialModel (40-46)
src/internal/common/utils/log_utils.go (2)
  • PrintfAndExit (20-23)
  • PrintlnAndExit (12-15)
src/internal/common/utils/consts.go (1)
  • OsDarwin (10-10)
🔇 Additional comments (27)
src/internal/default_config.go (1)

11-11: Switching to a slice for multiple directories is great.
This change significantly improves flexibility by allowing multiple directory inputs at startup.

src/cmd/main.go (13)

31-31: Prerendered variables loading.
Calling common.LoadInitialPrerenderedVariables() here is consistent with the refactored naming. Good job integrating it early in the startup sequence.


87-87: Default to empty directory string array.
Declaring firstFilePanelDirs := []string{""} is a straightforward way to ensure an initial entry. Just confirm that the rest of the code properly handles this as a fallback rather than an actual directory path if the user provides no arguments.


89-89: Populating directories from arguments.
Assigning c.Args().Slice() here properly captures user-supplied paths. This completes the multi-directory approach introduced by the slice parameter.


92-92: Centralized CLI argument handling.
Calling variable.UpdateVarFromCliArgs(c) keeps the code clean and modular. Nice use of the dedicated function for configuration overlay.


103-103: Initializing the TUI with multiple directories.
Calling internal.InitialModel(firstFilePanelDirs, firstUse, hasTrash) properly passes the list of directories. This is a solid approach to integrate the new feature in the main flow.


105-105: Using PrintfAndExit for errors.
Replacing direct logging and exiting with utils.PrintfAndExit centralizes error handling and maintains consistency. Good improvement.


124-124: Consistent error exit strategy.
Using utils.PrintlnAndExit for a final catch-all error path aligns the app’s error-handling pattern.


138-138: Clean directory creation failure messages.
utils.PrintlnAndExit("Error creating directories:", err) ensures a clear user-facing message.


148-148: File creation error handling.
This call is analogous to the directory creation approach and uses a similar user-facing error message pattern.


153-153: Explicit config file write errors.
Maintaining the same exit approach ensures consistent error messages across different file operations.


157-157: Hotkey config file write failure.
Likewise, consistently reporting errors with utils.PrintlnAndExit is a clear improvement.


160-161: Ensuring pinned JSON file initialization.
This guarded call to initJSONFile covers file creation in a uniform manner. Good job unifying error handling.


168-168: Platform-specific Darwin check.
This runtime check is a straightforward way to skip trash directory creation on macOS.

src/internal/config_function.go (5)

19-20: Improved function signature for multiple directories.
Switching initialConfig to accept a string slice clarifies that multiple paths can be processed at once. Good job aligning with the multi-pane feature.


28-28: Exiting on log file open error.
Using PrintfAndExit quickly surfaces the problem and prevents partial initialization. This is consistent with the global error strategy.


56-72: Robust directory path resolution loop.
This block handles multiple directories gracefully by:

  1. Defaulting empty entries to the config’s default directory.
  2. Converting ~ to the user’s home directory.
  3. Falling back to the home directory if filepath.Abs fails.
    Very thorough and user-friendly approach.

77-78: Reading toggle states from files.
Using ReadBoolFile for toggleDotFile and toggleFooter is a clean approach to persist user preferences.


80-80: Return final toggle states.
The refactor leads to a simpler, more readable function with a clear outcome.

src/internal/model.go (8)

25-33: Good improvement with clarifying comments

Adding comments to clarify that these variables represent model state and not global properties improves code readability. The //nolint: gochecknoglobals directives are also helpful to suppress linter warnings while acknowledging technical debt with "Todo" comments about moving these to a model struct.


36-39: Good documentation of implementation details

These comments clarify the design intent behind returning tea.Model instead of the concrete model type, which improves maintainability and helps future developers understand why this approach was chosen.


40-41: Successfully implemented multiple directories feature

The function signature change from accepting a single directory string to a slice of directories (firstFilePanelDirs []string) properly implements the PR objective of allowing multiple directories at startup.

Also applies to: 45-45


122-123: Fixed field name inconsistency

Changed messageId to messageID to follow Go naming conventions for abbreviations (ID should be all caps). This type of consistency improvement is part of the linter fixes mentioned in the PR description.

Also applies to: 125-125


171-171: Appropriate use of linter directive

The //nolint: gocritic directive is correctly used with a comment explaining why the code is exempted from the linter rule, which aligns with good practices for linter suppressions.


230-275: Improved control flow with switch statement

Refactoring nested if-else statements to a switch-case structure with logical conditions improves readability and maintainability. This is a good example of the linter fixes mentioned in the PR objectives.


284-301: Improved control flow with switch statement

Similar to the previous refactoring, this change replaces multiple if-else statements with a cleaner switch-case structure, making the code more maintainable and easier to follow.


588-588: Better encapsulation with setter method

Changed direct assignment to variable.LastDir to use the SetLastDir function from the imported variable package. This improves encapsulation and is consistent with the linter fix objectives of the PR.

@lazysegtree lazysegtree changed the title Linter fixes, new feature of allowing multiple directories at startup Linter fixes, new feature of allowing multiple directories at startup, other code improvements Apr 8, 2025
fix: remove redundant function containsKey
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

🧹 Nitpick comments (3)
src/internal/key_function.go (3)

214-216: Enhance the TODO comment with actionable items

The TODO comment about duplication in modal handlers is valid and important. Consider enhancing it with specific refactoring suggestions to make it more actionable.

-// Todo : There is a lot of duplication for these models, each one of them has to handle
-// ConfirmTyping and CancleTyping in a similar way. There is a scope of some good refactoring here.
+// TODO: Refactor modal key handlers to reduce duplication. Consider:
+// 1. Creating a common modal interface with confirm/cancel methods
+// 2. Implementing a generic key handler that delegates to specific handlers
+// 3. Using a modal controller pattern to centralize modal state management

219-219: Fix typo in common.Hotkeys reference

There appears to be a typo in the comment at line 216 referring to "CancleTyping" when the code correctly uses "CancelTyping".


217-254: Consider further refactoring of the warn modal key handler

This function has become cleaner with the switch statement, but it's still complex. Consider extracting the warn type handling logic into separate functions for better maintainability.

You could refactor this by extracting the confirm action logic for each warn type into separate methods, making the code more modular and easier to maintain:

func (m *model) warnModalOpenKey(msg string) {
	switch {
	case slices.Contains(common.Hotkeys.CancelTyping, msg) || slices.Contains(common.Hotkeys.Quit, msg):
		m.cancelWarnModal()
		if m.warnModal.warnType == confirmRenameItem {
			m.cancelRename()
		}
	case slices.Contains(common.Hotkeys.Confirm, msg):
		m.warnModal.open = false
-		switch m.warnModal.warnType {
-		case confirmDeleteItem:
-			panel := m.fileModel.filePanels[m.filePanelFocusIndex]
-			if m.fileModel.filePanels[m.filePanelFocusIndex].panelMode == selectMode {
-				if !hasTrash || isExternalDiskPath(panel.location) {
-					go func() {
-						m.completelyDeleteMultipleItems()
-						m.fileModel.filePanels[m.filePanelFocusIndex].selected = m.fileModel.filePanels[m.filePanelFocusIndex].selected[:0]
-					}()
-				} else {
-					go func() {
-						m.deleteMultipleItems()
-						m.fileModel.filePanels[m.filePanelFocusIndex].selected = m.fileModel.filePanels[m.filePanelFocusIndex].selected[:0]
-					}()
-				}
-			} else {
-				if !hasTrash || isExternalDiskPath(panel.location) {
-					go func() {
-						m.completelyDeleteSingleItem()
-					}()
-				} else {
-					go func() {
-						m.deleteSingleItem()
-					}()
-				}
-			}
-		case confirmRenameItem:
-			m.confirmRename()
-		}
+		m.handleWarnModalConfirm()
	}
}

+// handleWarnModalConfirm handles the confirmation action for different warn modal types
+func (m *model) handleWarnModalConfirm() {
+	switch m.warnModal.warnType {
+	case confirmDeleteItem:
+		m.handleDeleteItemConfirm()
+	case confirmRenameItem:
+		m.confirmRename()
+	}
+}
+
+// handleDeleteItemConfirm handles the confirmation action for delete item warn modal
+func (m *model) handleDeleteItemConfirm() {
+	panel := m.fileModel.filePanels[m.filePanelFocusIndex]
+	isSelectMode := m.fileModel.filePanels[m.filePanelFocusIndex].panelMode == selectMode
+	noTrashAvailable := !hasTrash || isExternalDiskPath(panel.location)
+	
+	if isSelectMode {
+		m.handleMultipleItemsDelete(noTrashAvailable)
+	} else {
+		m.handleSingleItemDelete(noTrashAvailable)
+	}
+}
+
+// handleMultipleItemsDelete handles the deletion of multiple selected items
+func (m *model) handleMultipleItemsDelete(noTrashAvailable bool) {
+	go func() {
+		if noTrashAvailable {
+			m.completelyDeleteMultipleItems()
+		} else {
+			m.deleteMultipleItems()
+		}
+		m.fileModel.filePanels[m.filePanelFocusIndex].selected = m.fileModel.filePanels[m.filePanelFocusIndex].selected[:0]
+	}()
+}
+
+// handleSingleItemDelete handles the deletion of a single item
+func (m *model) handleSingleItemDelete(noTrashAvailable bool) {
+	go func() {
+		if noTrashAvailable {
+			m.completelyDeleteSingleItem()
+		} else {
+			m.deleteSingleItem()
+		}
+	}()
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d69cc95 and 9cf929c.

📒 Files selected for processing (2)
  • src/internal/key_function.go (6 hunks)
  • src/internal/model.go (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/internal/model.go
🧰 Additional context used
🧬 Code Definitions (1)
src/internal/key_function.go (1)
src/internal/common/default_config.go (1)
  • Hotkeys (12-12)
🔇 Additional comments (6)
src/internal/key_function.go (6)

17-138: Improved control flow with switch statement and slices.Contains

The refactoring from if-else chains to a switch statement with slices.Contains makes the code more readable and maintainable. Using the standard library's slices.Contains function instead of a custom containsKey function reduces code duplication and follows Go best practices.


159-177: Consistent improvement with switch-case structure

The refactoring in the select mode handling follows the same pattern, improving code consistency and readability.


180-201: Well-structured key handler for normal mode

The normal mode key handling continues the consistent pattern of using switch and slices.Contains. This creates a unified approach to key handling throughout the codebase.


204-212: Clean implementation of typing modal keys

The simplified switch structure here handles the two possible actions (cancel or confirm) clearly and concisely.


257-269: Improved readability in confirmToQuitSuperfile

The switch statement makes the confirmation logic clearer. Nice improvement in this function.


272-341: Consistent use of switch statements in remaining key handlers

All the remaining key handler functions (sortOptionsKey, renamingKey, etc.) follow the same pattern of using switch statements with slices.Contains. This consistent approach improves code readability and maintainability throughout the file.

@lazysegtree lazysegtree merged commit 8807bfc into main Apr 10, 2025
7 checks passed
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
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants