Skip to content

✨ Ruby #57

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 3 commits into from
Apr 6, 2025
Merged

✨ Ruby #57

merged 3 commits into from
Apr 6, 2025

Conversation

NatoBoram
Copy link
Collaborator

@NatoBoram NatoBoram commented Apr 3, 2025

Summary by CodeRabbit

  • New Features
    • Introduced Ruby language support, enabling enhanced syntax parsing and robust language registration.
  • Documentation
    • Added a user guide with installation instructions and usage examples for seamless integration.
  • Tests
    • Provided a testing setup to verify accurate Ruby code parsing.
  • Chores
    • Implemented updated package configurations and automated post-installation tasks for a smooth setup experience.

Copy link

coderabbitai bot commented Apr 3, 2025

Walkthrough

This pull request introduces a Ruby language package for ast-grep. It adds documentation detailing installation and usage, type definitions and configuration exports for Ruby parser settings, a testing setup using the nursery package, package metadata including build and publish scripts, and a post-installation script. These changes enable dynamic registration of Ruby language support via tree-sitter and NAPI integration.

Changes

File(s) Change Summary
packages/ruby/README.md Added a README with installation commands and usage examples for integrating Ruby language support with ast-grep.
packages/ruby/index.d.ts, index.js, postinstall.js Introduced a LanguageRegistration type, exported configuration object (including libraryPath, extensions, languageSymbol, expandoChar), and a post-install script that invokes the setup function from @ast-grep/setup-lang.
packages/ruby/nursery.js Created a testing setup file that configures and tests the Ruby language parser by parsing example Ruby code and asserting the correctness of node kinds.
packages/ruby/package.json Added package metadata for @ast-grep/lang-ruby (version 0.0.1), including build, source, and test scripts, dependencies, devDependencies, publish configuration, and pnpm settings to include built dependencies only.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as Command Line (pnpm)
    participant Setup as Postinstall Script
    participant Reg as Ruby Registration
    participant Parser as Tree-sitter Parser

    CLI->>Setup: Execute postinstall.js
    Setup->>Reg: Call setup with __dirname
    Reg-->>Setup: Return registration config (libraryPath, extensions, etc.)
    CLI->>Parser: Load Ruby parser via registration config
    Parser-->>CLI: Ruby language support activated
Loading

Possibly related PRs

  • ✨ JavaScript #53: The changes in the main PR for the Ruby package and the retrieved PR for the JavaScript package both introduce a new LanguageRegistration type and a registration constant, indicating a direct relationship at the code level.
  • ✨ Haskell #50: The changes in the main PR for the Ruby package and the retrieved PR for the Haskell package both introduce a new LanguageRegistration type and a registration constant, indicating a direct relationship at the code level.
  • ✨ Bash #46: The changes in the main PR for the Ruby package involve the introduction of a new type definition and a constant related to language registration, while the retrieved PR for the Bash package includes similar changes with a new type definition and constant for language registration, indicating a parallel implementation for different languages.

Suggested reviewers

  • HerringtonDarkholme

Poem

I'm a hopping little bunny, full of cheer,
Ruby dreams now coded, oh so clear!
Docs and tests in neat array,
With each new commit, I wanna play 🐰
Bound along in code with delight,
Ast-grep shines ever so bright!
Happy hops to these changes tonight!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67ff2cb and 700c703.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • .changeset/shaky-ravens-accept.md (1 hunks)
  • packages/ruby/README.md (1 hunks)
  • packages/ruby/index.d.ts (1 hunks)
  • packages/ruby/index.js (1 hunks)
  • packages/ruby/nursery.js (1 hunks)
  • packages/ruby/package.json (1 hunks)
  • packages/ruby/postinstall.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/shaky-ravens-accept.md
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/ruby/postinstall.js
  • packages/ruby/index.d.ts
  • packages/ruby/README.md
  • packages/ruby/nursery.js
  • packages/ruby/package.json
  • packages/ruby/index.js

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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

🧹 Nitpick comments (7)
packages/ruby/postinstall.js (1)

1-4: Looks good but could benefit from error handling

The postinstall script correctly imports the necessary function and passes the current directory. However, it lacks error handling which could be useful for troubleshooting installation issues.

Consider adding a try-catch block to handle potential errors during installation:

const { postinstall } = require('@ast-grep/setup-lang')
-postinstall({
-  dirname: __dirname,
-})
+try {
+  postinstall({
+    dirname: __dirname,
+  })
+} catch (error) {
+  console.error('Failed to complete Ruby language setup:', error)
+  process.exit(1)
+}
packages/ruby/index.d.ts (1)

1-7: Add JSDoc comments to improve documentation

The type definition is clear and well-structured, but adding JSDoc comments would make it more maintainable and help developers understand the purpose of each property.

Consider adding descriptive JSDoc comments:

+/**
+ * Configuration for registering a language with ast-grep
+ */
type LanguageRegistration = {
+  /** Path to the compiled tree-sitter language library */
  libraryPath: string
+  /** File extensions associated with this language */
  extensions: string[]
+  /** Symbol used to identify the language in tree-sitter */
  languageSymbol?: string
+  /** Character used for meta variables in patterns */
  metaVarChar?: string
+  /** Character used for expandable wildcards in patterns */
  expandoChar?: string
}
packages/ruby/nursery.js (1)

10-15: Expand test coverage for more Ruby syntax elements

The current test case verifies basic functionality with a simple method call, which is a good start. However, adding more test cases would ensure broader syntax coverage.

