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

refactor: new components are generated automatically #2940

Merged
merged 9 commits into from
Jan 15, 2025

Conversation

irisSong
Copy link
Collaborator

@irisSong irisSong commented Jan 14, 2025

🤔 这个变动的性质是?

  • 新特性提交
  • 日常 bug 修复
  • 站点、文档改进
  • 演示代码改进
  • 组件样式/交互改进
  • TypeScript 定义更新
  • 包体积优化
  • 性能优化
  • 功能增强
  • 国际化改进
  • 重构
  • 代码风格优化
  • 测试用例
  • 分支合并
  • 其他改动(是关于什么的改动?)

🔗 相关 Issue

💡 需求背景和解决方案

☑️ 请求合并前的自查清单

⚠️ 请自检并全部勾选全部选项⚠️

  • 文档已补充或无须补充
  • 代码演示已提供或无须提供
  • TypeScript 定义已补充或无须补充
  • fork仓库代码是否为最新避免文件冲突
  • Files changed 没有 package.json lock 等无关文件

Summary by CodeRabbit

  • 依赖变更

    • 新增依赖 @inquirer/prompts@^7.2.3
    • 移除依赖 inquirer@^10.1.4
  • 脚本更新

    • 组件创建脚本升级,采用异步/等待模式
    • 改进用户交互和文件操作处理
    • 优化组件生成流程的错误处理
  • 演示代码生成

    • 增强演示模型功能,支持更多文档生成
    • 支持国际化标题,提升多语言支持
    • 改进组件演示代码结构,增强可读性和可重用性
    • 更新文档以反映新参数和使用示例

Copy link

coderabbitai bot commented Jan 14, 2025

变更概述

演练

此次变更主要涉及 package.json 和脚本文件的依赖和功能更新。在 package.json 中,将 inquirer 依赖替换为 @inquirer/prompts。脚本文件 create-component-mode.jsdemo.js 进行了重大重构,包括异步/等待模式、依赖更新、代码结构优化和国际化支持等改进。

变更

文件 变更摘要
package.json 移除 inquirer@^10.1.4,添加 @inquirer/prompts@^7.2.3
scripts/create-component-mode.js 重构为异步函数,更新 newCpt 对象,使用 fs.promises 进行文件操作
scripts/demo.js 更新 demoModel 函数签名,添加国际化支持,引入类型导出

建议标签

size/XXL

建议评审人

  • xiaoyatong
  • oasis-cloud

诗歌

🐰 代码跃动如春风,
依赖更新换新装,
异步编织魔法线,
兔子微笑看变迁!
技术之路永不慌 🌈

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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. (Beta)
  • @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.

@github-actions github-actions bot added the 3.x label Jan 14, 2025
@coderabbitai coderabbitai bot added size/XXL wonderful Wonderful solutions labels Jan 14, 2025
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: 1

🧹 Nitpick comments (2)
scripts/demo.js (1)

1-1: 建议:为函数添加参数校验

在第1行,demoModel函数新增了cNamedesc参数。建议在函数中添加对这两个参数的有效性校验,确保其类型和内容符合预期,防止后续使用时出现错误。

scripts/create-component-mode.js (1)

236-242: 提示:统一错误处理

在第236-242行的createNew函数中,对Promise.all(tasks)使用了try...catch,这很好地捕获了异步操作的错误。为了保持代码风格的一致性,建议在其他异步函数中也添加错误处理,例如在createReactcreateDemo等函数中。

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 44053c0 and 7c6c52c.

📒 Files selected for processing (3)
  • package.json (1 hunks)
  • scripts/create-component-mode.js (1 hunks)
  • scripts/demo.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
scripts/create-component-mode.js

[error] 33-35: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (3)
scripts/demo.js (2)

90-90: 确认:类型导出的正确性

第90行,导出类型export type { ${name}Props } from './types'。请确保./types文件中正确定义了${name}Props类型,并且路径无误。


153-153: ⚠️ Potential issue

修正:模板字符串中的变量名

第153行的doc模板中,import { name } from '@nutui/nutui-react'可能存在错误,name应为模板字符串变量${name}

建议修改为:

-import { name } from '@nutui/nutui-react'
+import { ${name} } from '@nutui/nutui-react'

Likely invalid or redundant comment.

package.json (1)

156-156: 确认:新依赖包的版本和兼容性

在第156行,添加了"@inquirer/prompts":"^7.2.3",同时移除了"inquirer":"^10.1.4"。请确保@inquirer/prompts版本7.2.3与项目其他依赖兼容,并且在代码中已正确替换inquirer的用法。

scripts/create-component-mode.js Outdated Show resolved Hide resolved
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 (3)
scripts/create-component-mode.js (3)

18-19: 为新属性添加注释说明

新增的 v15dd 属性缺少注释说明,这可能会影响其他开发者对这些属性的理解和正确使用。

建议添加注释说明这些属性的用途:

const newCpt = {
  version: '3.0.0',
  name: '',
  type: '',
  cName: '',
  desc: '',
  sort: '',
  show: true,
  taro: true,
+ // 是否兼容 v1.5 版本
  v15: false,
+ // 是否支持 DD 小程序
  dd: true,
  author: '',
}

96-105: 优化:提取重复的文件创建逻辑

多个函数中存在相似的文件创建逻辑,建议提取为一个通用的辅助函数以减少代码重复。

建议创建一个通用的文件创建函数:

