Add the include to the file. Returns True if file was modified (or would be modified in dry-run).
(file_path: Path, include_path: str, dry_run: bool = True)
| 160 | |
| 161 | |
| 162 | def add_include(file_path: Path, include_path: str, dry_run: bool = True) -> bool: |
| 163 | """ |
| 164 | Add the include to the file. |
| 165 | |
| 166 | Returns True if file was modified (or would be modified in dry-run). |
| 167 | """ |
| 168 | try: |
| 169 | content = file_path.read_text(encoding="utf-8", errors="ignore") |
| 170 | |
| 171 | # Find insertion point |
| 172 | line_num, indent = find_insertion_point(content) |
| 173 | |
| 174 | # Build the include line |
| 175 | include_line = f'{indent}#include "{include_path}" // IWYU pragma: keep\n' |
| 176 | |
| 177 | # Insert the include |
| 178 | lines = content.splitlines(keepends=True) |
| 179 | |
| 180 | # If inserting at line_num, we want to add BEFORE that line |
| 181 | # But we want to add after header guard and before other includes |
| 182 | # So we need to add a blank line after the include if there isn't one |
| 183 | |
| 184 | if line_num < len(lines): |
| 185 | # Insert before line_num |
| 186 | new_lines = lines[:line_num] + [include_line, "\n"] + lines[line_num:] |
| 187 | else: |
| 188 | # Append at end |
| 189 | new_lines = lines + ["\n", include_line, "\n"] |
| 190 | |
| 191 | new_content = "".join(new_lines) |
| 192 | |
| 193 | if dry_run: |
| 194 | print(f" Would add include at line {line_num + 1}") |
| 195 | return True |
| 196 | else: |
| 197 | file_path.write_text(new_content, encoding="utf-8") |
| 198 | print(f" ✓ Added include at line {line_num + 1}") |
| 199 | return True |
| 200 | |
| 201 | except KeyboardInterrupt: |
| 202 | _thread.interrupt_main() |
| 203 | raise |
| 204 | except Exception as e: |
| 205 | print(f" ✗ Error modifying file: {e}", file=sys.stderr) |
| 206 | return False |
| 207 | |
| 208 | |
| 209 | def main(): |
no test coverage detected