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: Css in vue #108

Merged
merged 4 commits into from
Mar 29, 2024
Merged

feat: Css in vue #108

merged 4 commits into from
Mar 29, 2024

Conversation

ilevyor
Copy link
Contributor

@ilevyor ilevyor commented Mar 28, 2024

closes: #57

lets grit match css in vue files. parse file now returns an option, and none when trying to parse a vue file for a css pattern with no style element, similarly for js and script elements

Summary by CodeRabbit

  • New Features

    • Introduced a CSS pattern for better handling of Vue component visibility.
    • Added a Vue component to manage item count display with optional visibility and transition effects.
    • Enhanced support for the Vue language in CSS patterns, including handling of language attributes and code ranges in Vue files.
  • Bug Fixes

    • Improved error handling and reporting in various modules, ensuring clearer error messages and more robust application behavior.
  • Documentation

    • No user-facing documentation updates in this release.
  • Refactor

    • Updated the logic and handling of optional return values across several modules to improve code quality and error handling.
    • Streamlined build processes for TypeScript and Vue modules, including adjustments to Makefile and build rules.
  • Tests

    • Added and updated test functions for CSS in Vue, parsing Vue files, and other language-specific functionalities.

@ilevyor ilevyor requested a review from a team March 28, 2024 16:10
Copy link
Contributor

coderabbitai bot commented Mar 28, 2024

Walkthrough

This update introduces enhanced support for CSS within .vue files, making it possible to match <style> tags effectively. It includes modifications across various components, from pattern application in Vue components and language-specific parsing adjustments, to refinements in error handling and test enhancements. These changes collectively aim to improve the handling and parsing of CSS in Vue files, aligning with the goal of supporting CSS patterns within this context.

Changes

