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(python): Support Reference Aliases #4938

Merged
merged 1 commit into from
Oct 17, 2024
Merged

Conversation

noanflaherty
Copy link
Collaborator

@noanflaherty noanflaherty commented Oct 17, 2024

Adds support for specifying the alias used for reference imports.

Summary by CodeRabbit

  • New Features

    • Enhanced import statement generation to support aliases for imported references.
    • Introduced a new optional alias property for references.
  • Tests

    • Added test cases to verify the correct handling of imports with aliases in Python files.
    • Expanded test coverage for the toString method to include references with aliases.

Copy link

coderabbitai bot commented Oct 17, 2024

Walkthrough

The pull request introduces modifications to the PythonFile and Reference classes, enhancing the handling of import statements in Python code generation. In the PythonFile class, the writeImports method has been updated to include a conditional check for aliases when writing import statements. If a reference has an alias, it appends as ${reference.getAlias()} to the import statement. The Reference class has been updated to include a new optional alias property in the Args interface, a private alias member variable, and a constructor that accepts this new parameter. Additionally, a getAlias method has been added to retrieve the alias value. The changes are accompanied by new test cases that verify the correct generation of import statements with aliases in both the PythonFile and Reference test suites, ensuring the output matches expected formats.

Possibly related PRs

  • feat(python): Introduce PythonFile AST Node #4936: The changes in this PR introduce the PythonFile AST Node, which is directly related to the modifications in the writeImports method of the PythonFile class in the main PR, as both involve handling import statements in Python files.

Suggested reviewers

  • dsinghvi: Suggested as a reviewer for their expertise in the relevant codebase.

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

@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 and nitpick comments (6)
generators/pythonv2/codegen/src/ast/Reference.ts (1)

49-53: LGTM with a minor suggestion: write method update and getAlias method addition

The changes to the write method correctly handle the inclusion of the alias in the output when present. The new getAlias method provides appropriate access to the alias private member.

Consider using the newly added getAlias method in the write method for consistency:

-        if (this.alias) {
+        if (this.getAlias()) {
             writer.write(" as ");
-            writer.write(this.alias);
+            writer.write(this.getAlias()!);
         }

This change would make the code more consistent and easier to maintain in the future.

Also applies to: 72-74

generators/pythonv2/codegen/src/ast/__test__/Reference.test.ts (1)

53-60: LGTM! Consider adding a test with module path.

The new test case for handling classes with aliases is well-structured and aligns with the PR objectives. It effectively verifies the toString() method's behavior when a reference includes an alias.

To further enhance test coverage, consider adding another test case that includes both a module path and an alias. This would ensure that the toString() method correctly handles more complex scenarios. For example:

it("handles class with module path and alias", () => {
    const reference = python.reference({
        name: "AliasClass",
        modulePath: ["module", "submodule"],
        alias: "Alias"
    });
    expect(reference.toString()).toBe("AliasClass as Alias");
});

This additional test would verify that the presence of a module path doesn't affect the alias representation.

generators/pythonv2/codegen/src/ast/PythonFile.ts (1)

96-98: Consider handling edge cases for aliases.

While the implementation is correct, consider adding a check to ensure the alias is not an empty string. This would prevent generating invalid Python syntax in edge cases.

Here's a suggested improvement:

-if (reference.getAlias()) {
+const alias = reference.getAlias();
+if (alias && alias.trim() !== '') {
-    writer.write(` as ${reference.getAlias()}`);
+    writer.write(` as ${alias.trim()}`);
 }

This change ensures that only non-empty aliases are included in the import statement.

generators/pythonv2/codegen/src/ast/__test__/PythonFile.test.ts (3)

115-136: LGTM! Consider adding an explicit assertion.

The test case effectively demonstrates the use of an absolute import with an alias. It follows good testing practices and uses snapshot testing appropriately.

Consider adding an explicit assertion to verify the presence of the aliased import statement before the snapshot comparison. This could provide more specific feedback if the test fails. For example:

const output = writer.toString();
expect(output).toContain("from external_module.submodule import ExternalClass as AliasedClass");
expect(output).toMatchSnapshot();

138-159: LGTM! Consider adjusting the relative import path.

The test case effectively demonstrates the use of a relative import with an alias. It follows good testing practices and uses snapshot testing appropriately.

The modulePath in the reference suggests a relative import, but it's using an absolute path. Consider adjusting it to use a relative path for consistency with the test case description. For example:

const relativeRef = python.reference({
    modulePath: ["..", "sibling_dir"],
    name: "SiblingClass",
    alias: "AliasedSibling"
});

Also, consider adding an explicit assertion to verify the presence of the aliased import statement before the snapshot comparison, similar to the suggestion for the previous test case.


114-159: Great addition of test cases for aliased imports!

The new test cases effectively cover both absolute and relative imports with aliases, aligning well with the PR objectives. They enhance the test coverage for the PythonFile class and demonstrate good testing practices.

Consider adding more edge cases to further strengthen the test suite, such as:

  1. Multiple aliased imports in a single file
  2. Aliased imports with conflicting names
  3. Nested aliased imports

These additional test cases would help ensure robustness of the new feature across various scenarios.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 50137a7 and 1d48581.

⛔ Files ignored due to path filters (1)
  • generators/pythonv2/codegen/src/ast/__test__/__snapshots__/PythonFile.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (4)
  • generators/pythonv2/codegen/src/ast/PythonFile.ts (1 hunks)
  • generators/pythonv2/codegen/src/ast/Reference.ts (3 hunks)
  • generators/pythonv2/codegen/src/ast/test/PythonFile.test.ts (1 hunks)
  • generators/pythonv2/codegen/src/ast/test/Reference.test.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
generators/pythonv2/codegen/src/ast/Reference.ts (3)

17-18: LGTM: Addition of alias property to Args interface

The new alias property is correctly implemented as an optional string, which aligns with the PR objective of supporting reference aliases. The comment provides a clear description of its purpose.


26-26: LGTM: Addition of alias private member

The new alias private member is correctly typed as string | undefined, which is consistent with the optional alias property in the Args interface.


28-33: LGTM: Constructor update and alias assignment

The constructor signature has been correctly updated to include the alias parameter, and the assignment of the alias parameter to the private member is properly implemented.

generators/pythonv2/codegen/src/ast/PythonFile.ts (2)

95-98: LGTM! Correct implementation of import aliases.

The changes correctly implement the support for import aliases in Python. The conditional block is well-placed, and the alias is written in the correct format. This enhancement aligns with the PR objective and improves the flexibility of import statements in generated Python code.


Line range hint 1-111: Overall assessment: Well-implemented feature with minor suggestion.

The changes in this file successfully implement the support for reference aliases in Python imports. The implementation is correct and aligns well with the PR objectives. The suggested minor improvement for handling edge cases would further enhance the robustness of the code, but the current implementation is already functional and valuable.

@dsinghvi dsinghvi merged commit ae3f7c5 into main Oct 17, 2024
50 of 52 checks passed
@dsinghvi dsinghvi deleted the noa/support-reference-aliases branch October 17, 2024 18:39
exports[`PythonFile > Add a class with a relative import and alias 1`] = `
"from ...test_module.test.sibling_dir import SiblingClass

class TestClassWithRelativeAlias(SiblingClass as AliasedSibling):
Copy link
Collaborator

Choose a reason for hiding this comment

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

[blocking] this looks incorrect I don't think python supports inline as aliasing within the base class inheritance

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Ah true good catch. Will fix in a follow-up.

dsinghvi pushed a commit that referenced this pull request Oct 18, 2024
Add support for reference aliases
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

3 participants