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 #895

Closed
wants to merge 14 commits into from

Conversation

gwbaik9717
Copy link
Contributor

@gwbaik9717 gwbaik9717 commented Sep 5, 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
};

4. (Added) Relocated TypeScript to Root
In our monorepo setup, we've standardized the TypeScript version to 5.3.3 by relocating TypeScript to the root package.json. This change simplifies the management of the TypeScript version across all sub-projects.

What are the relevant tickets?

Fixes #888

Checklist

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

Summary by CodeRabbit

  • New Features

    • Introduced a new ESLint configuration to enhance code quality and maintainability.
    • Added pre-commit hook to enforce linting on staged files.
    • Simplified linting process by excluding unnecessary files from checks.
  • Bug Fixes

    • Removed unnecessary TypeScript dependencies across multiple projects to streamline development.
  • Documentation

    • Improved readability and consistency in code formatting and type definitions.
  • Chores

    • Updated project dependencies and scripts to enhance development workflow.

Copy link

coderabbitai bot commented Sep 5, 2024

Walkthrough

This update introduces several changes to the project's linting and formatting configurations. A new .eslintignore file is added to exclude specific files from linting, while a new ESLint configuration file (.eslintrc.js) establishes rules for JavaScript and TypeScript files. The CI workflow is modified to simplify linting commands, and a pre-commit hook is introduced using Husky to automate linting checks. Additionally, TypeScript dependencies are removed from multiple package configurations.

Changes

Files Change Summary
.eslintignore, .eslintrc.js New files created; .eslintignore specifies files to ignore during linting, and .eslintrc.js sets up ESLint rules and configurations.
.github/workflows/ci.yml Modified linting command from pnpm sdk lint to pnpm lint.
.husky/pre-commit New pre-commit hook added to run lint-staged for linting staged files.
examples/nextjs-scheduler/.eslintrc.js Added rule to disable the Next.js linting rule enforcing the use of Link component.
examples/*/package.json Removed TypeScript dependency from multiple example projects.
lint-staged.config.js New file created to configure linting for staged TypeScript files.
package.json, packages/sdk/package.json Updated scripts and dependencies; removed several ESLint-related dependencies and the linting script from SDK package.
packages/sdk/.eslintrc.js Simplified ESLint configuration by reducing rules and focusing on TSDoc syntax.
packages/sdk/src/* Various formatting changes made for improved readability in TypeScript files.

Assessment against linked issues

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

🐰 In the meadow, I hop with glee,
Linting now runs so effortlessly!
With Husky's help, no errors to find,
Clean code and joy, oh, how refined!
Let's celebrate this change with cheer,
A tidy project, oh 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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

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

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (21)
  • .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)
  • examples/react-tldraw/package.json (1 hunks)
  • examples/react-todomvc/package.json (1 hunks)
  • examples/vanilla-codemirror6/package.json (1 hunks)
  • examples/vanilla-quill/package.json (1 hunks)
  • lint-staged.config.js (1 hunks)
  • package.json (2 hunks)
  • packages/devtools/package.json (1 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 (15)
  • .eslintignore
  • .github/workflows/ci.yml
  • .husky/pre-commit
  • examples/nextjs-scheduler/package.json
  • examples/react-tldraw/package.json
  • examples/react-todomvc/package.json
  • examples/vanilla-codemirror6/package.json
  • examples/vanilla-quill/package.json
  • packages/sdk/package.json
  • packages/sdk/src/document/crdt/tree.ts
  • packages/sdk/src/document/document.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 (7)
examples/nextjs-scheduler/.eslintrc.js (1)

10-10: Consider the implications of disabling '@next/next/no-html-link-for-pages'.

Disabling this rule allows for the use of standard HTML <a> tags instead of Next.js's Link component. While this increases flexibility, it could potentially lead to less optimized client-side navigation experiences, as <a> tags do not benefit from Next.js's prefetching capabilities. Ensure that this change aligns with the project's performance and user experience goals.

packages/sdk/.eslintrc.js (1)

3-3: Approve the centralization of ESLint configuration but ensure necessary rules are maintained.

The move to extend ../../.eslintrc.js helps in maintaining consistency across sub-projects. However, ensure that any specific rules that are necessary for the SDK's unique requirements are not lost in this transition. The focus on TSDoc is commendable for emphasizing documentation quality.

Also applies to: 4-4

packages/devtools/package.json (1)

30-30: Approve the removal of TypeScript from local dependencies.

Standardizing TypeScript at the project root level is a strategic move to maintain consistency and avoid version conflicts across sub-projects. This change should help streamline development processes and ensure that all sub-projects are using the same TypeScript version.

lint-staged.config.js (1)

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

The use of Promise.all to handle multiple asynchronous operations concurrently is appropriate and efficient.

package.json (2)

19-21: Scripts for linting and Husky setup are correctly defined.

The lint script enforces a strict linting policy by treating warnings as errors, which is beneficial for maintaining code quality.


30-43: Dependencies and TypeScript version override are appropriately configured.

The new dependencies support the project's enhanced linting capabilities and Husky integration. The TypeScript version override is a good practice to maintain consistency and avoid potential conflicts.

.eslintrc.js (1)

1-61: ESLint configuration is comprehensive and well-structured.

The configuration effectively addresses common coding issues and adheres to best practices with the inclusion of plugins like prettier and jsdoc. This setup should significantly improve code quality and consistency across the project.

Comment on lines +20 to +38
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.log('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.

Consider improvements in error handling and execution method.

The use of execSync might block the Node.js event loop. Consider using exec for a non-blocking approach. Additionally, improve error handling by logging the error stack or message for better debugging.

@gwbaik9717
Copy link
Contributor Author

Previously, we had multiple unused versions of TypeScript in the project, one of which caused conflicts with typedoc. For the efficient management of TypeScript, I've standardized the version to 5.3.3 across all sub-projects. I’ve verified that the commands, including pnpm sdk build:docs, work correctly.

@gwbaik9717
Copy link
Contributor Author

@hackerwins
I’ve decided to focus on the issue setting up Husky and lint-staged for now. I’ll roll back the changes I made when relocating TypeScript to the previous setup, as I’ll need more time to address the dependency issues.

@gwbaik9717 gwbaik9717 closed this Sep 6, 2024
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.

Automate Linting with Husky to Prevent CI Failures
2 participants