Skip to content

fix: generated code fails to compile when prisma's output path overlaps with zenstack #1765

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

Merged
merged 1 commit into from
Oct 8, 2024

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Oct 8, 2024

Fixes #1743

Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request primarily involve the introduction of a new function, normalizedRelative, from the @zenstackhq/sdk package, which replaces the previous use of path.relative in various methods across multiple files. This update enhances the calculation of relative paths for Zod imports and Prisma client paths. Additionally, the SchemaLoadOptions type has been modified to include a new optional property, prismaLoadPath, allowing for more flexible Prisma client loading. A new regression test has also been added to address a specific issue related to import paths.

Changes

File Path Change Summary
packages/schema/src/plugins/enhancer/enhance/index.ts Updated getZodImport method to use normalizedRelative instead of path.relative.
packages/schema/src/plugins/enhancer/index.ts Modified run function to use normalizedRelative for calculating prismaClientPath.
packages/schema/src/plugins/prisma/index.ts Replaced path.relative with normalizedRelative in the logic for generating the Prisma client output path.
packages/sdk/src/index.ts Added export statement for path module: export * from './path';.
packages/sdk/src/path.ts Introduced normalizedRelative function to compute relative paths.
packages/sdk/src/prisma.ts Updated getPrismaClientImportSpec to use normalizedRelative for path calculations.
packages/testtools/src/schema.ts Added prismaLoadPath to SchemaLoadOptions type and modified Prisma client loading logic accordingly.
tests/regression/tests/issue-1743.test.ts Introduced a regression test for issue #1743, validating the correct import paths for the Prisma client.

Assessment against linked issues