Consider extending the test coverage with additional Ruby-specific syntax:

  testRunner: parse => {
    const sg = parse('Foo::bar()')
    const root = sg.root()
    const node = root.find('Foo::$METHOD()')
    assert.equal(node.kind(), 'call')
+    
+    // Test Ruby class definition
+    const classExample = parse('class MyClass < BaseClass; def method; end; end')
+    const classNode = classExample.root().find('class $CLASS < $PARENT; $$$; end')
+    assert.equal(classNode.kind(), 'class')
+    
+    // Test Ruby blocks
+    const blockExample = parse('[1, 2, 3].each { |num| puts num }')
+    const blockNode = blockExample.root().find('$ARRAY.each { |$VAR| $$$ }')
+    assert.equal(blockNode.kind(), 'call')
  },
packages/ruby/README.md (2)

14-24: Enhance usage examples with Ruby-specific patterns

The usage example shows the basic setup, but adding examples of Ruby-specific pattern matching would be more helpful for users.

Expand the usage examples to showcase Ruby syntax patterns:

## Usage

```js
import ruby from '@ast-grep/lang-ruby'
import { registerDynamicLanguage, parse } from '@ast-grep/napi'

registerDynamicLanguage({ ruby })

const sg = parse('ruby', `your code`)
sg.root().kind()
+
+// Examples of Ruby-specific pattern matching
+
+// Find class definitions
+const rubyCode = `
+class User < ApplicationRecord
+  has_many :posts
+  
+  def full_name
+    "#{first_name} #{last_name}"
+  end
+end
+`
+
+const sgRuby = parse('ruby', rubyCode)
+
+// Find class inheritance
+const classNode = sgRuby.root().find('class $CLASS < $PARENT; $$$; end')
+console.log(classNode.getText()) // Outputs the entire class
+
+// Find method definitions
+const methodNode = sgRuby.root().find('def $METHOD; $$$; end')
+console.log(methodNode.getText()) // Outputs the method definition

7-12: Mention alternative package managers

The installation instructions only mention pnpm, but users might be using npm or yarn.

Include alternative package manager commands:

## Installation

-In a pnpm project, run:
+Install using your preferred package manager:

```bash
+# Using pnpm
pnpm install @ast-grep/lang-ruby
pnpm install @ast-grep/napi
# install the tree-sitter-cli if no prebuild is available
pnpm install @tree-sitter/cli --save-dev
+
+# Using npm
+npm install @ast-grep/lang-ruby
+npm install @ast-grep/napi
+# install the tree-sitter-cli if no prebuild is available
+npm install @tree-sitter/cli --save-dev
+
+# Using yarn
+yarn add @ast-grep/lang-ruby
+yarn add @ast-grep/napi
+# install the tree-sitter-cli if no prebuild is available
+yarn add @tree-sitter/cli --dev
packages/ruby/index.js (1)

4-9: Clear Configuration and Exports

The exported configuration object is well structured and clearly defines the properties required for parsing Ruby files. Consider adding a brief comment explaining the purpose of the expandoChar: 'µ' property to aid future maintainers.

packages/ruby/package.json (1)

1-5: Basic Package Metadata

The initial metadata (name, version, main) is defined correctly. For improved clarity in the package listing, consider adding a meaningful description and author information.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 002639c and 67ff2cb.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • packages/ruby/README.md (1 hunks)
  • packages/ruby/index.d.ts (1 hunks)
  • packages/ruby/index.js (1 hunks)
  • packages/ruby/nursery.js (1 hunks)
  • packages/ruby/package.json (1 hunks)
  • packages/ruby/postinstall.js (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/ruby/postinstall.js (1)
packages/ruby/nursery.js (1)
  • require (1-1)
🔇 Additional comments (8)
packages/ruby/index.js (1)

1-2: Clean Import and Library Path Calculation

The use of the node:path module and path.join(__dirname, 'parser.so') is clear and follows modern Node.js practices.

packages/ruby/package.json (7)

6-12: Scripts Configuration

The defined scripts (build, source, prepublishOnly, postinstall, and test) clearly outline the package lifecycle. Ensure that all referenced scripts (such as nursery.js and postinstall.js) exist and are maintained for smooth operation.


13-20: Files Inclusion

The "files" array correctly includes the essential components for the package. Please verify that excluding files like nursery.js is intentional and that they are only used during development.


21-29: Dependencies and Peer Dependencies

Dependencies and peer dependencies are clearly defined. Double-check that the specified versions (especially for tree-sitter-cli, which is referenced in both peer and dev dependencies) are compatible with your build and test processes.


30-34: Optional Peer Dependency Configuration

The configuration in peerDependenciesMeta correctly marks tree-sitter-cli as optional, which helps avoid installation issues if it’s not present.


35-39: Development Dependencies

The devDependencies are appropriately set for testing and development. This ensures that the necessary tools (including the nursery runner and the Ruby parser) are available during development.


40-43: Publish Configuration

The publishConfig section is properly configured to ensure public access and correct registry targeting during publication.


44-46: pnpm Configuration

The pnpm configuration specifies onlyBuiltDependencies, which is useful if you intend to only include certain dependencies in the build. Please verify that this option is fully supported by your current pnpm version.

@NatoBoram NatoBoram force-pushed the feature/ruby branch 3 times, most recently from 6e926f6 to 0738ba8 Compare April 5, 2025 06:34
@HerringtonDarkholme HerringtonDarkholme merged commit ebf2bdb into ast-grep:main Apr 6, 2025
3 checks passed
@NatoBoram NatoBoram deleted the feature/ruby branch April 6, 2025 04:23
This was referenced Apr 6, 2025
@coderabbitai coderabbitai bot mentioned this pull request Apr 22, 2025
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