Skip to content

feat: Add fieldChildren method to napi's SgNode and pyo3's PyNode#1655

Merged
HerringtonDarkholme merged 2 commits intoast-grep:mainfrom
mohebifar:feat/napi-sg-node-field-children
Dec 11, 2024
Merged

feat: Add fieldChildren method to napi's SgNode and pyo3's PyNode#1655
HerringtonDarkholme merged 2 commits intoast-grep:mainfrom
mohebifar:feat/napi-sg-node-field-children

Conversation

@mohebifar
Copy link
Copy Markdown
Member

@mohebifar mohebifar commented Dec 11, 2024

napi's SgNode currently only exposes a field method that returns the first node matching the given field name. However, there are some cases where a node can have multiple children with the same field. For example, a jsx_element in TSX has multiple attribute fields.

Screenshot 2024-12-10 at 10 02 13 PM

This new fieldChildren returns an array of all the matching nodes.

Summary by CodeRabbit

  • New Features
    • Added a new method to retrieve all child nodes in a specified field.
  • Documentation
    • Updated documentation for existing methods to clarify their functionality.
  • Tests
    • Introduced a new test case to verify the functionality of the new method.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

The pull request introduces enhancements to the SgNode class and its associated methods within the crates/napi module. A new method, fieldChildren, is added to retrieve all child nodes of a specified field, accompanied by updates to the documentation of the existing field method for clarity. Additionally, a new test case is included in the test suite to verify the functionality of the fieldChildren method, ensuring that it correctly retrieves fields from JSX elements.

Changes

File Path Change Summary
crates/napi/test/index.spec.ts Added a test case for fieldChildren that verifies it retrieves all fields of a JSX element.
crates/napi/index.d.ts Updated documentation for field method and added fieldChildren method to SgNode class.
crates/napi/src/sg_node.rs Added field_children method to SgNode struct and updated documentation for field method.
crates/pyo3/src/py_node.rs Added field_children method to SgNode class for retrieving children of a specified field.
crates/pyo3/tests/test_traversal.py Added test_field_children() to test the functionality of finding JSX self-closing elements.
crates/pyo3/ast_grep_py/ast_grep_py.pyi Added field_children method to SgNode class for retrieving child nodes based on a field name.

Possibly related PRs

Suggested reviewers

  • HerringtonDarkholme

Poem

🐰 In the land of code where rabbits play,
New tests hop in to brighten the day.
With fieldChildren now in sight,
All fields retrieved, what a delight!
So let us code and test with glee,
For every change brings joy, you see! 🌟


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. (Experiment)
  • @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
Copy Markdown
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: 0

🧹 Outside diff range and nitpick comments (1)
crates/napi/__test__/index.spec.ts (1)

323-330: LGTM: Test case is well-structured, but could be expanded

The test effectively verifies the basic functionality. Consider adding additional test cases for:

  • Empty fields (no attributes)
  • Nested JSX elements with multiple fields
  • Fields with different names

Example additional test cases:

test('fieldChildren handles empty fields correctly', t => {
  const sg = tsx.parse('const el = <div />')
  const jsxElement = sg.root().find(tsx.kind('jsx_self_closing_element'))!
  const fields = jsxElement.fieldChildren('attribute')
  t.is(fields.length, 0)
})

test('fieldChildren works with nested elements', t => {
  const sg = tsx.parse('const el = <div><span id="1" /><span id="2" /></div>')
  const jsxElement = sg.root().find(tsx.kind('jsx_element'))!
  const fields = jsxElement.fieldChildren('jsx_element')
  t.is(fields.length, 2)
})
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between efba7e5 and 12dee5c.

📒 Files selected for processing (3)
  • crates/napi/__test__/index.spec.ts (1 hunks)
  • crates/napi/index.d.ts (1 hunks)
  • crates/napi/src/sg_node.rs (2 hunks)
🔇 Additional comments (3)
crates/napi/src/sg_node.rs (2)

261-261: LGTM: Documentation clarification is accurate

