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

chore: Adding NoConsoleLog rule to Biome linter #1348

Merged
merged 3 commits into from
Nov 13, 2024

Conversation

alexdigdir
Copy link
Contributor

@alexdigdir alexdigdir commented Nov 7, 2024

Hva er endret?

Dokumentasjon / Storybook / testdekning

  • Dokumentasjon er oppdatert eller ikke relevant / nødvendig.
  • Ny komponent har en eller flere stories i Storybook, eller så er ikke dette relevant.
  • Det er blitt lagt til nye tester / eksiterende tester er blitt utvidet, eller tester er ikke relevant.

Skjermbilder eller GIFs (valgfritt)

Summary by CodeRabbit

  • New Features

    • Introduced a new linter rule to disallow console log statements, enhancing code quality enforcement.
  • Chores

    • Updated the version of the @biomejs/biome package to improve stability and performance.
  • Bug Fixes

    • Enhanced error logging across various components to improve visibility and clarity of error messages.
  • Refactor

    • Updated export statement for the Filter type for better clarity in the codebase.
    • Modified the GuiActionsProps interface to accept a single action instead of an array, streamlining the component's structure.

@alexdigdir alexdigdir requested a review from a team November 7, 2024 11:39
Copy link

coderabbitai bot commented Nov 7, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces changes to multiple files, primarily focusing on the biome.jsonc configuration file, where a new linter rule noConsoleLog is added under the suspicious category with its level set to "error". The existing rule noArrayIndexKey is set to "off". Additionally, the package.json file is updated to change the version of the @biomejs/biome package from 1.9.2 to 1.9.4. A new shell script file .hooks/pre-push is also added to run linting checks before pushing changes.

Changes

File Change Summary
biome.jsonc Added new linter rule noConsoleLog with level set to "error" in linter.rules.suspicious; set noArrayIndexKey to "off".
package.json Updated version of @biomejs/biome from 1.9.2 to 1.9.4 in devDependencies.
.hooks/pre-push Created new file to execute pnpm lint-staged -- --color when triggered.
packages/docusaurus-tldraw-plugin/src/tldr.jsx Changed error logging from console.log to console.error for improved error visibility.
packages/frontend/src/analytics.ts Replaced console.log with console.info for successful initialization logging of Application Insights.
packages/frontend/src/auth/api.ts Changed error logging from console.log to console.error in getIsAuthenticated function.
packages/frontend/src/components/FilterBar/index.ts Modified export statement for Filter type from export { type Filter } to export type { Filter }.
packages/frontend/src/components/InboxItem/GuiActions.tsx Changed error logging from console.log to console.error in handleButtonClick; updated GuiActionsProps interface.
packages/frontend/src/main.tsx Updated logging method from console.log to console.error for missing "root" element.
packages/storybook/src/stories/GuiActions/guiActions.stories.tsx Changed logging from console.log to console.info in onDeleteSuccess callback.

Possibly related PRs

Suggested labels

dev

Suggested reviewers

  • seanes

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.

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

🧹 Outside diff range and nitpick comments (2)
package.json (1)

12-12: Document version bump reason in package.json.

