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

feat(sozo): Add --output-manifest option to sozo inspect #2952

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

Conversation

knownasred
Copy link

@knownasred knownasred commented Jan 26, 2025

Description

Adds a --output-manifest option to sozo inspect that will output the generated manifest to stdout.
Useful for scripts and to generate the frontend on the fly, removing the requirement of committing the manifest to git

Related issue

Fixes #2878

Tests

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

Added to documentation?

TODO: Add a PR to the dojo book adding documentation for the inspect command

  • 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

Summary by CodeRabbit

  • New Features

    • Added options to generate and output a world manifest during inspection.
    • Introduced ability to force manifest generation even when the world is not fully synced.
  • Improvements

    • Enhanced command-line inspection capabilities with more flexible manifest generation controls.

Copy link

coderabbitai bot commented Jan 26, 2025

Walkthrough

Ohayo, sensei! The changes introduce new capabilities to the InspectArgs struct in the inspect.rs file. Two new fields, output_manifest and force, have been added to provide more flexible manifest generation options. The implementation allows users to generate a JSON manifest on demand, with additional control over the generation process when the world's deployment status might not be perfectly synchronized.

Changes

File Change Summary
bin/sozo/src/commands/inspect.rs - Added output_manifest: bool and force: bool to InspectArgs struct
- Implemented generate_manifest() function for JSON manifest creation
- Updated run() method to handle new manifest generation logic

Assessment against linked issues

Objective Addressed Explanation
Manifest generation on demand [#2878]
Support JSON manifest output
Handle world synchronization states

Sequence Diagram

sequenceDiagram
    participant User
    participant InspectCommand
    participant WorldDiff
    participant ManifestGenerator

    User->>InspectCommand: sozo inspect --output-manifest
    InspectCommand->>WorldDiff: Check world status
    alt World is deployed and synced
        WorldDiff->>ManifestGenerator: Generate Manifest
        ManifestGenerator-->>User: Output JSON Manifest
    else World not synced
        alt Force flag is true
            WorldDiff->>ManifestGenerator: Generate Manifest with Warning
            ManifestGenerator-->>User: Output JSON Manifest
        else Force flag is false
            WorldDiff-->>User: Return Synchronization Error
        end
    end
Loading

Sensei, the implementation looks solid and addresses the key requirements for on-demand manifest generation! 🍵🥋


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 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 (3)
bin/sozo/src/commands/inspect.rs (3)

24-35: Ohayo! Consider adding a short form for the --output-manifest flag.

The CLI arguments are well-structured, but for consistency with -f, consider adding a short form (e.g., -o) for the --output-manifest flag.

 #[arg(
     long = "output-manifest",
+    short = 'o',
     help = "Outputs the generated manifest to stdout in JSON format."
 )]

49-63: Maintain naming consistency, sensei!

The field output_manifest is renamed to export_manifest during destructuring. Let's keep the naming consistent to avoid confusion.

