Apply fixes based on pycodestyle output. Args: issues_by_file: Dictionary mapping file paths to lists of issues. verbose: Whether to print verbose output. Returns: A tuple of (number of files fixed, total number of files with issues).
(
issues_by_file: Dict[str, List[Dict[str, str]]], verbose: bool = False
)
| 183 | |
| 184 | |
| 185 | def fix_from_pycodestyle( |
| 186 | issues_by_file: Dict[str, List[Dict[str, str]]], verbose: bool = False |
| 187 | ) -> Tuple[int, int]: |
| 188 | """Apply fixes based on pycodestyle output. |
| 189 | |
| 190 | Args: |
| 191 | issues_by_file: Dictionary mapping file paths to lists of issues. |
| 192 | verbose: Whether to print verbose output. |
| 193 | |
| 194 | Returns: |
| 195 | A tuple of (number of files fixed, total number of files with issues). |
| 196 | """ |
| 197 | fixed_files = set() |
| 198 | total_files = set(issues_by_file.keys()) |
| 199 | |
| 200 | for file_path, issues in issues_by_file.items(): |
| 201 | if verbose: |
| 202 | print(f"Processing {file_path} with {len(issues)} issues...") |
| 203 | |
| 204 | # Group issues by line number for more efficient processing |
| 205 | issues_by_line = defaultdict(list) |
| 206 | for issue in issues: |
| 207 | issues_by_line[int(issue["line"])].append(issue) |
| 208 | |
| 209 | # Read the file |
| 210 | try: |
| 211 | with open(file_path, "r") as f: |
| 212 | lines = f.readlines() |
| 213 | except Exception as e: |
| 214 | print(f"Error reading {file_path}: {e}", file=sys.stderr) |
| 215 | continue |
| 216 | |
| 217 | # Track if we made any changes to this file |
| 218 | file_modified = False |
| 219 | |
| 220 | # Process issues by line |
| 221 | for line_num, line_issues in sorted(issues_by_line.items()): |
| 222 | if line_num > len(lines): |
| 223 | print( |
| 224 | f"Warning: Line {line_num} is out of range for {file_path}", |
| 225 | file=sys.stderr, |
| 226 | ) |
| 227 | continue |
| 228 | |
| 229 | line_idx = line_num - 1 # Convert to 0-indexed |
| 230 | original_line = lines[line_idx] |
| 231 | modified_line = original_line |
| 232 | |
| 233 | for issue in line_issues: |
| 234 | code = issue["code"] |
| 235 | |
| 236 | # Apply specific fixes based on error code |
| 237 | if code == "E201": # Whitespace after '(' |
| 238 | modified_line = re.sub(r"\(\s+", "(", modified_line) |
| 239 | elif code == "E202": # Whitespace before ')' |
| 240 | modified_line = re.sub(r"\s+\)", ")", modified_line) |
| 241 | elif code == "E203": # Whitespace before ':' |
| 242 | modified_line = re.sub(r"\s+:", ":", modified_line) |