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

Remove python docstrings and Single-line comments #81

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

thecurz
Copy link

@thecurz thecurz commented Sep 18, 2024

Summary

Altered files

src/core/file/fileManipulator.ts:
I added the methods removeDocStrings() and removeHashComments() to be used in removeComments() so that it's easier to implement an option to only delete certain types of comments later on.
tests/core/file/fileManipulator.test.ts:
There are now 16 tests for Python comment removal.

Observations

Certain edge cases were not considered to avoid complexity.
For example in the code

""" docstring1""" """ docstring 2
"""

only the first docstring is removed. But this is not standard practice in Python

Time Complexity

  • removeDocStrings Function: O(m * n) where 'm' is the number of lines and 'n' is the average length of each line
  • removeHashComments Function: O((m * n) + m log m)

Benchmark

For a better idea of the time complexity, I ran a quick test where the algorithm was applied to a repeated string of Python code containing several docstrings and comments.
For 3 million lines, the algorithm ran in around one second on my computer. This is more likely than not a decent time since LLMs won't take this many tokens anyway.
image
image

Next steps

  • It could be useful to add an option to only remove docstrings or only single-line comments since docstrings could add useful context to the prompt but not the single-line comments.
  • The algorithm can be further optimized if the current time complexity isn't adequate enough.
    I'll be happy to help with the implementation of any of these!

Summary by CodeRabbit

  • New Features

    • Enhanced comment removal capabilities in Python code with new methods to remove docstrings and hash comments.
  • Bug Fixes

    • Improved handling of various edge cases in comment removal, including nested quotes and inline comments.
  • Tests

    • Expanded test cases for comment and docstring removal, covering a wider range of scenarios to ensure robustness and readability.

Copy link

coderabbitai bot commented Sep 18, 2024

Walkthrough

The changes introduced enhance the PythonManipulator class in the fileManipulator.ts file by adding methods for removing Python comments and docstrings. Specifically, two new methods, removeDocStrings and removeHashComments, are implemented to handle multi-line docstrings and single-line comments, respectively. The existing removeComments method is modified to call these new methods. Additionally, the test cases in fileManipulator.test.ts are updated to standardize string quotations and expand coverage for various comment and string scenarios.

Changes

Files Change Summary
src/core/file/fileManipulator.ts - Added: removeDocStrings(content: string): string
- Added: removeHashComments(content: string): string
- Modified: removeComments(content: string): string to include calls to the new methods.
tests/core/file/fileManipulator.test.ts - Standardized string quotation marks from single to double quotes.
- Expanded test cases for comment and docstring removal, covering various edge cases without altering the test for unsupported file types.

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.

Copy link

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

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 61f35ac and a6bfc9f.

Files selected for processing (2)
  • src/core/file/fileManipulator.ts (4 hunks)
  • tests/core/file/fileManipulator.test.ts (23 hunks)
Additional context used
Biome
src/core/file/fileManipulator.ts

[error] 60-60: Use !== instead of !=.
!= is only allowed when comparing against null

!= is only allowed when comparing against null

Using != may be unsafe if you are relying on type coercion
Unsafe fix: Use !==

(lint/suspicious/noDoubleEquals)


[error] 163-163: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 169-169: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 177-177: Reassigning a function parameter is confusing.

The parameter is declared here:

Use a local variable instead.

(lint/style/noParameterAssign)


[error] 178-178: Reassigning a function parameter is confusing.

The parameter is declared here:

Use a local variable instead.

(lint/style/noParameterAssign)

Additional comments not posted (16)
tests/core/file/fileManipulator.test.ts (16)

Line range hint 153-173: Test case "Python comment, docstring removal" effectively validates comment and docstring removal.

This test case ensures that both single-line comments and docstrings are properly removed from Python code, enhancing test coverage.


175-191: Test case "Python docstring removal mixing string declaration" correctly handles mixed string declarations.

This test validates that string literals containing triple quotes are preserved while actual docstrings are removed.


193-213: Test case "Python comment f-string is not removed" ensures f-strings are preserved.

This test confirms that f-strings and their contents remain intact during comment and docstring removal.


215-233: Test case "Python comment multi-line string literal is not removed" accurately preserves multi-line string literals.

The test verifies that multi-line string literals are not mistaken for docstrings and are left unmodified.


235-247: Test case "Python nested quotes" correctly handles nested quotes within docstrings.

This ensures that docstrings with nested single or double quotes are removed without affecting the integrity of string literals.