async function createFiles(dirPath: string, files: Array<{path: string, content: string}>) {
  for (const file of files) {
    const filePath = path.join(dirPath, file.path)
    await createFile(filePath, file.content)
  }
}

然后在各个函数中复用:

async function createReact() {
  const nameLc = newCpt.name.toLowerCase()
  const name = newCpt.name
  const dirPath = path.join(__dirname, `../src/packages/${nameLc}/`)
  await ensureDir(dirPath)

  const files = [
    { path: `${nameLc}.tsx`, content: demoModel(name).react },
    { path: `index.ts`, content: demoModel(name).index },
    { path: `types.ts`, content: demoModel(name).types },
  ]

- for (const file of files) {
-   const filePath = path.join(dirPath, file.path)
-   await createFile(filePath, file.content)
- }
+ await createFiles(dirPath, files)
}

Also applies to: 114-122, 134-141, 153-166


233-240: 优化:统一错误处理的语言并优化进程退出

错误处理中混合使用了中英文,且进程退出可以更优雅。

建议修改为:

  try {
    await Promise.all(tasks)
-   console.log('组件模板生成完毕,请开始你的表演~')
+   console.log('✨ 组件模板生成完毕!')
    process.exit()
  } catch (err) {
-   console.error('Error during component creation:', err)
+   console.error('❌ 组件创建失败:', err)
    process.exit(1)
  }

另外建议添加进程清理:

+ process.on('SIGINT', () => {
+   console.log('\n🛑 组件创建已取消')
+   process.exit(0)
+ })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c6c52c and 7a82d00.

📒 Files selected for processing (1)
  • scripts/create-component-mode.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
scripts/create-component-mode.js

[error] 33-35: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (1)
scripts/create-component-mode.js (1)

28-30: 优化:避免可能的空值引用

在使用 nav.some()category.packages.some() 时,如果 navcategory.packagesundefined,可能会导致运行时错误。

建议修改为:

- const repeat = nav.some((category) =>
-   category.packages.some((pkg) => pkg.name === value)
- )
+ const repeat = nav?.some((category) =>
+   category.packages?.some((pkg) => pkg.name === value)
+ )

Copy link

codecov bot commented Jan 14, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 85.58%. Comparing base (44053c0) to head (b5df8d3).
Report is 1 commits behind head on feat_v3.x.

Additional details and impacted files
@@            Coverage Diff             @@
##           feat_v3.x    #2940   +/-   ##
==========================================
  Coverage      85.58%   85.58%           
==========================================
  Files            277      277           
  Lines          18185    18185           
  Branches        2763     2763           
==========================================
  Hits           15563    15563           
  Misses          2617     2617           
  Partials           5        5           

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

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

🧹 Nitpick comments (2)
scripts/create-component-mode.js (2)

9-21: 需要为新属性添加注释说明

newCpt 对象新增了 v15dd 属性,但缺少相关说明。建议添加注释来解释这些属性的用途。

建议添加如下注释:

 const newCpt = {
   version: '3.0.0',
   name: '',
   type: '',
   cName: '',
   desc: '',
   sort: '',
   show: true,
   taro: true,
+  // 是否支持 Vue 1.5 版本
   v15: false,
+  // 是否支持按需引入
   dd: true,
   author: '',
 }

220-241: 建议优化任务执行顺序

当前使用 Promise.all 并行执行所有任务,但某些任务可能存在依赖关系。建议将任务分组,按照依赖顺序执行。

建议重构如下:

async function createNew() {
  try {
    // 第一组:基础文件创建
    await Promise.all([
      createIndexJs(),
      createScss(),
      createDoc(),
    ]);

    // 第二组:组件文件创建
    await Promise.all([
      createReact(),
      createReactTaro(),
    ]);

    // 第三组:示例和测试文件创建
    await Promise.all([
      createDemo(),
      createTaroDemo(),
      createTest(),
    ]);

    // 最后:更新配置
    await addToPackageJson();

    console.log('组件模板生成完毕,请开始你的表演~');
    process.exit();
  } catch (err) {
    console.error('Error during component creation:', err);
    process.exit(1);
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7a82d00 and b5df8d3.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • scripts/create-component-mode.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
scripts/create-component-mode.js

[error] 33-35: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: test
🔇 Additional comments (1)
scripts/create-component-mode.js (1)

64-82: 实现完善,错误处理得当!

ensureDircreateFile 函数实现了良好的错误处理机制,并提供了清晰的错误日志。

Comment on lines +83 to +84
async function createIndexJs() {
const destPath = path.join('src/packages', newCpt.name.toLowerCase())
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

安全警告:路径构造可能存在安全隐患

在构造文件路径时直接使用了用户输入(newCpt.name),这可能导致路径遍历漏洞。建议添加路径验证。

建议添加路径验证函数:

function validateComponentName(name) {
  // 只允许字母、数字和连字符
  const validPattern = /^[A-Za-z0-9-]+$/;
  if (!validPattern.test(name)) {
    throw new Error('组件名称只能包含字母、数字和连字符');
  }
  // 防止路径遍历
  if (name.includes('.') || name.includes('/') || name.includes('\\')) {
    throw new Error('组件名称包含非法字符');
  }
}

Also applies to: 90-94

@oasis-cloud oasis-cloud merged commit 4edcfd7 into jdf2e:feat_v3.x Jan 15, 2025
7 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jan 23, 2025
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants