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

bugfix: use the '<namespace>__<name>' format for model contract names #2406

Closed

Conversation

remybar
Copy link
Contributor

@remybar remybar commented Sep 10, 2024

Description

To avoid having conflicts between several models with a same name but in different namespaces, the model contract name now follow the following format: <namespace>__<name>.

Note that the double underscore __ is used as the separator between namespace and name. That means it should not be used in namespace and name. So, we probably should raise a warning/error if it's the case.

Related issue

#2349

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 naming conventions for various models and events to improve clarity and organization.
    • Introduced new contract selector structures for better contract path management.
  • Bug Fixes

    • Updated references in model registrations and event names to prevent potential conflicts and improve functionality.
    • Revised expected values in test assertions to align with updated logic and behavior.
  • Chores

    • Cleaned up import statements in the codebase to streamline dependencies and improve maintainability.
    • Modified formatting scripts to allow users to choose between checking and applying formatting.

Copy link

coderabbitai bot commented Sep 10, 2024

Walkthrough

Ohayo, sensei! The changes in this pull request involve renaming various models and adjusting their namespaces throughout the Dojo framework. This restructuring aims to enhance clarity and consistency in model references, ensuring that class hashes and identifiers align with the new naming conventions. Modifications include updates to import statements, model registrations, and JSON configuration files, while maintaining the core functionality of the code.

Changes

