Skip to content

feat: 增强组件管理功能 #1304

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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

Ljhhhhhh
Copy link
Contributor

@Ljhhhhhh Ljhhhhhh commented Apr 12, 2025

  1. 添加组件数据比较和更新功能
  2. 从materials/packages.json读取最新物料包配置
  3. 修复组件验证和关联方法中的问题

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

What is the current behavior?

Issue Number: N/A

What is the new behavior?

materials/packages.json 下更新依赖信息后,可通过 buildMaterial 指令同步更新到数据库

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Now dynamically updates material configurations by merging in the latest package details.
    • Enhanced component synchronization to automatically detect and apply updates based on data changes.
  • Bug Fixes

    • Improved error logging to more gracefully handle unexpected file scenarios.

1. 添加组件数据比较和更新功能
2. 从materials/packages.json读取最新物料包配置
3. 修复组件验证和关联方法中的问题
Copy link
Contributor

coderabbitai bot commented Apr 12, 2025

Walkthrough

The pull request enhances two scripts. In the build process, packages.json is read from the materials directory and its package configuration is merged into the material's npm field when applicable. In the database connection script, two new methods—normalizeJsonValue and isComponentDifferent—are introduced to standardize JSON values and compare component data. The initDB method now checks for component differences and calls updateComponent accordingly, with error logging in isValid updated for unknown files.

Changes

File(s) Summary
scripts/buildMaterials.mjs Reads packages.json from the materials directory, creates materialInfo, and merges package properties (excluding name) into material.npm if a package is specified.
scripts/connection.mjs Adds normalizeJsonValue and isComponentDifferent methods in MysqlConnection; updates initDB to check component differences and trigger updateComponent; refines error logging in isValid.

Sequence Diagram(s)

sequenceDiagram
    participant GM as generateComponents
    participant MI as Material Info Reader
    participant PK as packages.json Data
    GM->>MI: Read packages.json
    MI-->>GM: Return parsed data
    GM->>PK: Check if material.npm.package exists
    PK-->>GM: Return matching package information
    GM->>GM: Merge package properties into material.npm
Loading
sequenceDiagram
    participant IC as initDB
    participant DB as Database
    participant ICD as isComponentDifferent
    participant NC as normalizeJsonValue
    participant UC as updateComponent
    IC->>DB: Query existing component
    DB-->>IC: Return component data
    IC->>ICD: Compare new vs. existing component
    ICD->>NC: Standardize JSON values for comparison
    ICD-->>IC: Return comparison result
    alt Components differ
        IC->>UC: Call updateComponent
    else No differences
        IC->>IC: Continue processing
    end
Loading

Poem

Hopping through code under starry skies,
I nibble on changes with bright, twinkling eyes,
Merging packages and comparing each part,
A creative dance of logic and art,
CodeRabbit celebrates with a joyful hop—
Bounding ahead, never planning to stop!

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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.

@github-actions github-actions bot added the enhancement New feature or request label Apr 12, 2025
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: 0

🧹 Nitpick comments (3)
scripts/buildMaterials.mjs (1)

120-129: Good implementation of dynamic package configuration update.

The code correctly checks for package references in the material's npm configuration and updates them with the latest information from the centralized packages.json file. This enables maintaining package versions in a single location.

However, consider adding error handling in case the material has a package that doesn't exist in materialInfo.packages.

if (materialPackageInfo?.package) {
  const latestPackageInfo = materialInfo.packages.find((item) => item.package === materialPackageInfo.package)

  if (latestPackageInfo) {
    const { name: _name, ...rest } = latestPackageInfo
    material.npm = Object.assign(material.npm, rest)
+  } else {
+    logger.warn(`Package "${materialPackageInfo.package}" referenced in component but not found in packages.json`)
  }
}
scripts/connection.mjs (2)

135-184: Good implementation of component comparison logic.

The method thoroughly compares component fields, handling both primitive and object types appropriately. The normalization of JSON values ensures accurate comparison regardless of the serialization format.

There are two minor issues that could be improved:

  1. There's a redundant assignment of dbField at line 171 (it was already assigned at line 152)
  2. Consider using the existing logger instead of console.log for consistency
} else {
  // 对于基本类型,直接比较
- const dbField = this.fieldTransform(field)
  const newValue = String(newComponent[field])
  const dbValue = String(existingComponent[dbField])

  if (newValue !== dbValue) {
-   console.log(`${newComponent.component}字段 ${field} 需要更新: 新值: ${newValue} 旧值: ${dbValue}`)
+   logger.info(`${newComponent.component}字段 ${field} 需要更新: 新值: ${newValue} 旧值: ${dbValue}`)
    return true
  }
}

456-463: Enhanced component update logic.

The code now intelligently determines if a component needs updating by comparing its fields with the database version, avoiding unnecessary updates. This improves performance and ensures that only changed components are updated.

Consider adding a debug log when a component doesn't need updating to provide better visibility into the process.

const needUpdate = this.isComponentDifferent(component, existingComponent)

if (needUpdate) {
  this.updateComponent(component)
+} else {
+  logger.debug(`${component.component} is up to date, no update needed`)
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8a3f47b and e028db7.

📒 Files selected for processing (2)
  • scripts/buildMaterials.mjs (2 hunks)
  • scripts/connection.mjs (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (3)
scripts/buildMaterials.mjs (1)

20-21: Added feature to read package configurations from a central file.

This enhancement allows the application to read material package configurations from a centralized packages.json file.

scripts/connection.mjs (2)

97-133: Well-implemented JSON value normalization method.

This utility method effectively handles multiple JSON parsing scenarios, including nested JSON strings and different data types. The code is well-commented and provides a robust foundation for standardizing JSON values before comparison.


196-196: Improved error logging with fallback for unknown files.

This change enhances error reporting by handling cases where the file path is unknown, providing a clearer error message.

const parsed = JSON.parse(value)

// 如果解析结果仍然是字符串,且看起来像JSON,再次尝试解析
if (typeof parsed === 'string' && parsed.startsWith('{') && parsed.endsWith('}')) {
Copy link
Member

Choose a reason for hiding this comment

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

什么场景需要解析两遍?能举个示例吗?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

像 npm、snippets、configure 这几个字段,他原来是对象,从数据库获取后,大概会变成 '{"\name": "xxx"}'
如果不进一步对他们进行解析,无法获取最终的对象

Copy link
Member

Choose a reason for hiding this comment

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

那应该是对子属性进一步解析吧?应该没有字符串是需要两遍 JSON.parse 才能变成最终对象的?


// 检查每个字段是否有差异
for (const field of fieldsToCompare) {
if (!newComponent[field] && !existingComponent[this.fieldTransform(field)]) {
Copy link
Member

Choose a reason for hiding this comment

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

这里如果新值是 false,旧值是 undefined,那么是不是也不会触发更新?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

是的,你这么一说,这里应该优化一下

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants