|
| 1 | +import os |
| 2 | +from abc import ABC, abstractmethod |
| 3 | + |
| 4 | +from cedarscript_ast_parser import Command, CreateCommand, RmFileCommand, MvFileCommand, UpdateCommand, \ |
| 5 | + SelectCommand, IdentifierFromFile, SingleFileClause, Segment, Marker, MoveClause, DeleteClause, \ |
| 6 | + InsertClause, ReplaceClause, EditingAction, Region, BodyOrWhole, WhereClause, RegionClause |
| 7 | +from .text_editor_kit import \ |
| 8 | + normalize_indent, write_file, read_file, bow_to_search_range, \ |
| 9 | + FunctionBoundaries, SearchRange, analyze_indentation, IndentationInfo |
| 10 | + |
| 11 | +class CedarEditorException(Exception): |
| 12 | + def __init__(self, command_ordinal: int, description: str): |
| 13 | + match command_ordinal: |
| 14 | + case 0 | 1: |
| 15 | + items = '' |
| 16 | + case 2: |
| 17 | + items = "#1" |
| 18 | + case 3: |
| 19 | + items = "#1 and #2" |
| 20 | + case _: |
| 21 | + sequence = ", ".join(f'#{i}' for i in range(1, command_ordinal - 1)) |
| 22 | + items = f"{sequence} and #{command_ordinal - 1}" |
| 23 | + if command_ordinal <= 1: |
| 24 | + note = '' |
| 25 | + plural_indicator='' |
| 26 | + previous_cmd_notes = '' |
| 27 | + else: |
| 28 | + |
| 29 | + plural_indicator='s' |
| 30 | + previous_cmd_notes = f", bearing in mind the file was updated and now contains all changes expressed in command{plural_indicator} {items}" |
| 31 | + if 'syntax' in description.casefold(): |
| 32 | + probability_indicator = "most probably" |
| 33 | + else: |
| 34 | + probability_indicator= "might have" |
| 35 | + |
| 36 | + note = ( |
| 37 | + f"<note>*ALL* commands *before* command #{command_ordinal} were applied and *their changes are already committed*. " |
| 38 | + f"Re-read the file to catch up with the applied changes." |
| 39 | + f"ATTENTION: The previous command (#{command_ordinal - 1}) {probability_indicator} caused command #{command_ordinal} to fail " |
| 40 | + f"due to changes that left the file in an invalid state (check that by re-analyzing the file!)</note>" |
| 41 | + ) |
| 42 | + super().__init__( |
| 43 | + f"<error-details><error-location>COMMAND #{command_ordinal}</error-location>{note}" |
| 44 | + f"<description>{description}</description>" |
| 45 | + "<suggestion>NEVER apologize; just relax, take a deep breath, think step-by-step and write an in-depth analysis of what went wrong " |
| 46 | + "(specifying which command ordinal failed), then acknowledge which commands were already applied and concisely describe the state at which the file was left " |
| 47 | + "(saying what needs to be done now), " |
| 48 | + f"then write new commands that will fix the problem{previous_cmd_notes} " |
| 49 | + "(you'll get a one-million dollar tip if you get it right!) " |
| 50 | + "Use descriptive comment before each command.</suggestion></error-details>" |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +class CedarEditorBase(ABC): |
| 55 | + def __init__(self, root_path): |
| 56 | + self.root_path = os.path.abspath(root_path) |
| 57 | + print(f'[{self.__class__}] root: {self.root_path}') |
| 58 | + |
| 59 | + # TODO Add search_range: SearchRange parameter |
| 60 | + def find_function(self, source: str | list[str], file_name: str, function_name: str, offset: int | None = None) -> FunctionBoundaries: |
| 61 | + if not isinstance(source, str): |
| 62 | + source = '\n'.join(source) |
| 63 | + return self._find_function(source, file_name, function_name, offset) |
| 64 | + |
| 65 | + @abstractmethod |
| 66 | + def _find_function(self, source: str, file_name: str, function_name: str, offset: int | None = None) -> FunctionBoundaries | None: |
| 67 | + pass |
| 68 | + |
| 69 | + def apply_commands(self, commands: list[Command]): |
| 70 | + result = [] |
| 71 | + for i, command in enumerate(commands): |
| 72 | + try: |
| 73 | + match command: |
| 74 | + case UpdateCommand() as cmd: |
| 75 | + result.append(self._update_command(cmd)) |
| 76 | + case CreateCommand() as cmd: |
| 77 | + result.append(self._create_command(cmd)) |
| 78 | + case RmFileCommand() as cmd: |
| 79 | + result.append(self._rm_command(cmd)) |
| 80 | + case MvFileCommand() as cmd: |
| 81 | + raise ValueError('Noy implemented: MV') |
| 82 | + case SelectCommand() as cmd: |
| 83 | + raise ValueError('Noy implemented: SELECT') |
| 84 | + case _ as invalid: |
| 85 | + raise ValueError(f"Unknown command '{type(invalid)}'") |
| 86 | + except Exception as e: |
| 87 | + print(f'[apply_commands] (command #{i+1}) Failed: {command}') |
| 88 | + if isinstance(command, UpdateCommand): |
| 89 | + print(f'CMD CONTENT: ***{command.content}***') |
| 90 | + raise CedarEditorException(i+1, str(e)) from e |
| 91 | + return result |
| 92 | + |
| 93 | + def _update_command(self, cmd: UpdateCommand): |
| 94 | + file_path = os.path.join(self.root_path, cmd.target.file_path) |
| 95 | + content = cmd.content or [] |
| 96 | + |
| 97 | + match cmd.target: |
| 98 | + |
| 99 | + case IdentifierFromFile( |
| 100 | + identifier_type='FUNCTION', where_clause=WhereClause(field='NAME', operator='=', value=function_name) |
| 101 | + ): |
| 102 | + try: |
| 103 | + return self._update_content(file_path, cmd.action, content, function_name=function_name, offset = cmd.target.offset) |
| 104 | + except IOError as e: |
| 105 | + msg = f"function `{function_name}` in `{cmd.target.file_path}`" |
| 106 | + raise IOError(f"Error updating {msg}: {e}") |
| 107 | + |
| 108 | + case SingleFileClause(): |
| 109 | + try: |
| 110 | + return self._update_content(file_path, cmd.action, content) |
| 111 | + except IOError as e: |
| 112 | + msg = f"file `{cmd.target.file_path}`" |
| 113 | + raise IOError(f"Error updating {msg}: {e}") |
| 114 | + |
| 115 | + case _ as invalid: |
| 116 | + raise ValueError(f"Not implemented: {invalid}") |
| 117 | + |
| 118 | + def _update_content(self, file_path: str, action: EditingAction, content: str | None, |
| 119 | + search_range: SearchRange | None = None, function_name: str | None = None, offset: int | None = None) -> str: |
| 120 | + src = read_file(file_path) |
| 121 | + lines = src.splitlines() |
| 122 | + |
| 123 | + if function_name: |
| 124 | + function_boundaries = self.find_function(src, file_path, function_name, offset) |
| 125 | + if not function_boundaries: |
| 126 | + raise ValueError(f"Function '{function_name}' not found in {file_path}") |
| 127 | + if search_range: |
| 128 | + print(f'Discarding search range to use function range...') |
| 129 | + search_range = _get_index_range(action, lines, function_boundaries) |
| 130 | + else: |
| 131 | + search_range = _get_index_range(action, lines) |
| 132 | + |
| 133 | + self._apply_action(action, lines, search_range, content) |
| 134 | + |
| 135 | + write_file(file_path, lines) |
| 136 | + |
| 137 | + return f"Updated {'function ' + function_name if function_name else 'file'} in {file_path}\n -> {action}" |
| 138 | + |
| 139 | + def _apply_action(self, action: EditingAction, lines: list[str], search_range: SearchRange, content: str | None = None): |
| 140 | + index_start, index_end, reference_indent = search_range |
| 141 | + |
| 142 | + match action: |
| 143 | + |
| 144 | + case MoveClause(insert_position=insert_position, to_other_file=other_file, relative_indentation=relindent): |
| 145 | + saved_content = lines[index_start:index_end] |
| 146 | + lines[index_start:index_end] = [] |
| 147 | + # TODO Move from 'lines' to the same file or to 'other_file' |
| 148 | + dest_range = _get_index_range(InsertClause(insert_position), lines) |
| 149 | + indentation_info: IndentationInfo = analyze_indentation(saved_content) |
| 150 | + lines[dest_range.start:dest_range.end] = indentation_info.adjust_indentation(saved_content, dest_range.indent + (relindent or 0)) |
| 151 | + |
| 152 | + case DeleteClause(): |
| 153 | + lines[index_start:index_end] = [] |
| 154 | + |
| 155 | + case ReplaceClause() | InsertClause(): |
| 156 | + indentation_info: IndentationInfo = analyze_indentation(lines) |
| 157 | + lines[index_start:index_end] = normalize_indent(content, reference_indent, indentation_info) |
| 158 | + |
| 159 | + case _ as invalid: |
| 160 | + raise ValueError(f"Unsupported action type: {type(invalid)}") |
| 161 | + |
| 162 | + def _rm_command(self, cmd: RmFileCommand): |
| 163 | + file_path = os.path.join(self.root_path, cmd.file_path) |
| 164 | + |
| 165 | + def _delete_function(self, cmd): # TODO |
| 166 | + file_path = os.path.join(self.root_path, cmd.file_path) |
| 167 | + |
| 168 | + # def _create_command(self, cmd: CreateCommand): |
| 169 | + # file_path = os.path.join(self.root_path, cmd.file_path) |
| 170 | + # |
| 171 | + # os.makedirs(os.path.dirname(file_path), exist_ok=False) |
| 172 | + # with open(file_path, 'w') as file: |
| 173 | + # file.write(content) |
| 174 | + # |
| 175 | + # return f"Created file: {command['file']}" |
| 176 | + |
| 177 | + |
| 178 | +def _get_index_range(action: EditingAction, lines: list[str], search_range: SearchRange | FunctionBoundaries | None = None) -> SearchRange: |
| 179 | + match action: |
| 180 | + case RegionClause(region=r) | InsertClause(insert_position=r): |
| 181 | + return find_index_range_for_region(r, lines, search_range) |
| 182 | + case _ as invalid: |
| 183 | + raise ValueError(f"Unsupported action type: {type(invalid)}") |
| 184 | + |
| 185 | +def find_index_range_for_region(region: Region, lines: list[str], search_range: SearchRange | FunctionBoundaries | None = None) -> SearchRange: |
| 186 | + match region: |
| 187 | + case BodyOrWhole() as bow: |
| 188 | + # TODO Set indent char count |
| 189 | + index_range = bow_to_search_range(bow, search_range) |
| 190 | + case Marker() | Segment() as mos: |
| 191 | + if isinstance(search_range, FunctionBoundaries): |
| 192 | + search_range = search_range.whole |
| 193 | + index_range = mos.marker_or_segment_to_index_range( |
| 194 | + lines, |
| 195 | + search_range.start if search_range else 0, |
| 196 | + search_range.end if search_range else -1, |
| 197 | + ) |
| 198 | + case _ as invalid: |
| 199 | + raise ValueError(f"Invalid: {invalid}") |
| 200 | + return index_range |
0 commit comments