Skip to content

Add Husky pre-commit and pre-push hooks for automated doc checks #1413

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

Merged
merged 25 commits into from
Mar 4, 2025

Conversation

krofax
Copy link
Collaborator

@krofax krofax commented Feb 25, 2025

Description

Overview

This PR implements Git hooks using Husky to automate documentation quality checks, ensuring all contributions maintain consistent quality standards before they're committed or pushed.

Changes

  • Added pre-commit hook to run lint-staged for targeted checks on changed files
  • Added pre-push hook for comprehensive documentation validation
  • Configured lint-staged to run specific checks based on file types:
    • ESLint and spell checking for MDX files
    • Redirect fixes and breadcrumb generation for all files
    • Link validation across the docs

Benefits

  • Catches issues earlier in the development process
  • Ensures documentation quality is maintained consistently
  • Reduces the number of failed CI checks by validating locally first
  • Automates routine tasks like link checker and redirect links

Tests

Additional context

Metadata

@krofax krofax requested a review from a team as a code owner February 25, 2025 00:02
Copy link

netlify bot commented Feb 25, 2025

Deploy Preview for docs-optimism ready!

Name Link
🔨 Latest commit b90c291
🔍 Latest deploy log https://app.netlify.com/sites/docs-optimism/deploys/67c733ba813f720008d6a144
😎 Deploy Preview https://deploy-preview-1413--docs-optimism.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

Warning

Rate limit exceeded

@krofax has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 33 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 06d1235 and b90c291.

📒 Files selected for processing (1)
  • public/_redirects (1 hunks)
📝 Walkthrough

Walkthrough

This pull request introduces a new Git pre-push hook by adding a .husky/pre-push script that sets up the execution environment, applies automatic fixes using pnpm fix, and confirms the completion of these fixes before allowing the push to proceed. Additionally, the package.json file is updated to modify the "breadcrumbs" script execution command, transitioning from npx ts-node-esm --skip-project to node --loader ts-node/esm. Two new dependencies, "glob": "^11.0.1" and "@types/glob": "^8.1.0", are added. Minor grammatical adjustments are made in an MDX file, correcting the phrase "gas price fluctuations" to "gas price fluctuation." Other files, such as utils/create-breadcrumbs.ts and utils/fix-redirects.ts, have undergone changes in directory path resolution and removal of non-functional comments, respectively.

Sequence Diagram(s)

sequenceDiagram
    participant Developer
    participant Git
    participant PrePushHook
    Developer->>Git: Initiate push
    Git->>PrePushHook: Execute .husky/pre-push hook
    PrePushHook->>PrePushHook: Source Husky environment
    PrePushHook->>Output: Print "automatic fixes are being applied" message
    PrePushHook->>PNPM: Execute "pnpm fix"
    PNPM-->>PrePushHook: Fix process complete
    PrePushHook->>Output: Print confirmation message
    PrePushHook->>Git: Continue push operation
Loading

Possibly related PRs

  • fix metadata #1440: The changes in the main PR are related to those in the retrieved PR through the modifications made to the package.json file, specifically the addition of the same dependencies for the glob package and its type definitions.

Suggested reviewers

  • bradleycamacho
  • cpengilly

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.
  • @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
Contributor

@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 (2)
.husky/pre-push (1)

1-4: Add error handling and user feedback.

While the commands are correctly sequenced, consider enhancing the script with error handling and user feedback:

 . "$(dirname -- "$0")/_/husky.sh"
 
-pnpm fix-redirects
-pnpm link-checker
+echo "Running pre-push checks..."
+
+echo "📝 Fixing redirects..."
+if ! pnpm fix-redirects; then
+  echo "❌ Fix redirects failed"
+  exit 1
+fi
+
+echo "🔍 Checking links..."
+if ! pnpm link-checker; then
+  echo "❌ Link checker failed"
+  exit 1
+fi
+
+echo "✅ All pre-push checks passed"
package.json (1)

22-31: Consider optimizing lint-staged configuration.