The updated documentation clearly specifies that the method returns the first child node, which helps distinguish it from the new fieldChildren method.


273-283: LGTM: Implementation is clean and consistent

The implementation follows the established patterns in the codebase:

  • Uses consistent parameter types and naming
  • Leverages existing helper methods
  • Properly handles type conversions
crates/napi/index.d.ts (1)

134-134: LGTM: Type definitions are accurate and well-documented

The TypeScript declarations are consistent with the Rust implementation:

  • Return types match the Rust signatures
  • Documentation follows the established style
  • Method naming follows JavaScript conventions

Also applies to: 136-137

@codecov
Copy link
Copy Markdown

codecov bot commented Dec 11, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 87.11%. Comparing base (7316d2f) to head (d8abcc5).
Report is 29 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1655      +/-   ##
==========================================
+ Coverage   87.06%   87.11%   +0.05%     
==========================================
  Files          95       96       +1     
  Lines       15340    15458     +118     
==========================================
+ Hits        13356    13467     +111     
- Misses       1984     1991       +7     

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

@HerringtonDarkholme
Copy link
Copy Markdown
Member

Thanks. Can you also port this change to Python API?

@mohebifar
Copy link
Copy Markdown
Member Author

Will do now.

@mohebifar mohebifar changed the title feat: Add fieldChildren method to napi's SgNode feat: Add fieldChildren method to napi's SgNode and pyo3's PyNode Dec 11, 2024
Copy link
Copy Markdown
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: 0

🧹 Outside diff range and nitpick comments (2)
crates/pyo3/src/py_node.rs (1)

171-180: LGTM! Consider adding docstring.

The implementation follows the established pattern for node traversal methods and correctly maintains the root reference. Consider adding a docstring to document the method's purpose and return type.

Add a docstring similar to this:

