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

feat(file): Add permission checks for directory scanning #165

Merged
merged 1 commit into from
Nov 10, 2024

Conversation

yamadashy
Copy link
Owner

This PR adds permission checking before scanning directories in the searchFiles function.

related: #162

Copy link

stackblitz bot commented Nov 10, 2024

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link
Contributor

coderabbitai bot commented Nov 10, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduce a permission check mechanism in the searchFiles function of fileSearch.ts, enhancing error handling related to directory access. A new file, permissionCheck.ts, is added, which includes the checkDirectoryPermissions function for verifying directory permissions and a custom PermissionError class for handling related errors. The modifications ensure that permission issues are explicitly managed, providing detailed error messages and improving the overall control flow of file searching operations.

Changes

File Path Change Summary
src/core/file/fileSearch.ts - Updated searchFiles method to include permission checks.
- Imported checkDirectoryPermissions and PermissionError from permissionCheck.js.
- Enhanced error handling for globby function calls to throw PermissionError.
src/core/file/permissionCheck.ts - Introduced PermissionCheckResult interface.
- Added PermissionError class extending Error.
- Implemented checkDirectoryPermissions function for checking directory permissions.
- Added getMacOSPermissionMessage helper function for macOS-specific error messages.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FileSearch
    participant PermissionCheck

    User->>FileSearch: searchFiles(rootDir)
    FileSearch->>PermissionCheck: checkDirectoryPermissions(rootDir)
    alt Permission granted
        PermissionCheck-->>FileSearch: PermissionCheckResult
        FileSearch->>FileSearch: Perform file search
    else Permission denied
        PermissionCheck-->>FileSearch: PermissionError
        FileSearch->>User: Throw PermissionError
    end
Loading

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.

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.

src/core/file/permissionCheck.ts Outdated Show resolved Hide resolved
src/core/file/permissionCheck.ts Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (3)
src/core/file/fileSearch.ts (1)

39-47: LGTM: Good error handling for globby

The error handling for permission-related errors is well-implemented. Consider adding debug logging for better troubleshooting.

Add debug logging before throwing the error:

     if (error.code === 'EPERM' || error.code === 'EACCES') {
+      logger.debug(`Permission error encountered while scanning ${rootDir}: ${error.code}`);
       throw new PermissionError(
         'Permission denied while scanning directory. Please check folder access permissions for your terminal app.',
         rootDir,
       );
     }
src/core/file/permissionCheck.ts (2)

42-56: Refactor permission checks to reduce code duplication

The repeated try-catch blocks for checking read, write, and execute permissions can be consolidated into a loop. This enhances maintainability by reducing code duplication.

Apply this diff to refactor the permission checks:

- try {
-   await fsPromises.access(dirPath, constants.R_OK);
-   details.read = true;
- } catch {}
-
- try {
-   await fsPromises.access(dirPath, constants.W_OK);
-   details.write = true;
- } catch {}
-
- try {
-   await fsPromises.access(dirPath, constants.X_OK);
-   details.execute = true;
- } catch {}
+ const permissionTypes = [
+   { key: 'read', flag: constants.R_OK },
+   { key: 'write', flag: constants.W_OK },
+   { key: 'execute', flag: constants.X_OK },
+ ];
+
+ for (const { key, flag } of permissionTypes) {
+   try {
+     await fsPromises.access(dirPath, flag);
+     details[key] = true;
+   } catch {}
+ }

30-93: Add unit tests for checkDirectoryPermissions function

Including unit tests for the checkDirectoryPermissions function will help ensure its correct behavior across different scenarios and prevent future regressions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6d0da85 and 0d1c212.

📒 Files selected for processing (2)
  • src/core/file/fileSearch.ts (2 hunks)
  • src/core/file/permissionCheck.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Test (macos-latest, 16.x)
src/core/file/fileSearch.ts

[failure] 16-16: tests/core/file/fileSearch.test.ts > fileSearch > filterFiles > should call globby with correct parameters
Error: Cannot access directory /mock/root: undefined
❯ Module.searchFiles src/core/file/fileSearch.ts:16:11
❯ tests/core/file/fileSearch.test.ts:140:7


[failure] 16-16: tests/core/file/fileSearch.test.ts > fileSearch > filterFiles > Honor .gitignore files in subdirectories
Error: Cannot access directory /mock/root: undefined
❯ Module.searchFiles src/core/file/fileSearch.ts:16:11
❯ tests/core/file/fileSearch.test.ts:196:22


[failure] 16-16: tests/core/file/fileSearch.test.ts > fileSearch > filterFiles > should not apply .gitignore when useGitignore is false
Error: Cannot access directory /mock/root: undefined
❯ Module.searchFiles src/core/file/fileSearch.ts:16:11
❯ tests/core/file/fileSearch.test.ts:220:22

🪛 GitHub Check: Test (ubuntu-latest, 16.x)
src/core/file/fileSearch.ts

