Apply patches to file contents and return modified contents.
(contents: str, patches: Patches)
| 348 | |
| 349 | |
| 350 | def apply_patches(contents: str, patches: Patches) -> str: |
| 351 | """Apply patches to file contents and return modified contents.""" |
| 352 | tree = ast.parse(contents) |
| 353 | lines = contents.splitlines() |
| 354 | |
| 355 | modifications = list(_iter_patch_lines(tree, patches)) |
| 356 | |
| 357 | # If we have modifications and unittest is not imported, add it |
| 358 | if modifications and not _has_unittest_import(tree): |
| 359 | import_line = _find_import_insert_line(tree) |
| 360 | modifications.append( |
| 361 | ( |
| 362 | import_line, |
| 363 | "\nimport unittest # XXX: RUSTPYTHON; importing to be able to skip tests", |
| 364 | ) |
| 365 | ) |
| 366 | |
| 367 | # Going in reverse to not disrupt the line offset |
| 368 | for lineno, patch in sorted(modifications, reverse=True): |
| 369 | lines.insert(lineno, patch) |
| 370 | |
| 371 | joined = "\n".join(lines) |
| 372 | return f"{joined}\n" |
| 373 | |
| 374 | |
| 375 | def patches_to_json(patches: Patches) -> dict: |