34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
# File 'lib/clacky/tools/edit.rb', line 34
def execute(path:, old_string:, new_string:, replace_all: false, working_dir: nil)
path = expand_path(path, working_dir: working_dir)
unless File.exist?(path)
return { error: "File not found: #{path}" }
end
unless File.file?(path)
return { error: "Path is not a file: #{path}" }
end
begin
content = File.read(path)
match_result = Utils::StringMatcher.find_match(content, old_string)
unless match_result
return build_helpful_error(content, old_string, path)
end
actual_old_string = match_result[:matched_string]
occurrences = match_result[:occurrences]
if !replace_all && occurrences > 1
return {
error: "String appears #{occurrences} times in the file. Use replace_all: true to replace all occurrences, " \
"or provide a more specific string that appears only once."
}
end
content = replace_all ? content.gsub(actual_old_string, new_string) : content.sub(actual_old_string, new_string)
File.write(path, content)
{
path: File.expand_path(path),
replacements: replace_all ? occurrences : 1,
error: nil
}
rescue Errno::EACCES => e
{ error: "Permission denied: #{e.message}" }
rescue StandardError => e
{ error: "Failed to edit file: #{e.message}" }
end
end
|