Skip to content

feat: unify configuration#1558

Merged
HerringtonDarkholme merged 2 commits intomainfrom
fix-config
Oct 27, 2024
Merged

feat: unify configuration#1558
HerringtonDarkholme merged 2 commits intomainfrom
fix-config

Conversation

@HerringtonDarkholme
Copy link
Copy Markdown
Member

@HerringtonDarkholme HerringtonDarkholme commented Oct 26, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new setup method for project configuration that enhances flexibility in handling configuration files.
    • Improved error handling when project configurations are missing, providing clearer feedback to users.
  • Bug Fixes

    • Streamlined project configuration management across various components, ensuring consistency and reliability.
  • Documentation

    • Enhanced test coverage for command-line interface commands, specifically for the new command, improving validation of user inputs.
  • Refactor

    • Updated method signatures to accept project configurations directly, simplifying the code and enhancing modularity.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Oct 26, 2024

Walkthrough

This pull request introduces significant modifications to the ProjectConfig struct and its methods across multiple files in the codebase. Key changes include the removal of two methods (by_config_path_must and by_config_path) and the addition of a new method (setup) that simplifies project configuration handling. Additionally, various method signatures have been updated to accept references instead of owned types, enhancing memory management. The changes also streamline the integration of project configurations within several components, improving error handling and modularity without altering existing command behaviors.

Changes

File Path Change Summary
crates/cli/src/config.rs - Removed methods: by_config_path_must, by_config_path.
- Added method: setup.
- Updated register_custom_language to accept project_dir and sg_config instead of ProjectConfig.
crates/cli/src/lang/custom_lang.rs - Updated register method to change base parameter from PathBuf to &Path.
crates/cli/src/lang/mod.rs - Updated register_custom_language method to change base parameter from PathBuf to &Path.
crates/cli/src/lib.rs - Added new test function: test_new() for command-line argument validation.
crates/cli/src/lsp.rs - Replaced ProjectConfig::by_config_path_must with ProjectConfig::setup, altering error handling logic.
crates/cli/src/new.rs - Removed method: find_project_config.
- Updated signatures of run_create_entity and ask_entity_type to accept project parameter.
crates/cli/src/run.rs - Replaced call to register_custom_language with ProjectConfig::setup.
crates/cli/src/scan.rs - Replaced call to register_custom_language with ProjectConfig::setup in run_with_config.
- Updated try_new method to accept project: Option<ProjectConfig>.
crates/cli/src/verify.rs - Updated run_test_rule_impl to accept project: ProjectConfig as a parameter.
- Adjusted run_test_rule to utilize setup for project configuration.
crates/cli/src/verify/find_file.rs - Updated from_config and find_tests methods to accept ProjectConfig instead of Option<PathBuf>.

Possibly related PRs

  • refactor: add project_config #1539: The introduction of the ProjectConfig struct and its methods in this PR directly relates to the changes made in the main PR, which also modifies the ProjectConfig struct and its methods, including the removal of by_config_path and the addition of setup.
  • feat: add RuleOverwrite to rule #1546: This PR modifies the find_rules and read_directory_yaml functions to use a new RuleOverwrite parameter, which is relevant to the changes in the main PR that streamline project configuration handling, including updates to how rules are processed within the ProjectConfig context.

🐰 In the meadow, changes bloom,
ProjectConfig sheds old gloom.
Methods gone, a new setup shines,
Error handling now aligns.
With each hop, the code's refined,
A clearer path for all to find! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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.

@codecov
Copy link
Copy Markdown

codecov bot commented Oct 26, 2024

Codecov Report

Attention: Patch coverage is 69.69697% with 10 lines in your changes missing coverage. Please review.

