(code: str, new_class_def: str)
| 89 | |
| 90 | |
| 91 | def replace_base_class(code: str, new_class_def: str) -> str: |
| 92 | lines = code.splitlines(keepends=True) |
| 93 | class_start = None |
| 94 | class_end = None |
| 95 | |
| 96 | # Find the start line of class TeachingScene(Scene): |
| 97 | for i, line in enumerate(lines): |
| 98 | if re.match(r"^\s*class\s+TeachingScene\s*\(Scene\)\s*:", line): |
| 99 | class_start = i |
| 100 | break |
| 101 | |
| 102 | if class_start is not None: |
| 103 | # Find the end line of the class definition |
| 104 | # The class ends when a line with the same or less indentation is found |
| 105 | base_indent = len(lines[class_start]) - len(lines[class_start].lstrip()) |
| 106 | class_end = class_start + 1 |
| 107 | while class_end < len(lines): |
| 108 | line = lines[class_end] |
| 109 | # If an empty line or a line with less indentation is found, |
| 110 | # it means the class definition has ended |
| 111 | if line.strip() != "" and (len(line) - len(line.lstrip()) <= base_indent): |
| 112 | break |
| 113 | class_end += 1 |
| 114 | |
| 115 | # Replace the original TeachingScene definition with the new one |
| 116 | new_block = new_class_def.strip() + "\n\n" |
| 117 | return "".join(lines[:class_start]) + new_block + "".join(lines[class_end:]) |
| 118 | else: |
| 119 | # If TeachingScene does not exist, it should be inserted before the first class definition |
| 120 | for i, line in enumerate(lines): |
| 121 | if re.match(r"^\s*class\s+\w+", line): |
| 122 | insert_pos = i |
| 123 | break |
| 124 | else: |
| 125 | insert_pos = 0 |
| 126 | |
| 127 | new_block = new_class_def.strip() + "\n\n" |
| 128 | return "".join(lines[:insert_pos]) + new_block + "".join(lines[insert_pos:]) |
| 129 | |
| 130 | |
| 131 | # Save the program to the.py file |
no outgoing calls
no test coverage detected