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

Automate Linting with Husky and lint-staged to Prevent CI Failures #896

Merged
merged 13 commits into from
Sep 6, 2024

Conversation

gwbaik9717
Copy link
Contributor

@gwbaik9717 gwbaik9717 commented Sep 6, 2024

What this PR does / why we need it?

This PR addresses the issue where linting was not being automatically executed before commits, despite Husky being installed. The previous setup had Husky installed at v8, but proper pre-commit hooks were not in place to ensure that linting occurred consistently. Since Husky v5, the configuration and usage have changed. For more details, refer to the the documentation of Husky.

Key changes include:

  • Adding the missing pre-commit configuration in the .husky folder, and ensure Husky works as expected to automate linting at the pre-commit stage.
  • Integrating lint-staged to only lint the files that are staged for commit, improving efficiency.

With these updates, developers will no longer need to manually run lint checks, as the process will be automated and enforced during the commit phase.

Any background context you want to provide?

This PR brings several improvements to the linting setup, along with updates to the Husky and lint-staged configurations.

1. Relocate lint Command to Root

As part of the monorepo migration (issue #648), the lint command was previously located in the sdk package, requiring developers to run pnpm sdk lint. However, this command is intended to lint the entire project, not just the sdk.

To address this, I’ve moved the lint command to the root package.json. Now, you can simply run pnpm lint to lint the whole project.

2. Ignore files in .eslintignore in lint-staged

To prevent unnecessary files from being linted, we use an .eslintignore file to specify which paths should be excluded. Since lint-staged doesn’t automatically respect .eslintignore by default, I’ve added the lint-staged.config.js file to ensure that the ignore rules are applied. This allows us to avoid linting files specified in .eslintignore during the pre-commit stage.

Alternatively, if we want to eliminate this step, we would need to upgrade ESLint to version 8.5.0 or later (we are currently using 8.19.0). For more information, refer to the lint-staged documentation.

Additionally, I’ve moved the .eslintignore file from the sdk package to the root, so it now applies to the entire monorepo. If you need to exclude specific files in other sub-projects, you can add them to this file.

# sdk
packages/sdk/src/api/yorkie/v1/yorkie_grpc_web_pb.d.ts
packages/sdk/src/api/yorkie/v1/yorkie_pb.d.ts
packages/sdk/src/api/yorkie/v1/resources_grpc_web_pb.d.ts
packages/sdk/src/api/yorkie/v1/resources_pb.d.ts
packages/sdk/test/vitest.d.ts
packages/sdk/dist

# devtools
... add files to prevent from being linted

3. Centralize ESLint Configuration in the Root

Since we are now working in a monorepo, it makes sense to centralize ESLint rules in a single configuration file at the root. To achieve this, I’ve created a root .eslintrc.js file, and sub-projects like sdk can extend from it. This ensures consistency across the entire codebase while allowing for project-specific overrides.

Here’s an example of how the sdk package extends the root ESLint configuration:

module.exports = {
  extends: ['../../.eslintrc.js'],
  // skipped
};

What are the relevant tickets?

Fixes #888

Checklist

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

  • New Features

    • Introduced new ESLint configuration to enhance code quality and maintainability.
    • Added pre-commit hook to ensure code quality checks before commits.
    • Implemented lint-staged configuration for targeted linting of staged files.
  • Bug Fixes

    • Streamlined linting commands in CI workflow for improved efficiency.
  • Chores

    • Removed unnecessary dependencies and scripts from package configurations to simplify the project setup.
  • Style

    • Enhanced code readability through formatting adjustments across various files.

Copy link

coderabbitai bot commented Sep 6, 2024

Walkthrough

This update introduces several configuration files and modifications aimed at enhancing the linting process in a JavaScript and TypeScript project. Key changes include the addition of .eslintignore, .eslintrc.js, and lint-staged.config.js files, alongside updates to existing files for improved linting automation using Husky. The updates streamline the development workflow by ensuring that only relevant files are checked for linting errors before commits.

Changes

Files Change Summary
.eslintignore New file created to specify paths and files to be ignored by ESLint during linting processes.
.eslintrc.js New ESLint configuration file defining linting rules, plugins, and overrides for TypeScript.
.github/workflows/ci.yml Modified lint command in CI workflow from pnpm sdk lint to pnpm lint.
.husky/pre-commit New pre-commit hook configuration added to run lint-staged.
examples/nextjs-scheduler/.eslintrc.js Updated to extend from a higher-level ESLint configuration and modified specific linting rules.
examples/nextjs-scheduler/package.json Removed dependency on eslint-plugin-prettier.
lint-staged.config.js New file created to configure linting for staged TypeScript files.
package.json Added new linting scripts and development dependencies for ESLint and Husky.
packages/sdk/.eslintrc.js Simplified ESLint configuration by extending from a parent configuration and reducing rules.
packages/sdk/package.json Removed several scripts and dependencies related to ESLint and Husky.

Assessment against linked issues

Objective Addressed Explanation
Automate Linting with Husky to Prevent CI Failures (#888)

🐰 Hopping through the code, oh what a sight,
With linting now automated, everything's bright!
Pre-commit hooks in place, errors kept at bay,
A cleaner codebase, hip-hip-hooray!
Let's celebrate this change, with a joyful cheer,
For a smoother workflow, we hold so dear! 🌟


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

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 17c8704 and 1624665.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (16)
  • .eslintignore (1 hunks)
  • .eslintrc.js (1 hunks)
  • .github/workflows/ci.yml (1 hunks)
  • .husky/pre-commit (1 hunks)
  • examples/nextjs-scheduler/.eslintrc.js (1 hunks)
  • examples/nextjs-scheduler/package.json (1 hunks)
  • lint-staged.config.js (1 hunks)
  • package.json (2 hunks)
  • packages/sdk/.eslintrc.js (1 hunks)
  • packages/sdk/package.json (3 hunks)
  • packages/sdk/src/document/crdt/tree.ts (1 hunks)
  • packages/sdk/src/document/document.ts (3 hunks)
  • packages/sdk/src/document/json/array.ts (4 hunks)
  • packages/sdk/src/util/error.ts (1 hunks)
  • packages/sdk/test/helper/helper.ts (1 hunks)
  • packages/sdk/test/unit/document/crdt/counter_test.ts (1 hunks)
Files skipped from review due to trivial changes (10)
  • .eslintignore
  • .github/workflows/ci.yml
  • .husky/pre-commit
  • examples/nextjs-scheduler/package.json
  • packages/sdk/package.json
  • packages/sdk/src/document/crdt/tree.ts
  • packages/sdk/src/document/json/array.ts
  • packages/sdk/src/util/error.ts
  • packages/sdk/test/helper/helper.ts
  • packages/sdk/test/unit/document/crdt/counter_test.ts
Additional comments not posted (6)
examples/nextjs-scheduler/.eslintrc.js (2)

2-2: Approved: Extension of ESLint configuration.

Extending from ../../.eslintrc.js is a good practice for maintaining consistency across the project.


10-10: Verify the rationale for disabling '@next/next/no-html-link-for-pages'.

Turning off this rule allows more flexibility but could lead to practices that are less optimized for Next.js. It's important to ensure that this change aligns with the project's goals.

packages/sdk/.eslintrc.js (1)

3-4: Approved: Simplified ESLint configuration with a suggestion to verify adequacy.

Extending from ../../.eslintrc.js and focusing on TypeScript documentation with eslint-plugin-tsdoc is a streamlined approach. Ensure that this configuration adequately covers all SDK-specific linting requirements.

package.json (1)

Line range hint 20-35: Approved: Addition of linting scripts and dependencies.

The new lint and prepare scripts, along with the added dependencies, are essential for the automated linting process. Verify that these configurations are correctly integrated and functioning as intended.

lint-staged.config.js (1)

5-18: Well-implemented function for filtering ignored files.

The removeIgnoredFiles function correctly uses ESLint's API to filter out files that are specified in the .eslintignore file. The use of Promise.all for handling multiple asynchronous operations is efficient and appropriate.

packages/sdk/src/document/document.ts (1)

Line range hint 441-545: Formatting Improvements in Type Definitions: Enhanced Readability

The changes to the indentation levels in the type definitions significantly improve the readability and clarity of the code. This is particularly important in a file with complex logic and numerous type interactions. Here are a few points to consider:

  • Consistency: Ensure that similar formatting improvements are applied consistently across all type definitions in the project to maintain uniformity.
  • Review: While the changes are beneficial, it's crucial to review them thoroughly to ensure that no syntactical errors have been introduced and that they align with the project's coding standards.

Overall, these formatting adjustments are a positive step towards better code maintainability and readability.

Comment on lines +20 to +39
module.exports = {
'**/*.ts': async (files) => {
const filesToLint = await removeIgnoredFiles(files);

if (filesToLint.length > 0) {
const fileArgs = filesToLint.join(' ');
const command = `pnpm exec eslint ${fileArgs} --fix --max-warnings=0 --ext .ts`;
try {
execSync(command, { stdio: 'inherit' });
process.exit(0);
} catch (error) {
console.error('Linting failed. Commit will be aborted.');
process.exit(1);
}
} else {
console.log('No eligible files to lint. Skipping lint-staged command.');
process.exit(0);
}
},
};
Copy link

Choose a reason for hiding this comment

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

Robust linting configuration for TypeScript files.

The module export configuration for linting TypeScript files is well-implemented. The use of pnpm exec eslint with the --fix and --max-warnings=0 flags ensures that linting issues are automatically fixed and that no warnings are allowed.

Suggestion: Consider handling the process exit more gracefully by allowing other middleware in lint-staged to continue running if needed, rather than using process.exit() which stops all processes immediately.

Comment on lines +1 to +61
module.exports = {
root: true,
plugins: ['prettier', 'jsdoc', '@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
'prettier/prettier': 'error',
'object-shorthand': ['error', 'always'],
'no-unreachable': 'error',
},
overrides: [
{
files: ['**/*.ts', '**/*.tsx'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: ['plugin:@typescript-eslint/recommended'],
rules: {
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'jsdoc/require-jsdoc': [
'error',
{
contexts: ['MethodDefinition:not([accessibility="private"])'],
require: {
ClassDeclaration: true,
},
checkConstructors: false,
enableFixer: false,
},
],
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'variable',
format: ['camelCase', 'PascalCase'],
leadingUnderscore: 'allowDouble',
trailingUnderscore: 'allowDouble',
},
],
'@typescript-eslint/ban-types': [
'error',
{
types: { null: 'Use undefined instead of null' },
},
],
'@typescript-eslint/array-type': ['error', { default: 'generic' }],
'@typescript-eslint/no-this-alias': [
'error',
{
allowDestructuring: true,
allowedNames: ['node'],
},
],
},
},
],
};
Copy link

Choose a reason for hiding this comment

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

Review of ESLint Configuration: Generally Solid with Suggestions for Improvement

The ESLint configuration is well-structured and covers a broad range of rules that are essential for maintaining code quality and consistency, especially in a TypeScript project. Here are some observations and suggestions:

  • TypeScript Rules: The configuration disables some TypeScript rules (@typescript-eslint/no-non-null-assertion, @typescript-eslint/no-explicit-any, and @typescript-eslint/ban-ts-comment). While this may offer flexibility, it could compromise type safety. Consider enabling these rules if the project aims for strict type safety.
  • JSDoc Rules: The inclusion of JSDoc rules (jsdoc/require-jsdoc) is commendable as it enforces documentation, which is crucial for maintainability and clarity.
  • Prettier Integration: Enforcing prettier rules as errors is a good practice to ensure consistent code formatting.

Overall, the setup is robust, but revisiting the disabled TypeScript rules could further enhance the project's code quality.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1624665 and fa5f976.

Files selected for processing (2)
  • .eslintignore (1 hunks)
  • examples/nextjs-scheduler/.eslintrc.js (1 hunks)
Files skipped from review due to trivial changes (1)
  • .eslintignore
Files skipped from review as they are similar to previous changes (1)
  • examples/nextjs-scheduler/.eslintrc.js

Copy link
Member

@hackerwins hackerwins left a comment

Choose a reason for hiding this comment

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

Thanks for your contribution.
Let's merge and check if it works properly in CI too.

.husky/pre-commit 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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between fa5f976 and aa95c55.

Files selected for processing (1)
  • .husky/pre-commit (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • .husky/pre-commit

@hackerwins hackerwins merged commit 4837c7d into yorkie-team:main Sep 6, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Backlog
Development

Successfully merging this pull request may close these issues.

Automate Linting with Husky to Prevent CI Failures
2 participants