class Riffer::Rig::Tools::Edit
Public Instance Methods
(context: Riffer::Agent::Context?, path: String, old_string: String, new_string: String, ?replace_all: bool) → Riffer::Tools::Response
Source
# File lib/riffer/rig/tools/edit.rb, line 25 def call(context:, path:, old_string:, new_string:, replace_all: false) resolved = File.expand_path(path, context&.[](:cwd)) return error("File not found: #{path}", type: :not_found) unless File.file?(resolved) content = File.read(resolved) occurrences = content.scan(old_string).length return error("old_string not found in #{path}", type: :not_found) if occurrences.zero? if occurrences > 1 && !replace_all return error( "old_string is not unique in #{path} (#{occurrences} matches). Pass replace_all or add more context.", type: :ambiguous_match ) end # Block form so backslash sequences in new_string (\0, \1, \\) are inserted # literally instead of being interpreted as regexp backreferences. updated = replace_all ? content.gsub(old_string) { new_string } : content.sub(old_string) { new_string } File.write(resolved, updated) text("Edited #{path} (#{replace_all ? occurrences : 1} replacement#{'s' if replace_all && occurrences > 1})") end
@rbs context: Riffer::Agent::Context? @rbs path: String @rbs old_string: String @rbs new_string: String @rbs replace_all: bool @rbs return: Riffer::Tools::Response