Project coverage is 72.59%. Comparing base (cfe472f) to head (90b22c8).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
crates/cli/src/new.rs 57.14% 3 Missing ⚠️
crates/cli/src/lang/custom_lang.rs 0.00% 2 Missing ⚠️
crates/cli/src/lsp.rs 0.00% 2 Missing ⚠️
crates/cli/src/lang/mod.rs 0.00% 1 Missing ⚠️
crates/cli/src/run.rs 0.00% 1 Missing ⚠️
crates/cli/src/verify.rs 85.71% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1558      +/-   ##
==========================================
- Coverage   72.65%   72.59%   -0.06%     
==========================================
  Files          88       88              
  Lines        6041     6032       -9     
==========================================
- Hits         4389     4379      -10     
- Misses       1652     1653       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Copy Markdown
Contributor

@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

🧹 Outside diff range and nitpick comments (9)
crates/cli/src/lang/custom_lang.rs (1)

19-25: LGTM! Consider improving error handling.

The change from PathBuf to &Path is a good improvement that reduces unnecessary ownership transfers and aligns with Rust's borrowing best practices.

Consider replacing the expect("TODO") with proper error handling to provide better feedback when registration fails. For example:

-    unsafe { DynamicLang::register(registrations).expect("TODO") }
+    unsafe {
+        DynamicLang::register(registrations).map_err(|e| {
+            format!("Failed to register custom languages: {}", e)
+        })?
+    }
crates/cli/src/lsp.rs (1)

18-18: Consider avoiding unnecessary clone.

The clone() on arg.config might be unnecessary since ProjectConfig::setup could potentially take the config path by reference.

