Skip to content

fix: autocorrect everything #1586

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

Merged
merged 1 commit into from
Mar 20, 2025

Conversation

yihong0618
Copy link
Contributor

@yihong0618 yihong0618 commented Mar 19, 2025

What's Changed in this PR

Describe the change in this PR

about autocorrect:

https://github.com/huacnlee/autocorrect

This is a big pull request aim to use autocorrect everything to make the doc beauty

steps:

  • install autocorrect
  • autocorrect . --fix
  • some json file can not be change -> revert them
  • some md files the , must use English one like belowe, and the line need to roll back

image

use script to roll back the lines (scripts co-author is claude 3.7)
cc @sunng87 @killme2008

#!/usr/bin/env python3
import subprocess
import re
import os

def get_git_diff():
    """Get the current git diff output."""
    try:
        return subprocess.check_output(['git', 'diff'], text=True)
    except subprocess.CalledProcessError as e:
        print(f"Error getting git diff: {e}")
        return ""

def parse_diff(diff_text):
    """
    Parse git diff output to find files with changes starting with 'keywords:'.
    Returns a dict mapping filenames to lists of line numbers to revert.
    """
    files_to_fix = {}
    current_file = None
    line_number = 0
    
    # Split the diff into lines
    lines = diff_text.split('\n')
    
    # Regular expressions to match diff headers and line changes
    file_pattern = re.compile(r'^(\+\+\+|---) ([ab]/)?(.+)$')
    hunk_pattern = re.compile(r'^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@')
    
    for line in lines:
        # Check for file header
        file_match = file_pattern.match(line)
        if file_match and file_match.group(1) == '+++':
            current_file = file_match.group(3)
            continue
            
        # Check for hunk header to track line numbers
        hunk_match = hunk_pattern.match(line)
        if hunk_match:
            line_number = int(hunk_match.group(1)) - 1  # Start at the beginning of the hunk
            continue
            
        # Check for added lines
        if line.startswith('+'):
            line_number += 1
            # Check if the added line starts with "keywords:"
            if re.match(r'^\+\s*keywords:', line):
                if current_file not in files_to_fix:
                    files_to_fix[current_file] = []
                files_to_fix[current_file].append(line_number)
        elif not line.startswith('-'):  # Not a removed line
            line_number += 1
            
    return files_to_fix

def revert_changes(files_with_lines):
    """
    Revert only the specific lines containing 'keywords:' in the given files.
    """
    for file_path, lines in files_with_lines.items():
        if not os.path.exists(file_path):
            print(f"File {file_path} does not exist, skipping...")
            continue
            
        print(f"Reverting 'keywords:' changes in {file_path} at lines: {lines}")
        
        try:
            # Get the file diff to find the original and modified lines
            file_diff = subprocess.check_output(
                ['git', 'diff', file_path], 
                text=True
            )
            
            # Parse the diff to find original versions of the keywords lines
            original_lines = {}
            current_file_part = False
            hunk_active = False
            original_line_num = 0
            current_line_num = 0
            
            for diff_line in file_diff.splitlines():
                # Check if we're in the right file section
                if diff_line.startswith('+++'):
                    current_file_part = True
                    continue
                    
                if not current_file_part:
                    continue
                    
                # Parse hunk headers to track line numbers
                hunk_match = re.match(r'^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@', diff_line)
                if hunk_match:
                    original_line_num = int(hunk_match.group(1))
                    current_line_num = int(hunk_match.group(2))
                    hunk_active = True
                    continue
                    
                if not hunk_active:
                    continue
                    
                # Track line numbers and find keywords lines
                if diff_line.startswith('-'):
                    # This is an original line (before changes)
                    if re.search(r'^\-\s*keywords:', diff_line):
                        # Record this line as the original version for any modified keywords line
                        for line_num in lines:
                            if abs(line_num - current_line_num) < 3:  # Close proximity check
                                # Remove the '-' prefix but ensure it has a newline at the end
                                original_content = diff_line[1:]
                                if not original_content.endswith('\n'):
                                    original_content += '\n'
                                original_lines[line_num] = original_content
                    original_line_num += 1
                elif diff_line.startswith('+'):
                    # This is a modified line (after changes)
                    current_line_num += 1
                else:
                    # Line exists in both versions (unchanged)
                    original_line_num += 1
                    current_line_num += 1
            
            # Read the current content
            with open(file_path, 'r') as f:
                current_content = f.readlines()
                
            # Apply the fixes
            modified = False
            for line_num in lines:
                if 0 <= line_num - 1 < len(current_content):
                    # Adjust for zero-based indexing
                    idx = line_num - 1
                    
                    # Replace with original version if found
                    if line_num in original_lines:
                        current_content[idx] = original_lines[line_num]
                        modified = True
                    else:
                        # If we couldn't find the original line, try to repair it
                        # by removing the keywords: addition
                        current_line = current_content[idx]
                        if re.search(r'\s*keywords:', current_line):
                            # This is a new keywords line that didn't exist before
                            # Instead of removing it entirely, leave the line but remove keywords tag
                            modified_line = re.sub(r'\s*keywords:.*?($|,)', '', current_line)
                            if modified_line != current_line:
                                # Ensure proper line ending
                                if not modified_line.endswith('\n'):
                                    modified_line += '\n'
                                current_content[idx] = modified_line
                                modified = True
            
            if modified:
                # Write the modified content back to the file
                with open(file_path, 'w') as f:
                    f.writelines(current_content)
                
                print(f"Successfully reverted 'keywords:' changes in {file_path}")
            else:
                print(f"No changes were made to {file_path}")
                
        except subprocess.CalledProcessError as e:
            print(f"Error processing {file_path}: {e}")
        except Exception as e:
            print(f"Unexpected error processing {file_path}: {e}")

def main():
    print("Looking for files with 'keywords:' changes...")
    diff_output = get_git_diff()
    if not diff_output:
        print("No diff found or error occurred.")
        return
        
    files_to_fix = parse_diff(diff_output)
    
    if not files_to_fix:
        print("No files with 'keywords:' changes found.")
        return
        
    print(f"Found {len(files_to_fix)} files with 'keywords:' changes to revert.")
    revert_changes(files_to_fix)
    
if __name__ == "__main__":
    main()

Checklist

  • Please confirm that all corresponding versions of the documents have been revised.
  • Please ensure that the content in sidebars.ts matches the current document structure when you changed the document structure.
  • This change requires follow-up update in localized docs.

Copy link
Contributor

coderabbitai bot commented Mar 19, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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
Collaborator

@nicecui nicecui left a comment

Choose a reason for hiding this comment

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

LGTM, thank you very much!

@killme2008
Copy link
Contributor

Huge thanks!

Copy link
Contributor

@killme2008 killme2008 left a comment

Choose a reason for hiding this comment

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

LGTM

@killme2008 killme2008 merged commit 1f8eff0 into GreptimeTeam:main Mar 20, 2025
7 checks passed
@yihong0618
Copy link
Contributor Author

my pleasure

huacnlee pushed a commit to huacnlee/autocorrect that referenced this pull request Mar 20, 2025
this patch  add greptimedb to the use case.

more can track this pull request:
GreptimeTeam/docs#1586

Signed-off-by: yihong0618 <[email protected]>
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.

3 participants