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

fix: optimized the directory traversal in check-edit-links script #3590

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

sahitya-chandra
Copy link

@sahitya-chandra sahitya-chandra commented Jan 21, 2025

Description

  • Added an async generator in check-edit-links script for optimized directory traversal and memory efficiency.
  • Handles large directory more efficiently.

Related issue(s)
fixes #3586

Summary by CodeRabbit

  • Refactor
    • Improved file path generation and directory traversal mechanism
    • Enhanced code readability and maintainability
    • Simplified path generation function with generator-based approach

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Walkthrough

The pull request introduces a refactored implementation of directory traversal in the check-edit-links.js script. The primary change is the introduction of a new generator function walkDirectory that recursively traverses directories and yields markdown file paths. The generatePaths function has been simplified to use this new generator, replacing the previous concurrent processing approach with an asynchronous iteration method. The core functionality of generating edit links remains unchanged, with improved code readability and maintainability.

Changes

File Change Summary
scripts/markdown/check-edit-links.js - Added walkDirectory generator function for recursive directory traversal
- Refactored generatePaths to use generator-based approach
- Simplified function signature and removed accumulator parameter
- Improved error handling for directory processing

Assessment against linked issues

Objective Addressed Explanation
Optimize directory traversal [#3586]
Implement generator-based solution [#3586]
Improve memory efficiency [#3586]

Possibly related PRs

Suggested labels

ready-to-merge, bounty

Suggested reviewers

  • derberg
  • magicmatatjahu
  • devilkiller-ag
  • sambhavgupta0705
  • akshatnema

Poem

🐰 Hop, hop, through directories we go,
Markdown files in a generator's flow
Async magic, paths unfurled with grace
Efficiency dancing at a rabbit's pace!
Code traversed, links now shine bright 🌟

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (Beta)
  • @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

netlify bot commented Jan 21, 2025

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 44884e4
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/678f3ede037de50009fce90f
😎 Deploy Preview https://deploy-preview-3590--asyncapi-website.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

codecov bot commented Jan 21, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (e9dd904) to head (44884e4).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #3590   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           20        20           
  Lines          732       736    +4     
=========================================
+ Hits           732       736    +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@asyncapi-bot
Copy link
Contributor

⚡️ Lighthouse report for the changes in this PR:

Category Score
🔴 Performance 40
🟢 Accessibility 98
🟢 Best practices 92
🟢 SEO 100
🔴 PWA 33

Lighthouse ran on https://deploy-preview-3590--asyncapi-website.netlify.app/

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)
scripts/markdown/check-edit-links.js (3)

102-121: Consider performance and compatibility implications of generator usage.

While the generator implementation is clean and maintainable, there are some concerns:

  1. The regenerator-runtime dependency might be too heavyweight
  2. Sequential await calls in the loop could impact performance
  3. Memory management for large directories isn't addressed

Consider this alternative implementation using Promise.all for better performance:

-async function* walkDirectory(dir) {
+async function walkDirectory(dir) {
   try {
     const files = await fs.readdir(dir);
-    for (const file of files) {
-      if (file === '_section.md') continue;
-      
-      const filePath = path.join(dir, file);
-      const stats = await fs.stat(filePath);
-      
-      if (stats.isDirectory()) {
-        yield* walkDirectory(filePath);
-      } else if (stats.isFile() && file.endsWith('.md')) {
-        yield filePath;
-      }
-    }
+    const entries = await Promise.all(
+      files
+        .filter(file => file !== '_section.md')
+        .map(async file => {
+          const filePath = path.join(dir, file);
+          const stats = await fs.stat(filePath);
+          return { filePath, stats };
+        })
+    );
+
+    const results = await Promise.all(
+      entries.map(async ({ filePath, stats }) => {
+        if (stats.isDirectory()) {
+          return walkDirectory(filePath);
+        }
+        return stats.isFile() && filePath.endsWith('.md') ? [filePath] : [];
+      })
+    );
+
+    return results.flat();
   } catch (err) {
-    throw new Error(`Error processing directory ${dir}: ${err.message}`);
+    throw new Error(`Failed to process directory ${dir}: ${err.code === 'ENOENT' ? 'Directory not found' : err.message}`);
   }
 }
🧰 Tools
🪛 eslint

[error] 103-104: Delete

(prettier/prettier)


[error] 106-117: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.

(no-restricted-syntax)


[error] 107-107: Unexpected use of continue statement.

(no-continue)


[error] 108-108: Delete ······

(prettier/prettier)


[error] 110-110: Unexpected await inside a loop.

(no-await-in-loop)


[error] 111-111: Delete ······

(prettier/prettier)


123-136: Enhance error handling and type validation.

The function is more concise, but could benefit from improved robustness:

  1. Add type validation for editOptions
  2. Enhance error handling with specific error types

Consider these improvements:

 async function generatePaths(folderPath, editOptions) {
+  if (!Array.isArray(editOptions)) {
+    throw new TypeError('editOptions must be an array');
+  }
+  if (!folderPath || typeof folderPath !== 'string') {
+    throw new TypeError('folderPath must be a non-empty string');
+  }
   
   const result = [];
   try {
     for await (const filePath of walkDirectory(folderPath)) {
       const relativePath = path.relative(folderPath, filePath);
       const urlPath = relativePath.split(path.sep).join('/').replace('.md', '');
       
       result.push({
         filePath,
         urlPath,
         editLink: determineEditLink(urlPath, filePath, editOptions)
       });
     }
     return result;
   } catch (err) {
-    throw new Error(`Error processing directory ${folderPath}: ${err.message}`);
+    if (err.code === 'ENOENT') {
+      throw new Error(`Directory not found: ${folderPath}`);
+    }
+    throw new Error(`Failed to generate paths: ${err.message}`);
   }
 }
🧰 Tools
🪛 eslint

[error] 124-125: Delete ⏎··

(prettier/prettier)


[error] 127-136: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.

(no-restricted-syntax)


[error] 130-130: Delete ······

(prettier/prettier)


102-136: Consider memory optimization for large directory structures.

The current implementation loads all file paths into memory. For large directory structures, this could lead to high memory usage.

Consider these memory optimization strategies:

  1. Implement batch processing:
async function* batchProcessor(generator, batchSize = 1000) {
  let batch = [];
  for await (const item of generator) {
    batch.push(item);
    if (batch.length >= batchSize) {
      yield batch;
      batch = [];
    }
  }
  if (batch.length > 0) {
    yield batch;
  }
}
  1. Process results in chunks:
async function generatePaths(folderPath, editOptions) {
  const batchSize = 1000;
  const results = [];
  
  for await (const batch of batchProcessor(walkDirectory(folderPath), batchSize)) {
    const processedBatch = batch.map(filePath => {
      const relativePath = path.relative(folderPath, filePath);
      const urlPath = relativePath.split(path.sep).join('/').replace('.md', '');
      return {
        filePath,
        urlPath,
        editLink: determineEditLink(urlPath, filePath, editOptions)
      };
    });
    results.push(...processedBatch);
    
    // Optional: Process each batch independently
    // await processBatch(processedBatch);
  }
  
  return results;
}
🧰 Tools
🪛 eslint

[error] 103-104: Delete

(prettier/prettier)


[error] 106-117: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.

(no-restricted-syntax)


[error] 107-107: Unexpected use of continue statement.

(no-continue)


[error] 108-108: Delete ······

(prettier/prettier)


[error] 110-110: Unexpected await inside a loop.

(no-await-in-loop)


[error] 111-111: Delete ······

(prettier/prettier)


[error] 124-125: Delete ⏎··

(prettier/prettier)


[error] 127-136: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.

(no-restricted-syntax)


[error] 130-130: Delete ······

(prettier/prettier)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e9dd904 and 44884e4.

📒 Files selected for processing (1)
  • scripts/markdown/check-edit-links.js (1 hunks)
🧰 Additional context used
🪛 eslint
scripts/markdown/check-edit-links.js

[error] 103-104: Delete

(prettier/prettier)


[error] 106-117: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.

(no-restricted-syntax)


[error] 107-107: Unexpected use of continue statement.

(no-continue)


[error] 108-108: Delete ······

(prettier/prettier)


[error] 110-110: Unexpected await inside a loop.

(no-await-in-loop)


[error] 111-111: Delete ······

(prettier/prettier)


[error] 124-125: Delete ⏎··

(prettier/prettier)


[error] 127-136: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.

(no-restricted-syntax)


[error] 130-130: Delete ······

(prettier/prettier)

⏰ Context from checks skipped due to timeout of 180000ms (1)
  • GitHub Check: Lighthouse CI

@akshatnema
Copy link
Member

@sahitya-chandra Can you please showcase the performance enhancement of the script, by running the workflow in your forked repo?

@sahitya-chandra
Copy link
Author

sahitya-chandra commented Jan 21, 2025

before:
recursion based approach

Screenshot from 2025-01-21 12-45-24

after:
new approach uses async generator

Screenshot from 2025-01-21 12-51-51

@akshatnema sir first approach is better for small directory because it processes all the files parallely which is less memory efficient but,
the new approach is better for large directory because it uses generator and async/await not Promise.all(), so it handles one file at a time which is more memory efficient.

benefits of new approach:

Screenshot from 2025-01-21 12-57-58

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.

Optimize directory traversal in check-edit-links script
3 participants