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

Add labels option for single file #23

Merged
merged 11 commits into from
Jun 18, 2024
Merged

Add labels option for single file #23

merged 11 commits into from
Jun 18, 2024

Conversation

FilippoTrotter
Copy link
Collaborator

@FilippoTrotter FilippoTrotter commented Jun 10, 2024

Add label option possibility

Summary by CodeRabbit

  • New Features

    • Added support for start-label and end-label flags to define file section boundaries for processing.
    • Improved flag conflict handling to ensure only one of line or label flags can be specified.
  • Bug Fixes

    • Corrected the spelling of "Python" in the CommentChars map.
  • Tests

    • Enhanced test cases to include scenarios for processing files with start and end labels.

@FilippoTrotter FilippoTrotter linked an issue Jun 10, 2024 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Jun 10, 2024

Walkthrough

The recent changes introduce the functionality to define section boundaries within files using start and end labels, along with enhancements to error handling and test cases. These updates allow for more precise file modifications by specifying which sections to modify. Additionally, the changes rectify some minor bugs and improve upon existing error-handling mechanisms.

Changes

File Summary
cmd/tgcom/main.go Added new flags start-label and end-label and improved error handling.
internal/comment/comment.go Improved prefix comparison in the Uncomment function.
internal/file/file.go Added startLabel and endLabel parameters to ProcessFile and related functions. Enhanced logic to handle section-based processing.
internal/file/file_test.go Updated test cases with startLabel and endLabel parameters. Added Labels test case for section-based processing.
internal/language/language.go Corrected the spelling of "Python" and adjusted comment characters for various languages.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MainFunction
    participant FileProcessor
    participant CommentProcessor

    User ->> MainFunction: Execute program with flags
    MainFunction ->> MainFunction: Parse flags (start-label and end-label)
    alt Line flag specified
        MainFunction -->> User: Error - Conflicting flags
    end
    MainFunction ->> FileProcessor: ProcessSingleFile with flags
    FileProcessor ->> FileProcessor: Determine section based on labels
    FileProcessor ->> CommentProcessor: Modify content in specified section
    CommentProcessor -->> FileProcessor: Return modified content
    FileProcessor -->> MainFunction: Return result
    MainFunction -->> User: Output result
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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 4

Outside diff range and nitpick comments (1)
internal/file/file.go (1)

Line range hint 18-69: Consider handling errors from Close and Remove methods to prevent resource leaks.

The static analysis tool golangci-lint has flagged multiple instances where the error return values of Close and Remove methods are not checked. Ignoring these errors can lead to resource leaks or unhandled exceptions. Here's a proposed fix:

- inputFile.Close()
+ if err := inputFile.Close(); err != nil {
+     return fmt.Errorf("failed to close input file: %w", err)
+ }

- tmpFile.Close()
+ if err := tmpFile.Close(); err != nil {
+     return fmt.Errorf("failed to close temporary file: %w", err)
+ }

- os.Remove(tmpFilename)
+ if err := os.Remove(tmpFilename); err != nil {
+     return fmt.Errorf("failed to remove temporary file: %w", err)
+ }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 20229a9 and 11a6e95.

Files selected for processing (5)
  • cmd/tgcom/main.go (1 hunks)
  • internal/comment/comment.go (1 hunks)
  • internal/file/file.go (6 hunks)
  • internal/file/file_test.go (8 hunks)
  • internal/language/language.go (1 hunks)
Additional context used
golangci-lint
internal/comment/comment.go

[warning] 30-30: indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)

internal/file/file_test.go

[warning] 70-70: unused-parameter: parameter 'line' seems to be unused, consider removing or renaming it as _ (revive)

internal/file/file.go

23-23: Error return value of inputFile.Close is not checked (errcheck)


43-43: Error return value of tmpFile.Close is not checked (errcheck)


47-47: Error return value of tmpFile.Close is not checked (errcheck)


48-48: Error return value of os.Remove is not checked (errcheck)


55-55: Error return value of tmpFile.Close is not checked (errcheck)


