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

Enhancements to PR Code Suggestions Handling and Configuration #546

Merged
merged 5 commits into from
Dec 24, 2023

Conversation

mrT23
Copy link
Collaborator

@mrT23 mrT23 commented Dec 24, 2023

Type

Enhancement


Description

This PR introduces several enhancements to the PR code suggestions handling and configuration:

  • Refactored the code suggestion handling in pr_code_suggestions.py for consistency and improved functionality.
  • Updated the YAML parsing in _prepare_pr_code_suggestions method to include keys_fix_yaml parameter.
  • Added functionality to remove invalid suggestions where existing code is equal to improved code.
  • Updated the inline comment creation in various git providers to include absolute_position parameter.
  • Enhanced the find_line_number_of_relevant_line_in_file function to handle absolute position.
  • Added include_improved_code configuration option in configuration.toml and updated the documentation accordingly.

PR changes walkthrough

Relevant files                                                                                                                                 
Enhancement
7 files
pr_code_suggestions.py                                                                           
    pr_agent/tools/pr_code_suggestions.py

    **This file has undergone significant changes to improve the
    handling of code suggestions. The changes include:


    • Refactoring of the code suggestion handling for consistency
      and improved functionality.
    • Updating the YAML parsing in
      the _prepare_pr_code_suggestions method to include the
      keys_fix_yaml parameter.
    • Adding functionality to remove
      invalid suggestions where existing code is equal to improved
      code.
    • Updating the inline comment creation to include the
      absolute_position parameter.
    • Enhancing the
      find_line_number_of_relevant_line_in_file function to
      handle absolute position.
    • Adding the
      include_improved_code configuration option.**
+60/-35
pr_processing.py                                                                                       
    pr_agent/algo/pr_processing.py

    The find_line_number_of_relevant_line_in_file function has
    been enhanced to handle absolute position.

+46/-38
github_provider.py                                                                                   
    pr_agent/git_providers/github_provider.py

    The create_inline_comment method has been updated to
    include the absolute_position parameter.

+6/-2
bitbucket_provider.py                                                                             
    pr_agent/git_providers/bitbucket_provider.py

    The create_inline_comment method has been updated to
    include the absolute_position parameter.

+4/-2
gitlab_provider.py                                                                                   
    pr_agent/git_providers/gitlab_provider.py

    The create_inline_comment method has been updated to
    include the absolute_position parameter.

+1/-1
bitbucket_server_provider.py                                                               
    pr_agent/git_providers/bitbucket_server_provider.py

    The create_inline_comment method has been updated to
    include the absolute_position parameter.

+5/-2
git_provider.py                                                                                         
    pr_agent/git_providers/git_provider.py

    The create_inline_comment method has been updated to
    include the absolute_position parameter.

+3/-3
Documentation
2 files
pr_code_suggestions_prompts.toml                                                       
    pr_agent/settings/pr_code_suggestions_prompts.toml

    The instructions and YAML schema have been updated to
    reflect changes in pr_code_suggestions.py.

+24/-48
IMPROVE.md                                                                                                   
    docs/IMPROVE.md

    The documentation has been updated to include the
    include_improved_code configuration option.

+1/-0
Configuration changes
1 files
configuration.toml                                                                                   
    pr_agent/settings/configuration.toml

    The include_improved_code configuration option has been
    added.

+1/-0

…code_suggestions.py and pr_code_suggestions_prompts.toml

- Update key names in pr_code_suggestions.py to use snake_case for consistency
- Implement removal of invalid suggestions where existing code is equal to improved code
- Update YAML parsing in _prepare_pr_code_suggestions method to include keys_fix_yaml parameter
- Refactor push_inline_code_suggestions method to use updated key names
- Update _prepare_prediction_extended method to use new key names
- Refactor _prepare_markdown method to include suggestion label and use updated key names
- Update instructions and YAML schema in pr_code_suggestions_prompts.toml to reflect changes in pr_code_suggestions.py
- Remove redundant removal of invalid suggestions in rank_suggestions method
…e suggestion handling

- Update `create_inline_comment` method in various git providers to include `absolute_position` parameter
- Remove `create_inline_comment` method from providers that do not support inline comments
- Enhance `find_line_number_of_relevant_line_in_file` function to handle absolute position
- Modify `pr_code_suggestions.py` to handle improved code inclusion in suggestions
- Add `include_improved_code` configuration option in `configuration.toml` and update documentation accordingly
Copy link
Contributor