Objective Addressed Explanation
Ensure correct import paths for Prisma client in the same Zenstack output location (#1743)

Possibly related PRs


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

🧹 Outside diff range and nitpick comments (6)
packages/sdk/src/path.ts (1)

6-9: Consider adding error handling and unit tests.

While the current implementation is correct, consider the following improvements for increased robustness:

  1. Add input validation to handle potential edge cases (e.g., empty strings, non-string inputs).
  2. Implement unit tests to verify the function's behavior with various input combinations.

These additions would further enhance the reliability of the normalizedRelative function and prevent potential issues in the future.

Would you like assistance in drafting input validation logic or unit tests for this function?

packages/schema/src/plugins/enhancer/index.ts (1)

Line range hint 1-41: Overall assessment: Changes look good and address the PR objective.

The modifications in this file are minimal and focused, directly addressing the issue of incorrect import paths when Prisma and Zenstack output paths overlap. The introduction of normalizedRelative for path calculations is a solid approach to handle this issue more robustly.

Some suggestions for further improvement:

  1. Consider adding comments explaining why normalizedRelative is used instead of path.relative to help future maintainers understand the rationale behind this change.
  2. As mentioned earlier, adding unit tests to verify the behavior of normalizedRelative with various path configurations would increase confidence in this change.
packages/sdk/src/prisma.ts (1)

Line range hint 1-95: Summary: Effective solution for import path issues.

The changes in this file, particularly the introduction of normalizedRelative and its use in getPrismaClientImportSpec, directly address the PR objectives. This modification should resolve the issue of incorrect import paths when Prisma and Zenstack output to the same directory.

The implementation is minimal and focused, affecting only the necessary parts of the code. The rest of the file's functionality remains intact, which is a positive aspect of this change.

Consider adding a brief comment above the getPrismaClientImportSpec function explaining why normalizedRelative is used instead of path.relative. This would help future maintainers understand the rationale behind this specific implementation.

packages/testtools/src/schema.ts (2)

267-272: LGTM: Improved Prisma client loading logic

The new logic for determining the Prisma client load path is well-implemented. It correctly handles both absolute and relative paths for the new prismaLoadPath option while maintaining backwards compatibility.

One minor suggestion for improved readability:

Consider extracting the default path to a constant at the top of the file:

const DEFAULT_PRISMA_LOAD_PATH = 'node_modules/.prisma/client';

// Then in the loadSchema function:
const prismaLoadPath = options?.prismaLoadPath
    ? path.isAbsolute(options.prismaLoadPath)
        ? options.prismaLoadPath
        : path.join(projectDir, options.prismaLoadPath)
    : path.join(projectDir, DEFAULT_PRISMA_LOAD_PATH);

This change would make it easier to update the default path in the future if needed.


138-138: LGTM: Additional option for Prisma client customization

The addition of prismaClientOptions to SchemaLoadOptions is a good enhancement that provides more flexibility in configuring the Prisma client. While not directly related to the main PR objective, it's a valuable addition.

Consider adding a brief comment or updating the documentation to explain the purpose and usage of this new option. This will help users understand how to leverage this new functionality effectively.

packages/schema/src/plugins/enhancer/enhance/index.ts (1)

Add Comprehensive Tests for EnhancerGenerator Path Resolution

The current changes improve path resolution within the EnhancerGenerator class. However, there are no dedicated tests for this class to verify these modifications.

  • Action Items:
    • Implement unit tests for the EnhancerGenerator class focusing on path resolution.
    • Ensure tests cover scenarios with custom output paths and various operating systems.
🔗 Analysis chain

Line range hint 1-638: Verify the impact on enhanced Prisma client generation

While the changes are focused on improving path resolution for Zod imports, it's crucial to ensure that this modification doesn't inadvertently affect other parts of the EnhancerGenerator class.

Please run comprehensive tests to verify that the enhanced Prisma client generation process works correctly with these changes, especially in scenarios involving custom output paths and different operating systems.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the enhanced Prisma client generation process

# Test: Check if there are any test files related to EnhancerGenerator
echo "Searching for EnhancerGenerator test files..."
fd -e test.ts -e spec.ts EnhancerGenerator

# Test: Look for any error handling related to path resolution in the codebase
echo "Checking for path resolution error handling..."
rg -i 'path.*error' --type ts

# Test: Search for usage of normalizedRelative function
echo "Searching for usage of normalizedRelative function..."
rg 'normalizedRelative' --type ts

Length of output: 1855

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a2c78a1 and 34e1159.

📒 Files selected for processing (8)
  • packages/schema/src/plugins/enhancer/enhance/index.ts (2 hunks)
  • packages/schema/src/plugins/enhancer/index.ts (2 hunks)
  • packages/schema/src/plugins/prisma/index.ts (2 hunks)
  • packages/sdk/src/index.ts (1 hunks)
  • packages/sdk/src/path.ts (1 hunks)
  • packages/sdk/src/prisma.ts (2 hunks)
  • packages/testtools/src/schema.ts (2 hunks)
  • tests/regression/tests/issue-1743.test.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (18)
packages/sdk/src/path.ts (3)

1-1: LGTM: Appropriate import for path operations.

The import of the 'path' module is correct and necessary for the file path operations performed in this module.


3-5: LGTM: Clear and concise function documentation.

The JSDoc comment effectively describes the purpose and behavior of the normalizedRelative function, highlighting the normalization aspect.


6-9: LGTM: Effective implementation addressing the PR objectives.

The normalizedRelative function is well-implemented and directly addresses the issue of incorrect import paths mentioned in the PR objectives. By ensuring that the returned path always starts with './' or '../', it should resolve the compilation errors caused by incorrect imports.

Some key points:

  1. Correct use of path.relative for calculating relative paths.
  2. Proper normalization logic to ensure paths start with './' when necessary.
  3. Simple and focused implementation without unnecessary complexity.

This function should help resolve the issue described in #1743 where import statements were incorrectly referencing "prisma" instead of using relative paths.

packages/sdk/src/index.ts (1)

5-5: LGTM! New export added to address import path issues.

The addition of export * from './path'; aligns with the PR objectives to resolve import path problems when Prisma and Zenstack output to the same directory. This change expands the public API of the SDK, potentially providing the necessary functionality to address the reported issues.

To ensure the path module contains the expected functionality, particularly the normalizedRelative function mentioned in the summary, please run the following script:

This will help confirm that the path module includes the necessary changes to address the import path issues.

✅ Verification successful

Verification Successful: normalizedRelative function is correctly exported and utilized across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the contents of the 'path' module

# Test: Check for the presence of the normalizedRelative function
ast-grep --lang typescript --pattern 'export function normalizedRelative($_) { $$$ }' packages/sdk/src/path.ts

# Test: Look for any usage of the new normalizedRelative function
rg --type typescript 'normalizedRelative\(' packages/sdk/src

Length of output: 210


Script:

#!/bin/bash
# Description: Verify the presence and export of the 'normalizedRelative' function in the 'path.ts' module

# Test: Check for the presence of the normalizedRelative function
ast-grep --lang typescript --pattern 'export function normalizedRelative($_) { $$$ }' packages/sdk/src/path.ts

# Test: Look for any usage of the normalizedRelative function in .ts files
rg 'normalizedRelative\(' packages/sdk/src/**/*.ts

# Test: List all export statements in path.ts to verify correct exports
rg '^export' packages/sdk/src/path.ts

Length of output: 621

tests/regression/tests/issue-1743.test.ts (3)

1-3: LGTM: Proper test setup for regression testing.

The import statement and test suite setup are correct. The use of a dedicated test for issue 1743 is a good practice for regression testing.


4-25: Excellent: Schema accurately represents the issue scenario.

The schema definition effectively recreates the conditions described in issue #1743. Key points:

  • Prisma client output is set to '../lib/zenstack/prisma'
  • Enhancer plugin output is set to './lib/zenstack'
  • These overlapping paths are crucial for testing the import path resolution issue.

The minimal User model is sufficient for this test case.


26-32: Well-configured: Options effectively test the import path issue.

The loadSchema options are well-crafted to test the specific issue:

  • compile: true ensures that the code is generated, allowing for import path verification.
  • output and prismaLoadPath settings recreate the overlapping directory scenario.

These configurations are crucial for verifying that the fix correctly resolves import paths when Prisma and ZenStack outputs overlap.

packages/schema/src/plugins/enhancer/index.ts (1)

1-8: LGTM: Import statement updated correctly.

The addition of normalizedRelative to the import statement from '@zenstackhq/sdk' is consistent with its usage in the file and aligns with the PR objective of addressing import path issues.

packages/sdk/src/prisma.ts (2)

12-12: LGTM: New import statement added.

The new import for normalizedRelative from './path' is correctly added and will be used in the getPrismaClientImportSpec function.


38-38: LGTM: Improved relative path calculation.

The change from path.relative to normalizedRelative should address the issue of incorrect import paths when Prisma and Zenstack output to the same directory. This modification aligns with the PR objectives and should resolve the compilation errors mentioned in issue #1743.

To ensure this change resolves the issue completely, please verify with the following steps:

  1. Set up a test configuration where Prisma and Zenstack output to the same directory.
  2. Generate the code using this updated version.
  3. Confirm that the import statements in the generated files (e.g., policy.ts) are correct and the code compiles without errors.
packages/schema/src/plugins/prisma/index.ts (3)

1-8: LGTM: Import of normalizedRelative addresses path resolution issues.

The addition of normalizedRelative from @zenstackhq/sdk is a positive change that aligns with the PR's objective of fixing import path issues. This function is likely designed to handle path normalization more robustly, which should help address the compilation errors mentioned in the linked issue #1743.


Line range hint 1-69: Summary: Targeted fix improves path resolution for Prisma client imports.

The changes in this file are focused and effective in addressing the issue of incorrect import paths when Prisma and Zenstack output to the same directory. The introduction of normalizedRelative and its use in calculating the prismaClientPath should resolve the compilation errors reported in issue #1743. This implementation maintains the existing logic while improving cross-environment compatibility.

Overall, these changes align well with the PR objectives and provide a targeted solution to the reported problem.


69-69: LGTM: Improved path resolution addresses compilation issues.

The replacement of path.relative with normalizedRelative is a key improvement that directly addresses the issue reported in #1743. This change should provide more consistent and correct path resolution, especially when Prisma and Zenstack are configured to output to the same directory. The use of normalizedRelative is likely to generate correct import paths in files like policy.ts, resolving the compilation errors mentioned in the PR objectives.

To ensure this change resolves the reported issue, we can verify the generated import paths:

This script will help confirm that the import statements in the generated files are using the correct relative paths.

packages/testtools/src/schema.ts (2)

137-137: LGTM: New option enhances flexibility for Prisma client loading

The addition of the prismaLoadPath option to SchemaLoadOptions is a good enhancement. It allows users to specify a custom path for loading the Prisma client, which directly addresses the issue of overlapping output paths between Prisma and Zenstack.


Line range hint 1-424: Summary: Effective implementation addressing PR objectives

The changes in this file successfully address the main PR objective of fixing compilation issues when Prisma and Zenstack output paths overlap. The new prismaLoadPath option and its associated logic provide a flexible solution while maintaining backwards compatibility. The additional prismaClientOptions further enhances customization capabilities.

A few minor suggestions have been made for improved readability and documentation. Overall, these changes are well-implemented and align closely with the PR's goals.

packages/schema/src/plugins/enhancer/enhance/index.ts (3)

11-11: New import added for path normalization

The normalizedRelative function has been imported from @zenstackhq/sdk. This is likely to improve path resolution across different operating systems.


163-163: Improved path resolution for Zod imports

The use of normalizedRelative instead of path.relative is a good improvement. This change enhances cross-platform compatibility and addresses the issue of incorrect import paths being generated, which was the main objective of this PR.


Line range hint 1-638: Summary of changes and their impact

The modifications in this file are minimal but significant:

  1. Added import of normalizedRelative from @zenstackhq/sdk.
  2. Updated the getZodImport method to use normalizedRelative instead of path.relative.

These changes directly address the PR objective of fixing incorrect import paths generation when Prisma and Zenstack output paths overlap. The use of normalizedRelative should improve cross-platform compatibility and resolve the reported issues.

While the changes look good, it's important to ensure that:

  1. The new path resolution works correctly across different operating systems.
  2. The changes don't negatively impact other parts of the EnhancerGenerator class.
  3. Comprehensive tests are run to verify the enhanced Prisma client generation process.

Overall, this update seems to be a well-targeted fix for the reported issue.

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