Skip to content

refactor: add project_config#1539

Merged
HerringtonDarkholme merged 2 commits intomainfrom
severity-override
Oct 22, 2024
Merged

refactor: add project_config#1539
HerringtonDarkholme merged 2 commits intomainfrom
severity-override

Conversation

@HerringtonDarkholme
Copy link
Copy Markdown
Member

@HerringtonDarkholme HerringtonDarkholme commented Oct 21, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new ProjectConfig structure to enhance configuration management.
    • Added methods for locating configuration files, improving ease of use.
    • Updated project entity creation logic to utilize the new ProjectConfig, simplifying access to configurations.
  • Bug Fixes

    • Streamlined the retrieval of project and utility directories for better performance and clarity.
    • Improved error handling related to project configuration checks.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Oct 21, 2024

Walkthrough

The changes introduce a new struct called ProjectConfig in the crates/cli/src/config.rs file, consolidating project directory information and an instance of AstGrepConfig. Several methods are added to facilitate the retrieval of configuration files and streamline the handling of utility directories. Function signatures are updated to accept references to ProjectConfig, enhancing the clarity and maintainability of the configuration handling process. Additionally, the new.rs file is modified to utilize ProjectConfig for managing project-specific configurations in entity creation.

Changes

File Change Summary
crates/cli/src/config.rs Added struct ProjectConfig and methods by_config_path, by_project_dir, find. Updated find_rules, register_custom_language, build_util_walker, find_util_rules, read_directory_yaml, and read_config_from_dir to utilize ProjectConfig.
crates/cli/src/new.rs Added import for ProjectConfig. Updated function signatures for do_create_entity, create_new_rule, and create_new_util to accept ProjectConfig. Modified error handling and logic to streamline access to project configurations.

Poem

In the burrow deep, where the configs lie,
A new struct hops in, reaching for the sky.
With paths and rules, all tidy and neat,
Our project now dances, oh what a treat!
So let’s celebrate, with a joyful cheer,
For clarity's bloom, we hold so dear! 🐇✨


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.

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

🧹 Outside diff range and nitpick comments (2)
crates/cli/src/config.rs (2)

57-60: Introduce #[derive(Debug)] for ProjectConfig

Consider adding #[derive(Debug)] to ProjectConfig to facilitate easier debugging and logging.

Apply this change:

+#[derive(Debug)]
 pub struct ProjectConfig {
   pub project_dir: PathBuf,
   pub sg_config: AstGrepConfig,
 }

Line range hint 182-196: Handle absence of configuration file more gracefully

When no configuration file is found, find_config_path_with_default defaults to returning sgconfig.yml in the current directory, which may not exist. This could lead to an error when trying to read the file. Consider explicitly notifying the user that no configuration file was found.

You can adjust the function to return an error if the configuration file doesn't exist:

         } else {
-          break Ok(PathBuf::from(CONFIG_FILE));
+          break Err(anyhow::anyhow!("No configuration file found"));
         }

This change provides clear feedback when a configuration file is missing.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 90596b3 and 78cd064.

📒 Files selected for processing (1)
  • crates/cli/src/config.rs (4 hunks)
🧰 Additional context used
🔇 Additional comments (4)
crates/cli/src/config.rs (4)

86-88: Refactor enhances code readability

Refactoring to use ProjectConfig improves code clarity by encapsulating configuration details.


110-113: Accept references to avoid unnecessary cloning

Updating build_util_walker to accept references prevents unnecessary cloning of util_dirs, improving performance.


120-125: Simplify access to configuration with &ProjectConfig

Refactoring find_util_rules to accept &ProjectConfig streamlines access to configuration data and enhances maintainability.


151-160: Enhance function by accepting &ProjectConfig

Modifying read_directory_yaml to take &ProjectConfig simplifies parameter passing and improves code cohesion.

@codecov
Copy link
Copy Markdown

codecov bot commented Oct 21, 2024

Codecov Report

Attention: Patch coverage is 91.83673% with 4 lines in your changes missing coverage. Please review.

Project coverage is 72.31%. Comparing base (90596b3) to head (74828dd).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
crates/cli/src/new.rs 81.25% 3 Missing ⚠️
crates/cli/src/config.rs 96.96% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1539      +/-   ##
==========================================
+ Coverage   72.24%   72.31%   +0.07%     
==========================================
  Files          88       88              
  Lines        6009     6018       +9     
==========================================
+ Hits         4341     4352      +11     
+ Misses       1668     1666       -2     

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