PR Description updated to latest commit (5c49ff2)

Copy link
Contributor

PR Analysis

  • 🎯 Main theme: Enhancements to PR code suggestions handling and configuration
  • 📝 PR summary: This PR introduces several enhancements to the PR code suggestions handling and configuration. It includes refactoring of the code suggestion handling, updates to YAML parsing, removal of invalid suggestions, updates to inline comment creation in various git providers, and the addition of a new configuration option.
  • 📌 Type of PR: Enhancement
  • 🧪 Relevant tests added: No
  • ⏱️ Estimated effort to review [1-5]: 4, because the PR involves changes in multiple files and introduces new functionalities which require careful review.
  • 🔒 Security concerns: No security concerns found

PR Feedback

  • 💡 General suggestions: The PR is well-structured and the changes are logically grouped. However, it would be beneficial to include tests to ensure the new functionalities work as expected. Also, it would be helpful to include comments in the code to explain the purpose of the new functionalities and how they work.

  • 🤖 Code feedback:
    relevant filepr_agent/tools/pr_code_suggestions.py
    suggestion      Consider using more descriptive variable names for better code readability. For example, instead of 'd', use 'suggestion'. [important]
    relevant line'+ for d in data['code_suggestions']:'

    relevant filepr_agent/tools/pr_code_suggestions.py
    suggestion      It would be more efficient to use a list comprehension to filter out invalid suggestions. [medium]
    relevant line'+ for i, suggestion in enumerate(data['code_suggestions']):'

    relevant filepr_agent/algo/pr_processing.py
    suggestion      Consider adding a comment to explain the purpose of the 'absolute_position' parameter. [medium]
    relevant line'+ absolute_position: int = None) -> Tuple[int, int]:'

    relevant filepr_agent/git_providers/github_provider.py
    suggestion      Consider handling the case where 'absolute_position' is not provided. [important]
    relevant line'+ def create_inline_comment(self, body: str, relevant_file: str, relevant_line_in_file: str,'

How to use

Instructions

To invoke the PR-Agent, add a comment using one of the following commands:
/review: Request a review of your Pull Request.
/describe: Update the PR title and description based on the contents of the PR.
/improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
/ask <QUESTION>: Ask a question about the PR.
/update_changelog: Update the changelog based on the PR's contents.
/add_docs: Generate docstring for new components introduced in the PR.
/generate_labels: Generate labels for the PR based on the PR's contents.
see the tools guide for more details.

To edit any configuration parameter from the configuration.toml, add --config_path=new_value.
For example: /review --pr_reviewer.extra_instructions="focus on the file: ..."
To list the possible configuration parameters, add a /config comment.

@mrT23 mrT23 changed the title Tr/backticks review Single-label for suggestions Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@mrT23 mrT23 merged commit e698c7e into main Dec 24, 2023
3 checks passed
@mrT23 mrT23 deleted the tr/backticks_review branch December 24, 2023 11:35
@Codium-ai Codium-ai deleted a comment from codiumai-pr-agent-pro bot Dec 24, 2023
@mrT23
Copy link
Collaborator Author

mrT23 commented Dec 24, 2023

/add_docs

Copy link
Contributor

PR Documentation

Here is a list of the files that were modified in the PR, with docstring for each altered code component:

pr_processing.py                                                                                                                               

    find_line_number_of_relevant_line_in_file (function) [+44/-36]                                                           
    Component signature:
    def find_line_number_of_relevant_line_in_file(diff_files: List[FilePatchInfo], relevant_file: str, relevant_line_in_file: str, absolute_position: int = None) -> Tuple[int, int]

    Docstring:

    """
    Find the line number of the relevant line in a file within a list of diff files.
    
    Args:
        diff_files (List[FilePatchInfo]): A list of FilePatchInfo objects representing the diff files.
        relevant_file (str): The name of the relevant file.
        relevant_line_in_file (str): The relevant line in the file.
        absolute_position (int, optional): The absolute position of the relevant line. Defaults to None.
    
    Returns:
        Tuple[int, int]: A tuple containing the position of the relevant line and the absolute position.
    
    """