56-56: Error return value of os.Remove is not checked (errcheck)


62-62: Error return value of tmpFile.Close is not checked (errcheck)


63-63: Error return value of os.Remove is not checked (errcheck)


69-69: Error return value of os.Remove is not checked (errcheck)


80-80: Error return value of os.Remove is not checked (errcheck)

Additional comments not posted (7)
internal/language/language.go (1)

10-10: Corrected the spelling of "Python" in the comment characters map.

internal/comment/comment.go (1)

17-18: Improved handling of spaces after comment characters in Uncomment.

cmd/tgcom/main.go (3)

15-16: Added start-label and end-label flags to define section boundaries.


52-67: Enhanced error handling to prevent simultaneous use of line and label flags.


52-67: Improve clarity of error messages.

-		fmt.Println("Error: only  line OR label flags are allowed not both")
+		fmt.Println("Error: Specify either line number/range OR label, not both.")

Likely invalid or redundant comment.

internal/file/file_test.go (2)

120-132: Added a new test case to verify processing files with specific start and end labels.


26-26: Updated test cases to include startLabel and endLabel parameters.

Also applies to: 37-37, 48-48, 60-60, 75-75, 103-103

internal/file/file.go Outdated Show resolved Hide resolved
internal/file/file.go Outdated Show resolved Hide resolved
internal/comment/comment.go Outdated Show resolved Hide resolved
internal/file/file_test.go 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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 11a6e95 and a9ed9bd.

Files selected for processing (1)
  • cmd/tgcom/main.go (1 hunks)
Additional context used
golangci-lint
cmd/tgcom/main.go

23-23: Error return value of inputFile.Close is not checked (errcheck)


43-43: Error return value of tmpFile.Close is not checked (errcheck)


47-47: Error return value of tmpFile.Close is not checked (errcheck)


48-48: Error return value of os.Remove is not checked (errcheck)


55-55: Error return value of tmpFile.Close is not checked (errcheck)


56-56: Error return value of os.Remove is not checked (errcheck)


62-62: Error return value of tmpFile.Close is not checked (errcheck)


63-63: Error return value of os.Remove is not checked (errcheck)


69-69: Error return value of os.Remove is not checked (errcheck)


80-80: Error return value of os.Remove is not checked (errcheck)


[warning] 70-70: unused-parameter: parameter 'line' seems to be unused, consider removing or renaming it as _ (revive)


[warning] 30-30: indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)

Additional comments not posted (3)
cmd/tgcom/main.go (3)

14-16: The introduction of startLabelFlag and endLabelFlag aligns with the PR objectives to handle file sections by labels. Ensure that the flag descriptions are clear and concise.


52-63: Excellent error handling for label and line flag conflicts. This prevents ambiguous command usage and enforces clearer user intentions.

Tools
golangci-lint

55-55: Error return value of tmpFile.Close is not checked (errcheck)


56-56: Error return value of os.Remove is not checked (errcheck)


62-62: Error return value of tmpFile.Close is not checked (errcheck)


63-63: Error return value of os.Remove is not checked (errcheck)


79-81: The error handling in ProcessSingleFile is good, but consider logging the error details to help with debugging.

- fmt.Println("Error processing file:", err)
+ fmt.Println("Error processing file:", err.Error())

Likely invalid or redundant comment.

Tools
golangci-lint

80-80: Error return value of os.Remove is not checked (errcheck)

@FilippoTrotter FilippoTrotter mentioned this pull request Jun 12, 2024
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a9ed9bd and a8637a8.

Files selected for processing (2)
  • internal/file/file.go (6 hunks)
  • internal/file/file_test.go (8 hunks)
Additional context used
golangci-lint
internal/file/file_test.go

23-23: Error return value of inputFile.Close is not checked (errcheck)


43-43: Error return value of tmpFile.Close is not checked (errcheck)


47-47: Error return value of tmpFile.Close is not checked (errcheck)


48-48: Error return value of os.Remove is not checked (errcheck)


55-55: Error return value of tmpFile.Close is not checked (errcheck)