[failure] 16-16: tests/core/file/fileSearch.test.ts > fileSearch > filterFiles > should call globby with correct parameters
Error: Cannot access directory /mock/root: undefined
❯ Module.searchFiles src/core/file/fileSearch.ts:16:11
❯ tests/core/file/fileSearch.test.ts:140:7


[failure] 16-16: tests/core/file/fileSearch.test.ts > fileSearch > filterFiles > Honor .gitignore files in subdirectories
Error: Cannot access directory /mock/root: undefined
❯ Module.searchFiles src/core/file/fileSearch.ts:16:11
❯ tests/core/file/fileSearch.test.ts:196:22


[failure] 16-16: tests/core/file/fileSearch.test.ts > fileSearch > filterFiles > should not apply .gitignore when useGitignore is false
Error: Cannot access directory /mock/root: undefined
❯ Module.searchFiles src/core/file/fileSearch.ts:16:11
❯ tests/core/file/fileSearch.test.ts:220:22

🔇 Additional comments (2)
src/core/file/fileSearch.ts (2)

6-6: LGTM: Clean import addition

The new import statement correctly brings in the required permission-checking functionality.


55-64: LGTM: Well-structured error handling

The catch block properly differentiates between PermissionError and other errors, maintaining the error context and providing clear error messages.

src/core/file/fileSearch.ts Show resolved Hide resolved
src/core/file/fileSearch.ts Show resolved Hide resolved
src/core/file/permissionCheck.ts Outdated Show resolved Hide resolved
@yamadashy yamadashy force-pushed the feature/dir-permission branch from 0d1c212 to 5d9f7e7 Compare November 10, 2024 09:18
Copy link

codecov bot commented Nov 10, 2024

Codecov Report

Attention: Patch coverage is 38.88889% with 55 lines in your changes missing coverage. Please review.

Project coverage is 75.63%. Comparing base (6d0da85) to head (5d9f7e7).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
src/core/file/permissionCheck.ts 44.44% 40 Missing ⚠️
src/core/file/fileSearch.ts 16.66% 15 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #165      +/-   ##
==========================================
- Coverage   77.50%   75.63%   -1.87%     
==========================================
  Files          36       37       +1     
  Lines        1769     1859      +90     
  Branches      329      336       +7     
==========================================
+ Hits         1371     1406      +35     
- Misses        398      453      +55     

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

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

🧹 Outside diff range and nitpick comments (2)
src/core/file/fileSearch.ts (2)

39-47: Enhance error handling and add test coverage.

The permission error handling for globby is good, but could be improved:

  1. Add logging before throwing the error to help with debugging
  2. Consider handling other permission-related error codes (e.g., ENOENT)

Consider applying this enhancement:

     }).catch((error) => {
       // Handle EPERM errors specifically
       if (error.code === 'EPERM' || error.code === 'EACCES') {
+        logger.error(`Permission error scanning directory ${rootDir}:`, error.message);
         throw new PermissionError(
           'Permission denied while scanning directory. Please check folder access permissions for your terminal app.',
           rootDir,
         );
       }
+      // Handle non-existent directory
+      if (error.code === 'ENOENT') {
+        logger.error(`Directory not found ${rootDir}:`, error.message);
+        throw new Error(`Directory not found: ${rootDir}`);
+      }
       throw error;
     });
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 41-47: src/core/file/fileSearch.ts#L41-L47
Added lines #L41 - L47 were not covered by tests


55-64: Improve error type handling and logging.

The error handling is good but could be enhanced with better TypeScript practices and logging:

Consider applying these improvements:

     // Re-throw PermissionError as is
     if (error instanceof PermissionError) {
+      logger.debug('Re-throwing permission error:', error.message);
       throw error;
     }

-    if (error instanceof Error) {
+    const err = error as Error;
+    logger.error('Error filtering files:', err.message);
+    throw new Error(`Failed to filter files in directory ${rootDir}. Reason: ${err.message}`);
-    }
-
-    logger.error('An unexpected error occurred:', error);
-    throw new Error('An unexpected error occurred while filtering files.');

This change:

  1. Adds debug logging for permission errors
  2. Uses type assertion for better error handling
  3. Simplifies the error handling flow
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 56-58: src/core/file/fileSearch.ts#L56-L58
Added lines #L56 - L58 were not covered by tests

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0d1c212 and 5d9f7e7.

📒 Files selected for processing (2)
  • src/core/file/fileSearch.ts (2 hunks)
  • src/core/file/permissionCheck.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/core/file/fileSearch.ts

[warning] 13-17: src/core/file/fileSearch.ts#L13-L17
Added lines #L13 - L17 were not covered by tests


[warning] 41-47: src/core/file/fileSearch.ts#L41-L47
Added lines #L41 - L47 were not covered by tests


[warning] 56-58: src/core/file/fileSearch.ts#L56-L58
Added lines #L56 - L58 were not covered by tests