bitbucket_provider.py                                                                                                                     

    create_inline_comment (method) [+4/-2]                                                                                                           
    Component signature:
    def create_inline_comment(self, body: str, relevant_file: str, relevant_line_in_file: str, absolute_position: int = None)

    Docstring:

    """
    Create an inline comment for a specific line or file.
    
    Args:
        body (str): The content of the comment.
        relevant_file (str): The path of the relevant file.
        relevant_line_in_file (str): The line number or identifier of the relevant line in the file.
        absolute_position (int, optional): The absolute position of the comment. Defaults to None.
    
    Returns:
        dict: A dictionary containing the comment body, file path, and position if subject_type is "LINE", otherwise an empty dictionary.
    """

bitbucket_server_provider.py                                                                                                       

    create_inline_comment (method) [+5/-2]                                                                                                           
    Component signature:
    def create_inline_comment(self, body: str, relevant_file: str, relevant_line_in_file: str,
                              absolute_position: int = None):

    Docstring:

    """
    Create an inline comment for a given body of text.
    
    Args:
        body (str): The content of the comment.
        relevant_file (str): The path of the relevant file.
        relevant_line_in_file (str): The line number of the relevant line in the file.
        absolute_position (int, optional): The absolute position of the comment. Defaults to None.
    
    Returns:
        dict: A dictionary containing the comment body, file path, and position if subject_type is "LINE",
        otherwise an empty dictionary.
    """

git_provider.py                                                                                                                                 

    create_inline_comment (method) [+3/-2]                                                                                                           
    Component signature:
    def create_inline_comment(self, body: str, relevant_file: str, relevant_line_in_file: str,
                              absolute_position: int = None)

    Docstring:

    """
    This method creates an inline comment in a relevant file at a specific line or position.
    
    :param body: The content of the comment.
    :type body: str
    :param relevant_file: The path to the relevant file.
    :type relevant_file: str
    :param relevant_line_in_file: The line number or position in the file where the comment should be added.
    :type relevant_line_in_file: str
    :param absolute_position: The absolute position in the file where the comment should be added. (optional)
    :type absolute_position: int, optional
    :raises NotImplementedError: This git provider does not support creating inline comments yet
    """

github_provider.py                                                                                                                           

    create_inline_comment (method) [+6/-2]                                                                                                           
    Component signature:
    def create_inline_comment(self, body: str, relevant_file: str, relevant_line_in_file: str,
                              absolute_position: int = None)

    Docstring:

    """
    Create an inline comment for a specific line in a file or for the entire file.
    
    Args:
        body (str): The content of the comment.
        relevant_file (str): The path of the relevant file.
        relevant_line_in_file (str): The line number or identifier of the relevant line in the file.
        absolute_position (int, optional): The absolute position of the relevant line in the file. Defaults to None.
    
    Returns:
        dict: A dictionary containing the comment body, file path, and line position if subject_type is "LINE",
        otherwise an empty dictionary.
    
    Raises:
        None
    """

gitlab_provider.py                                                                                                                           

    create_inline_comment (method) [+1/-1]                                                                                                           
    Component signature:
    def create_inline_comment(self, body: str, relevant_file: str, relevant_line_in_file: str, absolute_position: int = None)

    Docstring:

    """
    Create an inline comment on a specific line in a file.
    
    Args:
        body (str): The content of the comment.
        relevant_file (str): The path of the relevant file.
        relevant_line_in_file (str): The line number in the relevant file where the comment should be created.
        absolute_position (int, optional): The absolute position in the file where the comment should be created. Defaults to None.
    
    Raises:
        NotImplementedError: This provider does not support creating inline comments yet.
    """