Consider adding a comment in package.json to document that this version bump is required for the NoConsoleLog rule support.

   "devDependencies": {
-    "@biomejs/biome": "1.9.4",
+    "@biomejs/biome": "1.9.4", // Required for NoConsoleLog rule support
     "lint-staged": "^15.2.7",
biome.jsonc (1)

62-62: Consider adding JSON schema validation to prevent syntax errors.

While fixing the JSON structure is good, we should prevent such issues in the future.

Consider:

  1. Adding pre-commit hooks to validate JSON files
  2. Ensuring your IDE is configured to validate JSON schema
  3. Adding JSON validation to your CI pipeline
  "scripts": {
+   "validate:config": "biome check biome.jsonc"
  }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e15c158 and 08afe15.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • biome.jsonc (2 hunks)
  • package.json (1 hunks)
🔇 Additional comments (1)
package.json (1)

12-12: Verify @biomejs/biome version bump compatibility.

The version bump from 1.9.2 to 1.9.4 looks good, but let's verify there are no breaking changes.

✅ Verification successful

Version bump is compatible with NoConsoleLog rule

The version bump from 1.9.2 to 1.9.4 is safe as:

  1. The NoConsoleLog rule is already configured in biome.jsonc
  2. The repository's CHANGELOG.md shows no breaking changes in recent versions
  3. The rule configuration in biome.jsonc is compatible with both versions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the changelog between versions 1.9.2 and 1.9.4 for breaking changes
# and verify if the NoConsoleLog rule requires this version

# Search for changelog or release notes in the repository
rg -i "changelog|release.*notes" -g "!node_modules"

# Check for any existing Biome configuration using NoConsoleLog rule
# to ensure the version requirement is consistent
rg -l "noConsoleLog" -g "*.{json,jsonc}"

Length of output: 18207


Script:

#!/bin/bash
# Check the content of biome.jsonc to see if NoConsoleLog rule is already configured
cat biome.jsonc

# Check the content of CHANGELOG.md to see if there are any breaking changes
cat CHANGELOG.md

Length of output: 13022

biome.jsonc Outdated
Comment on lines 49 to 51
"noConsoleLog": {
"level": "error"
},
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Several console.log statements found that need attention

The new noConsoleLog rule will cause build failures due to existing console.log statements in the codebase. Here are the locations that need to be addressed:

  • packages/docusaurus-tldraw-plugin/src/tldr.jsx - Error logging
  • packages/frontend/src/analytics.ts - Initialization logging
  • packages/frontend/src/components/FilterBar/FilterBar.tsx - Debug logging
  • packages/frontend/src/components/InboxItem/InboxItemsHeader.tsx - Debug logging
  • packages/frontend/src/components/InboxItem/InboxItem.tsx - Debug logging
  • packages/frontend/src/components/InboxItem/GuiActions.tsx - Error and success logging
  • packages/frontend/src/auth/api.ts - Error logging
  • packages/frontend/src/main.tsx - Error logging
  • packages/fastify-graphiql/Readme.md - Example code
  • packages/storybook/src/stories/GuiActions/guiActions.stories.tsx - Multiple debug logs

Consider:

  1. Replacing error logging with proper error handling/logging utilities
  2. Removing debug console.logs or replacing with appropriate logging mechanisms
  3. Using environment-based logging for development-only logs
🔗 Analysis chain

LGTM! Let's verify the impact of this new rule.

The addition of the noConsoleLog rule as an error is appropriate for maintaining code quality. However, we should verify the impact on the existing codebase.

Let's check for any existing console.log statements that might break the build:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for console.log statements in the codebase
# Exclude test files, configuration files, and build artifacts

# Search for console.log statements
echo "Searching for console.log statements..."
rg "console\.log\(" \
  --type ts \
  --type tsx \
  --type js \
  --type jsx \
  -g '!*.test.*' \
  -g '!*.spec.*' \
  -g '!**/test/**' \
  -g '!**/tests/**'

Length of output: 245


Script:

#!/bin/bash
# Let's try a different approach using ripgrep without file type filters
# but with explicit exclusions for test and build files

echo "Searching for console.log statements..."
rg "console\.log\(" \
  --type-not test \
  --type-not spec \
  -g '!*.test.*' \
  -g '!*.spec.*' \
  -g '!**/test/**' \
  -g '!**/tests/**' \
  -g '!**/dist/**' \
  -g '!**/build/**' \
  -g '!**/node_modules/**' \
  -g '!**/.git/**'

Length of output: 313


Script:

#!/bin/bash
# Simplify the search using basic ripgrep without type filters
# Just exclude common test and build directories

echo "Searching for console.log statements..."
rg "console\.log\(" \
  --glob '!node_modules' \
  --glob '!dist' \
  --glob '!build' \
  --glob '!.git' \
  --glob '!test' \
  --glob '!tests' \
  --glob '!*.test.*' \
  --glob '!*.spec.*'

Length of output: 1595

@seanes
Copy link
Contributor

seanes commented Nov 7, 2024

Smeller på en del checks der, ja :thinking_face: Kanskje kun ha "error" på det som kjøres på lint-staged, og ikke ha det i global config?

f.eks.

  "lint-staged": {
    "**/*.*": [
    "biome check --staged --no-errors-on-unmatched --write",
    "biome check --rule no-console --severity error"
    ]
  },

i packages/frontend/package.json?

Hva tenker du?

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

🧹 Outside diff range and nitpick comments (4)
packages/frontend/src/auth/api.ts (1)

Line range hint 1-11: Consider implementing proper error handling.

This is an authentication-related function where errors should be properly handled. Consider implementing proper error tracking/monitoring instead of just returning false silently.

Some suggestions:

  1. Implement error tracking (e.g., Sentry, Application Insights)
  2. Add error boundaries at the React component level
  3. Consider adding a notification system to inform users of authentication issues

Would you like me to help implement any of these suggestions?

packages/frontend/src/main.tsx (1)

48-48: Appropriate use of console.error, but error handling could be enhanced.

Using console.error is correct here since this is a fatal error condition. However, consider enhancing the error handling to provide more context and better developer experience.

Consider this improvement:

-  console.error(`element with id "root" is not in DOM`);
+  const errorMessage = 'Failed to initialize application: DOM element with id "root" not found. ' +
+    'Please ensure index.html contains <div id="root"></div>';
+  console.error(errorMessage);
+  throw new Error(errorMessage);

This change would:

  1. Provide more context about the error
  2. Include troubleshooting guidance
  3. Halt execution to prevent undefined behavior
packages/frontend/src/components/InboxItem/GuiActions.tsx (2)

Line range hint 53-58: Enhance error handling with user feedback.

The current error handling only logs to console without providing any feedback to users. Consider implementing proper error handling with user notifications.

Here's a suggested improvement:

      if (!response.ok) {
-        console.error(`Error: ${response.statusText}`);
+        const errorMessage = `Failed to perform action: ${response.statusText}`;
+        // Use your application's error handling utility/service
+        handleError(errorMessage);
+        // Show user feedback (assuming you have a notification system)
+        showErrorNotification(errorMessage);
      }
    } catch (error) {
-      console.error('Error performing action:', error);
+      const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
+      handleError('Error performing action: ' + errorMessage);
+      showErrorNotification('Failed to perform action. Please try again later.');
    }