Files Change Summary
.../css_in_vue/pattern.grit, .../css_in_vue/simple.vue Introduced CSS pattern for Vue components and a Vue component for display management with visibility control.
.../cli_bin/tests/apply.rs, .../core/src/pattern.rs, .../core/src/pattern/step.rs, .../wasm-bindings/src/match_pattern.rs Enhanced test functions, error handling, and pattern application logic.
.../language/src/{css, javascript, language, target_language, tsx, typescript, vue, xscript_util}.rs Added and modified functions for better parsing of Vue files and support for CSS within them.
resources/.../tree-sitter-*/build/Makefile, resources/.../tree-sitter-*/build/*.target.mk Adjusted build rules and order of included files for better compilation.
resources/.../tree-sitter-vue/grammar.js, resources/.../tree-sitter-vue/src/parser.c, resources/metavariable-grammars/vue-metavariable-grammar.js Updated grammar rules and parsing logic for Vue components.

Assessment against linked issues

Objective Addressed Explanation
CSS in .vue (#57)

Poem

In the realm of code, where logic intertwines,
A rabbit hopped through, leaving patterns behind.
With a whisk of its tail, Vue files came to life,
CSS embraced, in style tags so rife.

Through <style> and <script>, it danced with grace,
Merging worlds apart, in the web's vast space.
🌟 "To the future," it whispered, with a twinkle in its eye,
Where code flows like rivers, under the digital sky.

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>.
    • Generate unit-tests 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 tests 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

grit-app bot commented Mar 28, 2024

On commit d2956b9, Grit tried to heal these tests:

Job Original Status Final Status
code quality / clippy_check ❌ Failed ❗ Failed on attempt #3 after trying strategies ai, rerun
code quality / clippy ❌ Failed ❗ Failed on attempt #3 after trying strategies ai, rerun

Tip

You can view and edit CI healing settings on the Grit App.

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.

Review Status

Actionable comments generated: 4

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 542cca3 and d2956b9.
Files ignored due to path filters (6)
  • crates/cli_bin/tests/snapshots/apply__basic_css_in_vue_apply.snap is excluded by !**/*.snap
  • crates/wasm-bindings/wasm_parsers/tree-sitter-vue.wasm is excluded by !**/*.wasm
  • resources/language-metavariables/tree-sitter-typescript/node_modules/tree-sitter-javascript/src/grammar.json is excluded by !**/*.json
  • resources/language-metavariables/tree-sitter-vue/src/grammar.json is excluded by !**/*.json
  • resources/language-metavariables/tree-sitter-vue/src/node-types.json is excluded by !**/*.json
  • resources/node-types/vue-node-types.json is excluded by !**/*.json
Files selected for processing (23)
  • crates/cli_bin/fixtures/css_in_vue/pattern.grit (1 hunks)
  • crates/cli_bin/fixtures/css_in_vue/simple.vue (1 hunks)
  • crates/cli_bin/tests/apply.rs (6 hunks)
  • crates/core/src/pattern.rs (2 hunks)
  • crates/core/src/pattern/step.rs (3 hunks)
  • crates/language/src/css.rs (4 hunks)
  • crates/language/src/javascript.rs (2 hunks)
  • crates/language/src/language.rs (2 hunks)
  • crates/language/src/target_language.rs (5 hunks)
  • crates/language/src/tsx.rs (1 hunks)
  • crates/language/src/typescript.rs (1 hunks)
  • crates/language/src/vue.rs (2 hunks)
  • crates/language/src/xscript_util.rs (5 hunks)
  • crates/wasm-bindings/src/match_pattern.rs (2 hunks)
  • resources/language-metavariables/tree-sitter-typescript/build/Makefile (1 hunks)
  • resources/language-metavariables/tree-sitter-typescript/node_modules/tree-sitter-javascript/build/Makefile (1 hunks)
  • resources/language-metavariables/tree-sitter-typescript/node_modules/tree-sitter-javascript/build/tree_sitter_javascript_binding.target.mk (1 hunks)
  • resources/language-metavariables/tree-sitter-vue/build/Makefile (1 hunks)
  • resources/language-metavariables/tree-sitter-vue/build/tree_sitter_vue_binding.target.mk (1 hunks)
  • resources/language-metavariables/tree-sitter-vue/grammar.js (1 hunks)
  • resources/language-metavariables/tree-sitter-vue/node_modules/tree-sitter-html/build/Makefile (1 hunks)
  • resources/language-metavariables/tree-sitter-vue/src/parser.c (3 hunks)
  • resources/metavariable-grammars/vue-metavariable-grammar.js (1 hunks)
Additional comments (32)
crates/cli_bin/fixtures/css_in_vue/pattern.grit (1)
  • 1-3: The CSS pattern definition looks good and aligns with the PR's objectives.
crates/cli_bin/fixtures/css_in_vue/simple.vue (1)
  • 1-44: The Vue component example is well-structured and demonstrates the intended CSS pattern matching within a Vue file.
crates/language/src/vue.rs (3)
  • 8-11: New imports for error handling and utility functions have been added. Ensure these libraries are properly integrated and used throughout the file.
  • 68-87: The is_lang_attribute function checks if a node has a specific language attribute. Consider adding error handling for cases where utf8_text might fail due to unexpected node structures.
  • 89-108: The append_code_range function appends code ranges for specific node kinds. Ensure that the parent node kind and name arrays are correctly defined and used to prevent incorrect range inclusion.
Verification successful

The verification process has confirmed that parent_node_kind and name_array are correctly utilized in the append_code_range function and related functions across the codebase. These parameters are used to filter nodes of specific kinds and attributes, aligning with the intended functionality of appending code ranges for specific node kinds.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that parent node kinds and name arrays are correctly utilized.
grep -rn "parent_node_kind" .
grep -rn "name_array" .

Length of output: 2339

crates/language/src/xscript_util.rs (1)
  • 55-64: The parse_file function now returns an Option<Tree> to handle Vue files differently. Ensure that all calls to this function properly handle the None case to prevent runtime errors.
Verification successful

The verification process involved examining the usage of the parse_file function across various files in the codebase, particularly focusing on how the None return value is handled. The function parse_file is defined in xscript_util.rs and is used in several places, including language-specific implementations like css.rs, javascript.rs, language.rs, tsx.rs, and typescript.rs. The primary concern was ensuring that all calls to parse_file properly handle the possibility of a None return value, which could occur when parsing Vue files or under other specific conditions.

From the provided context and the examination of the code snippets, it is evident that the parse_file function has been adapted to return an Option<Tree> to accommodate scenarios where parsing might not yield a syntax tree, such as when parsing Vue files with specific language blocks. This change necessitates that all calls to parse_file across the codebase are checked to ensure they handle the None case appropriately to prevent runtime errors.

The verification process involved reviewing the implementation of parse_file in xscript_util.rs and tracing its usage across different files to check for proper handling of the None case. The examination included looking at how the function is invoked and how its return value is processed in various contexts, including language-specific parsing functions and other utility functions that rely on parsing functionality.

Based on the examination of the provided context and the additional information gathered from the code snippets, it is clear that the parse_file function's adaptation to return an Option<Tree> has been accounted for in its usage across the codebase. The calls to parse_file have been checked to ensure they properly handle the None return value, thus preventing potential runtime errors related to parsing Vue files or other specific scenarios.

Given the thorough verification process and the evidence provided by the examination of the code snippets, it can be concluded that the necessary changes to handle the None return value from parse_file have been implemented correctly across the codebase.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify handling of `None` return value from `parse_file`.
grep -rn "parse_file" .

Length of output: 1641



Script:

#!/bin/bash
# Examine the implementation of `parse_file` calls in each mentioned file to verify handling of `None` return value.
fd "pattern.rs" --exec cat {}
fd "css.rs" --exec cat {}
fd "javascript.rs" --exec cat {}
fd "language.rs" --exec cat {}
fd "tsx.rs" --exec cat {}
fd "typescript.rs" --exec cat {}
fd "xscript_util.rs" --exec cat {}

Length of output: 203174

resources/language-metavariables/tree-sitter-typescript/node_modules/tree-sitter-javascript/build/tree_sitter_javascript_binding.target.mk (2)
  • 139-139: The build rule for compiling .c files has been modified. Ensure that the updated command (do_cmd,cc,1) correctly reflects the intended build process for .c files. This change should align with the project's build requirements and conventions.
  • 147-147: Similarly, the build rule for compiling .c files from generated source has been adjusted. Verify that this change (do_cmd,cc,1) is consistent with the project's standards for handling generated sources and that it integrates smoothly with the overall build system.
crates/language/src/javascript.rs (1)
  • 181-181: The parse_file method's return type has been changed to Result<Option<tree_sitter::Tree>>. This adjustment allows for more nuanced error handling, specifically in cases where parsing might not yield a syntax tree (e.g., when a Vue file lacks a <script> tag). Ensure that all calls to this method and related error handling have been updated accordingly to handle the Option type.
crates/language/src/typescript.rs (1)
  • 230-230: The parse_file function in the TypeScript module now returns Result<Option<tree_sitter::Tree>>, aligning with the changes made in the JavaScript module. This modification enhances the handling of cases where a TypeScript file might not produce a syntax tree. Confirm that the usage of this function and the management of its return value are correctly adapted throughout the project.
crates/core/src/pattern/step.rs (2)
  • 278-290: The construction of FileOwner instances now includes more explicit error handling, utilizing anyhow for error messages. This change improves the clarity of errors related to file construction failures. Verify that the error messages provided are clear and informative, aiding in debugging and error resolution.
  • 312-318: Similarly, the construction of new files within the parse_file function has been updated to use anyhow for error handling. Ensure that these changes are consistent with the project's error handling strategy and that the error messages are descriptive enough to facilitate troubleshooting.
resources/language-metavariables/tree-sitter-vue/build/Makefile (1)
  • 330-330: The order of included files in the Makefile target has been rearranged, specifically moving $(srcdir)/build/config.gypi to a different position within the list. Ensure that this change does not affect the build process negatively, especially considering dependencies between the included files. It might be beneficial to verify that all necessary configurations are correctly applied in the new order.
resources/language-metavariables/tree-sitter-typescript/build/Makefile (1)
  • 330-330: The order of dependencies in the Makefile target definition has been updated. Ensure that this reordering does not affect the build process or introduce any unintended side effects.
resources/language-metavariables/tree-sitter-vue/node_modules/tree-sitter-html/build/Makefile (1)
  • 330-330: The order of dependencies in the Makefile target definition has been updated. Verify that this change does not impact the build process negatively or introduce any build issues.
resources/language-metavariables/tree-sitter-typescript/node_modules/tree-sitter-javascript/build/Makefile (1)
  • 330-330: The reordering of dependencies in the Makefile target definition has been noted. It's important to ensure that this change does not disrupt the build sequence or cause any dependency issues.
crates/wasm-bindings/src/match_pattern.rs (2)
  • 196-202: The error handling in the gritExternalFunctionCall function uses a generic error message when the actual error is not available. Consider logging the error to the console for debugging purposes or implementing a more detailed error handling strategy to provide more context about the failure.
  • 326-329: Including PatternLanguage::Css in the condition within get_language_for_tree is a significant change for supporting CSS in Vue files. Ensure that this addition is accompanied by adequate tests to verify that Vue files with CSS content are correctly parsed and handled.
crates/language/src/language.rs (1)
  • 328-336: The implementation of default_parse_file now correctly handles the case where parsing might not produce a tree by returning Result<Option<Tree>>. This is a good practice for handling files that cannot be parsed due to missing or incorrect syntax. Ensure that the error messages and logs provide enough context for debugging parsing issues.
crates/core/src/pattern.rs (2)
  • 236-251: The FileOwner::new method has been updated to return Result<Option<Self>>, accommodating the scenario where parsing a Vue file for a CSS pattern might not yield a <style> element. This change is crucial for gracefully handling files without the expected content. However, it's important to ensure that all callers of this method properly handle the None case to avoid unwrapping errors or logic mishaps.

Ensure all usages of FileOwner::new have been updated to handle the Option in the result correctly. This might involve adding checks or default behaviors when None is encountered.

  • 411-414: The handling of the Option returned by FileOwner::new is correctly implemented here, with a check for Some(owned_file) before proceeding to use the owned_file. This pattern ensures that files without the expected <style> tags are gracefully skipped without causing errors in the analysis process.
crates/language/src/target_language.rs (3)
  • 236-236: Adding "*.vue" to the file extensions for CSS patterns is a necessary update to support CSS within Vue files. This change allows the system to recognize and process Vue files when matching CSS patterns, aligning with the PR's objectives.
  • 392-392: Including "*.vue" in the file types builder for Vue files is crucial for ensuring that Vue files are correctly identified and processed across the system. This update supports the broader goal of integrating Vue language support, particularly for CSS pattern matching.
  • 429-429: Selecting "vue" as a file type in the context of CSS patterns is an essential part of enabling CSS pattern matching within Vue files. This change ensures that Vue files are appropriately considered when searching for CSS patterns, further integrating Vue support into the system.
crates/cli_bin/tests/apply.rs (6)
  • 891-922: The new test function basic_css_in_vue_apply is added to verify the application of CSS patterns in Vue files. This aligns with the PR's objective to enable CSS pattern matching within Vue files. The test setup and assertions follow the established patterns in the file, ensuring consistency.
  • 2064-2069: The use of the --language option in the language_option_file_pattern_apply test is a good practice for ensuring that the language-specific pattern application works as expected. However, it's important to verify that the language option is correctly implemented and tested across various languages and scenarios to ensure comprehensive coverage.
Verification successful

The provided context from the shell script execution and the additional context from the apply.rs file reveal that the --language option is indeed used in the test language_option_file_pattern_apply, which is designed to ensure that the language-specific pattern application works as expected. This test specifically checks the functionality of applying a pattern with the --language option set to "java", which is a direct implementation of the review comment's concern.

Given the evidence from the script execution that found the usage of --language in apply.rs, and the detailed examination of the apply.rs file that includes a test case explicitly testing the --language option, it can be concluded that the implementation and testing of the --language option across different languages and scenarios are present, at least to some extent, within the codebase.

However, the verification process focused on a single instance of the --language option usage within a test case. Comprehensive coverage across various languages and scenarios would require a broader examination of the codebase, including additional test cases and implementation details beyond what was provided in the initial context and the subsequent script execution results.

Based on the information available and the specific test case examined, the review comment regarding the importance of verifying the --language option's implementation and testing across various languages and scenarios is supported by the evidence found. However, a full assessment of comprehensive coverage would necessitate further investigation.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the implementation of the --language option across different languages
grep --recursive --files-with-matches "--language" .

Length of output: 174



Script:

#!/bin/bash
# Corrected script to verify the implementation of the --language option across different languages
grep --recursive --files-with-matches "\--language" .

Length of output: 87



Script:

#!/bin/bash
# Examine the usage of the --language option in the identified file
cat ./crates/cli_bin/tests/apply.rs

Length of output: 63362

* 2100-2105: The `language_option_inline_pattern_apply` test demonstrates the application of an inline pattern with a specified language option. This is a valuable test case for ensuring that inline patterns are correctly applied in the context of the specified language. It's crucial to ensure that the pattern syntax and the language option are compatible and effectively tested. * 2141-2146: The `language_option_named_pattern_apply` test introduces a named pattern with a language option. This test is important for verifying that named patterns can be applied with the correct language context. It's essential to ensure that the pattern definition and application are consistent with the language semantics and that the test covers various aspects of named pattern usage. * 2181-2186: The `language_option_conflict_apply` test checks for conflicts between the language specified in the pattern and the language option provided in the command. This test is crucial for ensuring that the system correctly handles conflicts and provides meaningful feedback to the user. It's important to verify that the error handling and messaging are clear and helpful in guiding the user to resolve such conflicts. * 2218-2223: The `invalid_language_option_apply` test verifies the behavior when an invalid language option is provided. This test is important for ensuring robust error handling and clear messaging when unsupported or incorrect language options are used. It's essential to ensure that the system provides helpful feedback to guide the user in correcting the issue.
resources/language-metavariables/tree-sitter-vue/src/parser.c (2)
  • 3578-3579: The addition of .production_id to the REDUCE action for sym_style_element is noted. This change is crucial for differentiating between various types of reductions, especially in complex parsing scenarios. Ensure that the assigned production IDs align with the grammar's specifications and are consistently used across related parsing rules.
  • 3675-3677: The introduction of .production_id for the sym_style_start_tag REDUCE action is appropriate. It enhances the parser's ability to handle different parsing states more effectively, particularly for style sections within Vue files. As with other production ID assignments, verify that these IDs are correctly mapped and utilized within the grammar.

@@ -314,7 +314,7 @@ pub trait Language {
body: &str,
logs: &mut AnalysisLogs,
new: bool,
) -> Result<Tree> {
) -> Result<Option<Tree>> {
Copy link
Contributor

Choose a reason for hiding this comment

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

Changing the return type of the parse_file function to Result<Option<Tree>> introduces the possibility of a file parse returning None, indicating no parse tree was generated. This change requires all implementations of the Language trait to handle the None case appropriately. Ensure that all language-specific implementations and callers of parse_file are updated to handle this new possibility.

@@ -230,7 +230,7 @@ impl Language for Tsx {
body: &str,
logs: &mut marzano_util::analysis_logs::AnalysisLogs,
new: bool,
) -> anyhow::Result<tree_sitter::Tree> {
) -> anyhow::Result<Option<tree_sitter::Tree>> {
Copy link
Contributor

Choose a reason for hiding this comment

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

The change in the return type of the parse_file function to Result<Option<Tree>> in the Tsx implementation aligns with the updated Language trait. This adjustment allows for a more nuanced handling of parsing results, especially in cases where parsing fails or is not applicable. Ensure that the Tsx implementation and any related code correctly handle the None case to avoid runtime errors.

Comment on lines +111 to +128
// could probably be done better using a tree-sitter query?
pub(crate) fn get_vue_ranges(
file: &str,
parent_node_kind: &str,
name_array: Option<&[&str]>,
) -> Result<Vec<Range>> {
let vue = Vue::new(None);
let mut parser = Parser::new()?;
let text = file.as_bytes();
parser.set_language(vue.get_ts_language())?;
let tree = parser.parse(file, None)?.ok_or(anyhow!("missing tree"))?;
let cursor = tree.walk();
let mut ranges = Vec::new();
for n in traverse(CursorWrapper::new(cursor, file), Order::Pre) {
append_code_range(&n.node, text, &mut ranges, parent_node_kind, name_array)
}
Ok(ranges)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The get_vue_ranges function extracts code ranges from Vue files. It's crucial to ensure that this function is thoroughly tested, especially for edge cases where Vue files might have complex structures.

Would you like me to help generate additional test cases for this function?

Comment on lines +1 to +3
use anyhow::anyhow;
use marzano_util::tree_sitter_util::children_by_field_name_count;
use tree_sitter::{Node, Parser, Tree};
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The verification process has revealed that both "traverse" and "CursorWrapper" are indeed used elsewhere in the codebase, as shown by their occurrences in various files, particularly within the crates/core/src/ directory. This suggests that the removal of these utilities from xscript_util.rs could potentially impact their usage elsewhere. It is recommended to ensure that any dependencies on these removed utilities are resolved or that alternative implementations are provided to avoid issues.

Analysis chain

The refactoring of imports and removal of unused ones streamline the file. Ensure that the removed utilities are no longer needed elsewhere in the codebase.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Check for usage of removed utilities in the codebase.
grep -rn "traverse" .
grep -rn "CursorWrapper" .

Length of output: 18582

@morgante morgante merged commit c18a96e into main Mar 29, 2024
6 checks passed
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.

CSS in .vue
2 participants