Module: Roast::Tools::ApplyDiff

Extended by:
ApplyDiff
Included in:
ApplyDiff
Defined in:
lib/roast/tools/apply_diff.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/roast/tools/apply_diff.rb', line 11

def included(base)
  base.class_eval do
    function(
      :apply_diff,
      "Show a diff to the user and apply changes based on their yes/no response",
      file_path: { type: "string", description: "Path to the file to modify" },
      old_content: { type: "string", description: "The current content to be replaced" },
      new_content: { type: "string", description: "The new content to replace with" },
      description: { type: "string", description: "Optional description of the change", required: false },
    ) do |params|
      Roast::Tools::ApplyDiff.call(
        params[:file_path],
        params[:old_content],
        params[:new_content],
        params[:description],
      )
    end
  end
end

Instance Method Details

#call(file_path, old_content, new_content, description = nil) ⇒ Object



32
33
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
# File 'lib/roast/tools/apply_diff.rb', line 32

def call(file_path, old_content, new_content, description = nil)
  unless File.exist?(file_path)
    error_msg = "File not found: #{file_path}"
    Roast::Helpers::Logger.error(error_msg + "\n")
    return error_msg
  end

  current_content = File.read(file_path)
  unless current_content.include?(old_content)
    error_msg = "Old content not found in file: #{file_path}"
    Roast::Helpers::Logger.error(error_msg + "\n")
    return error_msg
  end

  # Show the diff
  show_diff(file_path, old_content, new_content, description)

  # Ask for confirmation
  prompt_text = "Apply this change? (y/n)"
  response = ::CLI::UI::Prompt.ask(prompt_text)

  if response.to_s.downcase.start_with?("y")
    # Apply the change
    updated_content = current_content.gsub(old_content, new_content)
    File.write(file_path, updated_content)

    success_msg = "✅ Changes applied to #{file_path}"
    Roast::Helpers::Logger.info(success_msg + "\n")
    success_msg
  else
    cancel_msg = "❌ Changes cancelled for #{file_path}"
    Roast::Helpers::Logger.info(cancel_msg + "\n")
    cancel_msg
  end
rescue StandardError => e
  error_message = "Error applying diff: #{e.message}"
  Roast::Helpers::Logger.error(error_message + "\n")
  Roast::Helpers::Logger.debug(e.backtrace.join("\n") + "\n") if ENV["DEBUG"]
  error_message
end