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

LocalRepoService fixes #266

Merged
merged 4 commits into from
Feb 19, 2025
Merged

LocalRepoService fixes #266

merged 4 commits into from
Feb 19, 2025

Conversation

kinshuksinghbist
Copy link
Collaborator

@kinshuksinghbist kinshuksinghbist commented Feb 14, 2025

Fixes #261

added method _get_content(), to fix the local repo parsing issue.

Screenshot from 2025-02-17 10-16-55
Screenshot from 2025-02-17 10-25-20
Screenshot from 2025-02-17 10-32-16

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a method for retrieving structured content from specified paths within the local repository, improving content accessibility.
  • Refactor

    • Enhanced the retrieval and organization of repository content with a more robust approach to handling both directories and files.
    • Improved error handling to ensure reliable responses for invalid paths and unexpected conditions.

Copy link
Contributor

coderabbitai bot commented Feb 14, 2025

Walkthrough

The pull request introduces a new method _get_contents in the LocalRepoService class to retrieve contents from a specified path within the local repository. This method returns structured data, either as a list of dictionaries for directories or a single dictionary for files. The _fetch_repo_structure_async method has been updated to utilize _get_contents, enhancing the content retrieval process and maintaining consistent error handling for invalid paths.

Changes

File Summary of Changes
app/.../local_repo_service.py - Added _get_contents method for structured content retrieval
- Modified _fetch_repo_structure_async to call _get_contents instead of repo.get_contents
- Updated error handling and filtering logic

Sequence Diagram(s)

sequenceDiagram
  participant C as Client
  participant L as LocalRepoService
  participant G as _get_contents Method

  C->>L: Request repository structure
  L->>G: Invoke _get_contents(path)
  G-->>L: Return structured contents (files/directories)
  L-->>C: Deliver repository structure or error
Loading

Poem

Oh, my whiskers twitch with glee,
As code hops to paths so free.
New methods spring from clever minds,
In structured forms, the joy it finds.
With every fetch, a leap, a bound,
In the world of code, I dance around! 🐇

✨ 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.

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
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 comments (1)
app/modules/code_provider/local_repo/local_repo_service.py (1)

61-61: ⚠️ Potential issue

Fix comparison to None.

The pipeline warning indicates that comparison to None should use is operator.

Apply this diff to fix the warning:

-                if (start_line == end_line == 0) or (start_line == end_line == None):
+                if (start_line == end_line == 0) or (start_line is None and end_line is None):
🧰 Tools
🪛 Ruff (0.8.2)

61-61: Comparison to None should be cond is None

Replace with cond is None

(E711)

🪛 GitHub Actions: Pre-commit

[warning] 61-61: Comparison to None should be cond is None

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dfaa35e and 839ad93.

📒 Files selected for processing (1)
  • app/modules/code_provider/local_repo/local_repo_service.py (5 hunks)
🧰 Additional context used
🪛 GitHub Actions: Pre-commit
app/modules/code_provider/local_repo/local_repo_service.py

[warning] 61-61: Comparison to None should be cond is None

🔇 Additional comments (2)
app/modules/code_provider/local_repo/local_repo_service.py (2)

6-6: LGTM! Good addition of base_path parameter.

The changes properly handle path initialization and provide flexibility in repository location.

Also applies to: 18-18, 25-25


156-156: LGTM! Clean adaptation to the new content structure.

The changes properly handle the new dictionary-based content structure while maintaining the existing filtering logic.

Also applies to: 164-168, 173-173, 176-176, 179-179, 188-189

Comment on lines +275 to +335
def _get_contents(self, path: str) -> Union[List[dict], dict]:
"""
If the path is a directory, it returns a list of dictionaries,
each representing a file or subdirectory. If the path is a file, its content is read and returned.

:param path: Relative or absolute path within the local repository.
:return: A dict if the path is a file (with file content loaded), or a list of dicts if the path is a directory.
"""
if not isinstance(path, str):
raise TypeError(f"Expected path to be a string, got {type(path).__name__}")

if path == "/":
path = ""

abs_path = os.path.abspath(path)

if not os.path.exists(abs_path):
raise FileNotFoundError(f"Path '{abs_path}' does not exist.")

if os.path.isdir(abs_path):
contents = []
for item in os.listdir(abs_path):
item_path = os.path.join(abs_path, item)
if os.path.isdir(item_path):
contents.append({
"path": item_path,
"name": item,
"type": "dir",
"content": None, #path is a dir, content is not loaded
"completed": True
})
elif os.path.isfile(item_path):
contents.append({
"path": item_path,
"name": item,
"type": "file",
"content": None,
"completed": False
})
else:
contents.append({
"path": item_path,
"name": item,
"type": "other",
"content": None,
"completed": True
})
return contents