56-56: Error return value of os.Remove is not checked (errcheck)


62-62: Error return value of tmpFile.Close is not checked (errcheck)


63-63: Error return value of os.Remove is not checked (errcheck)


69-69: Error return value of os.Remove is not checked (errcheck)


80-80: Error return value of os.Remove is not checked (errcheck)


[warning] 30-30: indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)


[warning] 70-70: unused-parameter: parameter 'line' seems to be unused, consider removing or renaming it as _ (revive)


135-135: unnecessary leading newline (whitespace)

internal/file/file.go

23-23: Error return value of inputFile.Close is not checked (errcheck)


43-43: Error return value of tmpFile.Close is not checked (errcheck)


47-47: Error return value of tmpFile.Close is not checked (errcheck)


48-48: Error return value of os.Remove is not checked (errcheck)


55-55: Error return value of tmpFile.Close is not checked (errcheck)


56-56: Error return value of os.Remove is not checked (errcheck)


62-62: Error return value of tmpFile.Close is not checked (errcheck)


63-63: Error return value of os.Remove is not checked (errcheck)


69-69: Error return value of os.Remove is not checked (errcheck)


80-80: Error return value of os.Remove is not checked (errcheck)


[warning] 30-30: indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)


[warning] 70-70: unused-parameter: parameter 'line' seems to be unused, consider removing or renaming it as _ (revive)


135-135: unnecessary leading newline (whitespace)

Additional comments not posted (9)
internal/file/file_test.go (4)

26-26: Consider removing or renaming the unused parameter 'line' as it is not used within the function.


37-37: Ensure proper error handling for non-existing and empty files, and validate the behavior in dry run scenarios.

Also applies to: 48-48, 60-60, 75-75, 103-103


120-132: The new test case for label functionality appears to be well-implemented and covers the expected behavior when start and end labels are provided.


181-181: Ensure that the ProcessSingleFile function correctly handles the absence of labels by falling back to line number processing.

internal/file/file.go (5)

Line range hint 18-52: The implementation of ProcessFile function now supports both line numbers and labels for file processing. Ensure that the error handling and file operations are robust, especially with the introduction of backup and temporary file mechanisms.

Tools
golangci-lint

[warning] 30-30: indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)


84-89: The shouldProcessLine function provides a clear and concise way to determine whether a line should be processed based on the provided labels or line numbers. This is a good use of conditional logic to handle multiple scenarios.


91-123: The writeChanges function has been updated to handle sections of the file defined by labels. Ensure that the logic for entering and exiting sections is correctly implemented and that the file writing operations are error-free.


130-153: The printChanges function mirrors the logic of writeChanges but for dry run scenarios where changes are printed instead of written. This consistency in handling both scenarios is crucial for maintaining predictable behavior.

Tools
golangci-lint

135-135: unnecessary leading newline (whitespace)


189-204: The ProcessSingleFile function has been refactored to integrate label handling. Ensure that the error handling is consistent and that the function can gracefully handle both labels and line numbers.

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

Outside diff range and nitpick comments (1)
internal/file/file.go (1)

Line range hint 18-52: The addition of label parameters enhances the flexibility of file processing. Ensure to handle the error return values from file operations to prevent potential resource leaks.

+ if err := inputFile.Close(); err != nil {
+     log.Printf("Failed to close input file: %v", err)
+ }
+ if err := tmpFile.Close(); err != nil {
+     log.Printf("Failed to close temporary file: %v", err)
+ }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a8637a8 and ea9e2d4.

Files selected for processing (2)
  • internal/comment/comment.go (2 hunks)
  • internal/file/file.go (6 hunks)
Additional context used
golangci-lint
internal/comment/comment.go

23-23: Error return value of inputFile.Close is not checked (errcheck)


43-43: Error return value of tmpFile.Close is not checked (errcheck)


47-47: Error return value of tmpFile.Close is not checked (errcheck)


48-48: Error return value of os.Remove is not checked (errcheck)


55-55: Error return value of tmpFile.Close is not checked (errcheck)


