Skip to content
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

Sozo: split hash command into 'hash compute' and 'hash find' #2892

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

remybar
Copy link
Contributor

@remybar remybar commented Jan 10, 2025

Description

This PR splits the existing sozo hash command into 2 subcommands:

  • sozo hash compute which does the same thing than the actual sozo hash command,
  • sozo hash find which:
    • reads namespaces and resource names from the project configuration (manifest and profile configuration) or from the command-line through --namespaces and --resources options,
    • compute namespace hashes, resource name hashes and resource tag hashes to find a match with the provided hash.

Related issue

#2850

Tests

  • Yes
  • No, because they aren't needed
  • No, because I need help

Added to documentation?

  • README.md
  • Dojo Book
  • No documentation needed

Checklist

  • I've formatted my code (scripts/prettier.sh, scripts/rust_fmt.sh, scripts/cairo_fmt.sh)
  • I've linted my code (scripts/clippy.sh, scripts/docs.sh)
  • I've commented my code
  • I've requested a review after addressing the comments

Summary by CodeRabbit

  • New Features

    • Enhanced hash command functionality with new search capabilities.
    • Added ability to find hashes across namespaces and resources.
    • Introduced a more flexible command structure for hash operations.
  • Refactor

    • Restructured hash command implementation.
    • Updated command execution to ensure proper configuration context is passed during hash operations.

Copy link

coderabbitai bot commented Jan 10, 2025

Walkthrough

Ohayo, sensei! The pull request introduces a significant refactoring of the hash command in the Sozo CLI. The changes transform the HashArgs structure from a simple input-based approach to a more flexible command-based system. A new HashCommand enum is introduced, allowing two primary operations: Compute (maintaining the original hash computation) and Find (adding the ability to search for hashes across namespaces and resources). The modification enhances the command's versatility while preserving its core functionality.

Changes

File Change Summary
bin/sozo/src/commands/hash.rs - Added HashCommand enum with Compute and Find variants
- Replaced single input field with command field
- Introduced compute() and find() methods
- Updated run() method to handle new command structure
bin/sozo/src/commands/mod.rs - Modified Hash command execution to pass configuration to run() method

Sequence Diagram

sequenceDiagram
    participant User
    participant HashCommand
    participant Config
    
    User->>HashCommand: Execute with command
    alt Compute Hash
        HashCommand->>HashCommand: compute(input)
        HashCommand-->>User: Return hash result
    else Find Hash
        HashCommand->>Config: Retrieve namespaces/resources
        HashCommand->>HashCommand: find(hash, namespaces, resources)
        HashCommand-->>User: Return matching results
    end
Loading

🪧 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. (Beta)
  • @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.

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

🧹 Nitpick comments (4)
bin/sozo/src/commands/hash.rs (4)

32-32: Ohayo! Add description for Find command, sensei!

The Find command is missing its about string which should describe its functionality.

-    #[command(about = "")]
+    #[command(about = "Search for a hash among namespaces and resource names/tags")]

65-68: Enhance error message clarity, sensei!

The error message could be more descriptive about the 32-character limit for Starknet selectors.

-                return Err(anyhow::anyhow!("Input is too long for a starknet selector"));
+                return Err(anyhow::anyhow!(
+                    "Input exceeds the 32-character limit for a Starknet selector"
+                ));

98-104: Consider performance optimization and error handling improvements, sensei!

