Class: RobotLab::To::Tools::Edit
- Defined in:
- lib/robot_lab/to/tools/edit.rb
Overview
Exact-string replacement in an existing file. old_text must match the file's current contents exactly (whitespace included) and be unique unless replace_all is set. The ReadBeforeEdit guard requires the file to have been Read this session first, so old_text reflects real contents.
Instance Method Summary collapse
-
#apply(content, old_text, new_text, replace_all) ⇒ String
Pure replacement logic (testable in isolation).
- #execute(path:, old_text:, new_text:, replace_all: false) ⇒ Object
Methods inherited from FileTool
#name, name_segment, short_name
Instance Method Details
#apply(content, old_text, new_text, replace_all) ⇒ String
Pure replacement logic (testable in isolation). Returns the new content string, or an "Error: ..." string on a precondition failure.
40 41 42 43 44 45 46 47 48 |
# File 'lib/robot_lab/to/tools/edit.rb', line 40 def apply(content, old_text, new_text, replace_all) count = content.scan(old_text).size return "Error: old_text not found in file" if count.zero? if count > 1 && !replace_all return "Error: old_text is not unique (#{count} matches); add context or set replace_all" end replace_all ? content.gsub(old_text, new_text) : content.sub(old_text, new_text) end |
#execute(path:, old_text:, new_text:, replace_all: false) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/robot_lab/to/tools/edit.rb', line 22 def execute(path:, old_text:, new_text:, replace_all: false, **) resolved = File.(path, Dir.pwd) return "Error: file not found: #{path}" unless File.file?(resolved) original = File.read(resolved) result = apply(original, old_text.to_s, new_text.to_s, replace_all) return result if result.is_a?(String) && result.start_with?("Error:") File.write(resolved, result) "Edited #{path}" rescue SystemCallError => e "Error editing #{path}: #{e.}" end |