Class: Genie::ReplaceLinesInFile
- Inherits:
-
RubyLLM::Tool
- Object
- RubyLLM::Tool
- Genie::ReplaceLinesInFile
- Includes:
- SandboxedFileTool
- Defined in:
- lib/tools/replace_lines_in_file.rb
Instance Method Summary collapse
Methods included from SandboxedFileTool
#enforce_sandbox!, #initialize, #within_sandbox?
Instance Method Details
#execute(filepath:, start_line:, end_line:, content:) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/tools/replace_lines_in_file.rb', line 13 def execute(filepath:, start_line:, end_line:, content:) start_line = start_line.to_i end_line = end_line.to_i # Expand to absolute path filepath = File.(filepath) Genie.output "Replacing lines in file: #{filepath}", color: :blue enforce_sandbox!(filepath) # Check file exists unless File.exist?(filepath) raise "File not found. Cannot replace lines in a non-existent file." end # Read lines lines = File.readlines(filepath) total = lines.size # Validate indices if !start_line.is_a?(Integer) || !end_line.is_a?(Integer) || start_line < 0 || end_line < start_line || end_line > total raise "Invalid line numbers: start=#{start_line}, end=#{end_line}, file has #{total} lines." end # Split head and tail head = lines[0...start_line] tail = lines[(end_line + 1)..-1] || [] # Prepare new content lines new_lines = content.to_s.each_line.to_a # Combine updated = head + new_lines + tail # Write back File.open(filepath, "w") do |f| f.write(updated.join) end { success: true } rescue => e Genie.output "Error: #{e.message}", color: :red { error: e. } end |