Class: RubynCode::Tools::EditFile

Inherits:
Base
  • Object
show all
Defined in:
lib/rubyn_code/tools/edit_file.rb

Constant Summary collapse

TOOL_NAME =
'edit_file'
DESCRIPTION =
'Performs exact string replacement in a file. ' \
'Fails if old_text is not found or is ambiguous.'
PARAMETERS =
{
  path: { type: :string, required: true,
          description: 'Path to the file to edit' },
  old_text: { type: :string, required: true,
              description: 'The exact text to find and replace' },
  new_text: { type: :string, required: true,
              description: 'The replacement text' },
  replace_all: { type: :boolean, required: false, default: false,
                 description: 'Replace all occurrences (default: false)' }
}.freeze
RISK_LEVEL =
:write
REQUIRES_CONFIRMATION =
false

Instance Attribute Summary

Attributes inherited from Base

#project_root

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

description, #initialize, parameters, requires_confirmation?, risk_level, #safe_path, to_schema, tool_name, #truncate

Constructor Details

This class inherits a constructor from RubynCode::Tools::Base

Class Method Details

.summarize(output, _args) ⇒ Object

Take the first line of the tool’s output, which is already formatted as “Edited /path.rb (N replacements)”.



27
28
29
# File 'lib/rubyn_code/tools/edit_file.rb', line 27

def self.summarize(output, _args)
  output.to_s.lines.first.to_s.chomp[0, 200]
end

Instance Method Details

#execute(path:, old_text:, new_text:, replace_all: false) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rubyn_code/tools/edit_file.rb', line 31

def execute(path:, old_text:, new_text:, replace_all: false)
  resolved = read_file_safely(path)
  content = File.read(resolved)

  validate_occurrences!(path, content, old_text, replace_all)

  new_content = apply_replacement(content, old_text, new_text, replace_all)
  File.write(resolved, new_content)

  format_diff_result(path, content, old_text, new_text, replace_all)
end

#preview_content(path:, old_text:, new_text:, replace_all: false) ⇒ Hash

Compute the proposed file content without writing to disk. Used by IDE mode to preview the edit in a diff view before the user accepts. Raises if old_text is missing or ambiguous, same as execute.

Returns:

  • (Hash)

    { content: String, type: ‘modify’ }



48
49
50
51
52
53
54
55
# File 'lib/rubyn_code/tools/edit_file.rb', line 48

def preview_content(path:, old_text:, new_text:, replace_all: false)
  resolved = read_file_safely(path)
  content = File.read(resolved)

  validate_occurrences!(path, content, old_text, replace_all)

  { content: apply_replacement(content, old_text, new_text, replace_all), type: 'modify' }
end