pr_code_suggestions.py                                                                                                                   

    run (method) [+2/-2]                                                                                                                                               
    Component signature:
    async def run(self)

    Docstring:

    """
    Run the code suggestion generation process for a Pull Request.
    
    This method generates code suggestions for a Pull Request by performing the following steps:
    1. Log the start of the code suggestion generation process.
    2. If the `publish_output` configuration is enabled, publish a temporary comment indicating that the suggestions are being prepared.
    3. Log the start of the PR code suggestion preparation process.
    4. If the `is_extended` flag is False, call the `_prepare_prediction` method with fallback models.
    5. Call the `_prepare_pr_code_suggestions` method to prepare the PR code suggestions.
    6. If the `is_extended` flag is True, call the `_prepare_prediction_extended` method with fallback models.
    7. If the `data` dictionary is empty or does not contain the key 'code_suggestions', log that no code suggestions were found and return.
    8. If the `rank_suggestions` configuration is enabled for non-extended suggestions or the `rank_extended_suggestions` configuration is enabled for extended suggestions, log the start of the ranking process.
    9. Rank the code suggestions using the `rank_suggestions` method.
    10. If the `publish_output` configuration is enabled, log the start of the PR code suggestion pushing process.
    11. Remove the initial comment if it exists.
    12. If the `summarize` configuration is enabled, log the start of the summarize code suggestion pushing process and call the `publish_summarizes_suggestions` method.
    13. If the `summarize` configuration is disabled, log the start of the inline code suggestion pushing process and call the `push_inline_code_suggestions` method.
    14. If any exception occurs during the process, log the error message.
    
    Raises:
        Exception: If an error occurs during the code suggestion generation process.
    
    """

    _prepare_pr_code_suggestions (method) [+14/-2]                                                                                           
    Component signature:
    def _prepare_pr_code_suggestions(self) -> Dict

    Docstring:

    """
    Prepare the code suggestions for a pull request.
    
    Returns:
        Dict: The prepared code suggestions.
    """

    push_inline_code_suggestions (method) [+30/-13]                                                                                         
    Component signature:
    push_inline_code_suggestions(self, data)

    Docstring:

    """
    Pushes inline code suggestions to the git provider.
    
    Args:
        data (dict): A dictionary containing the data for the code suggestions.
    
    Returns:
        bool: True if the code suggestions were successfully published, False otherwise.
    """

    _prepare_prediction_extended (method) [+2/-2]                                                                                             
    Component signature:
    async def _prepare_prediction_extended(self, model: str) -> dict:

    Docstring:

    """
    Prepare extended prediction for a given model.
    
    :param model: The name of the model.
    :type model: str
    :return: A dictionary containing the prepared prediction data.
    :rtype: dict
    """

    rank_suggestions (method) [+2/-5]                                                                                                                     
    Component signature:
    async def rank_suggestions(self, data: List) -> List

    Docstring:

    """
    Call a model to rank (sort) code suggestions based on their importance order.
    
    Args:
        data (List): A list of code suggestions to be ranked.
    
    Returns:
        List: The ranked list of code suggestions.
    """

    publish_summarizes_suggestions (method) [+10/-9]                                                                                       
    Component signature:
    def publish_summarizes_suggestions(self, data: Dict)

    Docstring:

    """
    Publishes summarized code suggestions based on the provided data.
    
    Args:
        data (Dict): A dictionary containing the code suggestions.
    
    Raises:
        Exception: If there is an error while publishing the code suggestions.
    
    """

@mrT23
Copy link
Collaborator Author

mrT23 commented Dec 24, 2023

/describe

@codiumai-pr-agent-pro codiumai-pr-agent-pro bot changed the title Single-label for suggestions Enhancements to PR Code Suggestions Handling and Configuration Dec 24, 2023
Copy link
Contributor

PR Description updated to latest commit (663632e)

@mrT23
Copy link
Collaborator Author

mrT23 commented Dec 24, 2023

/improve --extended

Copy link
Contributor

PR Code Suggestions

💡 [error handling]

Consider adding error handling for when find_line_number_of_relevant_line_in_file returns -1 for position or absolute_position.

File: pr_agent/git_providers/bitbucket_provider.py (205-210)

Example code:

Existing code:

position, absolute_position = find_line_number_of_relevant_line_in_file(self.get_diff_files(),
                                                                        relevant_file.strip('`'),
                                                                        relevant_line_in_file, absolute_position)
if position == -1:
    if get_settings().config.verbosity_level >= 2:
        get_logger().info(f"Could not find position for {relevant_file} {relevant_line_in_file}")

Improved code:

position, absolute_position = find_line_number_of_relevant_line_in_file(self.get_diff_files(),
                                                                        relevant_file.strip('`'),
                                                                        relevant_line_in_file, absolute_position)
if position == -1 or absolute_position == -1:
    if get_settings().config.verbosity_level >= 2:
        get_logger().info(f"Could not find position for {relevant_file} {relevant_line_in_file}")
    return

💡 [error handling]

Consider adding error handling for when find_line_number_of_relevant_line_in_file returns -1 for position or absolute_position.

File: pr_agent/git_providers/github_provider.py (211-216)

Example code:

Existing code:

