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

♻️ Sort field & Spport CLI #296

Merged
merged 9 commits into from
Oct 10, 2024
Merged

Conversation

Wxh16144
Copy link
Contributor

@Wxh16144 Wxh16144 commented Oct 10, 2024

之前的方式添加看了头皮发麻,大家添加的都很随意,也没有按照字母进行排序。

  1. 使用 eslint 规则解决排序问题
  2. 添加 CLI 方便用户直接命令行添加(开发者不需要处理排序问题

Summary by CodeRabbit

  • New Features

    • Introduced a command-line interface (CLI) utility for adding packages and scopes.
    • Enhanced README.md with clearer instructions and examples for managing packages via CLI.
  • Bug Fixes

    • Updated .gitignore to exclude package_draft.json, preventing unnecessary tracking.
  • Refactor

    • Replaced the old ESLint configuration with a new setup that improves JSON file linting.

Wxh16144 and others added 6 commits October 10, 2024 16:23
[skip ci]

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Expanded the list of allowed packages to include `kwxoswoff20jscss`,
enabling its use in the project.

- **Version Update**
	- Project version updated to `1.132.0`.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

(cherry picked from commit bc3a35a)
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Chores**
- Updated allowed scopes in package management: removed `@scent` and
added `@felce`.
- No changes made to `devDependencies` or other core fields in
`package.json`.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

(cherry picked from commit ae318f1)

# Conflicts:
#	package.json
Copy link

coderabbitai bot commented Oct 10, 2024

Caution

Review failed

The head commit changed during the review from 25e6046 to 8e9079a.

Walkthrough

The changes in this pull request include the removal of the .eslintrc file and the introduction of a new ESLint configuration in eslint.config.mjs, which integrates JSONC support. Additionally, the .gitignore file has been updated to ignore package_draft.json. The README.md has been enhanced with clearer instructions for adding packages and scopes via the CLI, and a new script scripts/generate.js has been added to facilitate the management of packages and scopes through a command-line interface.

Changes

File Change Summary
.eslintrc, eslint.config.mjs Removed .eslintrc; added eslint.config.mjs with JSONC support and custom rules for package.json.
.gitignore Added entry for package_draft.json to ignore it in Git.
README.md Updated instructions for adding packages and scopes via CLI; improved structure and added examples.
scripts/generate.js New CLI utility for adding packages and scopes, including input validation and file writing functionality.

Suggested reviewers

  • fengmk2

Poem

🐇 In the land of code where rabbits play,
New scripts and rules come out to stay.
With JSONC and a CLI so bright,
We hop through packages, all feels just right!
So let's celebrate, with a joyful cheer,
For cleaner code and paths that are clear! 🌟


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 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.

@Wxh16144
Copy link
Contributor Author

唯一缺点是,当前 PR 会破坏 blame, 以后会不好追溯。大家都洗白了...

[skip ci]

## [1.133.0](cnpm/unpkg-white-list@v1.132.0...v1.133.0) (2024-10-10)

### Features

* add [@felce](https://github.com/felce) ([cnpm#294](cnpm#294)) ([ae318f1](cnpm@ae318f1))
* add kwxoswoff20jscss ([cnpm#295](cnpm#295)) ([bc3a35a](cnpm@bc3a35a))

(cherry picked from commit 61d6cfa)
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

🧹 Outside diff range and nitpick comments (7)
eslint.config.mjs (1)

1-2: LGTM! Consider using named imports for clarity.

The imports are correct and necessary for the ESLint configuration. However, for improved readability, consider using named imports.

You could refactor the imports as follows:

-import pluginJsonc from "eslint-plugin-jsonc";
-import parserJsonc from "jsonc-eslint-parser";
+import { configs } from "eslint-plugin-jsonc";
+import { parser as jsoncParser } from "jsonc-eslint-parser";

This change would make it clearer which specific exports are being used from each package.

README.md (2)

13-23: LGTM: Comprehensive CLI usage examples

The new section on adding specific package names and versions is well-structured and provides clear examples for different scenarios. This aligns perfectly with the PR objective of introducing CLI support.

Consider adding a brief explanation of the difference between the three examples (all versions, specific version, version range) to further clarify their use cases for users who might be less familiar with semantic versioning.


Line range hint 25-35: LGTM: Helpful JSON examples

The added JSON examples effectively illustrate the expected changes in the package.json file after using the CLI commands. This visual representation enhances user understanding and complements the CLI instructions well.

Consider adding a brief comment above each JSON example to explicitly state that these are the resulting changes in the package.json file. This would provide even more context for users who might be skimming the document.

Also applies to: 45-52

scripts/generate.js (4)

1-36: LGTM! Consider enhancing the help message.

The initial setup, imports, and constant definitions look good. The use of environment variables for debugging and dynamic output path generation are well-implemented.

Consider updating the help message to include information about the debug mode:

 const HELP = `
 Usage:
   npm run add --package={package name}:{version range}
   npm run add --scope=@{scope name}
+
+ Debug mode:
+   Set DEBUG=true environment variable to use draft output and enable debug logging.
 `;

38-74: LGTM! Consider enhancing error handling.

The addPkg function is well-implemented, including input validation, existence checking, and sorting of packages. It aligns well with the PR objectives.

Consider using a more consistent approach to error handling:

 function addPkg(input) {
   if (typeof input !== 'string' || input.length === 0) {
-    return console.log('💥 Invalid package name');
+    throw new Error('Invalid package name');
   }

   const [name, version] = input.split(':');
+
+  if (!version) {
+    throw new Error('Invalid package format. Use {package name}:{version range}');
+  }

   // exits
   if (PKG.allowPackages[name]) {
     throw new Error(`Package ${name} already exists`);
   }

   // ... rest of the function
 }

This change ensures that all error cases are handled consistently by throwing errors, which can be caught and logged in the main function.


76-102: LGTM! Consider aligning error handling with addPkg function.

The addScope function is well-implemented, including input validation, existence checking, and sorting of scopes. It aligns well with the PR objectives.

For consistency with the suggested changes in the addPkg function, consider updating the error handling:

 function addScope(input) {
   if (typeof input !== 'string' || input.length === 0) {
-    return console.log('💥 Invalid scope name');
+    throw new Error('Invalid scope name');
   } else if (!input.startsWith('@')) {
     input = '@' + input;
   }

   DEBUG && console.log(`Add scope: ${input}`);

   // exits
   if (PKG.allowScopes.includes(input)) {
     throw new Error(`Scope ${input} already exists`);
   }

   // ... rest of the function
 }

This change ensures that all error cases are handled consistently by throwing errors, which can be caught and logged in the main function.


104-132: LGTM! Consider enhancing argument parsing and error handling.

The main function effectively manages the script's execution flow, including argument parsing and function calls. The implementation of debug logging is commendable.

Consider the following improvements:

  1. Use a command-line argument parsing library like yargs or commander for more robust argument handling:
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');

function main() {
  const argv = yargs(hideBin(process.argv))
    .usage(HELP)
    .option('pkg', {
      describe: 'Add a package',
      type: 'string'
    })
    .option('scope', {
      describe: 'Add a scope',
      type: 'string'
    })
    .help('h')
    .alias('h', 'help')
    .argv;

  if (argv.pkg) {
    addPkg(argv.pkg);
  } else if (argv.scope) {
    addScope(argv.scope);
  } else {
    console.log(HELP);
  }
}
  1. Implement error handling:
function main() {
  // ... argument parsing

  try {
    if (argv.pkg) {
      addPkg(argv.pkg);
    } else if (argv.scope) {
      addScope(argv.scope);
    } else {
      console.log(HELP);
    }
  } catch (error) {
    console.error('Error:', error.message);
    process.exit(1);
  }
}

These changes will make the script more robust and user-friendly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 61d6cfa and 272184e.

📒 Files selected for processing (5)
  • .eslintrc (0 hunks)
  • .gitignore (1 hunks)
  • README.md (2 hunks)
  • eslint.config.mjs (1 hunks)
  • scripts/generate.js (1 hunks)
💤 Files with no reviewable changes (1)
  • .eslintrc
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🧰 Additional context used
🔇 Additional comments (9)
eslint.config.mjs (4)

4-6: LGTM! Proper use of flat config format and recommended configurations.

The configuration export is well-structured. It correctly uses the new ESLint flat config format and includes the recommended configurations from the JSONC plugin.


7-10: LGTM! Correct file targeting and parser configuration.

The configuration correctly targets both package.json and package_draft.json files using a concise pattern. The use of parserJsonc is appropriate for parsing these JSON files, allowing for potential comments in the JSON.


1-28: Overall, excellent implementation of ESLint rules for sorting entries.

This ESLint configuration successfully implements the sorting functionality requested in the PR objectives. It uses modern ESLint practices with the flat config format and targets the specific needs of your project. The rules are well-defined to enforce sorting in both package.json and package_draft.json files.

Great job on improving the project's code organization!


11-27: LGTM! Sorting rules are well-configured. Verify custom field names.

The sorting rules are correctly configured to enforce alphabetical ordering of entries, which aligns with the PR objectives. The use of "error" severity ensures strict adherence to the sorting rules.

Please verify that allowScopes and allowPackages are the correct field names in your package.json and package_draft.json files. If these are custom fields specific to your project, they look good. If not, you may need to adjust the pathPattern values.

To confirm the existence and structure of these fields, you can run the following command:

This command will output the contents of these fields if they exist, allowing you to verify their structure and presence.

✅ Verification successful

To complete our verification, we need to check if package_draft.json exists and if it contains similar fields. Let's run another script to gather this information.


LGTM! Configuration is correct for package.json. package_draft.json not present.

The verification process has confirmed that the allowScopes and allowPackages fields are correctly configured in package.json with the expected structure. The allowScopes field is an array of strings containing various scope names, and the allowPackages field is an object with package names as keys and version specifications as values.

However, package_draft.json does not exist in the current directory. This absence doesn't necessarily indicate an issue, as it might be an optional file or not required for this specific project.

The ESLint configuration is correctly set up to handle these fields in package.json. If package_draft.json is indeed needed for your project, you may want to create it with similar allowScopes and allowPackages fields. Otherwise, the current configuration is sufficient for package.json.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and structure of allowScopes and allowPackages fields

# Test: Check for allowScopes and allowPackages in package.json and package_draft.json
jq '.allowScopes, .allowPackages' package*.json

Length of output: 285940


Script:

#!/bin/bash
# Check for package_draft.json and its contents

if [ -f package_draft.json ]; then
    echo "package_draft.json exists. Contents of allowScopes and allowPackages:"
    jq '.allowScopes, .allowPackages' package_draft.json
else
    echo "package_draft.json does not exist in the current directory."
fi

Length of output: 160

README.md (3)

10-11: LGTM: Clear guidance on using CLI

The added note effectively emphasizes the importance of using the CLI for adding white-list entries. This aligns well with the PR objective of introducing CLI support and helps prevent potential issues from manual package.json modifications.


37-43: LGTM: Clear instructions for adding scopes

The new section on adding specific scopes using the CLI is well-written and provides a clear example. This addition completes the set of instructions for using the CLI to manage the white-list, aligning with the PR objectives.


Line range hint 1-52: Overall: Excellent improvements to README clarity and alignment with PR objectives

The changes to the README.md file successfully address the PR objectives by:

  1. Introducing clear instructions for using the new CLI functionality.
  2. Providing comprehensive examples for adding packages and scopes to the white-list.
  3. Improving the overall structure and readability of the document.

These updates will greatly enhance the user experience for developers working with the project, making it easier to manage entries in a consistent and organized manner.

scripts/generate.js (2)

134-136: LGTM! Script execution is correctly implemented.

The main function is called at the end of the file, which is the standard practice for Node.js scripts.


1-136: Overall, great implementation with room for minor enhancements.

The scripts/generate.js file successfully implements a CLI for adding packages and scopes, meeting the PR objectives. The code is well-structured, includes appropriate input validation, and implements sorting as required. The use of debug logging and dynamic output paths are commendable practices.

To further improve the script:

  1. Consider using a command-line argument parsing library for more robust handling of user inputs.
  2. Implement consistent error handling across all functions.
  3. Enhance the help message to include information about the debug mode.

These enhancements will make the script more robust, user-friendly, and maintainable.

# Conflicts:
#	package.json
Copy link

socket-security bot commented Oct 10, 2024

New and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/eslint-plugin-jsonc@2.16.0 environment, filesystem Transitive: eval +10 2.36 MB ota-meshi
npm/eslint@9.12.0 environment Transitive: eval, filesystem, shell, unsafe +84 10.3 MB eslintbot
npm/fs-extra@11.2.0 Transitive: environment, filesystem +3 112 kB ryanzim
npm/jsonc-eslint-parser@2.4.0 unsafe +2 640 kB ota-meshi

🚮 Removed packages: npm/eslint@8.57.1

View full report↗︎

@fengmk2 fengmk2 merged commit fa5c428 into cnpm:master Oct 10, 2024
4 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.

5 participants