{"repo": "EbodShojaei/bake", "n_pairs": 88, "version": "v2_function_scoped", "contexts": {"tests/test_assignment_alignment.py::241": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_conditional_blocks_break_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_bake.py::142": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py", "mbake/core/rules/final_newline.py"], "used_names": ["FinalNewlineRule"], "enclosing_function": "test_skips_when_disabled", "extracted_code": "# Source: mbake/core/rules/final_newline.py\nclass FinalNewlineRule(FormatterPlugin):\n \"\"\"Ensures files end with a final newline if configured.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\n \"final_newline\", priority=70\n ) # Run late, after content changes\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Ensure final newline if configured.\"\"\"\n ensure_final_newline = config.get(\"ensure_final_newline\", True)\n\n if not ensure_final_newline:\n return FormatResult(\n lines=lines, changed=False, errors=[], warnings=[], check_messages=[]\n )\n\n # Check if file is empty\n if not lines:\n return FormatResult(\n lines=lines, changed=False, errors=[], warnings=[], check_messages=[]\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Check if the last line ends with a newline\n # In check mode, respect the original_content_ends_with_newline parameter\n original_ends_with_newline = context.get(\n \"original_content_ends_with_newline\", False\n )\n\n # If original content already ends with newline, no change needed\n if check_mode and original_ends_with_newline:\n return FormatResult(\n lines=lines, changed=False, errors=[], warnings=[], check_messages=[]\n )\n\n # If the last line is not empty, we need to add a newline\n if formatted_lines and formatted_lines[-1] != \"\":\n if check_mode:\n # Generate check message\n line_count = len(formatted_lines)\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n message = f\"{line_count}: Warning: Missing final newline\"\n else:\n message = f\"Warning: Missing final newline (line {line_count})\"\n\n check_messages.append(message)\n else:\n # Add empty line to ensure final newline\n formatted_lines.append(\"\")\n\n changed = True\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )", "n_imports_parsed": 4, "n_files_resolved": 9, "n_chars_extracted": 2525}, "tests/test_assignment_alignment.py::195": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["MakefileFormatter", "Path"], "enclosing_function": "test_alignment_fixture", "extracted_code": "# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 14932}, "tests/test_assignment_alignment.py::57": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_basic_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_comprehensive.py::745": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/conditionals.py", "mbake/core/rules/continuation.py", "mbake/core/rules/pattern_spacing.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/whitespace.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_temp_file_cleanup", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 8, "n_files_resolved": 9, "n_chars_extracted": 21779}, "tests/test_reversed_assignment_operators.py::131": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_detect_reversed_operators_with_various_spacing", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_completions.py::108": {"resolved_imports": ["mbake/cli.py", "mbake/completions.py"], "used_names": ["Path", "ShellType", "write_completion_script"], "enclosing_function": "test_write_completion_script_file", "extracted_code": "# Source: mbake/completions.py\nclass ShellType(str, Enum):\n \"\"\"Supported shell types for completion generation.\"\"\"\n\n BASH = \"bash\"\n ZSH = \"zsh\"\n FISH = \"fish\"\n\ndef write_completion_script(\n shell: ShellType, output_file: Optional[Path] = None\n) -> None:\n \"\"\"Write completion script to a file or stdout.\"\"\"\n script = get_completion_script(shell)\n if output_file:\n output_file.write_text(script + \"\\n\")\n else:\n sys.stdout.write(script + \"\\n\")", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 481}, "tests/test_reversed_assignment_operators.py::220": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_multiple_reversed_operators_in_same_file", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_validate_command.py::34": {"resolved_imports": ["mbake/cli.py"], "used_names": ["Path", "app", "patch", "tempfile"], "enclosing_function": "test_validate_simple_makefile", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 165}, "tests/test_auto_phony_insertion.py::818": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_unusual_suffix_patterns", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_reversed_assignment_operators.py::38": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_detect_reversed_question_mark_operator", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_validate_command.py::48": {"resolved_imports": ["mbake/cli.py"], "used_names": ["Path", "app", "patch", "tempfile"], "enclosing_function": "test_validate_simple_makefile", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 165}, "tests/test_gnu_error_format.py::160": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_real_world_input_mk_scenario", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_assignment_alignment.py::59": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_basic_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_auto_phony_insertion.py::47": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_auto_insert_common_phony_targets", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_gnu_error_format.py::161": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_real_world_input_mk_scenario", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_reversed_assignment_operators.py::180": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_warning_message_format", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_cli.py::43": {"resolved_imports": ["mbake/cli.py", "mbake/config.py"], "used_names": ["app", "patch"], "enclosing_function": "test_format_stdin_basic", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 165}, "tests/test_completions.py::59": {"resolved_imports": ["mbake/cli.py", "mbake/completions.py"], "used_names": ["CliRunner", "app"], "enclosing_function": "test_completions_invalid_shell", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 165}, "tests/test_cli.py::67": {"resolved_imports": ["mbake/cli.py", "mbake/config.py"], "used_names": ["app", "patch"], "enclosing_function": "test_format_stdin_with_errors", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 165}, "tests/test_auto_phony_insertion.py::582": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_phony_target_detection_with_suffix_rules", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_auto_phony_insertion.py::557": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_phony_target_detection_with_suffix_rules", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_comprehensive.py::700": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/conditionals.py", "mbake/core/rules/continuation.py", "mbake/core/rules/pattern_spacing.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/whitespace.py"], "used_names": ["MakefileFormatter"], "enclosing_function": "test_error_handling", "extracted_code": "# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 8, "n_files_resolved": 9, "n_chars_extracted": 14932}, "tests/test_assignment_alignment.py::177": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_empty_value_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_comprehensive.py::1593": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/conditionals.py", "mbake/core/rules/continuation.py", "mbake/core/rules/pattern_spacing.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/whitespace.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter", "Path"], "enclosing_function": "test_suffix_phony_issue_fixture", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 8, "n_files_resolved": 9, "n_chars_extracted": 21779}, "tests/test_completions.py::76": {"resolved_imports": ["mbake/cli.py", "mbake/completions.py"], "used_names": ["ShellType", "get_completion_script"], "enclosing_function": "test_get_completion_script", "extracted_code": "# Source: mbake/completions.py\nclass ShellType(str, Enum):\n \"\"\"Supported shell types for completion generation.\"\"\"\n\n BASH = \"bash\"\n ZSH = \"zsh\"\n FISH = \"fish\"\n\ndef get_completion_script(shell: ShellType) -> str:\n \"\"\"Get the completion script for the specified shell.\"\"\"\n # Always generate completions for mbake since that's the actual command\n # User aliases will work with mbake completions automatically\n if shell == ShellType.BASH:\n return get_bash_completion(\"mbake\").strip()\n elif shell == ShellType.ZSH:\n return get_zsh_completion(\"mbake\").strip()\n elif shell == ShellType.FISH:\n return get_fish_completion(\"mbake\").strip()\n else:\n raise ValueError(f\"Unsupported shell: {shell}\")", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 746}, "tests/test_comprehensive.py::671": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/conditionals.py", "mbake/core/rules/continuation.py", "mbake/core/rules/pattern_spacing.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/whitespace.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_file_support_detection", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 8, "n_files_resolved": 9, "n_chars_extracted": 21779}, "tests/test_validate_command.py::41": {"resolved_imports": ["mbake/cli.py"], "used_names": ["Path", "app", "patch", "tempfile"], "enclosing_function": "test_validate_simple_makefile", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 165}, "tests/test_bake.py::246": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_applies_all_rules", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 21779}, "tests/test_version_utils.py::116": {"resolved_imports": ["mbake/utils/version_utils.py"], "used_names": ["check_for_updates", "patch"], "enclosing_function": "test_update_available", "extracted_code": "# Source: mbake/utils/version_utils.py\ndef check_for_updates(\n package_name: str = \"mbake\", include_prerelease: bool = False\n) -> tuple[bool, Optional[str], str]:\n \"\"\"Check if there's a newer version available on PyPI.\n\n Args:\n package_name: Name of the package to check\n include_prerelease: Whether to include pre-release versions\n\n Returns:\n tuple of (update_available, latest_version, current_version)\n \"\"\"\n latest_version = get_pypi_version(\n package_name, include_prerelease=include_prerelease\n )\n\n if latest_version is None:\n return False, None, current_version\n\n try:\n current_parsed = parse_version(current_version)\n latest_parsed = parse_version(latest_version)\n\n update_available = latest_parsed > current_parsed\n return update_available, latest_version, current_version\n except VersionError:\n return False, latest_version, current_version", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 949}, "tests/test_gnu_error_format.py::107": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_combined_errors_line_numbers", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_gnu_error_format.py::28": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_duplicate_target_error_format", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_bake.py::172": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["ContinuationRule"], "enclosing_function": "test_formats_simple_continuation", "extracted_code": "# Source: mbake/core/rules/continuation.py\nclass ContinuationRule(FormatterPlugin):\n \"\"\"Handles proper formatting of line continuations with backslashes.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"continuation\", priority=9) # Run before tabs rule\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Normalize line continuation formatting.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n normalize_continuations = config.get(\"normalize_line_continuations\", True)\n\n if not normalize_continuations:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n i = 0\n while i < len(lines):\n line = lines[i]\n\n # Check if line ends with backslash (continuation)\n if line.rstrip().endswith(\"\\\\\"):\n # Collect all continuation lines\n continuation_lines = [line]\n j = i + 1\n\n while j < len(lines):\n current_line = lines[j]\n continuation_lines.append(current_line)\n\n # If this line doesn't end with backslash, it's the last line\n if not current_line.rstrip().endswith(\"\\\\\"):\n j += 1\n break\n\n j += 1\n\n # Format the continuation block\n formatted_block = self._format_continuation_block(continuation_lines)\n\n if formatted_block != continuation_lines:\n changed = True\n\n formatted_lines.extend(formatted_block)\n i = j\n else:\n formatted_lines.append(line)\n i += 1\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n def _format_continuation_block(self, lines: list[str]) -> list[str]:\n \"\"\"Format a block of continuation lines.\"\"\"\n if not lines:\n return lines\n\n # First line is the assignment/recipe line - keep it as is\n first_line = lines[0]\n formatted_lines = [first_line]\n\n # If there's only one line, return early\n if len(lines) == 1:\n return formatted_lines\n\n # Check if this is a recipe continuation (starts with tab)\n is_recipe = first_line.startswith(\"\\t\")\n\n # Check if this continuation block contains shell control structures\n # If so, preserve original indentation for recipes (ShellFormattingRule will handle it)\n if is_recipe and self._contains_shell_control_structures(lines):\n # For recipe continuations with shell control structures, preserve indentation\n # Only normalize spacing around backslashes\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n content = line.rstrip()[:-1].rstrip()\n formatted_lines.append(content + \" \\\\\")\n else:\n # Last line of continuation - preserve original indentation\n formatted_lines.append(line)\n return formatted_lines\n\n # Normalize indentation for variable assignments and simple recipe continuations\n # Find the indentation of the first continuation line (second line)\n first_continuation_line = lines[1]\n # Get leading whitespace (spaces/tabs) from the first continuation line\n leading_whitespace = \"\"\n for char in first_continuation_line:\n if char in (\" \", \"\\t\"):\n leading_whitespace += char\n else:\n break\n\n # Format all continuation lines (from second line onwards)\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n # Also remove leading whitespace to normalize indentation\n content = line.rstrip()[:-1].rstrip().lstrip()\n # Apply consistent indentation from first continuation line\n formatted_lines.append(leading_whitespace + content + \" \\\\\")\n else:\n # Last line of continuation - apply consistent indentation\n stripped_content = line.lstrip()\n formatted_lines.append(leading_whitespace + stripped_content)\n\n return formatted_lines\n\n def _contains_shell_control_structures(self, lines: list[str]) -> bool:\n \"\"\"Check if continuation block contains shell control structure keywords.\"\"\"\n # Shell control structure keywords that have semantic indentation meaning\n # These keywords should preserve their indentation relative to each other\n shell_keywords = (\n \"if\",\n \"then\",\n \"else\",\n \"elif\",\n \"fi\",\n \"for\",\n \"do\",\n \"done\",\n \"while\",\n \"until\",\n \"case\",\n \"esac\",\n )\n\n for line in lines:\n # Strip leading whitespace and make command prefixes for checking\n stripped = line.lstrip(\"\\t \").lstrip(\"@-+ \")\n # Remove trailing backslash and whitespace for cleaner matching\n content = stripped.rstrip(\" \\\\\")\n\n # Check if line starts with a shell keyword (most common case)\n for keyword in shell_keywords:\n # Match keyword at start of line, followed by space, semicolon, or end of line\n if (\n content.startswith(keyword + \" \")\n or content.startswith(keyword + \";\")\n or content == keyword\n # Also check for keywords after shell operators (; || &&)\n or f\"; {keyword}\" in content\n or f\"|| {keyword}\" in content\n or f\"&& {keyword}\" in content\n ):\n return True\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 6400}, "tests/test_comprehensive.py::749": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/conditionals.py", "mbake/core/rules/continuation.py", "mbake/core/rules/pattern_spacing.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/whitespace.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_temp_file_cleanup", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 8, "n_files_resolved": 9, "n_chars_extracted": 21779}, "tests/test_assignment_alignment.py::160": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_recipe_lines_not_aligned", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_auto_phony_insertion.py::56": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_auto_insert_common_phony_targets", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_version_utils.py::81": {"resolved_imports": ["mbake/utils/version_utils.py"], "used_names": ["MagicMock", "get_pypi_version", "patch"], "enclosing_function": "test_successful_fetch", "extracted_code": "# Source: mbake/utils/version_utils.py\ndef get_pypi_version(\n package_name: str = \"mbake\", timeout: int = 5, include_prerelease: bool = False\n) -> Optional[str]:\n \"\"\"Get the latest version of a package from PyPI.\n\n Args:\n package_name: Name of the package to check\n timeout: Request timeout in seconds\n include_prerelease: Whether to include pre-release versions\n\n Returns:\n Latest version string, or None if unable to fetch\n \"\"\"\n try:\n url = f\"https://pypi.org/pypi/{package_name}/json\"\n with urllib.request.urlopen(url, timeout=timeout) as response:\n data = json.loads(response.read().decode())\n\n if include_prerelease:\n # Get all available versions from releases\n releases = data.get(\"releases\", {})\n if not releases:\n return None\n\n # Parse all versions and find the latest\n versions = []\n for version_str in releases:\n try:\n parsed = parse_version(version_str)\n versions.append((parsed, version_str))\n except VersionError:\n # Skip invalid versions\n continue\n\n if not versions:\n return None\n\n # Sort by parsed version and return the latest\n versions.sort(key=lambda x: x[0])\n latest_version: str = versions[-1][1]\n return latest_version\n else:\n # Return only the latest stable version\n version = data[\"info\"][\"version\"]\n if isinstance(version, str):\n return version\n return None\n except (urllib.error.URLError, json.JSONDecodeError, KeyError, OSError):\n return None", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1883}, "tests/test_bake.py::220": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["PhonyRule"], "enclosing_function": "test_groups_phony_declarations", "extracted_code": "# Source: mbake/core/rules/phony.py\nclass PhonyRule(FormatterPlugin):\n \"\"\"Unified rule for detecting, inserting, and organizing .PHONY declarations.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"phony\", priority=40)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"\n Unified phony rule that:\n 1. Always detects phony targets (for check mode)\n 2. Inserts missing .PHONY declarations (if enabled)\n 3. Adds missing targets to existing .PHONY (if enabled)\n 4. Groups/ungroups based on group_phony_declarations\n \"\"\"\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Get format-disabled line information from context\n disabled_line_indices = context.get(\"disabled_line_indices\", set())\n block_start_index = context.get(\"block_start_index\", 0)\n\n # Always detect phony targets (for check mode)\n detected_targets = PhonyAnalyzer.detect_phony_targets_excluding_conditionals(\n lines, disabled_line_indices, block_start_index\n )\n\n # Check if .PHONY declarations exist\n has_phony = MakefileParser.has_phony_declarations(lines)\n auto_insert_enabled = config.get(\"auto_insert_phony_declarations\", False)\n group_phony = config.get(\"group_phony_declarations\", True)\n\n if not has_phony:\n # No .PHONY exists - insert if enabled\n if not detected_targets:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # In check mode, always report missing declarations\n if check_mode:\n phony_at_top = config.get(\"phony_at_top\", True)\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n ordered_targets = list(detected_targets)\n\n if phony_at_top:\n insert_index = MakefileParser.find_phony_insertion_point(lines)\n line_num = insert_index + 1\n else:\n line_num = 1\n\n if auto_insert_enabled:\n if gnu_format:\n message = f\"{line_num}: Warning: Missing .PHONY declaration for targets: {', '.join(ordered_targets)}\"\n else:\n message = f\"Warning: Missing .PHONY declaration for targets: {', '.join(ordered_targets)} (line {line_num})\"\n else:\n if gnu_format:\n message = f\"{line_num}: Warning: Consider adding .PHONY declaration for targets: {', '.join(ordered_targets)}\"\n else:\n message = f\"Warning: Consider adding .PHONY declaration for targets: {', '.join(ordered_targets)} (line {line_num})\"\n\n check_messages.append(message)\n return FormatResult(\n lines=lines,\n changed=auto_insert_enabled,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Actually insert if enabled\n if not auto_insert_enabled:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Insert declarations\n return self._insert_phony_declarations(\n lines,\n list(detected_targets),\n config,\n errors,\n warnings,\n check_messages,\n )\n\n # .PHONY exists - enhance and organize\n existing_phony_targets = self._extract_phony_targets(lines)\n existing_phony_set = set(existing_phony_targets)\n\n # Find missing targets\n missing_targets = [t for t in detected_targets if t not in existing_phony_set]\n\n # In check mode, report missing targets\n if check_mode and missing_targets:\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n phony_line_num = self._find_first_phony_line(lines)\n\n if auto_insert_enabled:\n if gnu_format:\n message = f\"{phony_line_num}: Warning: Missing targets in .PHONY declaration: {', '.join(missing_targets)}\"\n else:\n message = f\"Warning: Missing targets in .PHONY declaration: {', '.join(missing_targets)} (line {phony_line_num})\"\n else:\n if gnu_format:\n message = f\"{phony_line_num}: Warning: Consider adding targets to .PHONY declaration: {', '.join(missing_targets)}\"\n else:\n message = f\"Warning: Consider adding targets to .PHONY declaration: {', '.join(missing_targets)} (line {phony_line_num})\"\n\n check_messages.append(message)\n\n # Only organize .PHONY declarations (group/ungroup) if auto_insert_phony_declarations is enabled\n if not auto_insert_enabled:\n # If auto-insertion is disabled, don't modify existing .PHONY declarations\n # (but still report missing targets in check mode)\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Organize .PHONY declarations (group/ungroup)\n if group_phony:\n # Group mode: ensure all .PHONY declarations are grouped\n return self._group_phony_declarations(\n lines,\n existing_phony_set | detected_targets,\n missing_targets if auto_insert_enabled else [],\n config,\n check_mode,\n errors,\n warnings,\n check_messages,\n )\n else:\n # Ungroup mode: ensure all .PHONY declarations are individual\n return self._ungroup_phony_declarations(\n lines,\n existing_phony_set | detected_targets,\n missing_targets if auto_insert_enabled else [],\n config,\n check_mode,\n errors,\n warnings,\n check_messages,\n )\n\n def _insert_phony_declarations(\n self,\n lines: list[str],\n target_names: list[str],\n config: dict,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Insert .PHONY declarations for detected targets.\"\"\"\n group_phony = config.get(\"group_phony_declarations\", True)\n phony_at_top = config.get(\"phony_at_top\", True)\n\n if not group_phony:\n # Insert individual declarations before each target\n return self._insert_individual_phony_declarations(\n lines, target_names, config, errors, warnings, check_messages\n )\n\n # Insert grouped declaration\n new_phony_line = f\".PHONY: {' '.join(target_names)}\"\n\n if phony_at_top:\n insert_index = MakefileParser.find_phony_insertion_point(lines)\n formatted_lines = []\n for i, line in enumerate(lines):\n if i == insert_index:\n formatted_lines.append(new_phony_line)\n formatted_lines.append(\"\") # Add blank line after\n formatted_lines.append(line)\n else:\n formatted_lines = [new_phony_line, \"\"] + lines\n\n warnings.append(\n f\"Auto-inserted .PHONY declaration for {len(target_names)} targets: {', '.join(target_names)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=True,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _insert_individual_phony_declarations(\n self,\n lines: list[str],\n target_names: list[str],\n config: dict,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Insert individual .PHONY declarations before each target.\"\"\"\n target_positions = self._find_target_line_positions(lines, target_names)\n\n if not target_positions:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Sort targets by position in reverse order for insertion\n sorted_targets = sorted(\n target_positions.items(), key=lambda x: x[1], reverse=True\n )\n\n formatted_lines = lines[:]\n inserted_targets = []\n\n for target_name, line_index in sorted_targets:\n if not self._has_phony_declaration_nearby(\n formatted_lines, line_index, target_name\n ):\n formatted_lines.insert(line_index, f\".PHONY: {target_name}\")\n inserted_targets.append(target_name)\n\n if inserted_targets:\n warnings.append(\n f\"Auto-inserted individual .PHONY declarations for {len(inserted_targets)} targets: {', '.join(inserted_targets)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=len(inserted_targets) > 0,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _group_phony_declarations(\n self,\n lines: list[str],\n all_phony_targets: set[str],\n new_targets: list[str],\n config: dict,\n check_mode: bool,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Group all .PHONY declarations into a single declaration.\"\"\"\n # Order targets by declaration order\n ordered_targets = self._order_targets_by_declaration(all_phony_targets, lines)\n\n if check_mode:\n # In check mode, only report if there are new targets or if declarations need grouping\n has_multiple_phony = (\n sum(1 for line in lines if line.strip().startswith(\".PHONY:\")) > 1\n )\n changed = len(new_targets) > 0 or has_multiple_phony\n return FormatResult(\n lines=lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Build grouped declaration\n phony_line = f\".PHONY: {' '.join(ordered_targets)}\"\n phony_at_top = config.get(\"phony_at_top\", True)\n\n # Remove all existing .PHONY declarations first\n lines_without_phony = []\n for line in lines:\n if not line.strip().startswith(\".PHONY:\"):\n lines_without_phony.append(line)\n\n # Insert grouped declaration at the appropriate location\n if phony_at_top:\n # Use smart placement (same logic as when inserting new .PHONY)\n insert_index = MakefileParser.find_phony_insertion_point(\n lines_without_phony\n )\n formatted_lines = []\n for i, line in enumerate(lines_without_phony):\n if i == insert_index:\n formatted_lines.append(phony_line)\n formatted_lines.append(\"\") # Add blank line after\n formatted_lines.append(line)\n else:\n # Place at absolute top\n formatted_lines = [phony_line, \"\"] + lines_without_phony\n\n if new_targets:\n warnings.append(\n f\"Added {len(new_targets)} missing targets to .PHONY declaration: {', '.join(new_targets)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=True,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _ungroup_phony_declarations(\n self,\n lines: list[str],\n all_phony_targets: set[str],\n new_targets: list[str],\n config: dict,\n check_mode: bool,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Split grouped .PHONY declarations into individual declarations.\"\"\"\n # Find all .PHONY line indices\n phony_line_indices = []\n for i, line in enumerate(lines):\n if line.strip().startswith(\".PHONY:\"):\n phony_line_indices.append(i)\n\n if not phony_line_indices:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Find target positions\n target_positions: dict[str, int] = {}\n target_pattern = re.compile(r\"^([^:=]+):\")\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n if not stripped or stripped.startswith(\"#\") or line.startswith(\"\\t\"):\n continue\n match = target_pattern.match(stripped)\n if match:\n target_name = match.group(1).strip().split()[0]\n if (\n target_name in all_phony_targets\n and target_name not in target_positions\n ):\n target_positions[target_name] = i\n\n if check_mode:\n # In check mode, report if declarations need splitting\n has_grouped = any(\n len(line.strip()[7:].strip().split()) > 1\n for line in lines\n if line.strip().startswith(\".PHONY:\")\n )\n return FormatResult(\n lines=lines,\n changed=has_grouped or len(new_targets) > 0,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Check if declarations are already individual (not grouped)\n has_grouped_declarations = any(\n len(line.strip()[7:].strip().split()) > 1\n for line in lines\n if line.strip().startswith(\".PHONY:\")\n )\n\n # If already individual and no new targets, no change needed\n if not has_grouped_declarations and not new_targets:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Build new lines with individual declarations\n formatted_lines = []\n skip_indices = set(phony_line_indices)\n insertions: dict[int, str] = {}\n\n for target_name, target_line_index in target_positions.items():\n insertions[target_line_index] = f\".PHONY: {target_name}\"\n\n for i, line in enumerate(lines):\n if i in skip_indices:\n continue\n if i in insertions:\n formatted_lines.append(insertions[i])\n formatted_lines.append(line)\n\n # Only warn if we actually split grouped declarations (not if already individual)\n if has_grouped_declarations:\n warnings.append(\n f\"Split grouped .PHONY declarations into {len(target_positions)} individual declarations\"\n )\n elif new_targets:\n warnings.append(\n f\"Added {len(new_targets)} missing targets to .PHONY declarations: {', '.join(new_targets)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=True,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _extract_phony_targets(self, lines: list[str]) -> list[str]:\n \"\"\"Extract targets from existing .PHONY declarations.\"\"\"\n phony_targets = []\n seen_targets = set()\n\n for line in lines:\n stripped = line.strip()\n if stripped.startswith(\".PHONY:\"):\n content = stripped[7:].strip()\n if content.endswith(\"\\\\\"):\n content = content[:-1].strip()\n targets = [t.strip() for t in content.split() if t.strip()]\n for target in targets:\n if target not in seen_targets:\n phony_targets.append(target)\n seen_targets.add(target)\n\n return phony_targets\n\n def _order_targets_by_declaration(\n self, phony_targets: set[str], lines: list[str]\n ) -> list[str]:\n \"\"\"Order phony targets by their declaration order in the file.\"\"\"\n target_pattern = re.compile(r\"^([^:=]+):\")\n ordered_targets = []\n seen_targets = set()\n\n for line in lines:\n stripped = line.strip()\n if (\n not stripped\n or stripped.startswith(\"#\")\n or line.startswith(\"\\t\")\n or stripped.startswith(\".PHONY:\")\n ):\n continue\n match = target_pattern.match(stripped)\n if match:\n target_name = match.group(1).strip().split()[0]\n if target_name in phony_targets and target_name not in seen_targets:\n ordered_targets.append(target_name)\n seen_targets.add(target_name)\n\n # Add any remaining targets\n for target in phony_targets:\n if target not in seen_targets:\n ordered_targets.append(target)\n\n return ordered_targets\n\n def _find_target_line_positions(\n self, lines: list[str], target_names: list[str]\n ) -> dict[str, int]:\n \"\"\"Find the line index where each target appears.\"\"\"\n target_positions: dict[str, int] = {}\n target_pattern = re.compile(r\"^([^:=]+):(:?)\\s*(.*)$\")\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n if not stripped or stripped.startswith(\"#\") or line.startswith(\"\\t\"):\n continue\n match = target_pattern.match(stripped)\n if match:\n target_list = match.group(1).strip()\n is_double_colon = match.group(2) == \":\"\n target_body = match.group(3).strip()\n\n if is_double_colon or \"%\" in target_list:\n continue\n\n if re.match(r\"^\\s*[A-Z_][A-Z0-9_]*\\s*[+:?]?=\", target_body):\n continue\n\n target_names_on_line = [\n t.strip() for t in target_list.split() if t.strip()\n ]\n for target_name in target_names_on_line:\n if (\n target_name in target_names\n and target_name not in target_positions\n ):\n target_positions[target_name] = i\n\n return target_positions\n\n def _has_phony_declaration_nearby(\n self, lines: list[str], target_line_index: int, target_name: str\n ) -> bool:\n \"\"\"Check if there's already a .PHONY declaration for this target nearby.\"\"\"\n start_check = max(0, target_line_index - 5)\n for i in range(start_check, target_line_index):\n line = lines[i].strip()\n if line.startswith(\".PHONY:\"):\n content = line[7:].strip()\n if content.endswith(\"\\\\\"):\n content = content[:-1].strip()\n targets = [t.strip() for t in content.split() if t.strip()]\n if target_name in targets:\n return True\n return False\n\n def _find_first_phony_line(self, lines: list[str]) -> int:\n \"\"\"Find the line number of the first .PHONY declaration.\"\"\"\n for i, line in enumerate(lines):\n if line.strip().startswith(\".PHONY:\"):\n return i + 1 # 1-indexed\n return 1", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 20442}, "tests/test_reversed_assignment_operators.py::211": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_multiple_reversed_operators_in_same_file", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_assignment_alignment.py::239": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_conditional_blocks_break_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_bake.py::265": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_handles_file_formatting", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 21779}, "tests/test_validate_command.py::87": {"resolved_imports": ["mbake/cli.py"], "used_names": ["Path", "app", "patch", "tempfile"], "enclosing_function": "test_validate_makefile_with_relative_include", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 165}, "tests/test_cli.py::121": {"resolved_imports": ["mbake/cli.py", "mbake/config.py"], "used_names": ["app", "patch"], "enclosing_function": "test_format_stdin_preserves_empty_input", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 165}, "tests/test_bake.py::130": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py", "mbake/core/rules/final_newline.py"], "used_names": ["FinalNewlineRule"], "enclosing_function": "test_detects_missing_final_newline", "extracted_code": "# Source: mbake/core/rules/final_newline.py\nclass FinalNewlineRule(FormatterPlugin):\n \"\"\"Ensures files end with a final newline if configured.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\n \"final_newline\", priority=70\n ) # Run late, after content changes\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Ensure final newline if configured.\"\"\"\n ensure_final_newline = config.get(\"ensure_final_newline\", True)\n\n if not ensure_final_newline:\n return FormatResult(\n lines=lines, changed=False, errors=[], warnings=[], check_messages=[]\n )\n\n # Check if file is empty\n if not lines:\n return FormatResult(\n lines=lines, changed=False, errors=[], warnings=[], check_messages=[]\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Check if the last line ends with a newline\n # In check mode, respect the original_content_ends_with_newline parameter\n original_ends_with_newline = context.get(\n \"original_content_ends_with_newline\", False\n )\n\n # If original content already ends with newline, no change needed\n if check_mode and original_ends_with_newline:\n return FormatResult(\n lines=lines, changed=False, errors=[], warnings=[], check_messages=[]\n )\n\n # If the last line is not empty, we need to add a newline\n if formatted_lines and formatted_lines[-1] != \"\":\n if check_mode:\n # Generate check message\n line_count = len(formatted_lines)\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n message = f\"{line_count}: Warning: Missing final newline\"\n else:\n message = f\"Warning: Missing final newline (line {line_count})\"\n\n check_messages.append(message)\n else:\n # Add empty line to ensure final newline\n formatted_lines.append(\"\")\n\n changed = True\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )", "n_imports_parsed": 4, "n_files_resolved": 9, "n_chars_extracted": 2525}, "tests/test_completions.py::67": {"resolved_imports": ["mbake/cli.py", "mbake/completions.py"], "used_names": ["ShellType", "get_completion_script"], "enclosing_function": "test_get_completion_script", "extracted_code": "# Source: mbake/completions.py\nclass ShellType(str, Enum):\n \"\"\"Supported shell types for completion generation.\"\"\"\n\n BASH = \"bash\"\n ZSH = \"zsh\"\n FISH = \"fish\"\n\ndef get_completion_script(shell: ShellType) -> str:\n \"\"\"Get the completion script for the specified shell.\"\"\"\n # Always generate completions for mbake since that's the actual command\n # User aliases will work with mbake completions automatically\n if shell == ShellType.BASH:\n return get_bash_completion(\"mbake\").strip()\n elif shell == ShellType.ZSH:\n return get_zsh_completion(\"mbake\").strip()\n elif shell == ShellType.FISH:\n return get_fish_completion(\"mbake\").strip()\n else:\n raise ValueError(f\"Unsupported shell: {shell}\")", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 746}, "tests/test_reversed_assignment_operators.py::185": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_warning_message_format", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_assignment_alignment.py::58": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_basic_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_reversed_assignment_operators.py::59": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_detect_reversed_question_mark_operator", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_auto_phony_insertion.py::297": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_consolidate_multiple_phony_declarations", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_comprehensive.py::115": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/conditionals.py", "mbake/core/rules/continuation.py", "mbake/core/rules/pattern_spacing.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/whitespace.py"], "used_names": ["AssignmentSpacingRule"], "enclosing_function": "test_assignment_operator_spacing", "extracted_code": "# Source: mbake/core/rules/assignment_spacing.py\nclass AssignmentSpacingRule(FormatterPlugin):\n \"\"\"Handles spacing around assignment operators (=, :=, +=, ?=).\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"assignment_spacing\", priority=15)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Normalize spacing around assignment operators.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n space_around_assignment = config.get(\"space_around_assignment\", True)\n\n for i, line in enumerate(lines, 1):\n new_line = line # Default to original line\n\n # Skip recipe lines (lines starting with tab) or comments or empty lines\n if (\n line.startswith(\"\\t\")\n or line.strip().startswith(\"#\")\n or not line.strip()\n ):\n pass # Keep original line\n # Check if line contains assignment operator\n elif re.match(r\"^[A-Za-z_][A-Za-z0-9_]*\\s*(:=|\\+=|\\?=|=|!=)\\s*\", line):\n # Check for reversed assignment operators first\n reversed_warning = self._check_reversed_operators(line, i)\n if reversed_warning:\n warnings.append(reversed_warning)\n\n # Skip substitution references like $(VAR:pattern=replacement) which are not assignments\n # or skip invalid target-like lines of the form VAR=token:... (no space after '=')\n if re.search(\n r\"\\$\\([^)]*:[^)]*=[^)]*\\)\", line\n ) or self._is_invalid_target_syntax(line):\n pass # Keep original line\n else:\n # Extract the parts - be more careful about the operator\n match = re.match(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|=|!=)\\s*(.*)\", line\n )\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n # Only format if this is actually an assignment (not a target)\n if operator in [\"=\", \":=\", \"?=\", \"+=\", \"!=\"]:\n if space_around_assignment:\n # Only add trailing space if there's actually a value\n if value.strip():\n new_line = f\"{var_name} {operator} {value}\"\n else:\n new_line = f\"{var_name} {operator}\"\n else:\n new_line = f\"{var_name}{operator}{value}\"\n\n # Single append at the end\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n def _is_invalid_target_syntax(self, line: str) -> bool:\n \"\"\"Check if line contains invalid target syntax that should be preserved.\"\"\"\n stripped = line.strip()\n # Only flag when there is NO whitespace after '=' before the first ':'\n # This avoids flagging typical assignments whose values contain ':' (URLs, times, paths).\n if not re.match(r\"^[A-Za-z_][A-Za-z0-9_]*=\\S*:\\S*\", stripped):\n return False\n # Allow colon-safe values to pass (URLs, datetimes, drive/path patterns)\n after_eq = stripped.split(\"=\", 1)[1]\n return not PatternUtils.value_is_colon_safe(after_eq)\n\n def _check_reversed_operators(self, line: str, line_number: int) -> str:\n \"\"\"Check for reversed assignment operators and return warning message if found.\"\"\"\n stripped = line.strip()\n\n # Skip if this is not a variable assignment line\n if not re.match(r\"^[A-Za-z_][A-Za-z0-9_]*\\s*=\", stripped):\n return \"\"\n\n # Check for reversed operators: =?, =:, =+\n # Pattern: variable = [space] [?:+] [space or end or value]\n # This handles both \"FOO = ? bar\" and \"FOO =?bar\" cases\n reversed_match = re.search(r\"=\\s*([?:+])(?:\\s|$|[a-zA-Z0-9_])\", stripped)\n if reversed_match:\n reversed_char = reversed_match.group(1)\n correct_operator = f\"{reversed_char}=\"\n reversed_operator = f\"={reversed_char}\"\n\n # Get the variable name for context\n var_match = re.match(r\"^([A-Za-z_][A-Za-z0-9_]*)\", stripped)\n var_name = var_match.group(1) if var_match else \"variable\"\n\n return (\n f\"Line {line_number}: Possible typo in assignment operator '{reversed_operator}' \"\n f\"for variable '{var_name}', did you mean '{correct_operator}'? \"\n f\"Make will treat this as a regular assignment with '{reversed_char}' as part of the value.\"\n )\n\n return \"\"", "n_imports_parsed": 8, "n_files_resolved": 9, "n_chars_extracted": 5176}, "tests/test_validate_command.py::116": {"resolved_imports": ["mbake/cli.py"], "used_names": ["app"], "enclosing_function": "test_validate_nonexistent_file", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 165}, "tests/test_reversed_assignment_operators.py::86": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_no_warnings_for_correct_operators", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_bake.py::174": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["ContinuationRule"], "enclosing_function": "test_formats_simple_continuation", "extracted_code": "# Source: mbake/core/rules/continuation.py\nclass ContinuationRule(FormatterPlugin):\n \"\"\"Handles proper formatting of line continuations with backslashes.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"continuation\", priority=9) # Run before tabs rule\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Normalize line continuation formatting.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n normalize_continuations = config.get(\"normalize_line_continuations\", True)\n\n if not normalize_continuations:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n i = 0\n while i < len(lines):\n line = lines[i]\n\n # Check if line ends with backslash (continuation)\n if line.rstrip().endswith(\"\\\\\"):\n # Collect all continuation lines\n continuation_lines = [line]\n j = i + 1\n\n while j < len(lines):\n current_line = lines[j]\n continuation_lines.append(current_line)\n\n # If this line doesn't end with backslash, it's the last line\n if not current_line.rstrip().endswith(\"\\\\\"):\n j += 1\n break\n\n j += 1\n\n # Format the continuation block\n formatted_block = self._format_continuation_block(continuation_lines)\n\n if formatted_block != continuation_lines:\n changed = True\n\n formatted_lines.extend(formatted_block)\n i = j\n else:\n formatted_lines.append(line)\n i += 1\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n def _format_continuation_block(self, lines: list[str]) -> list[str]:\n \"\"\"Format a block of continuation lines.\"\"\"\n if not lines:\n return lines\n\n # First line is the assignment/recipe line - keep it as is\n first_line = lines[0]\n formatted_lines = [first_line]\n\n # If there's only one line, return early\n if len(lines) == 1:\n return formatted_lines\n\n # Check if this is a recipe continuation (starts with tab)\n is_recipe = first_line.startswith(\"\\t\")\n\n # Check if this continuation block contains shell control structures\n # If so, preserve original indentation for recipes (ShellFormattingRule will handle it)\n if is_recipe and self._contains_shell_control_structures(lines):\n # For recipe continuations with shell control structures, preserve indentation\n # Only normalize spacing around backslashes\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n content = line.rstrip()[:-1].rstrip()\n formatted_lines.append(content + \" \\\\\")\n else:\n # Last line of continuation - preserve original indentation\n formatted_lines.append(line)\n return formatted_lines\n\n # Normalize indentation for variable assignments and simple recipe continuations\n # Find the indentation of the first continuation line (second line)\n first_continuation_line = lines[1]\n # Get leading whitespace (spaces/tabs) from the first continuation line\n leading_whitespace = \"\"\n for char in first_continuation_line:\n if char in (\" \", \"\\t\"):\n leading_whitespace += char\n else:\n break\n\n # Format all continuation lines (from second line onwards)\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n # Also remove leading whitespace to normalize indentation\n content = line.rstrip()[:-1].rstrip().lstrip()\n # Apply consistent indentation from first continuation line\n formatted_lines.append(leading_whitespace + content + \" \\\\\")\n else:\n # Last line of continuation - apply consistent indentation\n stripped_content = line.lstrip()\n formatted_lines.append(leading_whitespace + stripped_content)\n\n return formatted_lines\n\n def _contains_shell_control_structures(self, lines: list[str]) -> bool:\n \"\"\"Check if continuation block contains shell control structure keywords.\"\"\"\n # Shell control structure keywords that have semantic indentation meaning\n # These keywords should preserve their indentation relative to each other\n shell_keywords = (\n \"if\",\n \"then\",\n \"else\",\n \"elif\",\n \"fi\",\n \"for\",\n \"do\",\n \"done\",\n \"while\",\n \"until\",\n \"case\",\n \"esac\",\n )\n\n for line in lines:\n # Strip leading whitespace and make command prefixes for checking\n stripped = line.lstrip(\"\\t \").lstrip(\"@-+ \")\n # Remove trailing backslash and whitespace for cleaner matching\n content = stripped.rstrip(\" \\\\\")\n\n # Check if line starts with a shell keyword (most common case)\n for keyword in shell_keywords:\n # Match keyword at start of line, followed by space, semicolon, or end of line\n if (\n content.startswith(keyword + \" \")\n or content.startswith(keyword + \";\")\n or content == keyword\n # Also check for keywords after shell operators (; || &&)\n or f\"; {keyword}\" in content\n or f\"|| {keyword}\" in content\n or f\"&& {keyword}\" in content\n ):\n return True\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 6400}, "tests/test_version_utils.py::91": {"resolved_imports": ["mbake/utils/version_utils.py"], "used_names": ["error", "get_pypi_version", "patch"], "enclosing_function": "test_network_error", "extracted_code": "# Source: mbake/utils/version_utils.py\ndef get_pypi_version(\n package_name: str = \"mbake\", timeout: int = 5, include_prerelease: bool = False\n) -> Optional[str]:\n \"\"\"Get the latest version of a package from PyPI.\n\n Args:\n package_name: Name of the package to check\n timeout: Request timeout in seconds\n include_prerelease: Whether to include pre-release versions\n\n Returns:\n Latest version string, or None if unable to fetch\n \"\"\"\n try:\n url = f\"https://pypi.org/pypi/{package_name}/json\"\n with urllib.request.urlopen(url, timeout=timeout) as response:\n data = json.loads(response.read().decode())\n\n if include_prerelease:\n # Get all available versions from releases\n releases = data.get(\"releases\", {})\n if not releases:\n return None\n\n # Parse all versions and find the latest\n versions = []\n for version_str in releases:\n try:\n parsed = parse_version(version_str)\n versions.append((parsed, version_str))\n except VersionError:\n # Skip invalid versions\n continue\n\n if not versions:\n return None\n\n # Sort by parsed version and return the latest\n versions.sort(key=lambda x: x[0])\n latest_version: str = versions[-1][1]\n return latest_version\n else:\n # Return only the latest stable version\n version = data[\"info\"][\"version\"]\n if isinstance(version, str):\n return version\n return None\n except (urllib.error.URLError, json.JSONDecodeError, KeyError, OSError):\n return None", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1883}, "tests/test_assignment_alignment.py::238": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_conditional_blocks_break_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_completions.py::97": {"resolved_imports": ["mbake/cli.py", "mbake/completions.py"], "used_names": ["ShellType", "io", "sys", "write_completion_script"], "enclosing_function": "test_write_completion_script_stdout", "extracted_code": "# Source: mbake/completions.py\nclass ShellType(str, Enum):\n \"\"\"Supported shell types for completion generation.\"\"\"\n\n BASH = \"bash\"\n ZSH = \"zsh\"\n FISH = \"fish\"\n\ndef write_completion_script(\n shell: ShellType, output_file: Optional[Path] = None\n) -> None:\n \"\"\"Write completion script to a file or stdout.\"\"\"\n script = get_completion_script(shell)\n if output_file:\n output_file.write_text(script + \"\\n\")\n else:\n sys.stdout.write(script + \"\\n\")", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 481}, "tests/test_assignment_alignment.py::104": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_comments_break_blocks", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_assignment_alignment.py::143": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_single_assignment_not_aligned", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_bake.py::173": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["ContinuationRule"], "enclosing_function": "test_formats_simple_continuation", "extracted_code": "# Source: mbake/core/rules/continuation.py\nclass ContinuationRule(FormatterPlugin):\n \"\"\"Handles proper formatting of line continuations with backslashes.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"continuation\", priority=9) # Run before tabs rule\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Normalize line continuation formatting.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n normalize_continuations = config.get(\"normalize_line_continuations\", True)\n\n if not normalize_continuations:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n i = 0\n while i < len(lines):\n line = lines[i]\n\n # Check if line ends with backslash (continuation)\n if line.rstrip().endswith(\"\\\\\"):\n # Collect all continuation lines\n continuation_lines = [line]\n j = i + 1\n\n while j < len(lines):\n current_line = lines[j]\n continuation_lines.append(current_line)\n\n # If this line doesn't end with backslash, it's the last line\n if not current_line.rstrip().endswith(\"\\\\\"):\n j += 1\n break\n\n j += 1\n\n # Format the continuation block\n formatted_block = self._format_continuation_block(continuation_lines)\n\n if formatted_block != continuation_lines:\n changed = True\n\n formatted_lines.extend(formatted_block)\n i = j\n else:\n formatted_lines.append(line)\n i += 1\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n def _format_continuation_block(self, lines: list[str]) -> list[str]:\n \"\"\"Format a block of continuation lines.\"\"\"\n if not lines:\n return lines\n\n # First line is the assignment/recipe line - keep it as is\n first_line = lines[0]\n formatted_lines = [first_line]\n\n # If there's only one line, return early\n if len(lines) == 1:\n return formatted_lines\n\n # Check if this is a recipe continuation (starts with tab)\n is_recipe = first_line.startswith(\"\\t\")\n\n # Check if this continuation block contains shell control structures\n # If so, preserve original indentation for recipes (ShellFormattingRule will handle it)\n if is_recipe and self._contains_shell_control_structures(lines):\n # For recipe continuations with shell control structures, preserve indentation\n # Only normalize spacing around backslashes\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n content = line.rstrip()[:-1].rstrip()\n formatted_lines.append(content + \" \\\\\")\n else:\n # Last line of continuation - preserve original indentation\n formatted_lines.append(line)\n return formatted_lines\n\n # Normalize indentation for variable assignments and simple recipe continuations\n # Find the indentation of the first continuation line (second line)\n first_continuation_line = lines[1]\n # Get leading whitespace (spaces/tabs) from the first continuation line\n leading_whitespace = \"\"\n for char in first_continuation_line:\n if char in (\" \", \"\\t\"):\n leading_whitespace += char\n else:\n break\n\n # Format all continuation lines (from second line onwards)\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n # Also remove leading whitespace to normalize indentation\n content = line.rstrip()[:-1].rstrip().lstrip()\n # Apply consistent indentation from first continuation line\n formatted_lines.append(leading_whitespace + content + \" \\\\\")\n else:\n # Last line of continuation - apply consistent indentation\n stripped_content = line.lstrip()\n formatted_lines.append(leading_whitespace + stripped_content)\n\n return formatted_lines\n\n def _contains_shell_control_structures(self, lines: list[str]) -> bool:\n \"\"\"Check if continuation block contains shell control structure keywords.\"\"\"\n # Shell control structure keywords that have semantic indentation meaning\n # These keywords should preserve their indentation relative to each other\n shell_keywords = (\n \"if\",\n \"then\",\n \"else\",\n \"elif\",\n \"fi\",\n \"for\",\n \"do\",\n \"done\",\n \"while\",\n \"until\",\n \"case\",\n \"esac\",\n )\n\n for line in lines:\n # Strip leading whitespace and make command prefixes for checking\n stripped = line.lstrip(\"\\t \").lstrip(\"@-+ \")\n # Remove trailing backslash and whitespace for cleaner matching\n content = stripped.rstrip(\" \\\\\")\n\n # Check if line starts with a shell keyword (most common case)\n for keyword in shell_keywords:\n # Match keyword at start of line, followed by space, semicolon, or end of line\n if (\n content.startswith(keyword + \" \")\n or content.startswith(keyword + \";\")\n or content == keyword\n # Also check for keywords after shell operators (; || &&)\n or f\"; {keyword}\" in content\n or f\"|| {keyword}\" in content\n or f\"&& {keyword}\" in content\n ):\n return True\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 6400}, "tests/test_version_utils.py::154": {"resolved_imports": ["mbake/utils/version_utils.py"], "used_names": ["check_for_updates", "patch"], "enclosing_function": "test_network_error", "extracted_code": "# Source: mbake/utils/version_utils.py\ndef check_for_updates(\n package_name: str = \"mbake\", include_prerelease: bool = False\n) -> tuple[bool, Optional[str], str]:\n \"\"\"Check if there's a newer version available on PyPI.\n\n Args:\n package_name: Name of the package to check\n include_prerelease: Whether to include pre-release versions\n\n Returns:\n tuple of (update_available, latest_version, current_version)\n \"\"\"\n latest_version = get_pypi_version(\n package_name, include_prerelease=include_prerelease\n )\n\n if latest_version is None:\n return False, None, current_version\n\n try:\n current_parsed = parse_version(current_version)\n latest_parsed = parse_version(latest_version)\n\n update_available = latest_parsed > current_parsed\n return update_available, latest_version, current_version\n except VersionError:\n return False, latest_version, current_version", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 949}, "tests/test_validate_command.py::86": {"resolved_imports": ["mbake/cli.py"], "used_names": ["Path", "app", "patch", "tempfile"], "enclosing_function": "test_validate_makefile_with_relative_include", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 165}, "tests/test_assignment_alignment.py::80": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_alignment_with_different_operators", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_version_utils.py::117": {"resolved_imports": ["mbake/utils/version_utils.py"], "used_names": ["check_for_updates", "patch"], "enclosing_function": "test_update_available", "extracted_code": "# Source: mbake/utils/version_utils.py\ndef check_for_updates(\n package_name: str = \"mbake\", include_prerelease: bool = False\n) -> tuple[bool, Optional[str], str]:\n \"\"\"Check if there's a newer version available on PyPI.\n\n Args:\n package_name: Name of the package to check\n include_prerelease: Whether to include pre-release versions\n\n Returns:\n tuple of (update_available, latest_version, current_version)\n \"\"\"\n latest_version = get_pypi_version(\n package_name, include_prerelease=include_prerelease\n )\n\n if latest_version is None:\n return False, None, current_version\n\n try:\n current_parsed = parse_version(current_version)\n latest_parsed = parse_version(latest_version)\n\n update_available = latest_parsed > current_parsed\n return update_available, latest_version, current_version\n except VersionError:\n return False, latest_version, current_version", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 949}, "tests/test_assignment_alignment.py::236": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_conditional_blocks_break_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_version_utils.py::152": {"resolved_imports": ["mbake/utils/version_utils.py"], "used_names": ["check_for_updates", "patch"], "enclosing_function": "test_network_error", "extracted_code": "# Source: mbake/utils/version_utils.py\ndef check_for_updates(\n package_name: str = \"mbake\", include_prerelease: bool = False\n) -> tuple[bool, Optional[str], str]:\n \"\"\"Check if there's a newer version available on PyPI.\n\n Args:\n package_name: Name of the package to check\n include_prerelease: Whether to include pre-release versions\n\n Returns:\n tuple of (update_available, latest_version, current_version)\n \"\"\"\n latest_version = get_pypi_version(\n package_name, include_prerelease=include_prerelease\n )\n\n if latest_version is None:\n return False, None, current_version\n\n try:\n current_parsed = parse_version(current_version)\n latest_parsed = parse_version(latest_version)\n\n update_available = latest_parsed > current_parsed\n return update_available, latest_version, current_version\n except VersionError:\n return False, latest_version, current_version", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 949}, "tests/test_reversed_assignment_operators.py::276": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_mixed_correct_and_incorrect_operators", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_assignment_alignment.py::106": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_comments_break_blocks", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_assignment_alignment.py::233": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_conditional_blocks_break_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_bake.py::51": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["TabsRule"], "enclosing_function": "test_handles_mixed_indentation", "extracted_code": "# Source: mbake/core/rules/tabs.py\nclass TabsRule(FormatterPlugin):\n \"\"\"Ensures tabs are used for recipe indentation instead of spaces.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"tabs\", priority=10)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Convert spaces to tabs for recipe lines only.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n # Track conditional context when indentation is enabled\n indent_conditionals = config.get(\"indent_nested_conditionals\", False)\n tab_width = config.get(\"tab_width\", 4)\n conditional_stack: list[str] = [] if indent_conditionals else []\n\n for line_index, line in enumerate(lines):\n # Skip empty lines\n if not line.strip():\n formatted_lines.append(line)\n continue\n\n # Skip comments\n if line.strip().startswith(\"#\"):\n formatted_lines.append(line)\n continue\n\n # Get active recipe prefix for this line\n active_prefix = LineUtils.get_active_recipe_prefix(lines, line_index)\n\n # Skip lines that start directly with the active recipe prefix (already properly formatted)\n # But only if they don't need conditional indentation\n if (\n line.startswith(active_prefix) or line.startswith(active_prefix + \"\\t\")\n ) and not indent_conditionals:\n formatted_lines.append(line)\n continue\n\n stripped = line.strip()\n\n # Track conditional context if indentation is enabled\n if indent_conditionals:\n self._update_conditional_stack(stripped, conditional_stack)\n\n # Handle conditional directives - these should start at column 1 according to GNU Make syntax\n # BUT: nested conditionals inside else blocks should preserve indentation\n if line.startswith(\" \") and stripped.startswith(\n (\"ifeq\", \"ifneq\", \"ifdef\", \"ifndef\", \"else\", \"endif\")\n ):\n\n # Check if this is a nested conditional that should preserve indentation\n if self._is_nested_conditional(line_index, lines, stripped):\n # This is a nested conditional inside an else block - preserve indentation\n formatted_lines.append(line)\n else:\n # This is a top-level conditional directive - move to column 1\n new_line = stripped\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n else:\n formatted_lines.append(line)\n # Check if this is a recipe line (command that should be executed)\n # Recipe lines are indented lines that are not:\n # - Variable assignments\n # - Include statements\n # - Variable definition continuations\n # - Function calls\n # - Other makefile constructs\n # - Lines that start with the active .RECIPEPREFIX character\n elif (\n line.startswith(\" \")\n and stripped # Not empty\n and not stripped.startswith(\"#\") # Not a comment\n and not self._is_target_definition(stripped) # Not a target definition\n # Note: we DO want to process continuation lines for tab conversion\n and not self._is_variable_assignment_line(\n stripped\n ) # Not a variable assignment\n and not stripped.startswith(\n (\"include\", \"-include\", \"vpath\")\n ) # Not include/vpath\n and not self._is_variable_continuation(\n line, line_index, lines\n ) # Not variable continuation\n and not LineUtils.is_makefile_construct(\n stripped\n ) # Not a makefile construct\n and not (\n line.startswith(active_prefix)\n or line.startswith(active_prefix + \"\\t\")\n ) # Not direct .RECIPEPREFIX line\n ):\n # Convert leading spaces to tab for recipe lines\n content = line.lstrip()\n # Apply conditional nesting indentation if enabled\n if indent_conditionals and conditional_stack:\n # Recipe should align with the conditional directive that contains it\n # Calculate spaces needed, accounting for the mandatory tab's visual width\n conditional_indent = (len(conditional_stack) - 1) * tab_width\n # Subtract tab_width to compensate for the mandatory tab's visual width\n recipe_spaces = max(0, conditional_indent - tab_width)\n new_line = \"\\t\" + \" \" * recipe_spaces + content\n else:\n # For recipe lines, always use exactly one tab (GNU Make requirement)\n new_line = \"\\t\" + content\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n else:\n formatted_lines.append(line)\n # Enhanced recipe alignment when nested conditionals are enabled\n # This ONLY processes lines that actually have alignment problems\n elif (\n config.get(\"indent_nested_conditionals\", False)\n and self._needs_recipe_alignment(line) # MUST have alignment problems\n and line.startswith(\"\\t\")\n and stripped # Not empty\n and not stripped.startswith(\"#\") # Not a comment\n and not self._is_target_definition(stripped) # Not a target definition\n and not self._is_variable_assignment_line(\n stripped\n ) # Not a variable assignment\n and not stripped.startswith(\n (\"include\", \"-include\", \"vpath\")\n ) # Not include/vpath\n and not self._is_variable_continuation(\n line, line_index, lines\n ) # Not variable continuation\n and not LineUtils.is_makefile_construct(\n stripped\n ) # Not a makefile construct\n ):\n # Clean up mixed whitespace in recipe lines when conditional indentation is enabled\n content = line.lstrip()\n # Apply conditional nesting indentation if enabled\n if indent_conditionals and conditional_stack:\n # Recipe should align with the conditional directive that contains it\n # Calculate spaces needed, accounting for the mandatory tab's visual width\n conditional_indent = (len(conditional_stack) - 1) * tab_width\n # Subtract tab_width to compensate for the mandatory tab's visual width\n recipe_spaces = max(0, conditional_indent - tab_width)\n new_line = \"\\t\" + \" \" * recipe_spaces + content\n else:\n # For recipe lines, always use exactly one tab (GNU Make requirement)\n new_line = \"\\t\" + content\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n else:\n formatted_lines.append(line)\n elif line.startswith(\"\\t\"):\n # Already starts with tab - but may need conditional nesting adjustment\n if (\n indent_conditionals\n and conditional_stack\n and stripped\n and not stripped.startswith(\"#\")\n and not self._is_target_definition(stripped)\n and not self._is_variable_assignment_line(stripped)\n and not stripped.startswith((\"include\", \"-include\", \"vpath\"))\n and not self._is_variable_continuation(line, line_index, lines)\n and not LineUtils.is_makefile_construct(stripped)\n ):\n # This is a recipe line that needs conditional nesting indentation\n content = (\n line.lstrip()\n ) # Remove all leading whitespace (tabs/spaces)\n if conditional_stack:\n # Recipe should align with the conditional directive that contains it\n # Calculate spaces needed, accounting for the mandatory tab's visual width\n conditional_indent = (len(conditional_stack) - 1) * tab_width\n # Subtract tab_width to compensate for the mandatory tab's visual width\n recipe_spaces = max(0, conditional_indent - tab_width)\n new_line = \"\\t\" + \" \" * recipe_spaces + content\n else:\n # No nesting - just use one tab\n new_line = \"\\t\" + content\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n else:\n formatted_lines.append(line)\n else:\n # Not a recipe line or no conditional context - preserve as-is\n formatted_lines.append(line)\n else:\n # Not a recipe line, preserve as-is\n formatted_lines.append(line)\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n def _is_nested_conditional(\n self, line_index: int, lines: list[str], stripped: str\n ) -> bool:\n \"\"\"Check if this conditional directive is nested inside another conditional block.\"\"\"\n if line_index == 0:\n return False\n\n # Track conditional nesting depth\n conditional_depth = 0\n\n # Look backwards to see if we're inside a conditional block\n for i in range(line_index - 1, -1, -1):\n prev_line = lines[i]\n prev_stripped = prev_line.strip()\n\n # Skip empty lines and comments\n if not prev_stripped or prev_stripped.startswith(\"#\"):\n continue\n\n # Check for conditional directives\n if prev_stripped.startswith(\"endif\"):\n conditional_depth += 1\n elif prev_stripped.startswith((\"ifeq\", \"ifneq\", \"ifdef\", \"ifndef\")):\n conditional_depth -= 1\n\n # If we've reached depth 0, we found the matching opening conditional\n if conditional_depth < 0:\n # We are inside a conditional block, so this could be nested\n # But only preserve indentation for conditionals inside else blocks\n # or for nested conditionals that have meaningful indentation\n return True\n\n return False\n\n def _is_variable_continuation(\n self, line: str, line_index: int, lines: list[str]\n ) -> bool:\n \"\"\"Check if this line is a continuation of a variable definition.\"\"\"\n if line_index == 0:\n return False\n\n # Look at the previous line(s) to see if this is a continuation\n for i in range(line_index - 1, -1, -1):\n prev_line = lines[i]\n prev_stripped = prev_line.strip()\n\n # Skip empty lines and comments\n if not prev_stripped or prev_stripped.startswith(\"#\"):\n continue\n\n # If we find a line ending with \\, this could be a continuation\n if prev_stripped.endswith(\"\\\\\"):\n # Check if it's a variable assignment or part of one\n # Look for the original assignment line\n for j in range(i, -1, -1):\n check_line = lines[j].strip()\n if not check_line or check_line.startswith(\"#\"):\n continue\n if \"=\" in check_line and not check_line.startswith(\"\\t\"):\n return True\n if not check_line.endswith(\"\\\\\"):\n break\n return False\n else:\n # No backslash, so this is not a continuation\n return False\n\n return False\n\n def _is_variable_assignment_line(self, stripped: str) -> bool:\n \"\"\"Check if this is a Makefile variable assignment (not a shell command with =).\"\"\"\n if \"=\" not in stripped:\n return False\n\n # Use the existing LineUtils method which properly detects Makefile variable assignments\n return LineUtils.is_variable_assignment(stripped)\n\n def _is_target_definition(self, stripped: str) -> bool:\n \"\"\"Check if this is a target definition (not a command with colons).\"\"\"\n if \":\" not in stripped:\n return False\n\n # Basic target pattern: target_name : prerequisites\n # The colon should be at the top level, not inside quotes, parentheses, etc.\n\n # Find the position of the first unquoted, unescaped colon\n in_single_quote = False\n in_double_quote = False\n paren_depth = 0\n i = 0\n\n while i < len(stripped):\n char = stripped[i]\n\n # Handle escape sequences\n if char == \"\\\\\" and i + 1 < len(stripped):\n i += 2 # Skip escaped character\n continue\n\n # Handle quotes\n if char == \"'\" and not in_double_quote:\n in_single_quote = not in_single_quote\n elif char == '\"' and not in_single_quote:\n in_double_quote = not in_double_quote\n elif char == \"(\" and not in_single_quote and not in_double_quote:\n paren_depth += 1\n elif char == \")\" and not in_single_quote and not in_double_quote:\n paren_depth -= 1\n elif (\n char == \":\"\n and not in_single_quote\n and not in_double_quote\n and paren_depth == 0\n ):\n # Found an unquoted, top-level colon\n # Check if this looks like a target definition\n target_part = stripped[:i].strip()\n\n # Empty target part means this isn't a target definition\n if not target_part:\n return False\n\n # Target names shouldn't contain spaces (unless escaped or quoted)\n # But make does allow multiple targets separated by spaces\n # So we'll be conservative and say if it contains unquoted spaces, it's likely not a target\n\n # Check for obvious non-target patterns\n return not (\n target_part.startswith((\"@\", \"-\", \"+\")) # Recipe prefixes\n or \"=\" in target_part # Variable assignments within\n or target_part.endswith(\"\\\\\") # Continuation lines\n )\n\n i += 1\n\n return False\n\n def _needs_recipe_alignment(self, line: str) -> bool:\n \"\"\"Check if line has mixed whitespace or excessive tabs that need alignment.\"\"\"\n if not line:\n return False\n\n # Check for mixed tabs and spaces at the beginning\n leading_chars = []\n for char in line:\n if char in [\" \", \"\\t\"]:\n leading_chars.append(char)\n else:\n break\n\n # Mixed whitespace means we have both tabs and spaces in the leading whitespace\n has_tab = \"\\t\" in leading_chars\n has_space = \" \" in leading_chars\n mixed_whitespace = has_tab and has_space\n\n # Check for excessive tabs (more than one leading tab)\n if line.startswith(\"\\t\"):\n tab_count = 0\n for char in line:\n if char == \"\\t\":\n tab_count += 1\n else:\n break\n excessive_tabs = tab_count > 1\n else:\n excessive_tabs = False\n\n return mixed_whitespace or excessive_tabs\n\n def _update_conditional_stack(\n self, stripped_line: str, conditional_stack: list[str]\n ) -> None:\n \"\"\"Update the conditional stack based on the current line.\"\"\"\n if not stripped_line:\n return\n\n # Check for conditional directives\n if stripped_line.startswith((\"ifeq\", \"ifneq\", \"ifdef\", \"ifndef\")):\n # Opening conditional - add to stack\n conditional_type = (\n stripped_line.split()[0]\n if \" \" in stripped_line\n else stripped_line.split(\"(\")[0]\n )\n conditional_stack.append(conditional_type)\n elif stripped_line.startswith(\"endif\"):\n # Closing conditional - remove from stack\n if conditional_stack:\n conditional_stack.pop()", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 17332}, "tests/test_bake.py::129": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py", "mbake/core/rules/final_newline.py"], "used_names": ["FinalNewlineRule"], "enclosing_function": "test_detects_missing_final_newline", "extracted_code": "# Source: mbake/core/rules/final_newline.py\nclass FinalNewlineRule(FormatterPlugin):\n \"\"\"Ensures files end with a final newline if configured.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\n \"final_newline\", priority=70\n ) # Run late, after content changes\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Ensure final newline if configured.\"\"\"\n ensure_final_newline = config.get(\"ensure_final_newline\", True)\n\n if not ensure_final_newline:\n return FormatResult(\n lines=lines, changed=False, errors=[], warnings=[], check_messages=[]\n )\n\n # Check if file is empty\n if not lines:\n return FormatResult(\n lines=lines, changed=False, errors=[], warnings=[], check_messages=[]\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Check if the last line ends with a newline\n # In check mode, respect the original_content_ends_with_newline parameter\n original_ends_with_newline = context.get(\n \"original_content_ends_with_newline\", False\n )\n\n # If original content already ends with newline, no change needed\n if check_mode and original_ends_with_newline:\n return FormatResult(\n lines=lines, changed=False, errors=[], warnings=[], check_messages=[]\n )\n\n # If the last line is not empty, we need to add a newline\n if formatted_lines and formatted_lines[-1] != \"\":\n if check_mode:\n # Generate check message\n line_count = len(formatted_lines)\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n message = f\"{line_count}: Warning: Missing final newline\"\n else:\n message = f\"Warning: Missing final newline (line {line_count})\"\n\n check_messages.append(message)\n else:\n # Add empty line to ensure final newline\n formatted_lines.append(\"\")\n\n changed = True\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )", "n_imports_parsed": 4, "n_files_resolved": 9, "n_chars_extracted": 2525}, "tests/test_bake.py::111": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["WhitespaceRule"], "enclosing_function": "test_removes_trailing_whitespace", "extracted_code": "# Source: mbake/core/rules/whitespace.py\nclass WhitespaceRule(FormatterPlugin):\n \"\"\"Handles trailing whitespace removal and line normalization.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\n \"whitespace\", priority=45\n ) # Run late to clean up after other rules\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Remove trailing whitespace and normalize empty lines.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n remove_trailing_whitespace = config.get(\"remove_trailing_whitespace\", True)\n normalize_empty_lines = config.get(\"normalize_empty_lines\", True)\n\n prev_was_empty = False\n\n for line in lines:\n # Remove trailing whitespace if enabled\n if remove_trailing_whitespace:\n cleaned_line = line.rstrip()\n if cleaned_line != line:\n changed = True\n line = cleaned_line\n\n # Normalize consecutive empty lines if enabled\n if normalize_empty_lines:\n is_empty = not line.strip()\n if is_empty and prev_was_empty:\n # Skip this empty line (already have one)\n changed = True\n continue\n prev_was_empty = is_empty\n\n formatted_lines.append(line)\n\n # Remove extra trailing empty lines\n while (\n len(formatted_lines) > 1\n and formatted_lines[-1] == \"\"\n and formatted_lines[-2] == \"\"\n ):\n formatted_lines.pop()\n changed = True\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 1932}, "tests/test_assignment_alignment.py::176": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_empty_value_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_bake.py::41": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["TabsRule"], "enclosing_function": "test_preserves_existing_tabs", "extracted_code": "# Source: mbake/core/rules/tabs.py\nclass TabsRule(FormatterPlugin):\n \"\"\"Ensures tabs are used for recipe indentation instead of spaces.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"tabs\", priority=10)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Convert spaces to tabs for recipe lines only.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n # Track conditional context when indentation is enabled\n indent_conditionals = config.get(\"indent_nested_conditionals\", False)\n tab_width = config.get(\"tab_width\", 4)\n conditional_stack: list[str] = [] if indent_conditionals else []\n\n for line_index, line in enumerate(lines):\n # Skip empty lines\n if not line.strip():\n formatted_lines.append(line)\n continue\n\n # Skip comments\n if line.strip().startswith(\"#\"):\n formatted_lines.append(line)\n continue\n\n # Get active recipe prefix for this line\n active_prefix = LineUtils.get_active_recipe_prefix(lines, line_index)\n\n # Skip lines that start directly with the active recipe prefix (already properly formatted)\n # But only if they don't need conditional indentation\n if (\n line.startswith(active_prefix) or line.startswith(active_prefix + \"\\t\")\n ) and not indent_conditionals:\n formatted_lines.append(line)\n continue\n\n stripped = line.strip()\n\n # Track conditional context if indentation is enabled\n if indent_conditionals:\n self._update_conditional_stack(stripped, conditional_stack)\n\n # Handle conditional directives - these should start at column 1 according to GNU Make syntax\n # BUT: nested conditionals inside else blocks should preserve indentation\n if line.startswith(\" \") and stripped.startswith(\n (\"ifeq\", \"ifneq\", \"ifdef\", \"ifndef\", \"else\", \"endif\")\n ):\n\n # Check if this is a nested conditional that should preserve indentation\n if self._is_nested_conditional(line_index, lines, stripped):\n # This is a nested conditional inside an else block - preserve indentation\n formatted_lines.append(line)\n else:\n # This is a top-level conditional directive - move to column 1\n new_line = stripped\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n else:\n formatted_lines.append(line)\n # Check if this is a recipe line (command that should be executed)\n # Recipe lines are indented lines that are not:\n # - Variable assignments\n # - Include statements\n # - Variable definition continuations\n # - Function calls\n # - Other makefile constructs\n # - Lines that start with the active .RECIPEPREFIX character\n elif (\n line.startswith(\" \")\n and stripped # Not empty\n and not stripped.startswith(\"#\") # Not a comment\n and not self._is_target_definition(stripped) # Not a target definition\n # Note: we DO want to process continuation lines for tab conversion\n and not self._is_variable_assignment_line(\n stripped\n ) # Not a variable assignment\n and not stripped.startswith(\n (\"include\", \"-include\", \"vpath\")\n ) # Not include/vpath\n and not self._is_variable_continuation(\n line, line_index, lines\n ) # Not variable continuation\n and not LineUtils.is_makefile_construct(\n stripped\n ) # Not a makefile construct\n and not (\n line.startswith(active_prefix)\n or line.startswith(active_prefix + \"\\t\")\n ) # Not direct .RECIPEPREFIX line\n ):\n # Convert leading spaces to tab for recipe lines\n content = line.lstrip()\n # Apply conditional nesting indentation if enabled\n if indent_conditionals and conditional_stack:\n # Recipe should align with the conditional directive that contains it\n # Calculate spaces needed, accounting for the mandatory tab's visual width\n conditional_indent = (len(conditional_stack) - 1) * tab_width\n # Subtract tab_width to compensate for the mandatory tab's visual width\n recipe_spaces = max(0, conditional_indent - tab_width)\n new_line = \"\\t\" + \" \" * recipe_spaces + content\n else:\n # For recipe lines, always use exactly one tab (GNU Make requirement)\n new_line = \"\\t\" + content\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n else:\n formatted_lines.append(line)\n # Enhanced recipe alignment when nested conditionals are enabled\n # This ONLY processes lines that actually have alignment problems\n elif (\n config.get(\"indent_nested_conditionals\", False)\n and self._needs_recipe_alignment(line) # MUST have alignment problems\n and line.startswith(\"\\t\")\n and stripped # Not empty\n and not stripped.startswith(\"#\") # Not a comment\n and not self._is_target_definition(stripped) # Not a target definition\n and not self._is_variable_assignment_line(\n stripped\n ) # Not a variable assignment\n and not stripped.startswith(\n (\"include\", \"-include\", \"vpath\")\n ) # Not include/vpath\n and not self._is_variable_continuation(\n line, line_index, lines\n ) # Not variable continuation\n and not LineUtils.is_makefile_construct(\n stripped\n ) # Not a makefile construct\n ):\n # Clean up mixed whitespace in recipe lines when conditional indentation is enabled\n content = line.lstrip()\n # Apply conditional nesting indentation if enabled\n if indent_conditionals and conditional_stack:\n # Recipe should align with the conditional directive that contains it\n # Calculate spaces needed, accounting for the mandatory tab's visual width\n conditional_indent = (len(conditional_stack) - 1) * tab_width\n # Subtract tab_width to compensate for the mandatory tab's visual width\n recipe_spaces = max(0, conditional_indent - tab_width)\n new_line = \"\\t\" + \" \" * recipe_spaces + content\n else:\n # For recipe lines, always use exactly one tab (GNU Make requirement)\n new_line = \"\\t\" + content\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n else:\n formatted_lines.append(line)\n elif line.startswith(\"\\t\"):\n # Already starts with tab - but may need conditional nesting adjustment\n if (\n indent_conditionals\n and conditional_stack\n and stripped\n and not stripped.startswith(\"#\")\n and not self._is_target_definition(stripped)\n and not self._is_variable_assignment_line(stripped)\n and not stripped.startswith((\"include\", \"-include\", \"vpath\"))\n and not self._is_variable_continuation(line, line_index, lines)\n and not LineUtils.is_makefile_construct(stripped)\n ):\n # This is a recipe line that needs conditional nesting indentation\n content = (\n line.lstrip()\n ) # Remove all leading whitespace (tabs/spaces)\n if conditional_stack:\n # Recipe should align with the conditional directive that contains it\n # Calculate spaces needed, accounting for the mandatory tab's visual width\n conditional_indent = (len(conditional_stack) - 1) * tab_width\n # Subtract tab_width to compensate for the mandatory tab's visual width\n recipe_spaces = max(0, conditional_indent - tab_width)\n new_line = \"\\t\" + \" \" * recipe_spaces + content\n else:\n # No nesting - just use one tab\n new_line = \"\\t\" + content\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n else:\n formatted_lines.append(line)\n else:\n # Not a recipe line or no conditional context - preserve as-is\n formatted_lines.append(line)\n else:\n # Not a recipe line, preserve as-is\n formatted_lines.append(line)\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n def _is_nested_conditional(\n self, line_index: int, lines: list[str], stripped: str\n ) -> bool:\n \"\"\"Check if this conditional directive is nested inside another conditional block.\"\"\"\n if line_index == 0:\n return False\n\n # Track conditional nesting depth\n conditional_depth = 0\n\n # Look backwards to see if we're inside a conditional block\n for i in range(line_index - 1, -1, -1):\n prev_line = lines[i]\n prev_stripped = prev_line.strip()\n\n # Skip empty lines and comments\n if not prev_stripped or prev_stripped.startswith(\"#\"):\n continue\n\n # Check for conditional directives\n if prev_stripped.startswith(\"endif\"):\n conditional_depth += 1\n elif prev_stripped.startswith((\"ifeq\", \"ifneq\", \"ifdef\", \"ifndef\")):\n conditional_depth -= 1\n\n # If we've reached depth 0, we found the matching opening conditional\n if conditional_depth < 0:\n # We are inside a conditional block, so this could be nested\n # But only preserve indentation for conditionals inside else blocks\n # or for nested conditionals that have meaningful indentation\n return True\n\n return False\n\n def _is_variable_continuation(\n self, line: str, line_index: int, lines: list[str]\n ) -> bool:\n \"\"\"Check if this line is a continuation of a variable definition.\"\"\"\n if line_index == 0:\n return False\n\n # Look at the previous line(s) to see if this is a continuation\n for i in range(line_index - 1, -1, -1):\n prev_line = lines[i]\n prev_stripped = prev_line.strip()\n\n # Skip empty lines and comments\n if not prev_stripped or prev_stripped.startswith(\"#\"):\n continue\n\n # If we find a line ending with \\, this could be a continuation\n if prev_stripped.endswith(\"\\\\\"):\n # Check if it's a variable assignment or part of one\n # Look for the original assignment line\n for j in range(i, -1, -1):\n check_line = lines[j].strip()\n if not check_line or check_line.startswith(\"#\"):\n continue\n if \"=\" in check_line and not check_line.startswith(\"\\t\"):\n return True\n if not check_line.endswith(\"\\\\\"):\n break\n return False\n else:\n # No backslash, so this is not a continuation\n return False\n\n return False\n\n def _is_variable_assignment_line(self, stripped: str) -> bool:\n \"\"\"Check if this is a Makefile variable assignment (not a shell command with =).\"\"\"\n if \"=\" not in stripped:\n return False\n\n # Use the existing LineUtils method which properly detects Makefile variable assignments\n return LineUtils.is_variable_assignment(stripped)\n\n def _is_target_definition(self, stripped: str) -> bool:\n \"\"\"Check if this is a target definition (not a command with colons).\"\"\"\n if \":\" not in stripped:\n return False\n\n # Basic target pattern: target_name : prerequisites\n # The colon should be at the top level, not inside quotes, parentheses, etc.\n\n # Find the position of the first unquoted, unescaped colon\n in_single_quote = False\n in_double_quote = False\n paren_depth = 0\n i = 0\n\n while i < len(stripped):\n char = stripped[i]\n\n # Handle escape sequences\n if char == \"\\\\\" and i + 1 < len(stripped):\n i += 2 # Skip escaped character\n continue\n\n # Handle quotes\n if char == \"'\" and not in_double_quote:\n in_single_quote = not in_single_quote\n elif char == '\"' and not in_single_quote:\n in_double_quote = not in_double_quote\n elif char == \"(\" and not in_single_quote and not in_double_quote:\n paren_depth += 1\n elif char == \")\" and not in_single_quote and not in_double_quote:\n paren_depth -= 1\n elif (\n char == \":\"\n and not in_single_quote\n and not in_double_quote\n and paren_depth == 0\n ):\n # Found an unquoted, top-level colon\n # Check if this looks like a target definition\n target_part = stripped[:i].strip()\n\n # Empty target part means this isn't a target definition\n if not target_part:\n return False\n\n # Target names shouldn't contain spaces (unless escaped or quoted)\n # But make does allow multiple targets separated by spaces\n # So we'll be conservative and say if it contains unquoted spaces, it's likely not a target\n\n # Check for obvious non-target patterns\n return not (\n target_part.startswith((\"@\", \"-\", \"+\")) # Recipe prefixes\n or \"=\" in target_part # Variable assignments within\n or target_part.endswith(\"\\\\\") # Continuation lines\n )\n\n i += 1\n\n return False\n\n def _needs_recipe_alignment(self, line: str) -> bool:\n \"\"\"Check if line has mixed whitespace or excessive tabs that need alignment.\"\"\"\n if not line:\n return False\n\n # Check for mixed tabs and spaces at the beginning\n leading_chars = []\n for char in line:\n if char in [\" \", \"\\t\"]:\n leading_chars.append(char)\n else:\n break\n\n # Mixed whitespace means we have both tabs and spaces in the leading whitespace\n has_tab = \"\\t\" in leading_chars\n has_space = \" \" in leading_chars\n mixed_whitespace = has_tab and has_space\n\n # Check for excessive tabs (more than one leading tab)\n if line.startswith(\"\\t\"):\n tab_count = 0\n for char in line:\n if char == \"\\t\":\n tab_count += 1\n else:\n break\n excessive_tabs = tab_count > 1\n else:\n excessive_tabs = False\n\n return mixed_whitespace or excessive_tabs\n\n def _update_conditional_stack(\n self, stripped_line: str, conditional_stack: list[str]\n ) -> None:\n \"\"\"Update the conditional stack based on the current line.\"\"\"\n if not stripped_line:\n return\n\n # Check for conditional directives\n if stripped_line.startswith((\"ifeq\", \"ifneq\", \"ifdef\", \"ifndef\")):\n # Opening conditional - add to stack\n conditional_type = (\n stripped_line.split()[0]\n if \" \" in stripped_line\n else stripped_line.split(\"(\")[0]\n )\n conditional_stack.append(conditional_type)\n elif stripped_line.startswith(\"endif\"):\n # Closing conditional - remove from stack\n if conditional_stack:\n conditional_stack.pop()", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 17332}, "tests/test_bake.py::175": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["ContinuationRule"], "enclosing_function": "test_formats_simple_continuation", "extracted_code": "# Source: mbake/core/rules/continuation.py\nclass ContinuationRule(FormatterPlugin):\n \"\"\"Handles proper formatting of line continuations with backslashes.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"continuation\", priority=9) # Run before tabs rule\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Normalize line continuation formatting.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n normalize_continuations = config.get(\"normalize_line_continuations\", True)\n\n if not normalize_continuations:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n i = 0\n while i < len(lines):\n line = lines[i]\n\n # Check if line ends with backslash (continuation)\n if line.rstrip().endswith(\"\\\\\"):\n # Collect all continuation lines\n continuation_lines = [line]\n j = i + 1\n\n while j < len(lines):\n current_line = lines[j]\n continuation_lines.append(current_line)\n\n # If this line doesn't end with backslash, it's the last line\n if not current_line.rstrip().endswith(\"\\\\\"):\n j += 1\n break\n\n j += 1\n\n # Format the continuation block\n formatted_block = self._format_continuation_block(continuation_lines)\n\n if formatted_block != continuation_lines:\n changed = True\n\n formatted_lines.extend(formatted_block)\n i = j\n else:\n formatted_lines.append(line)\n i += 1\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n def _format_continuation_block(self, lines: list[str]) -> list[str]:\n \"\"\"Format a block of continuation lines.\"\"\"\n if not lines:\n return lines\n\n # First line is the assignment/recipe line - keep it as is\n first_line = lines[0]\n formatted_lines = [first_line]\n\n # If there's only one line, return early\n if len(lines) == 1:\n return formatted_lines\n\n # Check if this is a recipe continuation (starts with tab)\n is_recipe = first_line.startswith(\"\\t\")\n\n # Check if this continuation block contains shell control structures\n # If so, preserve original indentation for recipes (ShellFormattingRule will handle it)\n if is_recipe and self._contains_shell_control_structures(lines):\n # For recipe continuations with shell control structures, preserve indentation\n # Only normalize spacing around backslashes\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n content = line.rstrip()[:-1].rstrip()\n formatted_lines.append(content + \" \\\\\")\n else:\n # Last line of continuation - preserve original indentation\n formatted_lines.append(line)\n return formatted_lines\n\n # Normalize indentation for variable assignments and simple recipe continuations\n # Find the indentation of the first continuation line (second line)\n first_continuation_line = lines[1]\n # Get leading whitespace (spaces/tabs) from the first continuation line\n leading_whitespace = \"\"\n for char in first_continuation_line:\n if char in (\" \", \"\\t\"):\n leading_whitespace += char\n else:\n break\n\n # Format all continuation lines (from second line onwards)\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n # Also remove leading whitespace to normalize indentation\n content = line.rstrip()[:-1].rstrip().lstrip()\n # Apply consistent indentation from first continuation line\n formatted_lines.append(leading_whitespace + content + \" \\\\\")\n else:\n # Last line of continuation - apply consistent indentation\n stripped_content = line.lstrip()\n formatted_lines.append(leading_whitespace + stripped_content)\n\n return formatted_lines\n\n def _contains_shell_control_structures(self, lines: list[str]) -> bool:\n \"\"\"Check if continuation block contains shell control structure keywords.\"\"\"\n # Shell control structure keywords that have semantic indentation meaning\n # These keywords should preserve their indentation relative to each other\n shell_keywords = (\n \"if\",\n \"then\",\n \"else\",\n \"elif\",\n \"fi\",\n \"for\",\n \"do\",\n \"done\",\n \"while\",\n \"until\",\n \"case\",\n \"esac\",\n )\n\n for line in lines:\n # Strip leading whitespace and make command prefixes for checking\n stripped = line.lstrip(\"\\t \").lstrip(\"@-+ \")\n # Remove trailing backslash and whitespace for cleaner matching\n content = stripped.rstrip(\" \\\\\")\n\n # Check if line starts with a shell keyword (most common case)\n for keyword in shell_keywords:\n # Match keyword at start of line, followed by space, semicolon, or end of line\n if (\n content.startswith(keyword + \" \")\n or content.startswith(keyword + \";\")\n or content == keyword\n # Also check for keywords after shell operators (; || &&)\n or f\"; {keyword}\" in content\n or f\"|| {keyword}\" in content\n or f\"&& {keyword}\" in content\n ):\n return True\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 6400}, "tests/test_bake.py::282": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_check_only_mode", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 21779}, "tests/test_comprehensive.py::404": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/conditionals.py", "mbake/core/rules/continuation.py", "mbake/core/rules/pattern_spacing.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/whitespace.py"], "used_names": ["ContinuationRule"], "enclosing_function": "test_multiline_variable_consolidation", "extracted_code": "# Source: mbake/core/rules/continuation.py\nclass ContinuationRule(FormatterPlugin):\n \"\"\"Handles proper formatting of line continuations with backslashes.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"continuation\", priority=9) # Run before tabs rule\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Normalize line continuation formatting.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n normalize_continuations = config.get(\"normalize_line_continuations\", True)\n\n if not normalize_continuations:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n i = 0\n while i < len(lines):\n line = lines[i]\n\n # Check if line ends with backslash (continuation)\n if line.rstrip().endswith(\"\\\\\"):\n # Collect all continuation lines\n continuation_lines = [line]\n j = i + 1\n\n while j < len(lines):\n current_line = lines[j]\n continuation_lines.append(current_line)\n\n # If this line doesn't end with backslash, it's the last line\n if not current_line.rstrip().endswith(\"\\\\\"):\n j += 1\n break\n\n j += 1\n\n # Format the continuation block\n formatted_block = self._format_continuation_block(continuation_lines)\n\n if formatted_block != continuation_lines:\n changed = True\n\n formatted_lines.extend(formatted_block)\n i = j\n else:\n formatted_lines.append(line)\n i += 1\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n def _format_continuation_block(self, lines: list[str]) -> list[str]:\n \"\"\"Format a block of continuation lines.\"\"\"\n if not lines:\n return lines\n\n # First line is the assignment/recipe line - keep it as is\n first_line = lines[0]\n formatted_lines = [first_line]\n\n # If there's only one line, return early\n if len(lines) == 1:\n return formatted_lines\n\n # Check if this is a recipe continuation (starts with tab)\n is_recipe = first_line.startswith(\"\\t\")\n\n # Check if this continuation block contains shell control structures\n # If so, preserve original indentation for recipes (ShellFormattingRule will handle it)\n if is_recipe and self._contains_shell_control_structures(lines):\n # For recipe continuations with shell control structures, preserve indentation\n # Only normalize spacing around backslashes\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n content = line.rstrip()[:-1].rstrip()\n formatted_lines.append(content + \" \\\\\")\n else:\n # Last line of continuation - preserve original indentation\n formatted_lines.append(line)\n return formatted_lines\n\n # Normalize indentation for variable assignments and simple recipe continuations\n # Find the indentation of the first continuation line (second line)\n first_continuation_line = lines[1]\n # Get leading whitespace (spaces/tabs) from the first continuation line\n leading_whitespace = \"\"\n for char in first_continuation_line:\n if char in (\" \", \"\\t\"):\n leading_whitespace += char\n else:\n break\n\n # Format all continuation lines (from second line onwards)\n for line in lines[1:]:\n if line.rstrip().endswith(\"\\\\\"):\n # Remove trailing whitespace before backslash, ensure single space\n # Also remove leading whitespace to normalize indentation\n content = line.rstrip()[:-1].rstrip().lstrip()\n # Apply consistent indentation from first continuation line\n formatted_lines.append(leading_whitespace + content + \" \\\\\")\n else:\n # Last line of continuation - apply consistent indentation\n stripped_content = line.lstrip()\n formatted_lines.append(leading_whitespace + stripped_content)\n\n return formatted_lines\n\n def _contains_shell_control_structures(self, lines: list[str]) -> bool:\n \"\"\"Check if continuation block contains shell control structure keywords.\"\"\"\n # Shell control structure keywords that have semantic indentation meaning\n # These keywords should preserve their indentation relative to each other\n shell_keywords = (\n \"if\",\n \"then\",\n \"else\",\n \"elif\",\n \"fi\",\n \"for\",\n \"do\",\n \"done\",\n \"while\",\n \"until\",\n \"case\",\n \"esac\",\n )\n\n for line in lines:\n # Strip leading whitespace and make command prefixes for checking\n stripped = line.lstrip(\"\\t \").lstrip(\"@-+ \")\n # Remove trailing backslash and whitespace for cleaner matching\n content = stripped.rstrip(\" \\\\\")\n\n # Check if line starts with a shell keyword (most common case)\n for keyword in shell_keywords:\n # Match keyword at start of line, followed by space, semicolon, or end of line\n if (\n content.startswith(keyword + \" \")\n or content.startswith(keyword + \";\")\n or content == keyword\n # Also check for keywords after shell operators (; || &&)\n or f\"; {keyword}\" in content\n or f\"|| {keyword}\" in content\n or f\"&& {keyword}\" in content\n ):\n return True\n\n return False", "n_imports_parsed": 8, "n_files_resolved": 9, "n_chars_extracted": 6400}, "tests/test_reversed_assignment_operators.py::34": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_detect_reversed_question_mark_operator", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_gnu_error_format.py::26": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_duplicate_target_error_format", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 21779}, "tests/test_bake.py::340": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["Config", "FormatterConfig", "MakefileFormatter"], "enclosing_function": "test_formats_fixture_correctly", "extracted_code": "# Source: mbake/config.py\nclass FormatterConfig:\n \"\"\"Configuration for Makefile formatting rules.\"\"\"\n\n # Spacing settings\n space_around_assignment: bool = True\n space_before_colon: bool = False\n space_after_colon: bool = True\n\n # Line continuation settings\n normalize_line_continuations: bool = True\n max_line_length: int = 120\n\n # PHONY settings\n auto_insert_phony_declarations: bool = False\n group_phony_declarations: bool = False\n phony_at_top: bool = False\n\n # General settings\n remove_trailing_whitespace: bool = True\n ensure_final_newline: bool = False\n normalize_empty_lines: bool = True\n max_consecutive_empty_lines: int = 2\n fix_missing_recipe_tabs: bool = True\n\n # Conditional formatting settings (Default disabled)\n indent_nested_conditionals: bool = False\n # Indentation settings\n tab_width: int = 2\n\n # Variable alignment settings\n align_variable_assignments: bool = False\n align_across_comments: bool = False\n\nclass Config:\n \"\"\"Main configuration class.\"\"\"\n\n formatter: FormatterConfig\n debug: bool = False\n verbose: bool = False\n # Error message formatting\n gnu_error_format: bool = (\n True # Use GNU standard error format (file:line: Error: message)\n )\n wrap_error_messages: bool = (\n False # Wrap long error messages (can interfere with IDE parsing)\n )\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> \"Config\":\n \"\"\"Load configuration from ~/.bake.toml.\"\"\"\n if config_path is None:\n config_path = Path.home() / \".bake.toml\"\n\n if not config_path.exists():\n raise FileNotFoundError(\n f\"Configuration file not found at {config_path}. \"\n \"Please create ~/.bake.toml with your formatting preferences.\"\n )\n\n try:\n with open(config_path, \"rb\") as f:\n data = tomllib.load(f)\n except Exception as e:\n raise ValueError(f\"Failed to parse configuration file: {e}\") from e\n\n # Extract formatter config, filtering out non-FormatterConfig keys\n formatter_data = data.get(\"formatter\", {})\n # Remove any keys that aren't valid FormatterConfig fields\n valid_formatter_keys = {\n \"space_around_assignment\",\n \"space_before_colon\",\n \"space_after_colon\",\n \"normalize_line_continuations\",\n \"max_line_length\",\n \"group_phony_declarations\",\n \"phony_at_top\",\n \"auto_insert_phony_declarations\",\n \"remove_trailing_whitespace\",\n \"ensure_final_newline\",\n \"normalize_empty_lines\",\n \"max_consecutive_empty_lines\",\n \"fix_missing_recipe_tabs\",\n \"indent_nested_conditionals\",\n \"tab_width\",\n \"align_variable_assignments\",\n \"align_across_comments\",\n }\n filtered_formatter_data = {\n k: v for k, v in formatter_data.items() if k in valid_formatter_keys\n }\n formatter_config = FormatterConfig(**filtered_formatter_data)\n\n # Extract global config (only from top level - these are global settings, not formatter settings)\n global_data = {}\n\n if \"debug\" in data:\n global_data[\"debug\"] = data[\"debug\"]\n if \"verbose\" in data:\n global_data[\"verbose\"] = data[\"verbose\"]\n if \"gnu_error_format\" in data:\n global_data[\"gnu_error_format\"] = data[\"gnu_error_format\"]\n if \"wrap_error_messages\" in data:\n global_data[\"wrap_error_messages\"] = data[\"wrap_error_messages\"]\n\n return cls(formatter=formatter_config, **global_data)\n\n @classmethod\n def load_or_default(\n cls, config_path: Optional[Path] = None, explicit: bool = False\n ) -> \"Config\":\n \"\"\"Load config or return defaults if not found.\n\n Args:\n config_path: Path to config file, or None for default\n explicit: True if config_path was explicitly specified by user\n \"\"\"\n if config_path is not None:\n # User explicitly specified a config file\n try:\n return cls.load(config_path)\n except FileNotFoundError:\n if explicit:\n raise\n return cls(formatter=FormatterConfig())\n\n # Try to find config file in current directory first, then home directory\n\n current_dir_config = Path.cwd() / \".bake.toml\"\n home_config = Path.home() / \".bake.toml\"\n\n if current_dir_config.exists():\n try:\n return cls.load(current_dir_config)\n except Exception:\n # If current directory config is invalid, fall back to home directory\n pass\n\n if home_config.exists():\n try:\n return cls.load(home_config)\n except Exception:\n # If home directory config is invalid, fall back to defaults\n pass\n\n # Return default configuration if no config file found\n return cls(formatter=FormatterConfig())\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Convert config to dictionary.\"\"\"\n return {\n \"formatter\": {\n \"space_around_assignment\": self.formatter.space_around_assignment,\n \"space_before_colon\": self.formatter.space_before_colon,\n \"space_after_colon\": self.formatter.space_after_colon,\n \"normalize_line_continuations\": self.formatter.normalize_line_continuations,\n \"max_line_length\": self.formatter.max_line_length,\n \"group_phony_declarations\": self.formatter.group_phony_declarations,\n \"phony_at_top\": self.formatter.phony_at_top,\n \"auto_insert_phony_declarations\": self.formatter.auto_insert_phony_declarations,\n \"remove_trailing_whitespace\": self.formatter.remove_trailing_whitespace,\n \"ensure_final_newline\": self.formatter.ensure_final_newline,\n \"normalize_empty_lines\": self.formatter.normalize_empty_lines,\n \"max_consecutive_empty_lines\": self.formatter.max_consecutive_empty_lines,\n \"fix_missing_recipe_tabs\": self.formatter.fix_missing_recipe_tabs,\n \"indent_nested_conditionals\": self.formatter.indent_nested_conditionals,\n \"tab_width\": self.formatter.tab_width,\n \"align_variable_assignments\": self.formatter.align_variable_assignments,\n \"align_across_comments\": self.formatter.align_across_comments,\n },\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"gnu_error_format\": self.gnu_error_format,\n \"wrap_error_messages\": self.wrap_error_messages,\n }\n\n\n# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 21779}, "tests/test_completions.py::27": {"resolved_imports": ["mbake/cli.py", "mbake/completions.py"], "used_names": ["CliRunner", "app"], "enclosing_function": "test_completions_command_stdout", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 165}, "tests/test_validate_command.py::115": {"resolved_imports": ["mbake/cli.py"], "used_names": ["app"], "enclosing_function": "test_validate_nonexistent_file", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 165}, "tests/test_bake.py::75": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["AssignmentSpacingRule"], "enclosing_function": "test_removes_assignment_spacing", "extracted_code": "# Source: mbake/core/rules/assignment_spacing.py\nclass AssignmentSpacingRule(FormatterPlugin):\n \"\"\"Handles spacing around assignment operators (=, :=, +=, ?=).\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"assignment_spacing\", priority=15)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Normalize spacing around assignment operators.\"\"\"\n formatted_lines = []\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n\n space_around_assignment = config.get(\"space_around_assignment\", True)\n\n for i, line in enumerate(lines, 1):\n new_line = line # Default to original line\n\n # Skip recipe lines (lines starting with tab) or comments or empty lines\n if (\n line.startswith(\"\\t\")\n or line.strip().startswith(\"#\")\n or not line.strip()\n ):\n pass # Keep original line\n # Check if line contains assignment operator\n elif re.match(r\"^[A-Za-z_][A-Za-z0-9_]*\\s*(:=|\\+=|\\?=|=|!=)\\s*\", line):\n # Check for reversed assignment operators first\n reversed_warning = self._check_reversed_operators(line, i)\n if reversed_warning:\n warnings.append(reversed_warning)\n\n # Skip substitution references like $(VAR:pattern=replacement) which are not assignments\n # or skip invalid target-like lines of the form VAR=token:... (no space after '=')\n if re.search(\n r\"\\$\\([^)]*:[^)]*=[^)]*\\)\", line\n ) or self._is_invalid_target_syntax(line):\n pass # Keep original line\n else:\n # Extract the parts - be more careful about the operator\n match = re.match(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|=|!=)\\s*(.*)\", line\n )\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n # Only format if this is actually an assignment (not a target)\n if operator in [\"=\", \":=\", \"?=\", \"+=\", \"!=\"]:\n if space_around_assignment:\n # Only add trailing space if there's actually a value\n if value.strip():\n new_line = f\"{var_name} {operator} {value}\"\n else:\n new_line = f\"{var_name} {operator}\"\n else:\n new_line = f\"{var_name}{operator}{value}\"\n\n # Single append at the end\n if new_line != line:\n changed = True\n formatted_lines.append(new_line)\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=[],\n )\n\n def _is_invalid_target_syntax(self, line: str) -> bool:\n \"\"\"Check if line contains invalid target syntax that should be preserved.\"\"\"\n stripped = line.strip()\n # Only flag when there is NO whitespace after '=' before the first ':'\n # This avoids flagging typical assignments whose values contain ':' (URLs, times, paths).\n if not re.match(r\"^[A-Za-z_][A-Za-z0-9_]*=\\S*:\\S*\", stripped):\n return False\n # Allow colon-safe values to pass (URLs, datetimes, drive/path patterns)\n after_eq = stripped.split(\"=\", 1)[1]\n return not PatternUtils.value_is_colon_safe(after_eq)\n\n def _check_reversed_operators(self, line: str, line_number: int) -> str:\n \"\"\"Check for reversed assignment operators and return warning message if found.\"\"\"\n stripped = line.strip()\n\n # Skip if this is not a variable assignment line\n if not re.match(r\"^[A-Za-z_][A-Za-z0-9_]*\\s*=\", stripped):\n return \"\"\n\n # Check for reversed operators: =?, =:, =+\n # Pattern: variable = [space] [?:+] [space or end or value]\n # This handles both \"FOO = ? bar\" and \"FOO =?bar\" cases\n reversed_match = re.search(r\"=\\s*([?:+])(?:\\s|$|[a-zA-Z0-9_])\", stripped)\n if reversed_match:\n reversed_char = reversed_match.group(1)\n correct_operator = f\"{reversed_char}=\"\n reversed_operator = f\"={reversed_char}\"\n\n # Get the variable name for context\n var_match = re.match(r\"^([A-Za-z_][A-Za-z0-9_]*)\", stripped)\n var_name = var_match.group(1) if var_match else \"variable\"\n\n return (\n f\"Line {line_number}: Possible typo in assignment operator '{reversed_operator}' \"\n f\"for variable '{var_name}', did you mean '{correct_operator}'? \"\n f\"Make will treat this as a regular assignment with '{reversed_char}' as part of the value.\"\n )\n\n return \"\"", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 5176}, "tests/test_completions.py::174": {"resolved_imports": ["mbake/cli.py", "mbake/completions.py"], "used_names": ["ShellType", "get_completion_script"], "enclosing_function": "test_stdin_flag_in_completions", "extracted_code": "# Source: mbake/completions.py\nclass ShellType(str, Enum):\n \"\"\"Supported shell types for completion generation.\"\"\"\n\n BASH = \"bash\"\n ZSH = \"zsh\"\n FISH = \"fish\"\n\ndef get_completion_script(shell: ShellType) -> str:\n \"\"\"Get the completion script for the specified shell.\"\"\"\n # Always generate completions for mbake since that's the actual command\n # User aliases will work with mbake completions automatically\n if shell == ShellType.BASH:\n return get_bash_completion(\"mbake\").strip()\n elif shell == ShellType.ZSH:\n return get_zsh_completion(\"mbake\").strip()\n elif shell == ShellType.FISH:\n return get_fish_completion(\"mbake\").strip()\n else:\n raise ValueError(f\"Unsupported shell: {shell}\")", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 746}, "tests/test_bake.py::219": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/continuation.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/target_spacing.py", "mbake/core/rules/whitespace.py"], "used_names": ["PhonyRule"], "enclosing_function": "test_groups_phony_declarations", "extracted_code": "# Source: mbake/core/rules/phony.py\nclass PhonyRule(FormatterPlugin):\n \"\"\"Unified rule for detecting, inserting, and organizing .PHONY declarations.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"phony\", priority=40)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"\n Unified phony rule that:\n 1. Always detects phony targets (for check mode)\n 2. Inserts missing .PHONY declarations (if enabled)\n 3. Adds missing targets to existing .PHONY (if enabled)\n 4. Groups/ungroups based on group_phony_declarations\n \"\"\"\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Get format-disabled line information from context\n disabled_line_indices = context.get(\"disabled_line_indices\", set())\n block_start_index = context.get(\"block_start_index\", 0)\n\n # Always detect phony targets (for check mode)\n detected_targets = PhonyAnalyzer.detect_phony_targets_excluding_conditionals(\n lines, disabled_line_indices, block_start_index\n )\n\n # Check if .PHONY declarations exist\n has_phony = MakefileParser.has_phony_declarations(lines)\n auto_insert_enabled = config.get(\"auto_insert_phony_declarations\", False)\n group_phony = config.get(\"group_phony_declarations\", True)\n\n if not has_phony:\n # No .PHONY exists - insert if enabled\n if not detected_targets:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # In check mode, always report missing declarations\n if check_mode:\n phony_at_top = config.get(\"phony_at_top\", True)\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n ordered_targets = list(detected_targets)\n\n if phony_at_top:\n insert_index = MakefileParser.find_phony_insertion_point(lines)\n line_num = insert_index + 1\n else:\n line_num = 1\n\n if auto_insert_enabled:\n if gnu_format:\n message = f\"{line_num}: Warning: Missing .PHONY declaration for targets: {', '.join(ordered_targets)}\"\n else:\n message = f\"Warning: Missing .PHONY declaration for targets: {', '.join(ordered_targets)} (line {line_num})\"\n else:\n if gnu_format:\n message = f\"{line_num}: Warning: Consider adding .PHONY declaration for targets: {', '.join(ordered_targets)}\"\n else:\n message = f\"Warning: Consider adding .PHONY declaration for targets: {', '.join(ordered_targets)} (line {line_num})\"\n\n check_messages.append(message)\n return FormatResult(\n lines=lines,\n changed=auto_insert_enabled,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Actually insert if enabled\n if not auto_insert_enabled:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Insert declarations\n return self._insert_phony_declarations(\n lines,\n list(detected_targets),\n config,\n errors,\n warnings,\n check_messages,\n )\n\n # .PHONY exists - enhance and organize\n existing_phony_targets = self._extract_phony_targets(lines)\n existing_phony_set = set(existing_phony_targets)\n\n # Find missing targets\n missing_targets = [t for t in detected_targets if t not in existing_phony_set]\n\n # In check mode, report missing targets\n if check_mode and missing_targets:\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n phony_line_num = self._find_first_phony_line(lines)\n\n if auto_insert_enabled:\n if gnu_format:\n message = f\"{phony_line_num}: Warning: Missing targets in .PHONY declaration: {', '.join(missing_targets)}\"\n else:\n message = f\"Warning: Missing targets in .PHONY declaration: {', '.join(missing_targets)} (line {phony_line_num})\"\n else:\n if gnu_format:\n message = f\"{phony_line_num}: Warning: Consider adding targets to .PHONY declaration: {', '.join(missing_targets)}\"\n else:\n message = f\"Warning: Consider adding targets to .PHONY declaration: {', '.join(missing_targets)} (line {phony_line_num})\"\n\n check_messages.append(message)\n\n # Only organize .PHONY declarations (group/ungroup) if auto_insert_phony_declarations is enabled\n if not auto_insert_enabled:\n # If auto-insertion is disabled, don't modify existing .PHONY declarations\n # (but still report missing targets in check mode)\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Organize .PHONY declarations (group/ungroup)\n if group_phony:\n # Group mode: ensure all .PHONY declarations are grouped\n return self._group_phony_declarations(\n lines,\n existing_phony_set | detected_targets,\n missing_targets if auto_insert_enabled else [],\n config,\n check_mode,\n errors,\n warnings,\n check_messages,\n )\n else:\n # Ungroup mode: ensure all .PHONY declarations are individual\n return self._ungroup_phony_declarations(\n lines,\n existing_phony_set | detected_targets,\n missing_targets if auto_insert_enabled else [],\n config,\n check_mode,\n errors,\n warnings,\n check_messages,\n )\n\n def _insert_phony_declarations(\n self,\n lines: list[str],\n target_names: list[str],\n config: dict,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Insert .PHONY declarations for detected targets.\"\"\"\n group_phony = config.get(\"group_phony_declarations\", True)\n phony_at_top = config.get(\"phony_at_top\", True)\n\n if not group_phony:\n # Insert individual declarations before each target\n return self._insert_individual_phony_declarations(\n lines, target_names, config, errors, warnings, check_messages\n )\n\n # Insert grouped declaration\n new_phony_line = f\".PHONY: {' '.join(target_names)}\"\n\n if phony_at_top:\n insert_index = MakefileParser.find_phony_insertion_point(lines)\n formatted_lines = []\n for i, line in enumerate(lines):\n if i == insert_index:\n formatted_lines.append(new_phony_line)\n formatted_lines.append(\"\") # Add blank line after\n formatted_lines.append(line)\n else:\n formatted_lines = [new_phony_line, \"\"] + lines\n\n warnings.append(\n f\"Auto-inserted .PHONY declaration for {len(target_names)} targets: {', '.join(target_names)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=True,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _insert_individual_phony_declarations(\n self,\n lines: list[str],\n target_names: list[str],\n config: dict,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Insert individual .PHONY declarations before each target.\"\"\"\n target_positions = self._find_target_line_positions(lines, target_names)\n\n if not target_positions:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Sort targets by position in reverse order for insertion\n sorted_targets = sorted(\n target_positions.items(), key=lambda x: x[1], reverse=True\n )\n\n formatted_lines = lines[:]\n inserted_targets = []\n\n for target_name, line_index in sorted_targets:\n if not self._has_phony_declaration_nearby(\n formatted_lines, line_index, target_name\n ):\n formatted_lines.insert(line_index, f\".PHONY: {target_name}\")\n inserted_targets.append(target_name)\n\n if inserted_targets:\n warnings.append(\n f\"Auto-inserted individual .PHONY declarations for {len(inserted_targets)} targets: {', '.join(inserted_targets)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=len(inserted_targets) > 0,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _group_phony_declarations(\n self,\n lines: list[str],\n all_phony_targets: set[str],\n new_targets: list[str],\n config: dict,\n check_mode: bool,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Group all .PHONY declarations into a single declaration.\"\"\"\n # Order targets by declaration order\n ordered_targets = self._order_targets_by_declaration(all_phony_targets, lines)\n\n if check_mode:\n # In check mode, only report if there are new targets or if declarations need grouping\n has_multiple_phony = (\n sum(1 for line in lines if line.strip().startswith(\".PHONY:\")) > 1\n )\n changed = len(new_targets) > 0 or has_multiple_phony\n return FormatResult(\n lines=lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Build grouped declaration\n phony_line = f\".PHONY: {' '.join(ordered_targets)}\"\n phony_at_top = config.get(\"phony_at_top\", True)\n\n # Remove all existing .PHONY declarations first\n lines_without_phony = []\n for line in lines:\n if not line.strip().startswith(\".PHONY:\"):\n lines_without_phony.append(line)\n\n # Insert grouped declaration at the appropriate location\n if phony_at_top:\n # Use smart placement (same logic as when inserting new .PHONY)\n insert_index = MakefileParser.find_phony_insertion_point(\n lines_without_phony\n )\n formatted_lines = []\n for i, line in enumerate(lines_without_phony):\n if i == insert_index:\n formatted_lines.append(phony_line)\n formatted_lines.append(\"\") # Add blank line after\n formatted_lines.append(line)\n else:\n # Place at absolute top\n formatted_lines = [phony_line, \"\"] + lines_without_phony\n\n if new_targets:\n warnings.append(\n f\"Added {len(new_targets)} missing targets to .PHONY declaration: {', '.join(new_targets)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=True,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _ungroup_phony_declarations(\n self,\n lines: list[str],\n all_phony_targets: set[str],\n new_targets: list[str],\n config: dict,\n check_mode: bool,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Split grouped .PHONY declarations into individual declarations.\"\"\"\n # Find all .PHONY line indices\n phony_line_indices = []\n for i, line in enumerate(lines):\n if line.strip().startswith(\".PHONY:\"):\n phony_line_indices.append(i)\n\n if not phony_line_indices:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Find target positions\n target_positions: dict[str, int] = {}\n target_pattern = re.compile(r\"^([^:=]+):\")\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n if not stripped or stripped.startswith(\"#\") or line.startswith(\"\\t\"):\n continue\n match = target_pattern.match(stripped)\n if match:\n target_name = match.group(1).strip().split()[0]\n if (\n target_name in all_phony_targets\n and target_name not in target_positions\n ):\n target_positions[target_name] = i\n\n if check_mode:\n # In check mode, report if declarations need splitting\n has_grouped = any(\n len(line.strip()[7:].strip().split()) > 1\n for line in lines\n if line.strip().startswith(\".PHONY:\")\n )\n return FormatResult(\n lines=lines,\n changed=has_grouped or len(new_targets) > 0,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Check if declarations are already individual (not grouped)\n has_grouped_declarations = any(\n len(line.strip()[7:].strip().split()) > 1\n for line in lines\n if line.strip().startswith(\".PHONY:\")\n )\n\n # If already individual and no new targets, no change needed\n if not has_grouped_declarations and not new_targets:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Build new lines with individual declarations\n formatted_lines = []\n skip_indices = set(phony_line_indices)\n insertions: dict[int, str] = {}\n\n for target_name, target_line_index in target_positions.items():\n insertions[target_line_index] = f\".PHONY: {target_name}\"\n\n for i, line in enumerate(lines):\n if i in skip_indices:\n continue\n if i in insertions:\n formatted_lines.append(insertions[i])\n formatted_lines.append(line)\n\n # Only warn if we actually split grouped declarations (not if already individual)\n if has_grouped_declarations:\n warnings.append(\n f\"Split grouped .PHONY declarations into {len(target_positions)} individual declarations\"\n )\n elif new_targets:\n warnings.append(\n f\"Added {len(new_targets)} missing targets to .PHONY declarations: {', '.join(new_targets)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=True,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _extract_phony_targets(self, lines: list[str]) -> list[str]:\n \"\"\"Extract targets from existing .PHONY declarations.\"\"\"\n phony_targets = []\n seen_targets = set()\n\n for line in lines:\n stripped = line.strip()\n if stripped.startswith(\".PHONY:\"):\n content = stripped[7:].strip()\n if content.endswith(\"\\\\\"):\n content = content[:-1].strip()\n targets = [t.strip() for t in content.split() if t.strip()]\n for target in targets:\n if target not in seen_targets:\n phony_targets.append(target)\n seen_targets.add(target)\n\n return phony_targets\n\n def _order_targets_by_declaration(\n self, phony_targets: set[str], lines: list[str]\n ) -> list[str]:\n \"\"\"Order phony targets by their declaration order in the file.\"\"\"\n target_pattern = re.compile(r\"^([^:=]+):\")\n ordered_targets = []\n seen_targets = set()\n\n for line in lines:\n stripped = line.strip()\n if (\n not stripped\n or stripped.startswith(\"#\")\n or line.startswith(\"\\t\")\n or stripped.startswith(\".PHONY:\")\n ):\n continue\n match = target_pattern.match(stripped)\n if match:\n target_name = match.group(1).strip().split()[0]\n if target_name in phony_targets and target_name not in seen_targets:\n ordered_targets.append(target_name)\n seen_targets.add(target_name)\n\n # Add any remaining targets\n for target in phony_targets:\n if target not in seen_targets:\n ordered_targets.append(target)\n\n return ordered_targets\n\n def _find_target_line_positions(\n self, lines: list[str], target_names: list[str]\n ) -> dict[str, int]:\n \"\"\"Find the line index where each target appears.\"\"\"\n target_positions: dict[str, int] = {}\n target_pattern = re.compile(r\"^([^:=]+):(:?)\\s*(.*)$\")\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n if not stripped or stripped.startswith(\"#\") or line.startswith(\"\\t\"):\n continue\n match = target_pattern.match(stripped)\n if match:\n target_list = match.group(1).strip()\n is_double_colon = match.group(2) == \":\"\n target_body = match.group(3).strip()\n\n if is_double_colon or \"%\" in target_list:\n continue\n\n if re.match(r\"^\\s*[A-Z_][A-Z0-9_]*\\s*[+:?]?=\", target_body):\n continue\n\n target_names_on_line = [\n t.strip() for t in target_list.split() if t.strip()\n ]\n for target_name in target_names_on_line:\n if (\n target_name in target_names\n and target_name not in target_positions\n ):\n target_positions[target_name] = i\n\n return target_positions\n\n def _has_phony_declaration_nearby(\n self, lines: list[str], target_line_index: int, target_name: str\n ) -> bool:\n \"\"\"Check if there's already a .PHONY declaration for this target nearby.\"\"\"\n start_check = max(0, target_line_index - 5)\n for i in range(start_check, target_line_index):\n line = lines[i].strip()\n if line.startswith(\".PHONY:\"):\n content = line[7:].strip()\n if content.endswith(\"\\\\\"):\n content = content[:-1].strip()\n targets = [t.strip() for t in content.split() if t.strip()]\n if target_name in targets:\n return True\n return False\n\n def _find_first_phony_line(self, lines: list[str]) -> int:\n \"\"\"Find the line number of the first .PHONY declaration.\"\"\"\n for i, line in enumerate(lines):\n if line.strip().startswith(\".PHONY:\"):\n return i + 1 # 1-indexed\n return 1", "n_imports_parsed": 3, "n_files_resolved": 8, "n_chars_extracted": 20442}, "tests/test_cli.py::103": {"resolved_imports": ["mbake/cli.py", "mbake/config.py"], "used_names": ["app", "patch"], "enclosing_function": "test_format_stdin_cannot_specify_files", "extracted_code": "# Source: mbake/cli.py\napp = typer.Typer(\n name=get_command_name(),\n help=\"Format and lint Makefiles according to best practices.\",\n no_args_is_help=True,\n)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 165}, "tests/test_assignment_alignment.py::178": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["AssignmentAlignmentRule"], "enclosing_function": "test_empty_value_alignment", "extracted_code": "# Source: mbake/core/rules/assignment_alignment.py\nclass AssignmentAlignmentRule(FormatterPlugin):\n \"\"\"Aligns assignment operators (=, :=, +=, ?=, !=) in consecutive variable assignments.\"\"\"\n\n # Pattern to match variable assignments\n # Captures: variable_name, operator, value\n ASSIGNMENT_PATTERN = re.compile(\n r\"^([A-Za-z_][A-Za-z0-9_]*)\\s*(:=|\\+=|\\?=|!=|=)\\s*(.*)\"\n )\n\n def __init__(self) -> None:\n # Run after target_spacing (priority 18) to ensure VPATH normalization works correctly\n super().__init__(\"assignment_alignment\", priority=19)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"Align assignment operators in consecutive blocks of variable assignments.\"\"\"\n align_assignments = config.get(\"align_variable_assignments\", False)\n align_across_comments = config.get(\"align_across_comments\", False)\n\n # If alignment is disabled, return lines unchanged\n if not align_assignments:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=[],\n warnings=[],\n check_messages=[],\n )\n\n formatted_lines = list(lines)\n changed = False\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Find and process assignment blocks\n blocks = self._find_assignment_blocks(lines, align_across_comments)\n\n for block in blocks:\n block_changed = self._align_block(formatted_lines, block)\n if block_changed:\n changed = True\n if check_mode:\n start_line = block[0][\"line_index\"] + 1\n end_line = block[-1][\"line_index\"] + 1\n check_messages.append(\n f\"Lines {start_line}-{end_line}: Variable assignments would be aligned\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _find_assignment_blocks(\n self, lines: list[str], align_across_comments: bool\n ) -> list[list[dict]]:\n \"\"\"Find consecutive blocks of variable assignments.\n\n Args:\n lines: List of lines to analyze\n align_across_comments: If True, include comment lines in blocks\n\n Returns:\n List of blocks, where each block is a list of assignment info dicts\n \"\"\"\n blocks: list[list[dict]] = []\n current_block: list[dict] = []\n in_continuation = False\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n\n # Track line continuations\n if in_continuation:\n if not stripped.endswith(\"\\\\\"):\n in_continuation = False\n continue\n\n # Skip recipe lines (lines starting with tab)\n if line.startswith(\"\\t\"):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track conditional blocks - don't align across them\n if stripped.startswith(\n (\"ifdef\", \"ifndef\", \"ifeq\", \"ifneq\", \"if \", \"else\", \"endif\")\n ):\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Track if we're entering a target (colon without assignment)\n if (\n \":\" in stripped\n and not re.search(r\":=|\\+=|\\?=|!=\", stripped)\n and re.match(r\"^[A-Za-z_][A-Za-z0-9_.-]*\\s*:\", stripped)\n ):\n # It's a target definition, not a URL or path\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle empty lines - they always break blocks\n if not stripped:\n if current_block:\n blocks.append(current_block)\n current_block = []\n continue\n\n # Handle comment lines\n if stripped.startswith(\"#\"):\n if align_across_comments and current_block:\n # Include comment in the block as a pass-through\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": True,\n \"original\": line,\n }\n )\n elif current_block:\n # Comment breaks the block\n blocks.append(current_block)\n current_block = []\n continue\n\n # Check for variable assignment\n match = self.ASSIGNMENT_PATTERN.match(stripped)\n if match:\n var_name = match.group(1)\n operator = match.group(2)\n value = match.group(3)\n\n current_block.append(\n {\n \"line_index\": i,\n \"is_comment\": False,\n \"var_name\": var_name,\n \"operator\": operator,\n \"value\": value,\n \"original\": line,\n }\n )\n\n # Check for line continuation\n if stripped.endswith(\"\\\\\"):\n in_continuation = True\n else:\n # Non-assignment line breaks the block\n if current_block:\n blocks.append(current_block)\n current_block = []\n\n # Don't forget the last block\n if current_block:\n blocks.append(current_block)\n\n # Filter out blocks with fewer than 2 actual assignments\n return [\n block\n for block in blocks\n if sum(1 for item in block if not item.get(\"is_comment\", False)) >= 2\n ]\n\n def _align_block(self, lines: list[str], block: list[dict]) -> bool:\n \"\"\"Align assignment operators in a block.\n\n Args:\n lines: The full list of lines (will be modified in place)\n block: List of assignment info dicts for this block\n\n Returns:\n True if any changes were made\n \"\"\"\n # Find the maximum variable name length (only from actual assignments)\n max_var_len = max(\n len(item[\"var_name\"]) for item in block if not item.get(\"is_comment\", False)\n )\n\n changed = False\n\n for item in block:\n if item.get(\"is_comment\", False):\n # Keep comments as-is\n continue\n\n line_index = item[\"line_index\"]\n var_name = item[\"var_name\"]\n operator = item[\"operator\"]\n value = item[\"value\"]\n\n # Calculate padding needed\n padding = max_var_len - len(var_name)\n\n # Build the aligned line\n if value.strip():\n new_line = f\"{var_name}{' ' * padding} {operator} {value}\"\n else:\n new_line = f\"{var_name}{' ' * padding} {operator}\"\n\n if lines[line_index] != new_line:\n lines[line_index] = new_line\n changed = True\n\n return changed", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 7576}, "tests/test_comprehensive.py::453": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_spacing.py", "mbake/core/rules/conditionals.py", "mbake/core/rules/continuation.py", "mbake/core/rules/pattern_spacing.py", "mbake/core/rules/phony.py", "mbake/core/rules/tabs.py", "mbake/core/rules/whitespace.py"], "used_names": ["PhonyRule"], "enclosing_function": "test_phony_grouping", "extracted_code": "# Source: mbake/core/rules/phony.py\nclass PhonyRule(FormatterPlugin):\n \"\"\"Unified rule for detecting, inserting, and organizing .PHONY declarations.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(\"phony\", priority=40)\n\n def format(\n self, lines: list[str], config: dict, check_mode: bool = False, **context: Any\n ) -> FormatResult:\n \"\"\"\n Unified phony rule that:\n 1. Always detects phony targets (for check mode)\n 2. Inserts missing .PHONY declarations (if enabled)\n 3. Adds missing targets to existing .PHONY (if enabled)\n 4. Groups/ungroups based on group_phony_declarations\n \"\"\"\n errors: list[str] = []\n warnings: list[str] = []\n check_messages: list[str] = []\n\n # Get format-disabled line information from context\n disabled_line_indices = context.get(\"disabled_line_indices\", set())\n block_start_index = context.get(\"block_start_index\", 0)\n\n # Always detect phony targets (for check mode)\n detected_targets = PhonyAnalyzer.detect_phony_targets_excluding_conditionals(\n lines, disabled_line_indices, block_start_index\n )\n\n # Check if .PHONY declarations exist\n has_phony = MakefileParser.has_phony_declarations(lines)\n auto_insert_enabled = config.get(\"auto_insert_phony_declarations\", False)\n group_phony = config.get(\"group_phony_declarations\", True)\n\n if not has_phony:\n # No .PHONY exists - insert if enabled\n if not detected_targets:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # In check mode, always report missing declarations\n if check_mode:\n phony_at_top = config.get(\"phony_at_top\", True)\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n ordered_targets = list(detected_targets)\n\n if phony_at_top:\n insert_index = MakefileParser.find_phony_insertion_point(lines)\n line_num = insert_index + 1\n else:\n line_num = 1\n\n if auto_insert_enabled:\n if gnu_format:\n message = f\"{line_num}: Warning: Missing .PHONY declaration for targets: {', '.join(ordered_targets)}\"\n else:\n message = f\"Warning: Missing .PHONY declaration for targets: {', '.join(ordered_targets)} (line {line_num})\"\n else:\n if gnu_format:\n message = f\"{line_num}: Warning: Consider adding .PHONY declaration for targets: {', '.join(ordered_targets)}\"\n else:\n message = f\"Warning: Consider adding .PHONY declaration for targets: {', '.join(ordered_targets)} (line {line_num})\"\n\n check_messages.append(message)\n return FormatResult(\n lines=lines,\n changed=auto_insert_enabled,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Actually insert if enabled\n if not auto_insert_enabled:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Insert declarations\n return self._insert_phony_declarations(\n lines,\n list(detected_targets),\n config,\n errors,\n warnings,\n check_messages,\n )\n\n # .PHONY exists - enhance and organize\n existing_phony_targets = self._extract_phony_targets(lines)\n existing_phony_set = set(existing_phony_targets)\n\n # Find missing targets\n missing_targets = [t for t in detected_targets if t not in existing_phony_set]\n\n # In check mode, report missing targets\n if check_mode and missing_targets:\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n phony_line_num = self._find_first_phony_line(lines)\n\n if auto_insert_enabled:\n if gnu_format:\n message = f\"{phony_line_num}: Warning: Missing targets in .PHONY declaration: {', '.join(missing_targets)}\"\n else:\n message = f\"Warning: Missing targets in .PHONY declaration: {', '.join(missing_targets)} (line {phony_line_num})\"\n else:\n if gnu_format:\n message = f\"{phony_line_num}: Warning: Consider adding targets to .PHONY declaration: {', '.join(missing_targets)}\"\n else:\n message = f\"Warning: Consider adding targets to .PHONY declaration: {', '.join(missing_targets)} (line {phony_line_num})\"\n\n check_messages.append(message)\n\n # Only organize .PHONY declarations (group/ungroup) if auto_insert_phony_declarations is enabled\n if not auto_insert_enabled:\n # If auto-insertion is disabled, don't modify existing .PHONY declarations\n # (but still report missing targets in check mode)\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Organize .PHONY declarations (group/ungroup)\n if group_phony:\n # Group mode: ensure all .PHONY declarations are grouped\n return self._group_phony_declarations(\n lines,\n existing_phony_set | detected_targets,\n missing_targets if auto_insert_enabled else [],\n config,\n check_mode,\n errors,\n warnings,\n check_messages,\n )\n else:\n # Ungroup mode: ensure all .PHONY declarations are individual\n return self._ungroup_phony_declarations(\n lines,\n existing_phony_set | detected_targets,\n missing_targets if auto_insert_enabled else [],\n config,\n check_mode,\n errors,\n warnings,\n check_messages,\n )\n\n def _insert_phony_declarations(\n self,\n lines: list[str],\n target_names: list[str],\n config: dict,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Insert .PHONY declarations for detected targets.\"\"\"\n group_phony = config.get(\"group_phony_declarations\", True)\n phony_at_top = config.get(\"phony_at_top\", True)\n\n if not group_phony:\n # Insert individual declarations before each target\n return self._insert_individual_phony_declarations(\n lines, target_names, config, errors, warnings, check_messages\n )\n\n # Insert grouped declaration\n new_phony_line = f\".PHONY: {' '.join(target_names)}\"\n\n if phony_at_top:\n insert_index = MakefileParser.find_phony_insertion_point(lines)\n formatted_lines = []\n for i, line in enumerate(lines):\n if i == insert_index:\n formatted_lines.append(new_phony_line)\n formatted_lines.append(\"\") # Add blank line after\n formatted_lines.append(line)\n else:\n formatted_lines = [new_phony_line, \"\"] + lines\n\n warnings.append(\n f\"Auto-inserted .PHONY declaration for {len(target_names)} targets: {', '.join(target_names)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=True,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _insert_individual_phony_declarations(\n self,\n lines: list[str],\n target_names: list[str],\n config: dict,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Insert individual .PHONY declarations before each target.\"\"\"\n target_positions = self._find_target_line_positions(lines, target_names)\n\n if not target_positions:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Sort targets by position in reverse order for insertion\n sorted_targets = sorted(\n target_positions.items(), key=lambda x: x[1], reverse=True\n )\n\n formatted_lines = lines[:]\n inserted_targets = []\n\n for target_name, line_index in sorted_targets:\n if not self._has_phony_declaration_nearby(\n formatted_lines, line_index, target_name\n ):\n formatted_lines.insert(line_index, f\".PHONY: {target_name}\")\n inserted_targets.append(target_name)\n\n if inserted_targets:\n warnings.append(\n f\"Auto-inserted individual .PHONY declarations for {len(inserted_targets)} targets: {', '.join(inserted_targets)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=len(inserted_targets) > 0,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _group_phony_declarations(\n self,\n lines: list[str],\n all_phony_targets: set[str],\n new_targets: list[str],\n config: dict,\n check_mode: bool,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Group all .PHONY declarations into a single declaration.\"\"\"\n # Order targets by declaration order\n ordered_targets = self._order_targets_by_declaration(all_phony_targets, lines)\n\n if check_mode:\n # In check mode, only report if there are new targets or if declarations need grouping\n has_multiple_phony = (\n sum(1 for line in lines if line.strip().startswith(\".PHONY:\")) > 1\n )\n changed = len(new_targets) > 0 or has_multiple_phony\n return FormatResult(\n lines=lines,\n changed=changed,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Build grouped declaration\n phony_line = f\".PHONY: {' '.join(ordered_targets)}\"\n phony_at_top = config.get(\"phony_at_top\", True)\n\n # Remove all existing .PHONY declarations first\n lines_without_phony = []\n for line in lines:\n if not line.strip().startswith(\".PHONY:\"):\n lines_without_phony.append(line)\n\n # Insert grouped declaration at the appropriate location\n if phony_at_top:\n # Use smart placement (same logic as when inserting new .PHONY)\n insert_index = MakefileParser.find_phony_insertion_point(\n lines_without_phony\n )\n formatted_lines = []\n for i, line in enumerate(lines_without_phony):\n if i == insert_index:\n formatted_lines.append(phony_line)\n formatted_lines.append(\"\") # Add blank line after\n formatted_lines.append(line)\n else:\n # Place at absolute top\n formatted_lines = [phony_line, \"\"] + lines_without_phony\n\n if new_targets:\n warnings.append(\n f\"Added {len(new_targets)} missing targets to .PHONY declaration: {', '.join(new_targets)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=True,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _ungroup_phony_declarations(\n self,\n lines: list[str],\n all_phony_targets: set[str],\n new_targets: list[str],\n config: dict,\n check_mode: bool,\n errors: list[str],\n warnings: list[str],\n check_messages: list[str],\n ) -> FormatResult:\n \"\"\"Split grouped .PHONY declarations into individual declarations.\"\"\"\n # Find all .PHONY line indices\n phony_line_indices = []\n for i, line in enumerate(lines):\n if line.strip().startswith(\".PHONY:\"):\n phony_line_indices.append(i)\n\n if not phony_line_indices:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Find target positions\n target_positions: dict[str, int] = {}\n target_pattern = re.compile(r\"^([^:=]+):\")\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n if not stripped or stripped.startswith(\"#\") or line.startswith(\"\\t\"):\n continue\n match = target_pattern.match(stripped)\n if match:\n target_name = match.group(1).strip().split()[0]\n if (\n target_name in all_phony_targets\n and target_name not in target_positions\n ):\n target_positions[target_name] = i\n\n if check_mode:\n # In check mode, report if declarations need splitting\n has_grouped = any(\n len(line.strip()[7:].strip().split()) > 1\n for line in lines\n if line.strip().startswith(\".PHONY:\")\n )\n return FormatResult(\n lines=lines,\n changed=has_grouped or len(new_targets) > 0,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Check if declarations are already individual (not grouped)\n has_grouped_declarations = any(\n len(line.strip()[7:].strip().split()) > 1\n for line in lines\n if line.strip().startswith(\".PHONY:\")\n )\n\n # If already individual and no new targets, no change needed\n if not has_grouped_declarations and not new_targets:\n return FormatResult(\n lines=lines,\n changed=False,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n # Build new lines with individual declarations\n formatted_lines = []\n skip_indices = set(phony_line_indices)\n insertions: dict[int, str] = {}\n\n for target_name, target_line_index in target_positions.items():\n insertions[target_line_index] = f\".PHONY: {target_name}\"\n\n for i, line in enumerate(lines):\n if i in skip_indices:\n continue\n if i in insertions:\n formatted_lines.append(insertions[i])\n formatted_lines.append(line)\n\n # Only warn if we actually split grouped declarations (not if already individual)\n if has_grouped_declarations:\n warnings.append(\n f\"Split grouped .PHONY declarations into {len(target_positions)} individual declarations\"\n )\n elif new_targets:\n warnings.append(\n f\"Added {len(new_targets)} missing targets to .PHONY declarations: {', '.join(new_targets)}\"\n )\n\n return FormatResult(\n lines=formatted_lines,\n changed=True,\n errors=errors,\n warnings=warnings,\n check_messages=check_messages,\n )\n\n def _extract_phony_targets(self, lines: list[str]) -> list[str]:\n \"\"\"Extract targets from existing .PHONY declarations.\"\"\"\n phony_targets = []\n seen_targets = set()\n\n for line in lines:\n stripped = line.strip()\n if stripped.startswith(\".PHONY:\"):\n content = stripped[7:].strip()\n if content.endswith(\"\\\\\"):\n content = content[:-1].strip()\n targets = [t.strip() for t in content.split() if t.strip()]\n for target in targets:\n if target not in seen_targets:\n phony_targets.append(target)\n seen_targets.add(target)\n\n return phony_targets\n\n def _order_targets_by_declaration(\n self, phony_targets: set[str], lines: list[str]\n ) -> list[str]:\n \"\"\"Order phony targets by their declaration order in the file.\"\"\"\n target_pattern = re.compile(r\"^([^:=]+):\")\n ordered_targets = []\n seen_targets = set()\n\n for line in lines:\n stripped = line.strip()\n if (\n not stripped\n or stripped.startswith(\"#\")\n or line.startswith(\"\\t\")\n or stripped.startswith(\".PHONY:\")\n ):\n continue\n match = target_pattern.match(stripped)\n if match:\n target_name = match.group(1).strip().split()[0]\n if target_name in phony_targets and target_name not in seen_targets:\n ordered_targets.append(target_name)\n seen_targets.add(target_name)\n\n # Add any remaining targets\n for target in phony_targets:\n if target not in seen_targets:\n ordered_targets.append(target)\n\n return ordered_targets\n\n def _find_target_line_positions(\n self, lines: list[str], target_names: list[str]\n ) -> dict[str, int]:\n \"\"\"Find the line index where each target appears.\"\"\"\n target_positions: dict[str, int] = {}\n target_pattern = re.compile(r\"^([^:=]+):(:?)\\s*(.*)$\")\n\n for i, line in enumerate(lines):\n stripped = line.strip()\n if not stripped or stripped.startswith(\"#\") or line.startswith(\"\\t\"):\n continue\n match = target_pattern.match(stripped)\n if match:\n target_list = match.group(1).strip()\n is_double_colon = match.group(2) == \":\"\n target_body = match.group(3).strip()\n\n if is_double_colon or \"%\" in target_list:\n continue\n\n if re.match(r\"^\\s*[A-Z_][A-Z0-9_]*\\s*[+:?]?=\", target_body):\n continue\n\n target_names_on_line = [\n t.strip() for t in target_list.split() if t.strip()\n ]\n for target_name in target_names_on_line:\n if (\n target_name in target_names\n and target_name not in target_positions\n ):\n target_positions[target_name] = i\n\n return target_positions\n\n def _has_phony_declaration_nearby(\n self, lines: list[str], target_line_index: int, target_name: str\n ) -> bool:\n \"\"\"Check if there's already a .PHONY declaration for this target nearby.\"\"\"\n start_check = max(0, target_line_index - 5)\n for i in range(start_check, target_line_index):\n line = lines[i].strip()\n if line.startswith(\".PHONY:\"):\n content = line[7:].strip()\n if content.endswith(\"\\\\\"):\n content = content[:-1].strip()\n targets = [t.strip() for t in content.split() if t.strip()]\n if target_name in targets:\n return True\n return False\n\n def _find_first_phony_line(self, lines: list[str]) -> int:\n \"\"\"Find the line number of the first .PHONY declaration.\"\"\"\n for i, line in enumerate(lines):\n if line.strip().startswith(\".PHONY:\"):\n return i + 1 # 1-indexed\n return 1", "n_imports_parsed": 8, "n_files_resolved": 9, "n_chars_extracted": 20442}, "tests/test_assignment_alignment.py::40": {"resolved_imports": ["mbake/config.py", "mbake/core/formatter.py", "mbake/core/rules/assignment_alignment.py"], "used_names": ["MakefileFormatter"], "enclosing_function": "test_alignment_disabled_by_default", "extracted_code": "# Source: mbake/core/formatter.py\nclass MakefileFormatter:\n \"\"\"Main formatter class that applies all formatting rules.\"\"\"\n\n def __init__(self, config: Config):\n \"\"\"Initialize formatter with configuration.\"\"\"\n self.config = config\n self.format_disable_handler = FormatDisableHandler()\n\n # Complete rule system with all formatting rules\n self.rules: list[FormatterPlugin] = [\n # Rule type detection (run first)\n RuleTypeDetectionRule(), # Detect rule types\n # Error detection rules\n DuplicateTargetRule(), # Detect duplicate targets\n TargetValidationRule(), # Validate target syntax\n RecipeValidationRule(), # Validate recipe syntax\n SpecialTargetValidationRule(), # Validate special targets\n SuffixValidationRule(), # Validate suffix rules\n # Basic formatting rules\n WhitespaceRule(), # Clean up whitespace\n TabsRule(), # Ensure proper recipe tabs\n ShellFormattingRule(), # Format shell commands\n AssignmentSpacingRule(), # Format variable assignments\n AssignmentAlignmentRule(), # Align variable assignments\n TargetSpacingRule(), # Format target lines\n PatternSpacingRule(), # Format pattern rules\n # PHONY-related rules\n PhonyRule(), # Unified: detect, insert, and organize .PHONY\n # Advanced rules\n ContinuationRule(), # Handle line continuations\n ConditionalRule(), # Format conditionals\n # Final cleanup\n FinalNewlineRule(), # Ensure final newline\n ]\n\n # Sort rules by priority\n self.rules.sort(key=lambda rule: rule.priority)\n\n def register_rule(self, rule: FormatterPlugin) -> None:\n \"\"\"Register a custom formatting rule.\"\"\"\n self.rules.append(rule)\n self.rules.sort()\n logger.info(f\"Registered custom rule: {rule.name}\")\n\n def format_file(\n self, file_path: Path, check_only: bool = False\n ) -> tuple[bool, list[str], list[str]]:\n \"\"\"Format a Makefile.\n\n Args:\n file_path: Path to the Makefile\n check_only: If True, only check formatting without modifying\n\n Returns:\n tuple of (changed, errors, warnings)\n \"\"\"\n if not file_path.exists():\n return False, [f\"File not found: {file_path}\"], []\n\n try:\n # Read file\n with open(file_path, encoding=\"utf-8\") as f:\n original_content = f.read()\n\n # Split into lines, preserving line endings\n lines = original_content.splitlines()\n\n # Apply formatting\n formatted_lines, errors, warnings = self.format_lines(\n lines, check_only, original_content\n )\n\n # Check if content changed\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Find disabled regions to check if content is mostly disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(lines)\n\n # Check if the file is mostly or entirely in disabled regions\n total_lines = len(lines)\n disabled_line_count = 0\n for region in disabled_regions:\n disabled_line_count += region.end_line - region.start_line\n\n # If most content is disabled, preserve original newline behavior\n mostly_disabled = disabled_line_count >= (\n total_lines - 1\n ) # -1 to account for the format disable comment itself\n\n # Only add final newline if ensure_final_newline is true AND content isn't mostly disabled\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n and not mostly_disabled\n )\n\n if should_add_newline and formatted_lines:\n formatted_content += \"\\n\"\n elif mostly_disabled:\n # For mostly disabled files, preserve original newline behavior exactly\n original_ends_with_newline = original_content.endswith(\"\\n\")\n if original_ends_with_newline and not formatted_content.endswith(\"\\n\"):\n formatted_content += \"\\n\"\n\n changed = formatted_content != original_content\n\n if check_only:\n return changed, errors, warnings\n\n if changed:\n # Write formatted content back\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(formatted_content)\n\n if self.config.verbose:\n logger.info(f\"Formatted {file_path}\")\n else:\n if self.config.verbose:\n logger.info(f\"No changes needed for {file_path}\")\n\n return changed, errors, warnings\n\n except Exception as e:\n error_msg = f\"Error processing {file_path}: {e}\"\n logger.error(error_msg)\n return False, [error_msg], []\n\n def format_lines(\n self,\n lines: Sequence[str],\n check_only: bool = False,\n original_content: Union[str, None] = None,\n ) -> tuple[list[str], list[str], list[str]]:\n \"\"\"Format makefile lines and return formatted lines and errors.\"\"\"\n # Convert to list for easier manipulation\n original_lines = list(lines)\n\n # Find regions where formatting is disabled\n disabled_regions = self.format_disable_handler.find_disabled_regions(\n original_lines\n )\n\n config_dict = self.config.to_dict()[\"formatter\"]\n config_dict[\"_global\"] = {\n \"gnu_error_format\": self.config.gnu_error_format,\n \"wrap_error_messages\": self.config.wrap_error_messages,\n }\n\n context: dict[str, Any] = {}\n if original_content is not None:\n context[\"original_content_ends_with_newline\"] = original_content.endswith(\n \"\\n\"\n )\n context[\"original_line_count\"] = len(lines)\n\n # Simplified formatting - apply rules directly to lines\n formatted_lines = original_lines.copy()\n all_errors = []\n all_warnings = []\n all_check_messages = []\n\n # Apply formatting rules in priority order\n for rule in self.rules:\n if self.config.debug:\n logger.debug(f\"Applying rule: {rule.name}\")\n\n try:\n # Handle format disable regions\n if disabled_regions:\n # Only format lines not in disabled regions\n lines_to_format = []\n line_mapping = {}\n\n for i, line in enumerate(formatted_lines):\n if not self._is_line_disabled(i, disabled_regions):\n lines_to_format.append(line)\n line_mapping[len(lines_to_format) - 1] = i\n\n if lines_to_format:\n result = rule.format(\n lines_to_format, config_dict, check_only, **context\n )\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n # Merge formatted lines back\n for formatted_index, original_index in line_mapping.items():\n if formatted_index < len(result.lines):\n formatted_lines[original_index] = result.lines[\n formatted_index\n ]\n else:\n # No disabled regions, format normally\n result = rule.format(\n formatted_lines, config_dict, check_only, **context\n )\n formatted_lines = result.lines\n\n # Process errors, warnings, and check messages\n for error in result.errors:\n formatted_error = self._format_error(error, 0, config_dict)\n all_errors.append(formatted_error)\n\n for warning in result.warnings:\n all_warnings.append(warning)\n\n # In check mode, also collect check_messages\n if check_only:\n for check_msg in result.check_messages:\n all_check_messages.append(check_msg)\n\n except Exception as e:\n error_msg = f\"Error in rule {rule.name}: {e}\"\n logger.error(error_msg)\n all_errors.append(error_msg)\n\n # In check mode, merge check_messages into warnings for display\n if check_only and all_check_messages:\n all_warnings.extend(all_check_messages)\n\n return formatted_lines, all_errors, all_warnings\n\n def _is_line_disabled(\n self, line_index: int, disabled_regions: list[FormatRegion]\n ) -> bool:\n \"\"\"Check if a line is in a disabled region.\"\"\"\n for region in disabled_regions:\n if region.start_line <= line_index < region.end_line:\n return True\n return False\n\n def _format_error(self, message: str, line_num: int, config: dict) -> str:\n \"\"\"Format an error message with consistent GNU or traditional format.\"\"\"\n # Check if message is already formatted (has line number at start)\n import re\n\n if re.match(r\"^(\\d+|Makefile:\\d+):\\s*(Warning|Error):\", message):\n # Message is already formatted, return as-is\n return message\n\n gnu_format = config.get(\"_global\", {}).get(\"gnu_error_format\", True)\n\n if gnu_format:\n return f\"{line_num}: Error: {message}\"\n else:\n return f\"Error: {message} (line {line_num})\"\n\n def _final_cleanup(self, lines: list[str], config: dict) -> list[str]:\n \"\"\"Apply final cleanup steps.\"\"\"\n if not lines:\n return lines\n\n cleaned_lines = []\n\n # Normalize empty lines\n if config.get(\"normalize_empty_lines\", True):\n max_empty = config.get(\"max_consecutive_empty_lines\", 2)\n empty_count = 0\n\n for line in lines:\n if line.strip() == \"\":\n empty_count += 1\n if empty_count <= max_empty:\n cleaned_lines.append(line)\n else:\n empty_count = 0\n cleaned_lines.append(line)\n else:\n cleaned_lines = lines\n\n # Remove trailing empty lines at end of file\n while cleaned_lines and cleaned_lines[-1].strip() == \"\":\n cleaned_lines.pop()\n\n return cleaned_lines\n\n def validate_file(self, file_path: Path) -> list[str]:\n \"\"\"Validate a Makefile against formatting rules.\n\n Args:\n file_path: Path to the Makefile\n\n Returns:\n List of validation errors\n \"\"\"\n if not file_path.exists():\n return [f\"File not found: {file_path}\"]\n\n try:\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n return self.validate_lines(lines)\n\n except Exception as e:\n return [f\"Error reading {file_path}: {e}\"]\n\n def validate_lines(self, lines: Sequence[str]) -> list[str]:\n \"\"\"Validate lines against formatting rules.\n\n Args:\n lines: Sequence of lines to validate\n\n Returns:\n List of validation errors\n \"\"\"\n all_errors = []\n config_dict = self.config.to_dict()[\"formatter\"]\n lines_list = list(lines)\n\n for rule in self.rules:\n try:\n errors = rule.validate(lines_list, config_dict)\n all_errors.extend(errors)\n except Exception as e:\n all_errors.append(f\"Error in rule {rule.name}: {e}\")\n\n return all_errors\n\n def format(self, content: str) -> FormatterResult:\n \"\"\"Format content string and return result.\n\n Args:\n content: Makefile content as string\n\n Returns:\n FormatterResult with formatted content\n \"\"\"\n lines = content.splitlines()\n formatted_lines, errors, warnings = self.format_lines(lines, check_only=False)\n\n # Join lines back to content\n formatted_content = \"\\n\".join(formatted_lines)\n\n # Only add final newline if ensure_final_newline is true AND\n # the final line is not a format disable comment (which should be preserved exactly)\n should_add_newline = (\n self.config.formatter.ensure_final_newline\n and not formatted_content.endswith(\"\\n\")\n )\n\n if should_add_newline and formatted_lines:\n # Check if the final line is a format disable comment\n final_line = formatted_lines[-1]\n if self.format_disable_handler.is_format_disabled_line(final_line):\n # For format disable comments, preserve original file's newline behavior\n original_ends_with_newline = content.endswith(\"\\n\")\n if original_ends_with_newline:\n formatted_content += \"\\n\"\n else:\n # Regular line, apply ensure_final_newline setting\n formatted_content += \"\\n\"\n\n changed = formatted_content != content\n\n return FormatterResult(\n content=formatted_content, changed=changed, errors=errors, warnings=warnings\n )\n\n def _sort_errors_by_line_number(self, errors: list[str]) -> list[str]:\n \"\"\"Sort errors by line number for consistent reporting.\"\"\"\n\n def extract_line_number(error: str) -> int:\n try:\n # Extract line number from format \"filename:line: Error: ...\" or \"line: Error: ...\"\n if \":\" in error:\n parts = error.split(\":\")\n for part in parts:\n if part.strip().isdigit():\n return int(part.strip())\n return 0 # Default if no line number found\n except (ValueError, IndexError):\n return 0\n\n return sorted(errors, key=extract_line_number)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 14932}}}