+  /// Returns all child nodes that match the given field name.
+  /// 
+  /// # Arguments
+  /// * `name` - The field name to match
+  /// 
+  /// # Returns
+  /// A vector of matching child nodes
   fn field_children(&self, name: &str) -> Vec<SgNode> {
crates/pyo3/tests/test_traversal.py (1)

47-57: LGTM! Consider adding more test cases.

The test effectively verifies the basic functionality of field_children. Consider adding these additional test cases:

Add tests for:

  1. Empty case (node with no matching fields)
  2. Single field case
  3. Nested fields case

Example:

def test_field_children_edge_cases():
    # Test empty case
    source = '<div></div>'
    sg = SgRoot(source, "tsx")
    node = sg.root().find(kind="jsx_element")
    assert node
    attributes = node.field_children("attribute")
    assert len(attributes) == 0

    # Test single field
    source = '<div id="foo"></div>'
    sg = SgRoot(source, "tsx")
    node = sg.root().find(kind="jsx_element")
    assert node
    attributes = node.field_children("attribute")
    assert len(attributes) == 1
    assert attributes[0].text() == 'id="foo"'

    # Test nested fields
    source = '<div><span id="nested">text</span></div>'
    sg = SgRoot(source, "tsx")
    node = sg.root().find(kind="jsx_element")
    assert node
    children = node.field_children("child")
    assert len(children) == 1
    nested_attrs = children[0].field_children("attribute")
    assert len(nested_attrs) == 1
    assert nested_attrs[0].text() == 'id="nested"'
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 12dee5c and 78b7715.

📒 Files selected for processing (2)
  • crates/pyo3/src/py_node.rs (1 hunks)
  • crates/pyo3/tests/test_traversal.py (1 hunks)

@mohebifar
Copy link
Copy Markdown
Member Author

Thanks. Can you also port this change to Python API?

done!

@mohebifar mohebifar force-pushed the feat/napi-sg-node-field-children branch from 78b7715 to d8abcc5 Compare December 11, 2024 23:18
Copy link
Copy Markdown
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: 0

🧹 Outside diff range and nitpick comments (1)
crates/pyo3/ast_grep_py/ast_grep_py.pyi (1)

57-57: LGTM! Consider adding docstring type hints.

The method signature follows Python naming conventions and aligns well with existing tree traversal methods. The return type is consistent with other plural methods in the class.

Consider adding docstring type hints for better IDE support:

-    def field_children(self, name: str) -> List[SgNode]: ...
+    def field_children(self, name: str) -> List[SgNode]:
+        """Get all child nodes that match the given field name.
+        
+        Args:
+            name (str): The field name to match
+            
+        Returns:
+            List[SgNode]: List of child nodes matching the field name
+        """
+        ...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 78b7715 and d8abcc5.

📒 Files selected for processing (3)
  • crates/pyo3/ast_grep_py/ast_grep_py.pyi (1 hunks)
  • crates/pyo3/src/py_node.rs (1 hunks)
  • crates/pyo3/tests/test_traversal.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/pyo3/src/py_node.rs
  • crates/pyo3/tests/test_traversal.py

Copy link
Copy Markdown
Member

@HerringtonDarkholme HerringtonDarkholme left a comment

Choose a reason for hiding this comment

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

LGTM! Thanks!

@HerringtonDarkholme HerringtonDarkholme merged commit 6a557c2 into ast-grep:main Dec 11, 2024
@mohebifar mohebifar deleted the feat/napi-sg-node-field-children branch December 11, 2024 23:24
tmeijn pushed a commit to tmeijn/dotfiles that referenced this pull request Dec 21, 2024
This MR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [ast-grep/ast-grep](https://github.com/ast-grep/ast-grep) | minor | `0.31.1` -> `0.32.2` |

MR created with the help of [el-capitano/tools/renovate-bot](https://gitlab.com/el-capitano/tools/renovate-bot).

**Proposed changes to behavior should be submitted there as MRs.**

---

### Release Notes

<details>
<summary>ast-grep/ast-grep (ast-grep/ast-grep)</summary>

### [`v0.32.2`](https://github.com/ast-grep/ast-grep/blob/HEAD/CHANGELOG.md#0322)

[Compare Source](ast-grep/ast-grep@0.32.1...0.32.2)

-   fix: linting [`10f3e74`](ast-grep/ast-grep@10f3e74)
-   feat: distinguish manual type annotation [`4558c48`](ast-grep/ast-grep@4558c48)
-   feat: add ChildTypes helper [`0d477e9`](ast-grep/ast-grep@0d477e9)

### [`v0.32.1`](https://github.com/ast-grep/ast-grep/blob/HEAD/CHANGELOG.md#0321)

[Compare Source](ast-grep/ast-grep@0.32.0...0.32.1)

> 17 December 2024

-   fix(deps): update rust crate clap_complete to v4.5.39 [`6ad3c7b`](ast-grep/ast-grep@6ad3c7b)
-   fix: add npmignore to suppress gitignore [`11bb8e4`](ast-grep/ast-grep@11bb8e4)

### [`v0.32.0`](https://github.com/ast-grep/ast-grep/blob/HEAD/CHANGELOG.md#0320)

[Compare Source](ast-grep/ast-grep@0.31.1...0.32.0)

> 17 December 2024

-   feat: Add fieldChildren method to napi's SgNode and pyo3's PyNode [`#1655`](ast-grep/ast-grep#1655)
-   **Breaking change:** fix: rename range rule's row to line [`#1663`](ast-grep/ast-grep#1663)
-   fix: add biome formatting [`5a41f13`](ast-grep/ast-grep@5a41f13)
-   feat(napi): Typed SgNode and SgRoot [`55e65f3`](ast-grep/ast-grep@55e65f3)
-   fix: Use ts-node and versioned node-types URLs instead of heads [`dcb7916`](ast-grep/ast-grep@dcb7916)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever MR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this MR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this MR, check this box

---

This MR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOS43Ny4wIiwidXBkYXRlZEluVmVyIjoiMzkuNzcuMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiUmVub3ZhdGUgQm90Il19-->
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