position, absolute_position = find_line_number_of_relevant_line_in_file(self.diff_files,
                                                                        relevant_file.strip('`'),
                                                                        relevant_line_in_file,
                                                                        absolute_position)
if position == -1:
    if get_settings().config.verbosity_level >= 2:
        get_logger().info(f"Could not find position for {relevant_file} {relevant_line_in_file}")

Improved code:

position, absolute_position = find_line_number_of_relevant_line_in_file(self.diff_files,
                                                                        relevant_file.strip('`'),
                                                                        relevant_line_in_file,
                                                                        absolute_position)
if position == -1 or absolute_position == -1:
    if get_settings().config.verbosity_level >= 2:
        get_logger().info(f"Could not find position for {relevant_file} {relevant_line_in_file}")
    return

💡 [maintainability]

Consider refactoring the code to avoid deep nesting. Deeply nested code can be difficult to read and understand.

File: pr_agent/algo/pr_processing.py (275-290)

Example code:

Existing code:

for file in diff_files:
    if file.filename and (file.filename.strip() == relevant_file):
        patch = file.patch
        patch_lines = patch.splitlines()
        delta = 0
        start1, size1, start2, size2 = 0, 0, 0, 0
        if absolute_position != -1: # matching absolute to relative
            for i, line in enumerate(patch_lines):
                # new hunk
                if line.startswith('@@'):
                    delta = 0
                    match = re_hunk_header.match(line)
                    start1, size1, start2, size2 = map(int, match.groups()[:4])
                elif not line.startswith('-'):
                    delta += 1

Improved code:

for file in diff_files:
    if not file.filename or file.filename.strip() != relevant_file:
        continue
    patch = file.patch
    patch_lines = patch.splitlines()
    line_difference = 0
    start1, size1, start2, size2 = 0, 0, 0, 0
    if absolute_position != -1: # matching absolute to relative
        for i, line in enumerate(patch_lines):
            # new hunk
            if line.startswith('@@'):
                line_difference = 0
                match = re_hunk_header.match(line)
                start1, size1, start2, size2 = map(int, match.groups()[:4])
            elif not line.startswith('-'):
                line_difference += 1

💡 [best practice]

Instead of checking if a key exists in a dictionary and then extending it, you can use dict.setdefault(). This method returns the value of a key if it exists, otherwise it inserts a key with a value of default.

File: pr_agent/tools/pr_code_suggestions.py (227-230)

Example code:

Existing code:

if "code_suggestions" in data:
    data["code_suggestions"].extend(data_per_chunk["code_suggestions"])
else:
    data.update(data_per_chunk)

Improved code:

data.setdefault("code_suggestions", []).extend(data_per_chunk["code_suggestions"])

💡 [best practice]

It's a good practice to use list comprehensions for creating a new list from an existing one. It's more readable and usually faster.

File: pr_agent/tools/pr_code_suggestions.py (246-247)

Example code:

Existing code:

suggestion_list = []
for suggestion in data:
    suggestion_list.append(suggestion)

Improved code:

suggestion_list = [suggestion for suggestion in data]

💡 [maintainability]

Consider using a more descriptive variable name than delta. It's not immediately clear what delta is supposed to represent in this context.

File: pr_agent/algo/pr_processing.py (279-280)

Example code:

Existing code:

delta = 0
start1, size1, start2, size2 = 0, 0, 0, 0

Improved code:

line_difference = 0
start1, size1, start2, size2 = 0, 0, 0, 0

💡 [maintainability]

Consider using a more descriptive variable name than i. It's not immediately clear what i is supposed to represent in this context.

File: pr_agent/algo/pr_processing.py (282-289)

Example code:

Existing code:

for i, line in enumerate(patch_lines):
    if line.startswith('@@'):
        delta = 0
        match = re_hunk_header.match(line)
        start1, size1, start2, size2 = map(int, match.groups()[:4])
    elif not line.startswith('-'):
        delta += 1

Improved code:

for line_index, line in enumerate(patch_lines):
    if line.startswith('@@'):
        line_difference = 0
        match = re_hunk_header.match(line)
        start1, size1, start2, size2 = map(int, match.groups()[:4])
    elif not line.startswith('-'):
        line_difference += 1

💡 [maintainability]

Consider using a more descriptive variable name than i. It's not immediately clear what i is supposed to represent in this context.