🧹 Outside diff range and nitpick comments (2)
crates/cli/src/config.rs (1)

Line range hint 113-118: Simplify build_util_walker parameter handling

Consider changing the util_dirs parameter to a slice to avoid unnecessary Option wrapping and make the function more idiomatic.

Apply this diff:

-fn build_util_walker(base_dir: &Path, util_dirs: &Option<Vec<PathBuf>>) -> Option<WalkBuilder> {
-  let mut util_dirs = util_dirs.as_ref()?.iter();
+fn build_util_walker(base_dir: &Path, util_dirs: &[PathBuf]) -> Option<WalkBuilder> {
+  if util_dirs.is_empty() {
+    return None;
+  }
+  let mut util_dirs = util_dirs.iter();

Update the call sites accordingly:

-let Some(mut walker) = build_util_walker(project_dir, &sg_config.util_dirs) else {
+let Some(mut walker) = build_util_walker(project_dir, sg_config.util_dirs.as_deref().unwrap_or(&[])) else {
    return Ok(GlobalRules::default());
};
crates/cli/src/new.rs (1)

Line range hint 321-338: Refactor duplicated directory selection logic

The logic for selecting the util_dir in create_new_util is duplicated from create_new_rule. To adhere to the DRY principle and improve maintainability, consider utilizing the same helper function suggested earlier.

Update create_new_util using the select_directory helper function:

-let util_dir = if utils.len() > 1 {
-  let dirs = utils.iter().map(|p| p.display()).collect();
-  let display =
-    inquire::Select::new("Which util dir do you want to save your rule?", dirs).prompt()?;
-  project_dir.join(display.to_string())
-} else {
-  project_dir.join(&utils[0])
-};
+let util_dir = select_directory(
+  "Which util dir do you want to save your util?",
+  &utils,
+  &project_dir,
+  arg.yes,
+)?;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 78cd064 and 74828dd.

📒 Files selected for processing (2)
  • crates/cli/src/config.rs (5 hunks)
  • crates/cli/src/new.rs (6 hunks)
🧰 Additional context used
🔇 Additional comments (13)
crates/cli/src/config.rs (6)

57-60: Good introduction of ProjectConfig struct

Introducing the ProjectConfig struct improves configuration management by encapsulating related data, enhancing code readability and maintainability.


62-83: Well-implemented ProjectConfig methods

The methods by_config_path, by_project_dir, and find provide convenient ways to initialize project configurations, making the codebase more cohesive.


89-91: Effective use of ProjectConfig in find_rules

Refactoring to use ProjectConfig in find_rules enhances consistency in configuration handling.


123-128: Effective utilization of ProjectConfig in find_util_rules

Passing &ProjectConfig simplifies function parameters and enhances code clarity.


154-164: Consistent use of ProjectConfig in read_directory_yaml

Using ProjectConfig ensures consistency when accessing configuration data, improving maintainability.


229-230: Simplified read_config_from_dir function

Updating read_config_from_dir to return ProjectConfig streamlines configuration retrieval and aligns with the new structure.

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

161-161: Updated usage of read_config_from_dir with ProjectConfig

The function run_create_entity now correctly handles the ProjectConfig returned by read_config_from_dir, ensuring that the project configuration is appropriately utilized.


173-177: Refactored do_create_entity to accept ProjectConfig

The function signature of do_create_entity has been updated to accept ProjectConfig, and the subsequent match arms have been adjusted accordingly. The changes correctly adapt the function to the new configuration structure.


185-185: Consistent handling of ProjectConfig in ask_entity_type

The function ask_entity_type now properly uses read_config_from_dir to obtain a ProjectConfig and proceeds accordingly based on the result, maintaining consistency with the updated configuration handling.


242-246: Updated create_new_rule to utilize ProjectConfig

The function now accepts ProjectConfig and destructures it into project_dir and sg_config, allowing for clear access to project-related configurations.


252-254: Correct path construction for rule_dir

The code correctly joins project_dir with the selected or default rule_dir to determine where to save the new rule, ensuring that the rule is placed in the appropriate directory.


321-325: Adapted create_new_util to accept ProjectConfig

The function create_new_util now accepts ProjectConfig and destructures it to access project_dir and sg_config, aligning it with the updated configuration structure.


336-338: Correct path construction for util_dir

The code correctly joins project_dir with the selected or default util_dir to determine where to save the new utility, ensuring that the utility is placed in the appropriate directory.

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