Line range hint 6-8: Fix interface inconsistency between GuiActionProps and GuiActionsProps.

There's an inconsistency in how actions are typed across the component:

  1. GuiActionProps expects an array of actions
  2. GuiActionsProps expects a single action
  3. GuiActions component maps over the actions array but passes single actions to GuiActionButton

This needs to be unified. Here's a suggested fix:

 export interface GuiActionProps {
   actions: GuiActionButtonProps[];
   dialogToken: string;
 }

 interface GuiActionsProps {
-  actions: GuiActionButtonProps;
+  actions: GuiActionButtonProps[];
   dialogToken: string;
 }

 // Update the GuiActionButton component signature
-const GuiActionButton = ({ actions, dialogToken }: GuiActionsProps)
+const GuiActionButton = ({ action, dialogToken }: { action: GuiActionButtonProps; dialogToken: string })

 // Update the usage in GuiActions
 export const GuiActions = ({ actions, dialogToken }: GuiActionProps): JSX.Element => {
   return (
     <section className={styles.guiActions} data-id="dialog-gui-actions">
       {actions.map((actionProps) => (
-        <GuiActionButton key={actionProps.id} actions={actionProps} dialogToken={dialogToken} />
+        <GuiActionButton key={actionProps.id} action={actionProps} dialogToken={dialogToken} />
       ))}
     </section>
   );
 };

Also applies to: 17-20, 121-127

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 08afe15 and cb43729.

📒 Files selected for processing (10)
  • .hooks/pre-push (1 hunks)
  • biome.jsonc (1 hunks)
  • package.json (1 hunks)
  • packages/docusaurus-tldraw-plugin/src/tldr.jsx (1 hunks)
  • packages/frontend/src/analytics.ts (1 hunks)
  • packages/frontend/src/auth/api.ts (1 hunks)
  • packages/frontend/src/components/FilterBar/index.ts (1 hunks)
  • packages/frontend/src/components/InboxItem/GuiActions.tsx (1 hunks)
  • packages/frontend/src/main.tsx (1 hunks)
  • packages/storybook/src/stories/GuiActions/guiActions.stories.tsx (3 hunks)