The find method could benefit from:

  1. Early validation of input parameters
  2. Capacity hints for collections to avoid reallocations
     pub fn find(
         &self,
         config: &Config,
         hash: &String,
         namespaces: Option<Vec<String>>,
         resources: Option<Vec<String>>,
     ) -> Result<()> {
+        // Early validation of input parameters
+        if namespaces.as_ref().map_or(false, |n| n.is_empty())
+            && resources.as_ref().map_or(false, |r| r.is_empty())
+        {
+            return Err(anyhow::anyhow!(
+                "At least one namespace or resource must be provided"
+            ));
+        }

112-147: Optimize collection initialization, sensei!

Consider providing capacity hints for HashSet to avoid reallocations.

-            let mut ns_from_config = HashSet::new();
+            let mut ns_from_config = HashSet::with_capacity(10); // Adjust capacity based on expected size
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd1ccce and 80a9963.

📒 Files selected for processing (2)
  • bin/sozo/src/commands/hash.rs (3 hunks)
  • bin/sozo/src/commands/mod.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (2)
bin/sozo/src/commands/mod.rs (1)

115-115: Ohayo! LGTM, sensei!

The modification to pass the config to the hash command's run method is necessary to support the new find subcommand's functionality.

bin/sozo/src/commands/hash.rs (1)

Line range hint 223-281: Add tests for find functionality, sensei!

While the compute functionality is well-tested, there are no tests for the new find functionality. Consider adding tests for:

  • Finding namespace matches
  • Finding resource name matches
  • Finding tag matches
  • Invalid hash handling
  • Empty configuration scenarios

Would you like me to help generate these test cases?

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

🔭 Outside diff range comments (1)
bin/sozo/src/commands/hash.rs (1)

Line range hint 226-283: Let's enhance test coverage, sensei!

While the existing tests are good, we're missing tests for the new find command functionality.

Consider adding these test cases:

#[test]
fn test_hash_find_namespace() {
    let config = Config::default();
    let hash = "0x123"; // Use an actual computed namespace hash
    let args = HashArgs {
        command: HashCommand::Find {
            hash: hash.to_string(),
            namespaces: Some(vec!["test_namespace".to_string()]),
            resources: None,
        }
    };
    let result = args.find(&config, &hash.to_string(), None, None);
    assert!(result.is_ok());
}

#[test]
fn test_hash_find_with_config() {
    let config = Config::default();
    let args = HashArgs {
        command: HashCommand::Find {
            hash: "0x123".to_string(),
            namespaces: None,
            resources: None,
        }
    };
    let result = args.find(&config, &"0x123".to_string(), None, None);
    assert!(result.is_ok());
}
🧹 Nitpick comments (3)
bin/sozo/src/commands/hash.rs (3)

23-49: Well-structured command interface, sensei!

The HashCommand enum is well-designed with clear documentation. Consider adding examples in the help messages to make it even more user-friendly.

     #[command(about = "Compute the hash of the provided input.")]
     Compute {
-        #[arg(help = "Input to hash. It can be a comma separated list of inputs or a single \
-                      input. The single input can be a dojo tag or a felt.")]
+        #[arg(help = "Input to hash. It can be a comma separated list of inputs or a single \
+                      input. The single input can be a dojo tag or a felt. \
+                      Examples: 'dojo_examples-actions', '0x1,0x2,0x3'")]

Line range hint 52-97: Consider enhancing error handling and readability, sensei!

The compute method handles multiple input types well, but could benefit from:

  1. More descriptive error messages
  2. Extraction of the hash computation logic into separate functions
     pub fn compute(&self, input: &str) -> Result<()> {
         if input.is_empty() {
-            return Err(anyhow::anyhow!("Input is empty"));
+            return Err(anyhow::anyhow!("Input cannot be empty. Please provide a value to hash."));
         }
+        
+        self.compute_impl(input)
+    }
+
+    fn compute_impl(&self, input: &str) -> Result<()> {
         if input.contains('-') {
             return self.compute_tag(input);
         }

100-209: Ohayo! Let's improve the find method's organization, sensei!

The find method is comprehensive but could be more maintainable if split into smaller functions.

Consider extracting the namespace and resource collection logic into separate functions:

+    fn collect_namespaces_from_config(&self, profile_config: &ProfileConfig, manifest: &Option<Manifest>) -> Vec<String> {
+        let mut ns_from_config = HashSet::new();
+        ns_from_config.insert(profile_config.namespace.default);
+        // ... rest of namespace collection logic
+        Vec::from_iter(ns_from_config)
+    }
+
+    fn collect_resources_from_config(&self, profile_config: &ProfileConfig, manifest: &Option<Manifest>) -> Vec<String> {
+        let mut res_from_config = HashSet::new();
+        // ... rest of resource collection logic
+        Vec::from_iter(res_from_config)
+    }

Also, consider adding error handling for cases where no matches are found:

         // --- find the hash ---
+        let mut matches_found = false;
 
         // could be a namespace hash
         for ns in &namespaces {
             if hash == compute_bytearray_hash(ns) {
                 println!("Namespace found: {ns}");
+                matches_found = true;
             }
         }
+
+        if !matches_found {
+            println!("No matches found for hash: {:#066x}", hash);
+        }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 80a9963 and 9bbff84.

📒 Files selected for processing (2)
  • bin/sozo/src/commands/hash.rs (3 hunks)
  • bin/sozo/src/commands/mod.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • bin/sozo/src/commands/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (2)
bin/sozo/src/commands/hash.rs (2)

1-20: Ohayo sensei! Clean command structure implementation!

The command structure follows clap's best practices for subcommands, and the imports are well-organized.


212-221: Clean command dispatch implementation!

The run method is well-structured with proper tracing.

Copy link

codecov bot commented Jan 10, 2025

Codecov Report

Attention: Patch coverage is 31.61765% with 93 lines in your changes missing coverage. Please review.

Project coverage is 55.71%. Comparing base (5d1d308) to head (9bbff84).
Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
bin/sozo/src/commands/hash.rs 31.85% 92 Missing ⚠️
bin/sozo/src/commands/mod.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2892      +/-   ##
==========================================
- Coverage   55.77%   55.71%   -0.06%     
==========================================
  Files         446      449       +3     
  Lines       57794    57772      -22     
==========================================
- Hits        32234    32188      -46     
- Misses      25560    25584      +24     

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

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