56-56: Error return value of os.Remove is not checked (errcheck)


62-62: Error return value of tmpFile.Close is not checked (errcheck)


63-63: Error return value of os.Remove is not checked (errcheck)


69-69: Error return value of os.Remove is not checked (errcheck)


80-80: Error return value of os.Remove is not checked (errcheck)


139-139: File is not goimports-ed (goimports)


[warning] 70-70: unused-parameter: parameter 'line' seems to be unused, consider removing or renaming it as _ (revive)


136-136: unnecessary leading newline (whitespace)

internal/file/file.go

23-23: Error return value of inputFile.Close is not checked (errcheck)


43-43: Error return value of tmpFile.Close is not checked (errcheck)


47-47: Error return value of tmpFile.Close is not checked (errcheck)


48-48: Error return value of os.Remove is not checked (errcheck)


55-55: Error return value of tmpFile.Close is not checked (errcheck)


56-56: Error return value of os.Remove is not checked (errcheck)


62-62: Error return value of tmpFile.Close is not checked (errcheck)


63-63: Error return value of os.Remove is not checked (errcheck)


69-69: Error return value of os.Remove is not checked (errcheck)


80-80: Error return value of os.Remove is not checked (errcheck)


139-139: File is not goimports-ed (goimports)


[warning] 70-70: unused-parameter: parameter 'line' seems to be unused, consider removing or renaming it as _ (revive)


136-136: unnecessary leading newline (whitespace)

Additional comments not posted (2)
internal/comment/comment.go (2)

9-12: The HTML comment handling looks correct and concise.


52-63: The toggling of HTML comments is consistent with the rest of the module's handling of comment characters.

Tools
golangci-lint

55-55: Error return value of tmpFile.Close is not checked (errcheck)


56-56: Error return value of os.Remove is not checked (errcheck)


62-62: Error return value of tmpFile.Close is not checked (errcheck)


63-63: Error return value of os.Remove is not checked (errcheck)

Comment on lines 19 to 37

