From 43c56d7c92475f1f078692b96c999c4f5e03a8cb Mon Sep 17 00:00:00 2001 From: Sam Date: Tue, 4 Feb 2025 18:16:52 +1100 Subject: [PATCH] FIX: need to be able to search replace within lines (#1110) (this is needed for very simple diffs and HTML) --- lib/utils/diff_utils/simple_diff.rb | 3 +++ spec/lib/utils/diff_utils/simple_diff_spec.rb | 13 ++++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/lib/utils/diff_utils/simple_diff.rb b/lib/utils/diff_utils/simple_diff.rb index ca67629e..e03dfef3 100644 --- a/lib/utils/diff_utils/simple_diff.rb +++ b/lib/utils/diff_utils/simple_diff.rb @@ -19,6 +19,9 @@ module DiscourseAi raise ArgumentError, "content cannot be nil" if content.nil? raise ArgumentError, "search cannot be nil" if search.nil? raise ArgumentError, "replace cannot be nil" if replace.nil? + raise ArgumentError, "search cannot be empty" if search.empty? + + return content.gsub(search, replace) if content.include?(search) lines = content.split("\n") search_lines = search.split("\n") diff --git a/spec/lib/utils/diff_utils/simple_diff_spec.rb b/spec/lib/utils/diff_utils/simple_diff_spec.rb index ced6d727..8a29028f 100644 --- a/spec/lib/utils/diff_utils/simple_diff_spec.rb +++ b/spec/lib/utils/diff_utils/simple_diff_spec.rb @@ -25,7 +25,7 @@ RSpec.describe DiscourseAi::Utils::DiffUtils::SimpleDiff do lin 1 TEXT - expect(subject.apply(content, search, replace)).to eq(expected.strip) + expect(subject.apply(content, search, replace).strip).to eq(expected.strip) end it "raises error when no match is found" do @@ -61,10 +61,10 @@ RSpec.describe DiscourseAi::Utils::DiffUtils::SimpleDiff do end it "is forgiving of whitespace differences" do - content = "line1\n line2\nline3" + content = "line1\n line2\nline3" search = "line2" replace = "new_line2" - expect(subject.apply(content, search, replace)).to eq("line1\nnew_line2\nline3") + expect(subject.apply(content, search, replace).strip).to eq("line1\n new_line2\nline3") end it "is forgiving of small character differences" do @@ -121,6 +121,13 @@ RSpec.describe DiscourseAi::Utils::DiffUtils::SimpleDiff do expect(subject.apply(content, search, replace)).to eq(expected.strip) end + it "handles partial line matches" do + content = "abc hello efg\nabc hello efg" + search = "hello" + replace = "bob" + expect(subject.apply(content, search, replace)).to eq("abc bob efg\nabc bob efg") + end + it "handles JavaScript blocks in different orders" do content = <<~JS function first() {