elif os.path.isfile(abs_path):
with open(abs_path, "r", encoding="utf-8") as file:
file_content = file.read()
return {
"path": abs_path,
"name": os.path.basename(abs_path),
"type": "file",
"content": file_content, #path is a file, content is loaded
"completed": True
}


Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and large file protection.

The implementation needs additional error handling for robustness:

  1. File encoding issues
  2. Permission errors
  3. Memory constraints with large files

Apply this diff to improve error handling:

     def _get_contents(self, path: str) -> Union[List[dict], dict]:
         if not isinstance(path, str):
             raise TypeError(f"Expected path to be a string, got {type(path).__name__}")
 
         if path == "/":
             path = ""
         
         abs_path = os.path.abspath(path)
         
         if not os.path.exists(abs_path):
             raise FileNotFoundError(f"Path '{abs_path}' does not exist.")
+
+        if not os.access(abs_path, os.R_OK):
+            raise PermissionError(f"No read permission for '{abs_path}'")
         
         if os.path.isdir(abs_path):
             contents = []
             for item in os.listdir(abs_path):
                 item_path = os.path.join(abs_path, item)
+                try:
                     if os.path.isdir(item_path):
                         contents.append({
                             "path": item_path,
                             "name": item,
                             "type": "dir",
                             "content": None,
                             "completed": True
                         })
                     elif os.path.isfile(item_path):
+                        # Skip files larger than 10MB
+                        if os.path.getsize(item_path) > 10 * 1024 * 1024:
+                            logger.warning(f"Skipping large file: {item_path}")
+                            continue
                         contents.append({
                             "path": item_path,
                             "name": item,
                             "type": "file",
                             "content": None,  
                             "completed": False
                         })
                     else:
                         contents.append({
                             "path": item_path,
                             "name": item,
                             "type": "other",
                             "content": None,
                             "completed": True
                         })
+                except OSError as e:
+                    logger.error(f"Error accessing {item_path}: {e}")
+                    continue
             return contents
         
         elif os.path.isfile(abs_path):
+            # Skip files larger than 10MB
+            if os.path.getsize(abs_path) > 10 * 1024 * 1024:
+                raise ValueError(f"File too large: {abs_path}")
+
+            try:
                 with open(abs_path, "r", encoding="utf-8") as file:
                     file_content = file.read()
+            except UnicodeDecodeError:
+                logger.warning(f"Non-UTF-8 file detected: {abs_path}")
+                return {
+                    "path": abs_path,
+                    "name": os.path.basename(abs_path),
+                    "type": "file",
+                    "content": None,
+                    "completed": False,
+                    "error": "Non-UTF-8 encoding"
+                }
             return {
                 "path": abs_path,
                 "name": os.path.basename(abs_path),
                 "type": "file",
                 "content": file_content,
                 "completed": True
             }
