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

fix(zmodel): prefer to use triple-slash comments as ZModel documentation #1817

Merged
merged 3 commits into from
Oct 30, 2024

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Oct 29, 2024

fixes #1815 #1816

@ymc9 ymc9 marked this pull request as ready for review October 29, 2024 21:52
Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduce a new ZModelDocumentationProvider class that enhances documentation retrieval for AST nodes by processing comments and integrating with existing JSDoc functionality. The ZModelModule is updated to register this new documentation provider, and the ZModelWorkspaceManager class is modified to change its export style and improve plugin model handling. Additionally, the PrismaSchemaGenerator class is updated to refine comment formatting, while the starter.zmodel file's comment style is standardized. The test suite for the Prisma generator is expanded to cover new schema features and ensure comprehensive testing.

Changes

File Path Change Summary
packages/schema/src/language-server/zmodel-documentation-provider.ts - Added ZModelDocumentationProvider class.
- Implemented `getDocumentation(node: AstNode): string
packages/schema/src/language-server/zmodel-module.ts - Added DocumentationProvider method to register ZModelDocumentationProvider.
- Updated import for ZModelWorkspaceManager to named import.
packages/schema/src/language-server/zmodel-workspace-manager.ts - Changed export of ZModelWorkspaceManager from default to named export.
- Enhanced initializeWorkspace and loadPluginModels methods for better plugin handling.
packages/schema/src/plugins/prisma/schema-generator.ts - Updated comment formatting for model fields and enums in PrismaSchemaGenerator.
packages/schema/src/res/starter.zmodel - Changed comment style from block to single-line comments for various model declarations.
packages/schema/tests/generator/prisma-generator.test.ts - Added new models and fields in test cases, including enum Role and updated User model with access control attributes.

Assessment against linked issues

Objective Addressed Explanation
Support triple slash documentation in ZModel (#1815)

Possibly related PRs

  • fix: compatibility with Prisma's "omit" feature #1432: The changes in this PR involve handling comments and attributes, which may relate to the documentation retrieval aspect of the ZModelDocumentationProvider class introduced in the main PR.
  • OpenApi @@id support #1757: This PR enhances the handling of compound IDs in the OpenAPI generator, which could relate to the documentation generation aspect of the ZModelDocumentationProvider as it may need to accommodate complex data structures.
  • Improve working with entities related to entities that uses compound ids #1801: This PR focuses on improving the handling of entities with compound IDs, which is relevant to the documentation retrieval logic in the ZModelDocumentationProvider, especially if those entities are part of the AST nodes being documented.

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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
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 (8)
packages/schema/src/language-server/zmodel-documentation-provider.ts (2)

8-8: Fix typo in the comment.

Change "prefer to user" to "prefer to use".

-        // prefer to user triple-slash comments
+        // prefer to use triple-slash comments

7-16: Add JSDoc documentation for the method.

The method override should include JSDoc documentation describing its purpose and return type.

Add this documentation above the method:

+    /**
+     * Retrieves documentation for an AST node, preferring triple-slash comments over JSDoc comments.
+     * @param node The AST node to get documentation for
+     * @returns The documentation string if found, undefined otherwise
+     */
     getDocumentation(node: AstNode): string | undefined {
packages/schema/src/language-server/zmodel-workspace-manager.ts (2)

Line range hint 44-57: Add defensive programming for plugin detection.

The plugin detection logic could be more robust by adding null checks and validation.

Consider applying these improvements:

 documents.forEach((doc) => {
     const parsed = doc.parseResult.value as Model;
-    parsed.declarations.forEach((decl) => {
+    if (!parsed?.declarations) {
+        console.warn(`Invalid model structure in document: ${doc.uri}`);
+        return;
+    }
+    parsed.declarations.forEach((decl) => {
         if (isPlugin(decl)) {
             const providerField = decl.fields.find((f) => f.name === 'provider');
-            if (providerField) {
+            if (providerField?.value) {
                 const provider = getLiteral<string>(providerField.value);
                 if (provider) {
                     this.pluginModels.add(provider);
+                } else {
+                    console.warn(`Invalid provider value in plugin declaration: ${doc.uri}`);
                 }
             }
         }
     });
 });

Line range hint 95-107: Improve stability of directory sorting.

The current sort function might lead to unstable sorting results. Non-node_modules directories always return 1, and non-directory entries return 0, which might not maintain their relative order.

Consider this improved implementation:

-        ).sort((a, b) => {
-            // make sure the node_moudules folder is always the first one to be checked
-            // so it could be early exited if the plugin is found
-            if (a.isDirectory && b.isDirectory) {
-                const aName = Utils.basename(a.uri);
-                if (aName === 'node_modules') {
-                    return -1;
-                } else {
-                    return 1;
-                }
-            } else {
-                return 0;
-            }
+        ).sort((a, b) => {
+            const aName = Utils.basename(a.uri);
+            const bName = Utils.basename(b.uri);
+            
+            // Prioritize directories over files
+            if (a.isDirectory !== b.isDirectory) {
+                return a.isDirectory ? -1 : 1;
+            }
+            
+            // Among directories, prioritize node_modules
+            if (a.isDirectory && b.isDirectory) {
+                if (aName === 'node_modules') return -1;
+                if (bName === 'node_modules') return 1;
+            }
+            
+            // Maintain stable order for everything else
+            return aName.localeCompare(bName);
         });
packages/schema/src/language-server/zmodel-module.ts (1)

81-83: LGTM: Documentation provider registration follows best practices.

The registration of ZModelDocumentationProvider is well-integrated into the module's dependency injection system and follows Langium's architectural patterns.

Consider documenting the documentation provider's capabilities in the module's JSDoc comments, similar to the "Declaration of custom services" comment above, to help other developers understand its role in the architecture.

packages/schema/src/plugins/prisma/schema-generator.ts (2)

288-291: LGTM! Consider extracting the comment formatting logic.

The implementation correctly handles non-Prisma attributes by converting them to triple-slash comments. The underscore wrapping ('/// - _' + ... + '_') helps distinguish attributes in the documentation.

Consider extracting the comment formatting logic into a helper function to improve reusability and maintain consistency:

+private formatAttributeComment(attr: DataModelAttribute): string {
+    return '/// - _' + this.zModelGenerator.generate(attr) + '_';
+}
+
 decl.attributes
     .filter((attr) => attr.decl.ref && !this.isPrismaAttribute(attr))
-    .forEach((attr) => model.addComment('/// - _' + this.zModelGenerator.generate(attr) + '_'));
+    .forEach((attr) => model.addComment(this.formatAttributeComment(attr)));

903-906: LGTM! Apply the same helper function here.

The implementation mirrors the model attribute handling, maintaining consistency in how non-Prisma attributes are converted to comments.

Use the same helper function suggested earlier to maintain consistency:

 decl.attributes
     .filter((attr) => attr.decl.ref && !this.isPrismaAttribute(attr))
-    .forEach((attr) => _enum.addComment('/// - _' + this.zModelGenerator.generate(attr) + '_'));
+    .forEach((attr) => _enum.addComment(this.formatAttributeComment(attr)));
packages/schema/tests/generator/prisma-generator.test.ts (1)

72-78: Consider using triple-slash comments for the Post model documentation

To maintain consistency with the preferred documentation style of triple-slash comments (///), consider updating the Post model's documentation accordingly.

Apply the following diff to update the documentation:

-/**
-  * My post model
-  * defined here
-  */
+/// My post model
+/// defined here
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 77817f5 and f7bf471.

📒 Files selected for processing (6)
  • packages/schema/src/language-server/zmodel-documentation-provider.ts (1 hunks)
  • packages/schema/src/language-server/zmodel-module.ts (2 hunks)
  • packages/schema/src/language-server/zmodel-workspace-manager.ts (1 hunks)
  • packages/schema/src/plugins/prisma/schema-generator.ts (4 hunks)
  • packages/schema/src/res/starter.zmodel (3 hunks)
  • packages/schema/tests/generator/prisma-generator.test.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/schema/src/res/starter.zmodel
🔇 Additional comments (9)
packages/schema/src/language-server/zmodel-documentation-provider.ts (2)

1-6: LGTM! Clean and well-documented class declaration.

The class is properly documented and follows a good inheritance pattern by extending JSDocDocumentationProvider.


1-16: Verify integration and existing usage.

Let's ensure this implementation works well with existing code.

✅ Verification successful

Let me check the module registration to ensure proper integration.


Implementation is properly integrated and working as expected

The verification shows:

  • The documentation provider is correctly registered in the module system (zmodel-module.ts)
  • Triple-slash comments are already in use across .zmodel files with proper formatting
  • The implementation handles both documentation styles:
    • Triple-slash comments (e.g., /// User model)
    • Falls back to JSDoc when triple-slash isn't present
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the registration and usage of the documentation provider

# Test 1: Check if the provider is properly registered in the module system
echo "Checking module registration..."
rg -l "ZModelDocumentationProvider" --type ts

# Test 2: Check existing triple-slash comment usage in .zmodel files
echo "Checking existing triple-slash comments in .zmodel files..."
rg "^///" --type-add 'zmodel:*.zmodel' --type zmodel -A 1

Length of output: 1583


Script:

#!/bin/bash
# Check how ZModelDocumentationProvider is registered in the module system
echo "Checking ZModelDocumentationProvider registration in zmodel-module.ts..."
rg -A 5 "ZModelDocumentationProvider" packages/schema/src/language-server/zmodel-module.ts

# Check if there are any other documentation providers or related configurations
echo "Checking for other documentation provider configurations..."
ast-grep --pattern 'createZModelServices($$$) {
  $$$
}'

Length of output: 1033

packages/schema/src/language-server/zmodel-workspace-manager.ts (1)

12-12: Verify import statements across the codebase.

The change from default export to named export is a breaking change that requires updates to all importing files.

✅ Verification successful

Let me fix the regex syntax and try again to verify the imports.


Export change is safe and properly referenced

The change from default to named export is correctly handled. The class is only imported in one place (zmodel-module.ts) and it's already using the correct named import syntax. No other files in the codebase are affected by this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all imports of ZModelWorkspaceManager to ensure they're updated
# Test: Search for both default and named import patterns
echo "Checking for potentially outdated default imports..."
rg "import\s+ZModelWorkspaceManager\s+from" -g '!*.{md,json}' || true

echo -e "\nChecking current named imports..."
rg "import\s*{\s*ZModelWorkspaceManager\s*}" -g '!*.{md,json}' || true

Length of output: 472


Script:

#!/bin/bash
# Description: Find all imports of ZModelWorkspaceManager to ensure they're updated
# Test: Search for both default and named import patterns
echo "Checking for potentially outdated default imports..."
rg "import ZModelWorkspaceManager from" -g '!*.{md,json}' || true

echo -e "\nChecking current named imports..."
rg "import.*\{.*ZModelWorkspaceManager.*\}" -g '!*.{md,json}' || true

# Also check for any other references to ZModelWorkspaceManager
echo -e "\nChecking all references to ZModelWorkspaceManager..."
rg "ZModelWorkspaceManager" -g '!*.{md,json}' || true

Length of output: 1008

packages/schema/src/language-server/zmodel-module.ts (1)

30-30: LGTM: Import changes are well-structured.

The new import for ZModelDocumentationProvider and the updated import style for ZModelWorkspaceManager are correctly placed and align with the module's organization.

Also applies to: 37-37

packages/schema/src/plugins/prisma/schema-generator.ts (2)

768-770: LGTM! Clean implementation of comment handling.

The code effectively combines user-defined comments with formatted attribute comments using array spread operators. This approach maintains a clean separation between different types of documentation while preserving all information.

Also applies to: 772-772


916-918: LGTM! Consistent with field comment handling.

The implementation maintains consistency with the field comment handling pattern, effectively combining user-defined comments with formatted attribute comments.

packages/schema/tests/generator/prisma-generator.test.ts (3)

50-58: LGTM!

The Role enum is correctly defined with appropriate documentation comments and the @@schema("auth") attribute.


60-70: LGTM!

The User model is properly documented and includes the necessary field and model attributes for access control and schema specification.


98-105: LGTM!

The test cases effectively verify the presence and absence of the expected documentation comments in the generated Prisma schema.

Copy link
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)
packages/schema/tests/generator/prisma-generator.test.ts (2)

99-106: Add assertion to verify JSDoc comment exclusion.

While the assertions effectively verify triple-slash comments, consider adding an assertion to explicitly verify that JSDoc comments (lines 72-75) are not included in the output. This would ensure the generator correctly differentiates between comment styles.

Add this assertion:

expect(content).not.toContain('* My post model');

88-88: Add test case for customAttributesAsComments=false.

The customAttributesAsComments flag is consistently set to true across all test cases. Consider adding a test case that verifies the behavior when the flag is false to ensure complete coverage of this feature.

Add a new test case:

it('attributes not as comments', async () => {
    // ... test setup with model containing attributes ...
    
    await new PrismaSchemaGenerator(model).generate({
        // ... other options ...
        customAttributesAsComments: false,
    });

    const content = fs.readFileSync(name, 'utf-8');
    expect(content).not.toContain('/// @allow');
    expect(content).not.toContain('/// @deny');
});

Also applies to: 209-209, 242-242, 436-436, 487-487, 519-519

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f7bf471 and c3ca4c6.

📒 Files selected for processing (3)
  • packages/schema/src/language-server/zmodel-documentation-provider.ts (1 hunks)
  • packages/schema/src/plugins/prisma/schema-generator.ts (5 hunks)
  • packages/schema/tests/generator/prisma-generator.test.ts (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/schema/src/language-server/zmodel-documentation-provider.ts
🔇 Additional comments (3)
packages/schema/tests/generator/prisma-generator.test.ts (1)

50-78: LGTM! Comprehensive test data for documentation styles.

The test data effectively covers various documentation scenarios:

  • Single-line and multi-line comments
  • Model-level and field-level documentation
  • Different comment styles (triple-slash and JSDoc)
packages/schema/src/plugins/prisma/schema-generator.ts (2)

103-103: LGTM: Property initialization and validation look good!

The implementation properly handles the new customAttributesAsComments option with appropriate type checking and validation.

Also applies to: 121-128


296-296: LGTM: Consistent comment handling implementation!

The changes maintain consistency in handling comments across different entity types (models, fields, enums, and enum fields) using a clean and immutable approach with the spread operator.

Also applies to: 772-774, 905-905, 913-915

@ymc9 ymc9 merged commit d223819 into dev Oct 30, 2024
13 checks passed
@ymc9 ymc9 deleted the fix/zmodel-docs branch October 30, 2024 00:08
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