✅ Files skipped from review due to trivial changes (3)
  • .hooks/pre-push
  • packages/frontend/src/analytics.ts
  • packages/frontend/src/components/FilterBar/index.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • biome.jsonc
  • package.json
🔇 Additional comments (1)
packages/frontend/src/components/InboxItem/GuiActions.tsx (1)

54-54: Verify if console.error is allowed by the NoConsoleLog rule.

While the PR aims to implement the NoConsoleLog rule, this line introduces console.error for error logging. We should verify if this is intentionally allowed by the rule configuration.

Consider implementing a proper error logging service/utility instead of using console.error directly. This would:

  1. Provide consistent error handling across the application
  2. Enable better error tracking and monitoring
  3. Make it easier to switch logging implementations in the future

@@ -6,7 +6,7 @@ export const getIsAuthenticated = async (): Promise<boolean> => {
});
return response.ok;
} catch (error) {
console.log('error', error);
console.error('error', error);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove console.error as per NoConsoleLog rule.

While changing from console.log to console.error is more semantically correct for error logging, it still conflicts with the PR's objective of removing console logging via the NoConsoleLog rule.

-    console.error('error', error);
+    // Consider implementing proper error tracking/monitoring
+    return false;

Committable suggestion skipped: line range outside the PR's diff.

@@ -10,7 +10,7 @@ export const Tldr = ({ children, height }) => {
);

if (err) {
console.log(result.err);
console.error(result.err);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix undefined variable reference

The code references result.err but the destructured variable is named err. This will cause a runtime error as result is undefined.

Apply this fix:

-    console.error(result.err);
+    console.error(err);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.error(result.err);
console.error(err);

Comment on lines +13 to 14
console.error(result.err);
return <div>Error loading tldr file</div>;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling pattern

Given the PR's objective to remove console logging, consider implementing proper error handling:

  1. The error details would be lost once console logging is removed
  2. The generic error message "Error loading tldr file" provides little context for debugging

Consider this implementation:

-    console.error(err);
-    return <div>Error loading tldr file</div>;
+    return (
+      <div role="alert" className="tldr-error">
+        <h3>Failed to load TLDR file</h3>
+        <p>{err.message || 'An unexpected error occurred'}</p>
+      </div>
+    );

This approach:

  • Removes console logging as per the new linter rule
  • Preserves error details for users
  • Adds semantic HTML with proper ARIA attributes
  • Can be styled appropriately using the tldr-error class
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.error(result.err);
return <div>Error loading tldr file</div>;
return (
<div role="alert" className="tldr-error">
<h3>Failed to load TLDR file</h3>
<p>{err.message || 'An unexpected error occurred'}</p>
</div>
);

@@ -60,7 +60,7 @@ Default.args = {
},
],
dialogToken: 'your-dialog-token',
onDeleteSuccess: () => console.log('Deleted'),
onDeleteSuccess: () => console.info('Deleted'),
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reconsider the use of console.info as it doesn't align with the PR's intent

While replacing console.log with console.info technically bypasses the noConsoleLog rule, it doesn't align with the PR's objective of removing console logging. For Storybook stories, consider these better alternatives:

  1. Use Storybook's built-in action logger:
-onDeleteSuccess: () => console.info('Deleted'),
+onDeleteSuccess: action('onDeleteSuccess'),
  1. Or use a mock callback that updates component state to demonstrate the behavior visually:
const DeleteCallback = () => {
  const [deleted, setDeleted] = useState(false);
  return (
    <div>
      <GuiActions
        {...args}
        onDeleteSuccess={() => setDeleted(true)}
      />
      {deleted && <div>Item was deleted!</div>}
    </div>
  );
};

Also applies to: 89-89, 106-106

@alexdigdir alexdigdir merged commit 1836e17 into main Nov 13, 2024
23 checks passed
@alexdigdir alexdigdir deleted the chore/biome-console-error branch November 13, 2024 09:57
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.

2 participants