Class: Ask::Tools::Edit
- Inherits:
-
Ask::Tool
- Object
- Ask::Tool
- Ask::Tools::Edit
- Defined in:
- lib/ask/tools/shell/edit.rb
Overview
Edit a file by replacing exact text. Uses exact string matching — provide enough surrounding context for uniqueness.
Constant Summary collapse
- MAX_FILE_SIZE =
1_000_000
Instance Method Summary collapse
Instance Method Details
#execute(path:, old_string:, new_string:, replace_all: false) ⇒ Object
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 |
# File 'lib/ask/tools/shell/edit.rb', line 18 def execute(path:, old_string:, new_string:, replace_all: false) path = File.(path) unless File.exist?(path) return Ask::Result.error(message: "File does not exist: #{path}") end unless File.file?(path) return Ask::Result.error(message: "Not a file: #{path}") end if File.size(path) > MAX_FILE_SIZE return Ask::Result.error( message: "File too large (#{File.size(path)} bytes). Maximum is #{MAX_FILE_SIZE} bytes." ) end content = File.read(path) if replace_all count = content.scan(old_string).size return Ask::Result.error(message: "String not found") if count == 0 content = content.gsub(old_string, new_string) else index = content.index(old_string) return Ask::Result.error(message: "String not found") unless index count = 1 content = content.sub(old_string, new_string) end File.write(path, content) Ask::Result.ok(data: { path: path, replacements: count }, metadata: { path: path, replacements: count }) end |