Files Change Summary
crates/dojo-core/src/tests/... Renamed models and references from foo, case, and others to prefixed forms like dojo__foo, dojo__case, etc., across multiple test files.
crates/dojo-lang/src/compiler.rs, model.rs Renamed contract selector types and updated functionalities, introducing DojoContractSelector and modifying naming conventions.
examples/spawn-and-move/manifests/.../*.json Updated event names and model configurations to include new prefixes, enhancing namespace clarity while modifying class hashes and qualified paths.
examples/spawn-and-move/src/actions.cairo Removed unnecessary imports and streamlined import statements for clarity and efficiency in the tests.
crates/sozo/ops/src/tests/model.rs Updated expected values in test assertions for the test_model_ops function, reflecting changes in the underlying logic or behavior of model operations.
scripts/cairo_fmt.sh, rust_fmt.sh Enhanced formatting scripts to allow conditional execution for checking or fixing formatting based on command-line arguments.

Possibly related issues

Possibly related PRs

  • opt(torii): avoid calculating poseidon hash where possible #2394: The changes in the main PR involve renaming imports and references in the benchmarks.cairo file, while the retrieved PR focuses on optimizing the Poseidon hash calculations in the Torii module, which does not relate to the code changes made in the main PR.

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between bcc6f9b and 0aa518c.

Files selected for processing (3)
  • crates/sozo/ops/src/tests/model.rs (2 hunks)
  • scripts/cairo_fmt.sh (1 hunks)
  • scripts/rust_fmt.sh (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • crates/sozo/ops/src/tests/model.rs
  • scripts/cairo_fmt.sh
  • scripts/rust_fmt.sh

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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

Outside diff range, codebase verification and nitpick comments (3)
examples/spawn-and-move/manifests/dev/base/abis/models/dojo_examples-Position-1e145e26.json (1)

417-417: Ohayo sensei! Update references to the old event name.

The event name dojo_examples::models::position::Event still appears in the following files, which need to be updated to the new format to ensure consistency and avoid breaking dependencies:

  • crates/dojo-lang/src/manifest_test_data/manifest
  • bin/sozo/tests/test_data/manifest.json

Please update these references to align with the new event name format.

Analysis chain

Ohayo sensei! The event name change looks good and aligns with the PR objective.

The event name has been updated to follow the <namespace>__<name> format, which enhances clarity and consistency in model referencing. This change is consistent with the overall goal of the pull request.

To ensure the event name change does not break any dependencies, please run the following verification script:


Ohayo sensei! Let's re-run the verification with a corrected approach. I'll search for the old event name across all files to ensure no dependencies are broken. Please hold on.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the event name change does not break any dependencies.

# Test: Search for references to the old event name. Expect: No results.
rg --type cairo --type rust $'dojo_examples::models::position::Event'

Length of output: 98


Script:

#!/bin/bash
# Description: Verify the event name change does not break any dependencies.

# Test: Search for references to the old event name across all files.
rg 'dojo_examples::models::position::Event'

Length of output: 251

crates/dojo-lang/src/model.rs (2)

Line range hint 99-141: Ohayo sensei! The code for parsing model parameters looks mostly good to me, but I have a couple of nitpicks.

  1. The processed_args hashmap can be replaced with a simpler boolean flag for each argument to track duplicates. This will make the code more readable and efficient.

  2. The match on arg_name can be replaced with if conditions for better readability. Something like:

if arg_name == MODEL_VERSION_NAME {
    parameters.version = get_model_version(db, arg_value, diagnostics);
} else if arg_name == MODEL_NAMESPACE {
    parameters.namespace = get_model_namespace(db, arg_value, diagnostics);
} else if arg_name == MODEL_NOMAPPING {
    parameters.nomapping = true;
} else {
    diagnostics.push(PluginDiagnostic { ... });
}

Line range hint 154-704: Ohayo sensei! The handle_model_struct function works but it's quite complex and can be improved.

Here are some suggestions to refactor it:

  1. Break it down into smaller functions for better readability and maintainability. For example, separate functions can be created for:

    • Validating names
    • Generating hashes and selectors
    • Processing struct members to generate keys, values, and accessors
    • Interpolating the final code template
  2. Add more comments explaining what each section of the code is doing. The function is quite long, so comments will help future readers understand the code better.

  3. Use more descriptive variable names, especially for the interpolation variables in the large code template at the end. Names like type_name, model_version, serialized_keys etc. are a bit generic and not very descriptive in the context of this function.

  4. Consider moving the large code template string to a separate file or constant. It will declutter this function and the template can be reused elsewhere if needed.

Let me know if you would like me to submit a PR with these refactorings!

@remybar remybar force-pushed the bugfix-avoid_same_model_contract_names branch from f2a90cf to ac2d311 Compare September 10, 2024 14:09
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, codebase verification and nitpick comments (2)
examples/spawn-and-move/manifests/dev/base/models/dojo_examples-Position-1e145e26.toml (1)

2-3: Ohayo sensei! It looks like some references to the old qualified path still linger in the codebase.

To keep everything consistent and avoid any potential hiccups, please update all occurrences of dojo_examples::models::position to dojo_examples::models::dojo_examples__position. Here are the files that need attention:

  • crates/dojo-lang/src/manifest_test_data/manifest
  • bin/sozo/tests/test_data/manifest.json

Make sure these changes are reflected throughout the codebase to ensure everything runs smoothly. Keep up the great work, sensei!

Analysis chain

Ohayo sensei! The changes to the class_hash, original_class_hash, and qualified_path are consistent with the PR objectives.

The modifications indicate a change in the underlying class representation and a restructuring or renaming of the model's namespace. Please ensure that these changes are propagated throughout the codebase and that all references to this model are updated accordingly.

To verify the impact of these changes on other parts of the codebase, you can run the following script:

Also applies to: 6-6


Ohayo sensei! It seems like the initial verification didn't give us the clarity we need. Let's dig a bit deeper to ensure everything's in order. I'll run some additional checks to verify the propagation of the changes. Hang tight!

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all references to the `Position` model have been updated.

# Test 1: Search for the old qualified path. Expect: No occurrences.
rg --type rust $'dojo_examples::models::position'

# Test 2: Search for the new qualified path. Expect: Only occurrences of the new path.
rg --type rust $'dojo_examples::models::dojo_examples__position'

Length of output: 112


Script:

#!/bin/bash
# Re-run the search with a broader scope and check for potential errors.

# Test 1: Search for the old qualified path in all files. Expect: No occurrences.
rg 'dojo_examples::models::position' --glob '*'

# Test 2: Search for the new qualified path in all files. Expect: Only occurrences of the new path.
rg 'dojo_examples::models::dojo_examples__position' --glob '*'

Length of output: 1711

examples/spawn-and-move/manifests/dev/deployment/abis/models/dojo_examples-Moves-2e2accba.json (1)

433-433: Ohayo sensei! There's a lingering reference to the old event name.

The event name dojo_examples::models::moves::Event is still present in bin/sozo/tests/test_data/manifest.json. Please update this reference to the new format dojo_examples::models::dojo_examples__moves::Event to ensure consistency across the codebase.

  • File to update:
    • bin/sozo/tests/test_data/manifest.json
Analysis chain

Ohayo sensei! The event name change looks good, but please verify the usage.

The event name change is consistent with the PR objective of using the <namespace>__<name> format for model contract names.

However, this change may impact how the event is referenced in other parts of the codebase. Please ensure that all references to this event have been updated to use the new name.

Run the following script to verify the event usage:


Ohayo sensei! Let's make sure everything's in order. I'll run a couple of checks to verify the event name change.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all references to the `dojo_examples::models::moves::Event` event have been updated to use the new name.

# Test: Search for the old event name. Expect: No occurrences of the old name.
rg --type cairo --type rust $'dojo_examples::models::moves::Event'

Length of output: 95


Script:

#!/bin/bash
# Search for the old event name across all file types to ensure it's not being used anymore.
rg 'dojo_examples::models::moves::Event' --glob '*.*' -A 2

Length of output: 283


Script:

#!/bin/bash
# Search for the new event name to confirm its usage in the codebase.
rg 'dojo_examples::models::dojo_examples__moves::Event' --glob '*.*' -A 2

Length of output: 1540

@remybar remybar force-pushed the bugfix-avoid_same_model_contract_names branch 2 times, most recently from 924a9e1 to d9cae6e Compare September 10, 2024 20:05
Copy link

codecov bot commented Sep 11, 2024

Codecov Report

Attention: Patch coverage is 95.38462% with 3 lines in your changes missing coverage. Please review.

Project coverage is 67.97%. Comparing base (6112180) to head (0aa518c).
Report is 28 commits behind head on main.

Files with missing lines Patch % Lines
crates/dojo-lang/src/compiler.rs 92.68% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2406      +/-   ##
==========================================
- Coverage   68.13%   67.97%   -0.17%     
==========================================
  Files         364      364              
  Lines       47712    47818     +106     
==========================================
- Hits        32509    32503       -6     
- Misses      15203    15315     +112     

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

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Thank you @remybar for the work on that.

I'm trying to see any other option than having an arbitrary separator that may be messed up depending on how the user names the contract.

But it seems we don't have much alternative for now.

Comment on lines 90 to 105
let (source_path, source_name) =
contract_path.rsplit_once(CAIRO_PATH_SEPARATOR).unwrap_or(("", &contract_path));
let (_, source_name) =
source_name.rsplit_once(naming::DOJO_CONTRACT_SEPARATOR).unwrap_or(("", source_name));

let (path, name) = self.0.rsplit_once(CAIRO_PATH_SEPARATOR).unwrap_or(("", &self.0));
let name = name.to_case(Case::Snake);

source_path == path && source_name == name
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

We're not including the namespace in the comparison here, may we have conflicts at some point?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In fact, this match_contract_path function is used for external contracts only (the ones specified in Scarb.toml). I don't know if these external contracts can have a namespace in their names 🤔
But, for the spawn-and-move example, we have 2 external contracts without namespace (for example, the contract selector bestiary::RiverSkale must be matched with the contract path bestiary::dojo_examples_foes__river_skale).

So, I propose to compare namespaces if and only if the contract selector contains a namespace. But, in case of namespace remapping, is it possible to have an external contract with a namespace in its name remapped to another namespace ?

crates/dojo-lang/src/compiler.rs Show resolved Hide resolved
@remybar remybar force-pushed the bugfix-avoid_same_model_contract_names branch from 35157ed to bcc6f9b Compare September 11, 2024 06:48
@remybar
Copy link
Contributor Author

remybar commented Sep 11, 2024

I'm trying to see any other option than having an arbitrary separator that may be messed up depending on how the user names the contract.

But it seems we don't have much alternative for now.

Yes, I agree but I think it's not a really big constraint to avoid using __ in a struct name (for models or events) or in a contract name (for contracts). And we can check it at compile time to raise a warning/error to inform the dev and avoid him searching for hours why something fails 😅

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Comment on lines +4599 to +4605
"name": "dojo_examples::models::dojo_examples__moves::Event",
"kind": "enum",
"variants": []
}
],
"tag": "dojo_examples-Moves",
"qualified_path": "dojo_examples::models::moves",
"qualified_path": "dojo_examples::models::dojo_examples__moves",
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ohayo sensei! It looks like we've got a bit of a mix-up with the moves::Event references. Some files are using the new path dojo_examples::models::dojo_examples__moves::Event, while others are still rocking the old path dojo_examples::models::moves::Event.

Here's what needs attention:

  • Update all references to dojo_examples::models::dojo_examples__moves::Event to ensure consistency across the codebase.

Let's get those paths aligned to avoid any hiccups!

Analysis chain

Ohayo sensei! The renaming of moves event looks good to me.

The new name and qualified_path values enhance clarity by distinctly categorizing the event under the dojo_examples module.

However, please ensure that this change is thoroughly tested and validated to confirm that it behaves as expected and that all references to the moves event have been updated to match the new paths.

Run the following script to verify the event usage:


Ohayo sensei! Let's try a different approach to verify the usage of moves::Event in the codebase. I'll adjust the search command to look through all files and ensure everything aligns with the new paths.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all references to `moves` event match the new paths.

# Test: Search for the event usage. Expect: Only occurrences of the new paths.
rg --type cairo -A 5 $'moves::Event'

Length of output: 65


Script:

#!/bin/bash
# Description: Verify all references to `moves` event match the new paths.

# Test: Search for the event usage across all files.
rg -A 5 $'moves::Event'

Length of output: 3118

Comment on lines +3684 to +3690
"name": "dojo_examples::models::dojo_examples__mock_token::Event",
"kind": "enum",
"variants": []
}
],
"tag": "dojo_examples-MockToken",
"qualified_path": "dojo_examples::models::mock_token",
"qualified_path": "dojo_examples::models::dojo_examples__mock_token",
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ohayo sensei! There's an inconsistency in the mock_token::Event references.

The codebase contains both the new path dojo_examples::models::dojo_examples__mock_token::Event and an incorrect path dojo_examples::mock_token::mock_token::Event. Please review and update all references to ensure consistency with the new naming convention.

  • Inconsistent References: Ensure all references to mock_token::Event are updated to dojo_examples::models::dojo_examples__mock_token::Event.

This will help maintain clarity and prevent potential issues.

Analysis chain

Ohayo sensei! The renaming of mock_token event looks good to me.

The new name and qualified_path values enhance clarity by distinctly categorizing the event under the dojo_examples module.

However, please ensure that this change is thoroughly tested and validated to confirm that it behaves as expected and that all references to the mock_token event have been updated to match the new paths.

Run the following script to verify the event usage:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all references to `mock_token` event match the new paths.

# Test: Search for the event usage. Expect: Only occurrences of the new paths.
rg --type cairo -A 5 $'mock_token::Event'

Length of output: 70


Script:

#!/bin/bash
# Description: Verify all references to `mock_token` event match the new paths.

# Test: Search for the event usage without specifying a file type.
rg -A 5 'mock_token::Event'

Length of output: 5462

@remybar
Copy link
Contributor Author

remybar commented Sep 20, 2024

Replaced by #2457.

@remybar remybar closed this Sep 20, 2024
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.

2 participants