MCPcopy Create free account
hub / github.com/modelscope/ms-agent / replace_file_lines

Method replace_file_lines

ms_agent/tools/filesystem_tool.py:554–633  ·  view source on GitHub ↗

Replace specific line ranges in a file. Args: path(str): The relative file path to modify, a prefix dir will be automatically concatenated. content(str): The new content to insert/replace start_line(int): Start line number (1-based, inclusive). Use 0 to i

(self,
                                 path: str,
                                 content: str,
                                 start_line: int,
                                 end_line: int = None)

Source from the content-addressed store, hash-verified

552 return f'Replace content in file <{path}> failed, error: ' + str(e)
553
554 async def replace_file_lines(self,
555 path: str,
556 content: str,
557 start_line: int,
558 end_line: int = None):
559 """Replace specific line ranges in a file.
560
561 Args:
562 path(str): The relative file path to modify, a prefix dir will be automatically concatenated.
563 content(str): The new content to insert/replace
564 start_line(int): Start line number (1-based, inclusive). Use 0 to insert at beginning, -1 to append at end
565 end_line(int): End line number (1-based, inclusive). Optional for start_line=0 or -1
566
567 Returns:
568 Success or error message.
569 """
570 try:
571 target_path_real = self.get_real_path(path)
572 if target_path_real is None:
573 return f'<{path}> is out of the valid project path: {self.output_dir}'
574 file_path = target_path_real
575 # Read existing file content
576 if os.path.exists(file_path):
577 with open(file_path, 'r', encoding='utf-8') as f:
578 lines = f.readlines()
579 else:
580 # If file doesn't exist, create it
581 dirname = os.path.dirname(file_path)
582 if dirname:
583 os.makedirs(dirname, exist_ok=True)
584 lines = []
585
586 total_lines = len(lines)
587
588 # Ensure content ends with newline if it doesn't already
589 if content and not content.endswith('\n'):
590 content += '\n'
591
592 # Handle special cases
593 if start_line == 0:
594 # Insert at beginning
595 new_lines = [content] + lines
596 operation = 'Inserted at beginning'
597 elif start_line == -1:
598 # Append at end
599 new_lines = lines + [content]
600 operation = 'Appended at end'
601 else:
602 # Replace range (1-based, inclusive)
603 if end_line is None:
604 return 'Error: end_line is required when start_line is not 0 or -1'
605
606 if start_line < 1 or start_line > total_lines + 1:
607 return f'Error: start_line {start_line} is out of range (file has {total_lines} lines)'
608
609 if end_line < start_line:
610 return f'Error: end_line {end_line} must be >= start_line {start_line}'
611

Callers

nothing calls this directly

Calls 1

get_real_pathMethod · 0.95

Tested by

no test coverage detected