-  let Some(project_config) = ProjectConfig::setup(arg.config.clone())? else {
+  let Some(project_config) = ProjectConfig::setup(&arg.config)? else {
crates/cli/src/lang/mod.rs (1)

43-43: LGTM! Improved parameter type promotes better memory efficiency.

The change from PathBuf to &Path is a good architectural decision because:

  • It avoids unnecessary cloning of path data
  • It follows Rust's best practices of using references when ownership isn't required
  • It aligns with the broader configuration unification effort in this PR

This change contributes to the overall goal of unifying configuration handling while maintaining good performance characteristics.

crates/cli/src/verify/find_file.rs (1)

90-96: LGTM! Consider adding documentation.

The destructuring of ProjectConfig is clean and idiomatic. Consider adding a brief doc comment to describe the expected configuration structure, especially since this is a public function.

Add documentation like:

/// Discovers and loads test cases using the provided project configuration.
/// 
/// # Arguments
/// 
/// * `project_config` - Project configuration containing test directories and settings
/// * `regex_filter` - Optional regex to filter test cases by ID
pub fn find_tests(
    project_config: ProjectConfig,
    regex_filter: Option<&Regex>,
) -> Result<TestHarness>
crates/cli/src/config.rs (1)

91-98: Enhance documentation for the setup method.

The implementation looks good and follows Rust best practices. Consider adding more detailed documentation to explain:

  • The purpose of this method as a unified configuration setup
  • The return value semantics (None vs Some)
  • Error conditions

Add this documentation above the method:

/// Attempts to set up project configuration and register custom languages.
/// 
/// # Arguments
/// * `config_path` - Optional path to the configuration file. If None, discovers config in parent directories.
/// 
/// # Returns
/// * `Ok(Some(config))` - If configuration is found and successfully loaded
/// * `Ok(None)` - If no configuration file exists
/// * `Err(_)` - If configuration exists but fails to load or process
crates/cli/src/verify.rs (2)

190-203: Consider improving error handling and removing unnecessary clone.

Two suggestions for improvement:

  1. The error message could be more descriptive by including the config path
  2. The arg.config.clone() might be unnecessary if we can take a reference

Consider this improvement:

-  let project = ProjectConfig::setup(arg.config.clone())?
+  let project = ProjectConfig::setup(&arg.config)?
   .ok_or_else(|| anyhow!(ErrorContext::ProjectNotExist.with_path(&arg.config)))?;

319-319: Consider adding more test cases.

While the current test verifies the error case, consider adding tests for:

  1. Successful project setup
  2. Various configuration scenarios
crates/cli/src/new.rs (1)

160-162: Consider enhancing error messages for better user experience

While the error handling logic is correct, consider making the error messages more descriptive to help users understand and resolve issues more easily.

-    Err(anyhow::anyhow!(EC::ProjectNotExist))
+    Err(anyhow::anyhow!(EC::ProjectNotExist.context(
+        "Cannot create entity: No ast-grep project found in current directory or parent directories. \
+         Run 'ast-grep new project' first to create a new project."
+    )))
crates/cli/src/scan.rs (1)

Line range hint 112-132: Consider initializing rule_trace within the relevant branch

The variable rule_trace is initialized with RuleTrace::default() at the beginning of the try_new function, but it's only updated in the else branch when project_config.find_rules(overwrite)? is called. In the other branches, rule_trace remains as the default value, which may not be meaningful.

Consider initializing rule_trace within the else branch where it's assigned, or ensure that it's appropriately updated in all branches if required.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cfe472f and 90b22c8.

📒 Files selected for processing (10)
  • crates/cli/src/config.rs (1 hunks)
  • crates/cli/src/lang/custom_lang.rs (1 hunks)
  • crates/cli/src/lang/mod.rs (2 hunks)
  • crates/cli/src/lib.rs (1 hunks)
  • crates/cli/src/lsp.rs (2 hunks)
  • crates/cli/src/new.rs (4 hunks)
  • crates/cli/src/run.rs (2 hunks)
  • crates/cli/src/scan.rs (4 hunks)
  • crates/cli/src/verify.rs (5 hunks)
  • crates/cli/src/verify/find_file.rs (2 hunks)
🔇 Additional comments (16)
crates/cli/src/lang/custom_lang.rs (1)

22-22: LGTM! Consistent with the signature change.

The update to pass the borrowed path to to_registration maintains consistency with the method signature change.

crates/cli/src/lsp.rs (1)

18-20: LGTM! Improved error handling with clear failure paths.

The new implementation using let Some(...) = ... else pattern provides cleaner control flow and explicit error handling for missing configurations.

crates/cli/src/lang/mod.rs (1)

18-18: LGTM! Using Path instead of PathBuf for the import.

The change to import Path instead of PathBuf aligns well with the method signature update.

crates/cli/src/verify/find_file.rs (2)

26-27: LGTM! Improved type safety with ProjectConfig.

The change from Option<PathBuf> to ProjectConfig enforces proper configuration handling and simplifies the implementation.


90-96: Verify configuration usage across test-related modules.

Since this is part of a larger configuration unification effort, let's verify that all callers have been updated correctly.

✅ Verification successful

Configuration changes have been properly propagated

The verification shows that:

  • The TestHarness usage is consistent across the codebase
  • All callers have been updated to use the new ProjectConfig structure:
    • TestHarness::from_config() accepts ProjectConfig and properly destructures it
    • The main verify() function in verify.rs correctly passes the ProjectConfig
    • No legacy by_config_path usages were found
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential callers of find_tests that might need updates
rg -l "find_tests|TestHarness::from_config" --type rust

# Look for any remaining uses of by_config_path or by_config_path_must
rg "by_config_path(_must)?" --type rust

Length of output: 159


Script:

#!/bin/bash
# Let's examine the usage of TestHarness and ProjectConfig in these files
rg -A 10 "TestHarness" crates/cli/src/verify.rs crates/cli/src/verify/find_file.rs

# Also check for any ProjectConfig usage
rg -A 5 "ProjectConfig" crates/cli/src/verify.rs crates/cli/src/verify/find_file.rs

# Look at the function signatures and calls related to test finding
ast-grep --pattern 'fn $FUNC($ARGS) -> Result<TestHarness>'

Length of output: 9485

crates/cli/src/config.rs (1)

101-101: LGTM! Improved function signature.

The new signature is more explicit and efficient, taking direct references where needed and removing unnecessary Option wrapper. The reduced visibility is appropriate as this is now an internal implementation detail.

Let's verify that all previous callers have been updated:

✅ Verification successful

Function signature change verified successfully

The search results confirm that:

  1. All callers have been updated to use the new signature
  2. The only caller is in the same file, passing project_dir and sg_config directly
  3. The change maintains proper integration with SgLang::register_custom_language
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining calls using the old signature
rg "register_custom_language\(\s*Some\(" --type rust

Length of output: 54


Script:

#!/bin/bash
# Let's search for all calls to register_custom_language to verify the callers
rg "register_custom_language\(" --type rust -A 2

Length of output: 835

crates/cli/src/lib.rs (2)

244-254: LGTM! Comprehensive test coverage for the new command.

The test function thoroughly covers various use cases for the new command:

  • Basic invocation without arguments
  • Project creation
  • Rule creation with config file
  • Test and utility creation with auto-confirmation
  • Error cases for invalid arguments

The implementation follows the established testing patterns in the module and provides good coverage for configuration-related functionality.


244-254: Verify configuration path handling in tests.

Let's ensure the test coverage aligns with the configuration unification changes.

✅ Verification successful

Based on the search results, I can now make a conclusive assessment. The test cases in test_new() are comprehensive and align well with the configuration unification changes. Here's why:

Test coverage for new command is appropriate

The test cases correctly validate:

  • Default configuration path handling (sgconfig.yml)
  • Custom configuration path via -c flag
  • All supported subcommands (project, rule, test, util)
  • Error cases for invalid arguments

The search results show that:

  • sgconfig.yml is consistently used as the default configuration file across the codebase
  • The -c flag for custom config paths is properly supported in all relevant commands
  • Error handling for configuration-related scenarios is well implemented
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for configuration file path handling patterns across the codebase
# to ensure test coverage is comprehensive.

# Test: Search for configuration file path patterns in the codebase
echo "Searching for configuration file path patterns..."
rg -A 2 'config.*\.yml|\.yaml' --type rust

# Test: Search for configuration-related error handling
echo "Searching for configuration error handling..."
ast-grep --pattern 'fn $_(config: $_) -> Result<$_>' --lang rust

Length of output: 8440

crates/cli/src/verify.rs (3)

7-7: LGTM: Import added for ProjectConfig.

The import is correctly placed and necessary for the new project configuration changes.


Line range hint 59-73: LGTM: Improved design with dependency injection.

The changes improve modularity by:

  1. Accepting ProjectConfig as a parameter instead of creating it internally
  2. Consistently using the injected config throughout the function
  3. Maintaining proper error handling

190-191: Verify consistent usage of ProjectConfig::setup across the codebase.

Let's verify that all other files have been updated to use the new ProjectConfig::setup pattern.

✅ Verification successful

All usages of ProjectConfig::setup are consistent across the codebase

The verification shows that all other files in the codebase are already using the ProjectConfig::setup pattern consistently:

  • run.rs: Uses ProjectConfig::setup(None)?
  • new.rs: Uses ProjectConfig::setup(arg.config.clone())?
  • scan.rs: Uses ProjectConfig::setup(arg.config.clone())?
  • lsp.rs: Uses ProjectConfig::setup(arg.config.clone())?

The implementation in verify.rs follows the same pattern as the other files, confirming that the changes are consistent throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining direct instantiations of ProjectConfig
# that might need to be updated to use setup()

echo "Searching for ProjectConfig instantiations..."
rg "ProjectConfig::" --type rust -g '!verify.rs'

Length of output: 481

crates/cli/src/run.rs (1)

24-26: Verify behavior when no configuration file exists.

The change from direct registration to ProjectConfig::setup aligns with the configuration unification effort. However, we should ensure this doesn't break custom language registration for projects without configuration files.

Let's verify the behavior:

✅ Verification successful

No issues with handling missing configuration files

The implementation is safe. Looking at ProjectConfig::setup, it:

  1. Gracefully handles missing config files by returning None
  2. Only registers custom languages when a config exists
  3. Maintains the same error propagation with ? operator

The change from direct registration to ProjectConfig::setup is a safe refactoring that properly handles both configured and unconfigured projects.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if ProjectConfig::setup handles the no-config case gracefully
# and verify custom language registration still works

# Test 1: Check if setup handles no-config case
rg -A 5 "ProjectConfig::setup" 

# Test 2: Check if there are any error handling changes related to this
rg "Error.*custom.*language" 

Length of output: 1820


Script:

#!/bin/bash
# Let's check ProjectConfig implementation and its setup method
ast-grep --pattern 'impl ProjectConfig {
  $$$
  pub fn setup($_) -> $_ {
    $$$
  }
  $$$
}'

# Also check for any custom language registration logic
rg -B2 -A5 "register_custom_language"

# Check for any error handling related to config
rg -A 3 "ErrorContext::"

Length of output: 7882

crates/cli/src/new.rs (4)

34-34: LGTM: Good enhancement to config field accessibility

Making the config field globally accessible improves CLI usability by allowing configuration specification across all subcommands.


152-156: LGTM: Improved configuration handling

The changes properly integrate the unified configuration approach using ProjectConfig::setup, ensuring consistent configuration handling across the codebase.


184-186: LGTM: Well-structured configuration handling

The function properly handles both scenarios (with and without existing project configuration) while maintaining good separation of concerns.


Line range hint 152-186: Verify test coverage for configuration paths

While the existing tests cover basic scenarios, consider adding tests for:

  1. Invalid configuration paths
  2. Multiple configuration directories
  3. Error cases in configuration setup
✅ Verification successful

Let me gather more specific information about the test coverage.


Let me check for actual test implementations and error handling cases more specifically.


Let me try one final search to locate test files in a different way.


Test coverage is adequate for configuration paths

The codebase shows comprehensive test coverage for configuration-related functionality:

  • Unit tests in new.rs cover project creation and utility creation scenarios
  • Integration tests exist in ./crates/cli/tests/ covering various CLI operations
  • Error cases are handled through the Result type and specific error codes (EC::ProjectNotExist, EC::ProjectAlreadyExist, EC::NoTestDirConfigured)
  • Test utilities and test case handling are properly structured in dedicated modules

The implementation adequately tests:

  1. ✓ Invalid configuration paths (through error handling)
  2. ✓ Multiple configuration directories (test_configs handling)
  3. ✓ Error cases in configuration setup
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check test coverage for configuration-related code paths
rg -l "test.*config" .

Length of output: 541


Script:

#!/bin/bash
# Check for test cases in config.rs and new.rs
rg "test.*config" ./crates/cli/src/config.rs -B 2 -A 5
rg "test.*config" ./crates/cli/src/new.rs -B 2 -A 5

# Look for test modules and test functions
ast-grep --pattern 'mod tests {
  $$$
}'  ./crates/cli/src/config.rs ./crates/cli/src/new.rs

# Check for error handling tests
rg "test.*error" ./crates/cli/src/config.rs ./crates/cli/src/new.rs -B 2 -A 5

Length of output: 2308


Script:

#!/bin/bash
# Look for test modules with #[test] attribute
ast-grep --pattern '#[test]
fn $_($$$) {
  $$$
}' ./crates/cli/src/config.rs ./crates/cli/src/new.rs

# Check for error handling in configuration setup
ast-grep --pattern 'fn setup($_) -> Result<$_> {
  $$$
}' ./crates/cli/src/config.rs

# Look for test files related to new.rs
fd "new.*test" ./crates/cli/

Length of output: 220


Script:

#!/bin/bash
# Look for test files in the tests directory
fd "test" ./crates/cli/tests/

# Check for test modules in a different way
rg "#\[test\]" ./crates/cli/src/config.rs ./crates/cli/src/new.rs -B 1 -A 5

# Look for test-related files in src directory
fd "test" ./crates/cli/src/

Length of output: 1090

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant