Class: Genie::InsertIntoFile

Inherits:
RubyLLM::Tool
  • Object
show all
Includes:
SandboxedFileTool
Defined in:
lib/tools/insert_into_file.rb

Instance Method Summary collapse

Methods included from SandboxedFileTool

#enforce_sandbox!, #initialize, #within_sandbox?

Instance Method Details

#execute(filepath:, content:, line_number:) ⇒ Object



12
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/insert_into_file.rb', line 12

def execute(filepath:, content:, line_number:)
  line_number = line_number.to_i

  # Expand the filepath to an absolute path
  filepath = File.expand_path(filepath)

  Genie.output "Inserting into file: #{filepath}", color: :blue

  enforce_sandbox!(filepath)

  # Check file exists
  unless File.exist?(filepath)
    raise "File not found. Cannot insert into a non-existent file."
  end

  # Read existing lines
  lines = File.readlines(filepath)

  # Validate line_number
  total_lines = lines.size
  if !line_number.is_a?(Integer) || line_number < 1 || line_number > total_lines + 1
    raise ArgumentError, "Invalid line number: #{line_number}. Must be between 1 and #{total_lines + 1}."
  end

  # Prepare content lines
  content_lines = content.each_line.to_a

  # Show the content to be inserted
  indented = content.each_line.map { |line| "  #{line}" }.join
  Genie.output indented, color: :green

  # Perform insertion
  index = line_number - 1
  new_lines = lines[0...index] + content_lines + lines[index..-1]

  # Write back
  File.open(filepath, "w") do |file|
    file.write(new_lines.join)
  end

  { success: true }
rescue => e
  Genie.output "Error: #{e.message}", color: :red
  { error: e.message }
end