File: pr_agent/algo/pr_processing.py (305-311)

Example code:

Existing code:

for i, line in enumerate(patch_lines):
    if line.startswith('@@'):
        delta = 0
        match = re_hunk_header.match(line)
        start1, size1, start2, size2 = map(int, match.groups()[:4])
    elif not line.startswith('-'):
        delta += 1

Improved code:

for line_index, line in enumerate(patch_lines):
    if line.startswith('@@'):
        line_difference = 0
        match = re_hunk_header.match(line)
        start1, size1, start2, size2 = map(int, match.groups()[:4])
    elif not line.startswith('-'):
        line_difference += 1

💡 [maintainability]

Consider using a more descriptive variable name than i. It's not immediately clear what i is supposed to represent in this context.

File: pr_agent/algo/pr_processing.py (320-326)

Example code:

Existing code:

for i, line in enumerate(patch_lines):
    if line.startswith('@@'):
        delta = 0
        match = re_hunk_header.match(line)
        start1, size1, start2, size2 = map(int, match.groups()[:4])
    elif not line.startswith('-'):
        delta += 1

Improved code:

for line_index, line in enumerate(patch_lines):
    if line.startswith('@@'):
        line_difference = 0
        match = re_hunk_header.match(line)
        start1, size1, start2, size2 = map(int, match.groups()[:4])
    elif not line.startswith('-'):
        line_difference += 1

💡 [enhancement]

It's a good practice to use str.format() or f-string for string formatting. It's more readable and usually faster.

File: pr_agent/tools/pr_code_suggestions.py (310-311)

Example code:

Existing code:

data_markdown += f"Existing code:\n```{language_name}\n{s['existing_code'].rstrip()}\n```\n"
data_markdown += f"Improved code:\n```{language_name}\n{s['improved_code'].rstrip()}\n```\n"

Improved code:

data_markdown += f"Existing code:\n```{language_name}\n{s['existing_code'].rstrip(' \n')}\n```\n"
data_markdown += f"Improved code:\n```{language_name}\n{s['improved_code'].rstrip(' \n')}\n```\n"

💡 [enhancement]

Instead of using rstrip() twice, you can use it once with the characters you want to remove as an argument.

File: pr_agent/tools/pr_code_suggestions.py (310-311)

Example code:

Existing code:

data_markdown += f"Existing code:\n```{language_name}\n{s['existing_code'].rstrip()}\n```\n"
data_markdown += f"Improved code:\n```{language_name}\n{s['improved_code'].rstrip()}\n```\n"

Improved code:

data_markdown += f"Existing code:\n```{language_name}\n{s['existing_code'].rstrip(' \n')}\n```\n"
data_markdown += f"Improved code:\n```{language_name}\n{s['improved_code'].rstrip(' \n')}\n```\n"

💡 [enhancement]

It's a good practice to use str.format() or f-string for string formatting. It's more readable and usually faster.

File: pr_agent/tools/pr_code_suggestions.py (299-299)

Example code:

Existing code:

data_markdown += f"\n💡 [{label}]\n\n**{s['suggestion_content'].rstrip().rstrip()}**\n\n"

Improved code:

data_markdown += f"\n💡 [{label}]\n\n**{s['suggestion_content'].rstrip()}**\n\n"

💡 [enhancement]

Instead of using rstrip() twice, you can use it once with the characters you want to remove as an argument.

File: pr_agent/tools/pr_code_suggestions.py (299-299)

Example code:

Existing code:

data_markdown += f"\n💡 [{label}]\n\n**{s['suggestion_content'].rstrip().rstrip()}**\n\n"

Improved code:

data_markdown += f"\n💡 [{label}]\n\n**{s['suggestion_content'].rstrip(' \n')}**\n\n"

💡 [enhancement]

Consider using a more pythonic way to check if a key exists in a dictionary. Instead of (not 'code_suggestions' in data), you can use ('code_suggestions' not in data).

File: pr_agent/tools/pr_code_suggestions.py (68-70)

Example code:

Existing code:

if (not data) or (not 'code_suggestions' in data):
    get_logger().info('No code suggestions found for PR.')
    return

Improved code:

if (not data) or ('code_suggestions' not in data):
    get_logger().info('No code suggestions found for PR.')
    return

yochail pushed a commit to yochail/pr-agent that referenced this pull request Feb 11, 2024
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.

None yet

2 participants