The current configuration runs fix-redirects and link-checker on all files, which might be inefficient for large repositories.

 "lint-staged": {
   "**/*.mdx": [
     "eslint --max-warnings 0",
     "cspell lint"
   ],
-  "**/*": [
+  "**/*.{md,mdx}": [
     "pnpm fix-redirects",
     "pnpm link-checker"
   ]
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 677531f and d626649.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (4)
  • .husky/pre-commit (1 hunks)
  • .husky/pre-push (1 hunks)
  • package.json (3 hunks)
  • pages/app-developers/tutorials/transactions/sdk-estimate-costs.mdx (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • pages/app-developers/tutorials/transactions/sdk-estimate-costs.mdx
  • .husky/pre-commit
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Redirect rules - docs-optimism
  • GitHub Check: Header rules - docs-optimism
  • GitHub Check: Pages changed - docs-optimism
  • GitHub Check: pr-workflow
🔇 Additional comments (1)
package.json (1)

65-66: LGTM! Dependencies are up to date.

The latest versions of husky (^9.1.7) and lint-staged (^15.4.3) are being used.

Copy link
Contributor

@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 (1)
package.json (1)

19-20: Suppress Warning Messages in Metadata Validation Scripts
The validate-metadata and validate-pr-metadata scripts now set NODE_OPTIONS="--no-warnings" to suppress warning messages during execution. This reduces noise in logs but please verify that important warnings are not being unintentionally hidden in development or CI environments.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6be5a66 and 10364d2.

📒 Files selected for processing (3)
  • package.json (3 hunks)
  • utils/metadata-analyzer.ts (1 hunks)
  • utils/metadata-manager.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • utils/metadata-manager.ts
  • utils/metadata-analyzer.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules - docs-optimism
  • GitHub Check: Header rules - docs-optimism
  • GitHub Check: Pages changed - docs-optimism
🔇 Additional comments (3)
package.json (3)

24-25: Enable Husky Hook Installation and Optimize Postbuild Tasks
The addition of the "prepare": "husky" script ensures that Husky hooks are automatically set up during the preparation phase, which aligns with the PR’s goal of automating quality checks. The new "postbuild": "next-sitemap" script should correctly generate the sitemap after building. Confirm that these changes integrate seamlessly with your build and deployment pipelines.


27-35: Establish Lint-Staged Configuration for Automated Doc Checks
The newly added "lint-staged" section configures targeted commands for staged files:

  • For **/*.mdx files: running ESLint (with a no-warning threshold) and a spell check via cspell lint
  • For all files: running pnpm fix-redirects and pnpm link-checker
    This setup directly supports the PR objective of enforcing documentation quality before commits and pushes. Ensure that the glob patterns precisely match the intended files to avoid unintentional processing.

72-73: Add DevDependencies for Husky and Lint-Staged
The new devDependencies "husky": "^9.1.7" and "lint-staged": "^15.4.3" are included to support the hook and staged file validation workflows. Validate that these versions are fully compatible with your project requirements and any related tooling.

Copy link
Contributor

@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: 3

🧹 Nitpick comments (2)
.husky/pre-push (2)

1-6: Add a missing final newline to the file.

The file should end with a newline character to follow best practices for text files.

echo "✅ Fixes applied - your contribution is now ready for review!"
+

4-6: Consider adding more detailed output about which fixes are being applied.

To improve user experience, it would be helpful to provide more information about what specifically is being fixed.

echo "🔍 Running automatic fixes before pushing..."
-pnpm fix
+echo "   - Checking and fixing documentation issues..."
+echo "   - Running spell checker..."
+echo "   - Validating links..."
+echo "   - Generating breadcrumbs..."
+echo "   - Fixing redirects..."
+pnpm fix
echo "✅ Fixes applied - your contribution is now ready for review!"
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c2320f3 and 6d317b4.

📒 Files selected for processing (2)
  • .husky/pre-push (1 hunks)
  • package.json (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules - docs-optimism
  • GitHub Check: Header rules - docs-optimism
  • GitHub Check: Pages changed - docs-optimism
🔇 Additional comments (1)
.husky/pre-push (1)

1-2: The shebang and Husky initialization look good.

The script correctly initializes the Husky environment which is essential for Git hooks to work properly.

Copy link
Contributor

@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)
utils/create-breadcrumbs.ts (3)

5-5: Path resolution change improves script execution in different contexts.

The change from using __dirname to process.cwd() is a good improvement that makes the script more robust when executed from different contexts, particularly when run as part of Git hooks like the Husky pre-commit and pre-push hooks introduced in this PR. This ensures the script can correctly locate the pages directory regardless of the execution context.

Consider adding a check to verify that the pages directory exists and provide a meaningful error message if it doesn't:

const rootDir = path.join(process.cwd(), 'pages');
+
+// Verify that the pages directory exists
+try {
+  fs.access(rootDir).catch(() => {
+    console.error(`Error: Pages directory not found at ${rootDir}`);
+    console.error('Make sure the script is being run from the project root');
+    process.exit(1);
+  });
+} catch (error) {
+  // fs.access is asynchronous, handle any synchronous errors here
+  console.error(`Error checking pages directory: ${error.message}`);
+  process.exit(1);
+}

63-82: Function logic is sound but could benefit from error handling enhancement.

The generateFolderDescription function effectively creates descriptive content for folders based on their contents, with good fallback mechanisms. However, there's no error handling if the content extraction fails unexpectedly.

Consider adding a try-catch block to handle potential errors during content extraction:

async function generateFolderDescription(folderName: string, files: FileInfo[]): Promise<string> {
  if (files.length === 0) {
    return `Documentation for ${toTitleCase(folderName)} is coming soon.`;
  }

  // Try to find overview or introduction file
  const overviewFile = files.find(file => 
    file.url.toLowerCase().includes('overview') || 
    file.url.toLowerCase().includes('introduction')
  );

  if (overviewFile && overviewFile.content) {
+   try {
      const desc = extractFirstParagraph(overviewFile.content);
      if (desc) return desc;
+   } catch (error) {
+     console.warn(`Warning: Failed to extract paragraph from ${overviewFile.url}: ${error.message}`);
+     // Continue to fallback
+   }
  }

  // Generate description from files if no overview is found
  const topics = files.map(file => toTitleCase(path.basename(file.url))).join(', ');
  return `Documentation covering ${topics} in the ${toTitleCase(folderName)} section of the OP Stack ecosystem.`;
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 74-74: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


232-254: Debug logging enhancement needed for better troubleshooting.

The main function logs basic information about the process but could benefit from more detailed logging, especially when errors occur in the nested functions.

Enhance the error reporting in the main function to provide more context:

const main = async (): Promise<void> => {
  console.log('Starting breadcrumb update process...');
  console.log('Root directory:', rootDir);

  try {
    // Process main sections: builders, chain, connect, stack
    const mainSections = ['app-developers', 'operators', 'superchain', 'stack'];
    for (const section of mainSections) {
      const sectionPath = path.join(rootDir, section);
      try {
        await fs.access(sectionPath);
        await processSubfolders(sectionPath);
        console.log(`Completed processing ${section} section`);
      } catch (error) {
-       console.log(`Skipping ${section} - directory not found`);
+       console.log(`Skipping ${section} - ${error.code === 'ENOENT' ? 'directory not found' : `error: ${error.message}`}`);
      }
    }
    console.log('Finished updating all breadcrumbs.');
  } catch (error) {
-   console.error('Error in main process:', error);
+   console.error(`Error in main process: ${error.message}`);
+   console.error(error.stack);
    process.exit(1);
  }
};
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d317b4 and 3c8be7d.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • package.json (3 hunks)
  • utils/create-breadcrumbs.ts (1 hunks)
  • utils/fix-redirects.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • utils/fix-redirects.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
🔇 Additional comments (1)
utils/create-breadcrumbs.ts (1)

238-238:

❓ Verification inconclusive

Verify the main sections array against the current project structure.

The main sections array hardcodes specific folder names (app-developers, operators, superchain, stack), which might need maintenance as the project evolves.


🏁 Script executed:

#!/bin/bash
# Description: Verify that the main sections listed in the script match the actual directory structure

echo "Checking if the main sections exist in the pages directory..."

# Get the immediate directories in the pages directory
DIRS=$(find pages -maxdepth 1 -type d | grep -v "^pages$" | sed 's|pages/||')

echo "Found directories: $DIRS"

# Check if each main section exists
for section in 'app-developers' 'operators' 'superchain' 'stack'; do
  if echo "$DIRS" | grep -q "$section"; then
    echo "✅ Section '$section' exists"
  else
    echo "❌ Section '$section' not found in pages directory"
  fi
done

# Check if there are additional directories not included in the script
for dir in $DIRS; do
  if ! echo "app-developers operators superchain stack" | grep -q "$dir"; then
    echo "⚠️ Directory '$dir' exists but is not included in the script's main sections"
  fi
done

Length of output: 2607


Main Sections Array Consistency Check

The hardcoded array (['app-developers', 'operators', 'superchain', 'stack']) correctly includes the primary folders since they exist as expected in the pages directory. However, the directory scan also revealed additional folders—specifically notices, get-started, and connect—that are not present in the array. Please review whether these extra directories should be added to the main sections array or if they are meant to be managed separately.

@krofax krofax requested a review from 0xmariniere as a code owner March 4, 2025 16:45
@krofax krofax merged commit b81d740 into main Mar 4, 2025
8 checks passed
@krofax krofax deleted the husky-add branch March 4, 2025 17:14
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