src/core/file/permissionCheck.ts

[warning] 18-24: src/core/file/permissionCheck.ts#L18-L24
Added lines #L18 - L24 were not covered by tests


[warning] 57-61: src/core/file/permissionCheck.ts#L57-L61
Added lines #L57 - L61 were not covered by tests


[warning] 68-89: src/core/file/permissionCheck.ts#L68-L89
Added lines #L68 - L89 were not covered by tests


[warning] 92-94: src/core/file/permissionCheck.ts#L92-L94
Added lines #L92 - L94 were not covered by tests


[warning] 109-109: src/core/file/permissionCheck.ts#L109
Added line #L109 was not covered by tests


[warning] 111-112: src/core/file/permissionCheck.ts#L111-L112
Added lines #L111 - L112 were not covered by tests

🔇 Additional comments (5)
src/core/file/permissionCheck.ts (5)

1-4: Simplify imports using fs.promises directly

The imports can be simplified by using fs.promises directly instead of separate imports.

As suggested in the previous review, apply this change:

- import { constants } from 'node:fs';
- import * as fs from 'node:fs/promises';
+ import { constants, promises as fsPromises } from 'node:fs';

6-14: LGTM! Well-structured interface definition

The PermissionCheckResult interface is well-designed with clear optional properties and nested types.


16-25: Add tests and consider type safety for error codes

The PermissionError class implementation looks good, but:

  1. Test coverage is missing for this class
  2. Error codes could be typed for better type safety

Consider adding type safety for error codes:

+ type PermissionErrorCode = 'EPERM' | 'EACCES' | 'EISDIR';

  export class PermissionError extends Error {
    constructor(
      message: string,
      public readonly path: string,
-     public readonly code?: string,
+     public readonly code?: PermissionErrorCode,
    ) {

Would you like me to help generate unit tests for this class? Here's what we should test:

  • Constructor properly sets message, path, and code
  • Error name is correctly set to 'PermissionError'
  • Inheritance from Error class works as expected
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 18-24: src/core/file/permissionCheck.ts#L18-L24
Added lines #L18 - L24 were not covered by tests


92-112: Consider i18n support and add tests

The function provides excellent user guidance, but consider these improvements:

  1. Missing test coverage for both macOS and non-macOS paths
  2. Messages could be externalized for future i18n support
  3. The error message contains hard-coded UI paths that might change with macOS updates

Consider externalizing messages:

const PERMISSION_MESSAGES = {
  darwin: {
    header: 'Permission denied: Cannot access \'{path}\', error code: {code}.',
    instructions: `
1. Open System Settings
2. Navigate to Privacy & Security > Files and Folders
...`
  },
  default: 'Permission denied: Cannot access \'{path}\''
};

Let's check for similar message patterns:

#!/bin/bash
# Look for other platform-specific messages
rg "platform\(\) === '(\w+)'" -t ts

Would you like me to help:

  1. Generate unit tests for both macOS and non-macOS scenarios?
  2. Set up a basic i18n structure for message externalization?
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 92-94: src/core/file/permissionCheck.ts#L92-L94
Added lines #L92 - L94 were not covered by tests


[warning] 109-109: src/core/file/permissionCheck.ts#L109
Added line #L109 was not covered by tests


[warning] 111-112: src/core/file/permissionCheck.ts#L111-L112
Added lines #L111 - L112 were not covered by tests


27-90: 🛠️ Refactor suggestion

Refactor for better maintainability and add comprehensive tests

While the implementation is functionally correct, there are several improvements that could be made:

  1. The function is quite complex with multiple responsibilities
  2. Test coverage is missing for critical paths
  3. Error handling could be more modular

Consider breaking down the function into smaller, focused functions:

async function checkBasicAccess(dirPath: string): Promise<void> {
  await fsPromises.readdir(dirPath);
}

async function checkSpecificPermissions(dirPath: string): Promise<PermissionDetails> {
  const details = { read: false, write: false, execute: false };
  // ... permission checking logic ...
  return details;
}

async function handlePermissionError(error: unknown, dirPath: string): Promise<PermissionCheckResult> {
  // ... error handling logic ...
}

Let's verify the error handling paths:

Would you like me to help generate comprehensive tests covering:

  • Successful permission checks
  • Various permission combinations
  • Different error scenarios (EPERM, EACCES, EISDIR)
  • Platform-specific behavior
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 57-61: src/core/file/permissionCheck.ts#L57-L61
Added lines #L57 - L61 were not covered by tests


[warning] 68-89: src/core/file/permissionCheck.ts#L68-L89
Added lines #L68 - L89 were not covered by tests

src/core/file/fileSearch.ts Show resolved Hide resolved
@yamadashy yamadashy merged commit 2d09e46 into main Nov 10, 2024
37 checks passed
@yamadashy yamadashy deleted the feature/dir-permission branch November 10, 2024 09:28
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.

1 participant