//just for html
if commentChars == "<!-- -->" {
if strings.HasPrefix(trimmedLine, "<!--") && strings.HasSuffix(trimmedLine, "-->") {
// Check for both `<!--` and `<!-- ` prefixes.
if strings.HasPrefix(trimmedLine, "<!--"+" ") {
line = strings.Replace(line, "<!-- ", "", 1)
line = strings.Replace(line, "<!--", "", 1)
}

// Check for both '-->' and ' -->' suffixes
if strings.HasSuffix(trimmedLine, " "+"-->") {
line = strings.Replace(line, " "+"-->", "", 1)
line = strings.Replace(line, "-->", "", 1)
}

return line
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The updated handling of HTML comments improves accuracy. Consider adding a brief comment explaining the logic for future maintainability.

+ // Handle HTML comments by checking for optional spaces after the prefix and before the suffix.
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
//just for html
if commentChars == "<!-- -->" {
if strings.HasPrefix(trimmedLine, "<!--") && strings.HasSuffix(trimmedLine, "-->") {
// Check for both `<!--` and `<!-- ` prefixes.
if strings.HasPrefix(trimmedLine, "<!--"+" ") {
line = strings.Replace(line, "<!-- ", "", 1)
line = strings.Replace(line, "<!--", "", 1)
}
// Check for both '-->' and ' -->' suffixes
if strings.HasSuffix(trimmedLine, " "+"-->") {
line = strings.Replace(line, " "+"-->", "", 1)
line = strings.Replace(line, "-->", "", 1)
}
return line
}
}
//just for html
if commentChars == "<!-- -->" {
if strings.HasPrefix(trimmedLine, "<!--") && strings.HasSuffix(trimmedLine, "-->") {
// Handle HTML comments by checking for optional spaces after the prefix and before the suffix.
if strings.HasPrefix(trimmedLine, "<!--"+" ") {
line = strings.Replace(line, "<!-- ", "", 1)
line = strings.Replace(line, "<!--", "", 1)
}
// Check for both '-->' and ' -->' suffixes
if strings.HasSuffix(trimmedLine, " "+"-->") {
line = strings.Replace(line, " "+"-->", "", 1)
line = strings.Replace(line, "-->", "", 1)
}
return line
}
}
Tools
golangci-lint

23-23: Error return value of inputFile.Close is not checked (errcheck)

Comment on lines +91 to +124
func writeChanges(inputFile *os.File, outputFile *os.File, lineNum [2]int, startLabel, endLabel string, commentChars string, modFunc func(string, string) string) error {
scanner := bufio.NewScanner(inputFile)
writer := bufio.NewWriter(outputFile)
currentLine := 1
inSection := false
var err error

for scanner.Scan() {
lineContent := scanner.Text()
if lineNum[0] <= currentLine && currentLine <= lineNum[1] {

if strings.Contains(lineContent, endLabel) {
inSection = false
}

if shouldProcessLine(currentLine, lineNum, startLabel, endLabel, inSection) {
lineContent = modFunc(lineContent, commentChars)
}

if _, err := writer.WriteString(lineContent + "\n"); err != nil {
if strings.Contains(lineContent, startLabel) {
inSection = true
}

if _, err = writer.WriteString(lineContent + "\n"); err != nil {
return err
}

currentLine++
}

if lineNum[1] > currentLine {
if lineNum[1] > currentLine && startLabel == "" && endLabel == "" {
return errors.New("line number is out of range")
}

if err := scanner.Err(); err != nil {
if err = scanner.Err(); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

The implementation for writing changes based on labels is correct. Consider refactoring to reduce code duplication between writeChanges and printChanges.

+ // Use a helper function to determine if a line should be processed.
+ func shouldProcessLine(lineContent string, currentLine int, lineNum [2]int, startLabel, endLabel string) bool {
+     if startLabel != "" && endLabel != "" {
+         return strings.Contains(lineContent, startLabel) || strings.Contains(lineContent, endLabel)
+     }
+     return lineNum[0] <= currentLine && currentLine <= lineNum[1]
+ }

Committable suggestion was skipped due to low confidence.

Comment on lines +192 to +207
func ProcessSingleFile(filename string, lineStr, startLabel, endLabel string, modFunc func(string, string) string, dryRun bool) error {
commentChars, err := selectCommentChars(filename)
if err != nil {
return err
return fmt.Errorf("error selecting comment characters: %w", err)
}
lineNum := [2]int{startLine, endLine}

commentChars, err := selectCommentChars(filename)
if err != nil {
return err
var lineNum [2]int
if startLabel == "" && endLabel == "" {
startLine, endLine, err := extractLines(lineStr)
if err != nil {
return fmt.Errorf("error extracting line numbers: %w", err)
}
lineNum = [2]int{startLine, endLine}
}

return ProcessFile(filename, lineNum, commentChars, modFunc, dryRun)
return ProcessFile(filename, lineNum, startLabel, endLabel, commentChars, modFunc, dryRun)
Copy link
Contributor

Choose a reason for hiding this comment

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

The updates to handle labels and improve error messages enhance the function's usability and robustness. Consider using consistent error handling across all file operations.

+ if err := os.Remove(tmpFilename); err != nil {
+     log.Printf("Failed to remove temporary file: %v", err)
+ }

Committable suggestion was skipped due to low confidence.

Comment on lines +131 to +156
func printChanges(inputFile *os.File, lineNum [2]int, startLabel, endLabel, commentChars string, modFunc func(string, string) string) error {
scanner := bufio.NewScanner(inputFile)
currentLine := 1
inSection := false

for scanner.Scan() {

lineContent := scanner.Text()
if lineNum[0] <= currentLine && currentLine <= lineNum[1] {

if strings.Contains(lineContent, endLabel) {
inSection = false
}

if shouldProcessLine(currentLine, lineNum, startLabel, endLabel, inSection) {
modified := modFunc(lineContent, commentChars)
fmt.Printf("%d: %s -> %s\n", currentLine, lineContent, modified)
}

if strings.Contains(lineContent, startLabel) {
inSection = true
}

currentLine++
}

if lineNum[1] > currentLine {
if lineNum[1] > currentLine && startLabel == "" && endLabel == "" {
Copy link
Contributor

Choose a reason for hiding this comment

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

The function for printing changes during a dry run is implemented correctly. Ensure to handle potential errors from the scanner to prevent silent failures.

+ if err := scanner.Err(); err != nil {
+     log.Printf("Failed to scan file: %v", err)
+ }
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
func printChanges(inputFile *os.File, lineNum [2]int, startLabel, endLabel, commentChars string, modFunc func(string, string) string) error {
scanner := bufio.NewScanner(inputFile)
currentLine := 1
inSection := false
for scanner.Scan() {
lineContent := scanner.Text()
if lineNum[0] <= currentLine && currentLine <= lineNum[1] {
if strings.Contains(lineContent, endLabel) {
inSection = false
}
if shouldProcessLine(currentLine, lineNum, startLabel, endLabel, inSection) {
modified := modFunc(lineContent, commentChars)
fmt.Printf("%d: %s -> %s\n", currentLine, lineContent, modified)
}
if strings.Contains(lineContent, startLabel) {
inSection = true
}
currentLine++
}
if lineNum[1] > currentLine {
if lineNum[1] > currentLine && startLabel == "" && endLabel == "" {
func printChanges(inputFile *os.File, lineNum [2]int, startLabel, endLabel, commentChars string, modFunc func(string, string) string) error {
scanner := bufio.NewScanner(inputFile)
currentLine := 1
inSection := false
for scanner.Scan() {
lineContent := scanner.Text()
if strings.Contains(lineContent, endLabel) {
inSection = false
}
if shouldProcessLine(currentLine, lineNum, startLabel, endLabel, inSection) {
modified := modFunc(lineContent, commentChars)
fmt.Printf("%d: %s -> %s\n", currentLine, lineContent, modified)
}
if strings.Contains(lineContent, startLabel) {
inSection = true
}
currentLine++
}
if err := scanner.Err(); err != nil {
log.Printf("Failed to scan file: %v", err)
}
if lineNum[1] > currentLine && startLabel == "" && endLabel == "" {
Tools
golangci-lint

139-139: File is not goimports-ed (goimports)


136-136: unnecessary leading newline (whitespace)

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

Outside diff range and nitpick comments (1)
cmd/tgcom/main.go (1)

Line range hint 1-1: The file should be formatted according to Go standards using goimports.

- // Current file content
+ // goimports formatted file content

Please run goimports on this file to ensure it adheres to the Go style guide.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ea9e2d4 and 7f04f79.

Files selected for processing (3)
  • cmd/tgcom/main.go (3 hunks)
  • internal/file/file.go (6 hunks)
  • internal/file/file_test.go (8 hunks)
Additional context used
golangci-lint
cmd/tgcom/main.go

1-1: File is not goimports-ed (goimports)

internal/file/file_test.go

[warning] 69-69: unused-parameter: parameter 'line' seems to be unused, consider removing or renaming it as _ (revive)

internal/file/file.go

23-23: Error return value of inputFile.Close is not checked (errcheck)


43-43: Error return value of tmpFile.Close is not checked (errcheck)


47-47: Error return value of tmpFile.Close is not checked (errcheck)


48-48: Error return value of os.Remove is not checked (errcheck)


55-55: Error return value of tmpFile.Close is not checked (errcheck)


56-56: Error return value of os.Remove is not checked (errcheck)


62-62: Error return value of tmpFile.Close is not checked (errcheck)


63-63: Error return value of os.Remove is not checked (errcheck)


69-69: Error return value of os.Remove is not checked (errcheck)


80-80: Error return value of os.Remove is not checked (errcheck)


139-139: File is not goimports-ed (goimports)


136-136: unnecessary leading newline (whitespace)

Additional comments not posted (9)
cmd/tgcom/main.go (4)

16-17: The introduction of start-label and end-label flags is a good addition for specifying section boundaries. Make sure to update the documentation to explain how users can utilize these new flags effectively.


25-26: Ensure that startLabel and endLabel are properly retrieved from the flags. Good implementation of flag parsing.


53-64: Excellent error handling to ensure that users provide both start and end labels if one is specified, and to prevent the use of both line numbers and labels simultaneously. This should prevent common user errors.
[APROVED]


81-81: The call to file.ProcessSingleFile correctly includes the new label parameters. Ensure that the ProcessSingleFile function is updated accordingly to handle these parameters.

Verification successful

The ProcessSingleFile function in internal/file/file.go correctly handles the new label parameters startLabel and endLabel. The parameters are used to determine the line range or labels for processing the file, and they are passed to the ProcessFile function for further handling.

  • internal/file/file.go:
    • The ProcessSingleFile function includes startLabel and endLabel parameters.
    • These parameters are used within the function to determine the processing logic and are passed to ProcessFile.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that `ProcessSingleFile` function handles the new label parameters correctly.

# Test: Search for the function definition and ensure it includes handling for `startLabel` and `endLabel`.
rg --type go $'func ProcessSingleFile'

Length of output: 197



Script:

#!/bin/bash
# Description: Verify that `ProcessSingleFile` function handles the new label parameters correctly.

# Locate the implementation of the ProcessSingleFile function and display its content.
rg --type go --context 20 $'func ProcessSingleFile' internal/file/file.go

Length of output: 1265

internal/file/file_test.go (3)

25-25: The test for ProcessFile is well-implemented and checks for correct behavior when labels are not provided. Ensure that additional tests are added to verify the behavior when labels are used.


36-36: The test cases are comprehensive and cover a variety of scenarios including error handling and dry runs. The addition of the "Labels" test case is particularly valuable for testing the new label functionality.

Also applies to: 47-47, 59-59, 74-74, 102-102, 119-131


180-180: The ProcessSingleFile test checks the error handling correctly. Ensure that the function itself handles errors as expected and consider adding more detailed error messages for better debugging.

internal/file/file.go (2)

18-18: The modifications to ProcessFile, printChanges, and writeChanges to include label handling are well done. The shouldProcessLine function is a good addition to encapsulate the logic for deciding whether a line should be processed based on labels or line numbers.

Also applies to: 27-27, 52-52, 84-89, 91-91, 131-131


192-207: The ProcessSingleFile function has been updated to handle the new label parameters effectively. The error handling improvements, such as wrapping errors with additional context, are excellent for troubleshooting.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7f04f79 and 7216630.

Files selected for processing (1)
  • internal/file/file_test.go (8 hunks)
Additional context used
golangci-lint
internal/file/file_test.go

[warning] 69-69: unused-parameter: parameter 'line' seems to be unused, consider removing or renaming it as _ (revive)

Additional comments not posted (8)
internal/file/file_test.go (8)

25-25: Ensure the ProcessFile function is called with the correct parameters.


36-36: Test case for non-existing file correctly expects an error. This is a good practice to ensure robust error handling.


47-47: Good test coverage for edge cases like an empty file, ensuring the function behaves as expected under different conditions.


59-59: The ProcessFile function is tested for multiple lines, which is crucial for ensuring that the function handles ranges correctly.
[APROVED]


74-74: The test case 'WithBackup' is designed to expect an error when no changes are made. This is a good practice for testing the robustness of error handling.


102-102: The dry run functionality is well tested here. Capturing stdout to check the output is a smart way to ensure that the dry run logs the expected changes without making actual modifications.


119-131: The test case 'Labels' effectively checks the functionality of processing files with start and end labels. This is a crucial test given the new feature added to handle labels.


180-180: The ProcessSingleFile function is called within a loop for different test scenarios. It's good to see various edge cases being tested.

@puria puria merged commit 385742d into main Jun 18, 2024
1 check passed
@puria puria deleted the feat/labels_option branch June 18, 2024 13:12
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.

Use Labels for Heredoc-like Sections
3 participants