|
3 | 3 | from pathlib import Path |
4 | 4 |
|
5 | 5 | from cedarscript_ast_parser import Command, RmFileCommand, MvFileCommand, UpdateCommand, \ |
6 | | - SelectCommand, IdentifierFromFile, Segment, Marker, MoveClause, DeleteClause, \ |
| 6 | + SelectCommand, CreateCommand, IdentifierFromFile, Segment, Marker, MoveClause, DeleteClause, \ |
7 | 7 | InsertClause, ReplaceClause, EditingAction, BodyOrWhole, RegionClause, MarkerType |
8 | 8 | from cedarscript_ast_parser.cedarscript_ast_parser import MarkerCompatible, RelativeMarker, \ |
9 | 9 | RelativePositionType |
@@ -78,8 +78,8 @@ def apply_commands(self, commands: Sequence[Command]): |
78 | 78 | match command: |
79 | 79 | case UpdateCommand() as cmd: |
80 | 80 | result.append(self._update_command(cmd)) |
81 | | - # case CreateCommand() as cmd: |
82 | | - # result.append(self._create_command(cmd)) |
| 81 | + case CreateCommand() as cmd: |
| 82 | + result.append(self._create_command(cmd)) |
83 | 83 | case RmFileCommand() as cmd: |
84 | 84 | result.append(self._rm_command(cmd)) |
85 | 85 | case MvFileCommand(): |
@@ -255,14 +255,33 @@ def _rm_command(self, cmd: RmFileCommand): |
255 | 255 | def _delete_function(self, cmd): # TODO |
256 | 256 | file_path = os.path.join(self.root_path, cmd.file_path) |
257 | 257 |
|
258 | | - def _create_command(self, cmd: CreateCommand): |
259 | | - file_path = os.path.join(self.root_path, cmd.file_path) |
| 258 | + def _create_command(self, cmd: CreateCommand) -> str: |
| 259 | + """Handle the CREATE command to create new files with content. |
| 260 | + |
| 261 | + Args: |
| 262 | + cmd: The CreateCommand instance containing file_path and content |
260 | 263 | |
261 | | - os.makedirs(os.path.dirname(file_path), exist_ok=True) |
262 | | - with open(file_path, 'w') as file: |
263 | | - file.write(cmd.content) |
| 264 | + Returns: |
| 265 | + str: A message describing the result |
264 | 266 | |
265 | | - return f"Created file: {cmd.file_path}" |
| 267 | + Raises: |
| 268 | + ValueError: If the file already exists |
| 269 | + """ |
| 270 | + file_path = os.path.join(self.root_path, cmd.file_path) |
| 271 | + |
| 272 | + if os.path.exists(file_path): |
| 273 | + raise ValueError(f"File already exists: {cmd.file_path}") |
| 274 | + |
| 275 | + os.makedirs(os.path.dirname(file_path), exist_ok=True) |
| 276 | + |
| 277 | + content = cmd.content |
| 278 | + if isinstance(content, (list, tuple)): |
| 279 | + content = '\n'.join(content) |
| 280 | + |
| 281 | + # Process relative indentation in content |
| 282 | + write_file(file_path, IndentationInfo.default().apply_relative_indents(content)) |
| 283 | + |
| 284 | + return f"Created file: {cmd.file_path}" |
266 | 285 |
|
267 | 286 |
|
268 | 287 | def find_index_range_for_region(region: BodyOrWhole | Marker | Segment | RelativeMarker, |
|
0 commit comments