249-267: Test case "Python nested triple quotes with different types" effectively tests nested docstrings.

The test checks the removal of docstrings containing nested triple quotes of different types, ensuring robustness.


269-281: Test case "Python inline comments" confirms that inline comments are properly removed.

This test ensures that comments following code on the same line are correctly eliminated without affecting the code itself.


283-297: Test case "Python multi-line statement with string" preserves multi-line strings and removes comments.

This verifies that multi-line statements using backslashes are not disrupted during comment removal.


299-315: Test case "Python docstring with triple quotes inside string literals" ensures string literals are preserved.

The test confirms that string literals containing triple quotes are not mistaken for docstrings.


317-341: Test case "Python mixed comments and docstrings" accurately removes all comments and docstrings.

This comprehensive test covers multiple scenarios of comments and docstrings interleaved with code, ensuring thorough removal.


343-361: Test case "Python f-strings with triple quotes" preserves f-strings during comment removal.

The test ensures that multi-line f-strings with expressions are not altered.


363-373: Test case "Python escaped hash in string" correctly handles escaped characters.

This verifies that hashes escaped within strings are not treated as comment indicators.


375-393: Test case "Python nested function with docstrings" properly removes docstrings from nested functions.

The test confirms that docstrings in both outer and inner functions are removed without affecting the function definitions.


395-413: Test case "Python comment-like content in string" preserves strings containing comment-like content.

This ensures that strings with hash symbols are not inadvertently altered during comment removal.


415-430: Test case "Python docstring with backslashes" correctly handles backslashes within docstrings.

The test verifies that backslashes, even when escaping triple quotes, do not interfere with docstring removal.


432-442: Test case "Python mixed single and double quotes" preserves string literals with mixed quotes.

This test ensures that strings containing triple quotes are not mistaken for docstrings unless they are actual docstrings.

src/core/file/fileManipulator.ts Outdated Show resolved Hide resolved
src/core/file/fileManipulator.ts Outdated Show resolved Hide resolved
src/core/file/fileManipulator.ts Outdated Show resolved Hide resolved
src/core/file/fileManipulator.ts Outdated Show resolved Hide resolved
thecurz and others added 4 commits September 20, 2024 23:54
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a6bfc9f and b3bcfbd.

Files selected for processing (1)
  • src/core/file/fileManipulator.ts (4 hunks)
Additional context used
Biome
src/core/file/fileManipulator.ts

[error] 177-177: expected , but instead found :

Remove :

(parse)


[error] 177-177: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 182-182: This code is unreachable

... because this statement will return from the function beforehand

(lint/correctness/noUnreachable)

Additional comments not posted (2)
src/core/file/fileManipulator.ts (2)

43-99: LGTM!

The removeDocStrings function looks good. It correctly handles both single and double quote docstrings, and the logic to accumulate lines in a buffer until a complete docstring is found is sound.


101-174: LGTM!

The removeHashComments function looks good. The binary search approach to determine if a hash index falls within a string literal is efficient, and the logic to process the content in a loop, identifying hash comments and appending the relevant portions to the result string is correct.

Comment on lines +176 to +183
removeComments(content: string): string {
removeComments(content: string): string {
let result = this.removeDocStrings(content);
result = this.removeHashComments(result);
return rtrimLines(result);
}
return rtrimLines(content);
}
Copy link

Choose a reason for hiding this comment

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

Fix the syntax error and remove the unreachable code.

The removeComments function has the following issues:

  • There is a syntax error in the function signature. The : after the parameter list should be removed.
  • The last line of the function is unreachable due to the return statement on the previous line.

Apply this diff to fix the issues:

- removeComments(content: string): string {
+ removeComments(content: string) {
    let result = this.removeDocStrings(content);
    result = this.removeHashComments(result);
    return rtrimLines(result);
  }
-   return rtrimLines(content);
}
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
removeComments(content: string): string {
removeComments(content: string): string {
let result = this.removeDocStrings(content);
result = this.removeHashComments(result);
return rtrimLines(result);
}
return rtrimLines(content);
}
removeComments(content: string) {
let result = this.removeDocStrings(content);
result = this.removeHashComments(result);
return rtrimLines(result);
}
Tools
Biome

[error] 177-177: expected , but instead found :

Remove :

(parse)


[error] 177-177: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 182-182: This code is unreachable

... because this statement will return from the function beforehand

(lint/correctness/noUnreachable)

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