-let InspectArgs { world, starknet, resource, output_manifest: export_manifest, force } =
+let InspectArgs { world, starknet, resource, output_manifest, force } =
     self;

 config.tokio_handle().block_on(async {
     let (world_diff, _, _) =
         utils::get_world_diff_and_provider(starknet.clone(), world, &ws).await?;

-    if export_manifest {
+    if output_manifest {

514-536: Add documentation for the generate_manifest function.

Consider adding documentation comments to explain:

  • The purpose of the function
  • The meaning of the force parameter
  • The format of the generated manifest
+/// Generates a JSON manifest of the world's current state.
+///
+/// # Arguments
+/// * `world_diff` - The world diff containing the current state
+/// * `force` - If true, generates the manifest even if the world is not synced
+///
+/// # Returns
+/// * `Ok(())` if the manifest was generated successfully
+/// * `Err` if the world is not deployed or not synced (unless forced)
 fn generate_manifest(world_diff: &WorldDiff, force: bool) -> Result<()> {

Also, consider extracting error messages as constants for reusability:

+const ERR_WORLD_NOT_DEPLOYED: &str = "No world is deployed at address {}!";
+const ERR_WORLD_NOT_SYNCED: &str = "The world is not up to date. Use --force to generate the manifest anyway.";
+const WARN_FORCED_GENERATION: &str = "Warning: The world is not up to date, but generation is forced. The generated manifest might not represent the remote world.";

 fn generate_manifest(world_diff: &WorldDiff, force: bool) -> Result<()> {
     if world_diff.world_info.status == WorldStatus::NotDeployed {
         let formatted_address = format!("{:#066x}", world_diff.world_info.address).green();
-        return Err(anyhow!("No world is deployed at address {}!", formatted_address));
+        return Err(anyhow!(ERR_WORLD_NOT_DEPLOYED, formatted_address));
     }

     // Check if there is some contracts that are not up to date.
     if !world_diff.is_synced() {
         if !force {
-            return Err(anyhow!(
-                "The world is not up to date. Use --force to generate the manifest anyway."
-            ));
+            return Err(anyhow!(ERR_WORLD_NOT_SYNCED));
         } else {
-            eprintln!("Warning: The world is not up to date, but generation is forced. The generated manifest might not represent the remote world.");
+            eprintln!("{}", WARN_FORCED_GENERATION);
         }
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b722fd and cb7aacb.

📒 Files selected for processing (1)
  • bin/sozo/src/commands/inspect.rs (4 hunks)
🔇 Additional comments (1)
bin/sozo/src/commands/inspect.rs (1)

513-514: Address the TODO comment, sensei!

Consider moving this function to a more appropriate module, perhaps alongside other manifest-related functionality.

Let's check for other manifest-related code:

✅ Verification successful

Ohayo! Move generate_manifest to manifest.rs, sensei!

The generate_manifest function should be moved to crates/dojo/world/src/diff/manifest.rs as this module:

  • Is the central place for manifest-related functionality
  • Already handles WorldDiff to Manifest conversion
  • Contains related manifest generation code
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for manifest-related code
rg -l "Manifest" --type rust

Length of output: 430


Script:

#!/bin/bash
# Check the content of manifest.rs to verify it's the right context
cat crates/dojo/world/src/diff/manifest.rs

Length of output: 7815

@knownasred knownasred force-pushed the feat/output-manifest branch from cb7aacb to 971f8ef Compare January 26, 2025 17:59
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)
bin/sozo/src/commands/inspect.rs (3)

24-36: Ohayo! Consider enhancing the CLI argument documentation.

The help text for the --force flag could better explain the potential implications of forcing manifest generation when the world is not up to date. Also, consider if -o might conflict with other common CLI patterns (e.g., --output).

     #[arg(
         long = "output-manifest",
-        short = 'o',
         help = "Outputs the generated manifest to stdout in JSON format."
     )]
     output_manifest: bool,

     #[arg(
         long = "force",
         short = 'f',
-        help = "Force the generation of the manifest, even if the world is not up to date."
+        help = "Force the generation of the manifest, even if the world is not up to date. Warning: The generated manifest might not accurately represent the remote world state."
     )]
     force: bool,

57-64: Ohayo sensei! Consider flattening the nested if-else block.

The code is functionally correct, but readability could be improved by flattening the nested if-else structure.

-            if output_manifest {
-                generate_manifest(&world_diff, force)?;
-            } else {
-                if let Some(resource) = resource {
-                    inspect_resource(&resource, &world_diff)?;
-                } else {
-                    inspect_world(&world_diff);
-                }
-            }
+            if output_manifest {
+                return generate_manifest(&world_diff, force);
+            }
+            
+            if let Some(resource) = resource {
+                inspect_resource(&resource, &world_diff)?;
+            } else {
+                inspect_world(&world_diff);
+            }

514-539: Ohayo! A few suggestions to enhance error handling and user experience.

  1. The error message for NotDeployed status shows the address in green, which might be confusing in an error context
  2. The warning message could be more visible
  3. Consider wrapping errors with context
     if world_diff.world_info.status == WorldStatus::NotDeployed {
-        let formatted_address = format!("{:#066x}", world_diff.world_info.address).green();
+        let formatted_address = format!("{:#066x}", world_diff.world_info.address).red();
         return Err(anyhow!("No world is deployed at address {}!", formatted_address));
     }

     // Check if there is some contracts that are not up to date.
     if !world_diff.is_synced() {
         if !force {
-            return Err(anyhow!(
+            return Err(anyhow!(
                 "The world is not up to date. Use --force to generate the manifest anyway."
-            ));
+            ).context("Manifest generation failed"));
         } else {
-            eprintln!("Warning: The world is not up to date, but generation is forced. The generated manifest might not represent the remote world.");
+            eprintln!("{}", "WARNING: The world is not up to date, but generation is forced.".yellow());
+            eprintln!("{}", "The generated manifest might not represent the remote world.".yellow());
         }
     }

     let manifest = Manifest::new(&world_diff);

-    println!("{}", serde_json::to_string_pretty(&manifest)?);
+    println!("{}", serde_json::to_string_pretty(&manifest).context("Failed to serialize manifest")?);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cb7aacb and 971f8ef.

📒 Files selected for processing (1)
  • bin/sozo/src/commands/inspect.rs (4 hunks)

@knownasred knownasred force-pushed the feat/output-manifest branch from 971f8ef to 1cd6701 Compare January 27, 2025 19:34
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)
bin/sozo/src/commands/inspect.rs (3)

50-64: Ohayo! Let's improve the control flow, sensei!

The logic is correct, but we can make it more readable by flattening the nested if-else structure.

Consider this refactor:

-            if output_manifest {
-                generate_manifest(&world_diff, force)?;
-            } else {
-                if let Some(resource) = resource {
-                    inspect_resource(&resource, &world_diff)?;
-                } else {
-                    inspect_world(&world_diff);
-                }
-            }
+            if output_manifest {
+                return generate_manifest(&world_diff, force);
+            }
+            
+            if let Some(resource) = resource {
+                inspect_resource(&resource, &world_diff)?;
+                return Ok(());
+            }
+            
+            inspect_world(&world_diff);
+            Ok(())

519-520: Ohayo! Let's adjust the error message color, sensei!

Using green color for an address in an error message might be confusing. Consider using a neutral or error-indicating color.

-        let formatted_address = format!("{:#066x}", world_diff.world_info.address).green();
+        let formatted_address = format!("{:#066x}", world_diff.world_info.address).red();

526-528: Consider providing more specific error information, sensei!

The error message could be more helpful by indicating which specific aspects of the world are not up to date.

-                "The world is not up to date. Use --force to generate the manifest anyway."
+                "The world is not up to date (some contracts need deployment or initialization). Use --force to generate the manifest anyway."
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 971f8ef and 1cd6701.

📒 Files selected for processing (1)
  • bin/sozo/src/commands/inspect.rs (4 hunks)
🔇 Additional comments (2)
bin/sozo/src/commands/inspect.rs (2)

24-36: Ohayo! The CLI args are well-structured, sensei!

The new options follow CLI best practices with clear help messages and conventional short/long option naming.


514-539: Ohayo! Overall implementation looks solid, sensei!

The new manifest generation feature is well-implemented with proper error handling and user feedback. It successfully addresses the PR objective of enabling frontend generation on the fly.

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.

Thanks for the contribution here @knownasred.

Reading this, we may go directly to the fully remote generated manifest, to avoid confusion and maybe errors in using a manifest into a client application.

This way, as you have mentioned, one with sozo installed and the world_address is able to reconstruct the manifest.

Do you need any pointers to go this way, or it's clear where you will have to modify code for that?

sozo inspect is the good place to have this --output-manifest flag. 👍

@glihm glihm marked this pull request as draft January 30, 2025 22:17
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.

Manifest generation on demand
2 participants