📝 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
def _get_contents(self, path: str) -> Union[List[dict], dict]:
"""
If the path is a directory, it returns a list of dictionaries,
each representing a file or subdirectory. If the path is a file, its content is read and returned.
:param path: Relative or absolute path within the local repository.
:return: A dict if the path is a file (with file content loaded), or a list of dicts if the path is a directory.
"""
if not isinstance(path, str):
raise TypeError(f"Expected path to be a string, got {type(path).__name__}")
if path == "/":
path = ""
abs_path = os.path.abspath(path)
if not os.path.exists(abs_path):
raise FileNotFoundError(f"Path '{abs_path}' does not exist.")
if os.path.isdir(abs_path):
contents = []
for item in os.listdir(abs_path):
item_path = os.path.join(abs_path, item)
if os.path.isdir(item_path):
contents.append({
"path": item_path,
"name": item,
"type": "dir",
"content": None, #path is a dir, content is not loaded
"completed": True
})
elif os.path.isfile(item_path):
contents.append({
"path": item_path,
"name": item,
"type": "file",
"content": None,
"completed": False
})
else:
contents.append({
"path": item_path,
"name": item,
"type": "other",
"content": None,
"completed": True
})
return contents
elif os.path.isfile(abs_path):
with open(abs_path, "r", encoding="utf-8") as file:
file_content = file.read()
return {
"path": abs_path,
"name": os.path.basename(abs_path),
"type": "file",
"content": file_content, #path is a file, content is loaded
"completed": True
}
def _get_contents(self, path: str) -> Union[List[dict], dict]:
"""
If the path is a directory, it returns a list of dictionaries,
each representing a file or subdirectory. If the path is a file, its content is read and returned.
:param path: Relative or absolute path within the local repository.
:return: A dict if the path is a file (with file content loaded), or a list of dicts if the path is a directory.
"""
if not isinstance(path, str):
raise TypeError(f"Expected path to be a string, got {type(path).__name__}")
if path == "/":
path = ""
abs_path = os.path.abspath(path)
if not os.path.exists(abs_path):
raise FileNotFoundError(f"Path '{abs_path}' does not exist.")
if not os.access(abs_path, os.R_OK):
raise PermissionError(f"No read permission for '{abs_path}'")
if os.path.isdir(abs_path):
contents = []
for item in os.listdir(abs_path):
item_path = os.path.join(abs_path, item)
try:
if os.path.isdir(item_path):
contents.append({
"path": item_path,
"name": item,
"type": "dir",
"content": None, # path is a dir, content is not loaded
"completed": True
})
elif os.path.isfile(item_path):
# Skip files larger than 10MB
if os.path.getsize(item_path) > 10 * 1024 * 1024:
logger.warning(f"Skipping large file: {item_path}")
continue
contents.append({
"path": item_path,
"name": item,
"type": "file",
"content": None,
"completed": False
})
else:
contents.append({
"path": item_path,
"name": item,
"type": "other",
"content": None,
"completed": True
})
except OSError as e:
logger.error(f"Error accessing {item_path}: {e}")
continue
return contents
elif os.path.isfile(abs_path):
# Skip files larger than 10MB
if os.path.getsize(abs_path) > 10 * 1024 * 1024:
raise ValueError(f"File too large: {abs_path}")
try:
with open(abs_path, "r", encoding="utf-8") as file:
file_content = file.read()
except UnicodeDecodeError:
logger.warning(f"Non-UTF-8 file detected: {abs_path}")
return {
"path": abs_path,
"name": os.path.basename(abs_path),
"type": "file",
"content": None,
"completed": False,
"error": "Non-UTF-8 encoding"
}
return {
"path": abs_path,
"name": os.path.basename(abs_path),
"type": "file",
"content": file_content,
"completed": True
}

@dhirenmathur
Copy link
Contributor

@kinshuksinghbist did you verify that the output of this is the same format as the remote server output?

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

♻️ Duplicate comments (1)
app/modules/code_provider/local_repo/local_repo_service.py (1)

274-334: ⚠️ Potential issue

Add error handling and large file protection.

While the base implementation is solid, it needs additional error handling for robustness as previously suggested.

The implementation should include:

  1. File encoding issues
  2. Permission errors
  3. Memory constraints with large files

Please refer to the previous review comment for the detailed implementation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 839ad93 and e8ceec5.

📒 Files selected for processing (1)
  • app/modules/code_provider/local_repo/local_repo_service.py (4 hunks)
🧰 Additional context used
🪛 GitHub Actions: Pre-commit
app/modules/code_provider/local_repo/local_repo_service.py

[warning] 160-184: Code does not adhere to PEP 8 standards. Please format the code using Black.

🔇 Additional comments (2)
app/modules/code_provider/local_repo/local_repo_service.py (2)

6-6: LGTM!

The addition of Union to the typing imports is appropriate for the new method's return type annotation.


155-155: LGTM!

The changes to use dictionary access instead of attribute access are consistent with the new _get_contents method's return type.

Also applies to: 172-172, 175-175, 178-178, 187-188

Comment on lines 162 to +167
contents = [
item
for item in contents
if item.type == "dir"
or not any(item.name.endswith(ext) for ext in exclude_extensions)
]
item
for item in contents
if item['type'] == "dir"
or not any(item['name'].endswith(ext) for ext in exclude_extensions)
]
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix indentation to comply with PEP 8.

The list comprehension's indentation doesn't follow PEP 8 standards. Please adjust the indentation.

Apply this diff to fix the indentation:

-            contents = [
-                        item
-                        for item in contents
-                        if item['type'] == "dir"
-                        or not any(item['name'].endswith(ext) for ext in exclude_extensions)
-                    ]
+            contents = [
+                item
+                for item in contents
+                if item['type'] == "dir"
+                or not any(item['name'].endswith(ext) for ext in exclude_extensions)
+            ]
📝 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
contents = [
item
for item in contents
if item.type == "dir"
or not any(item.name.endswith(ext) for ext in exclude_extensions)
]
item
for item in contents
if item['type'] == "dir"
or not any(item['name'].endswith(ext) for ext in exclude_extensions)
]
contents = [
item
for item in contents
if item['type'] == "dir"
or not any(item['name'].endswith(ext) for ext in exclude_extensions)
]

@dhirenmathur dhirenmathur merged commit 3cf9101 into main Feb 19, 2025
3 of 4 checks passed
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.

Fails to parse local repo in LocalRepoService
2 participants