FIX: need to be able to search replace within lines (#1110)

(this is needed for very simple diffs and HTML)
This commit is contained in:
Sam 2025-02-04 18:16:52 +11:00 committed by GitHub
parent a7d032fa28
commit 43c56d7c92
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 13 additions and 3 deletions

View File

@ -19,6 +19,9 @@ module DiscourseAi
raise ArgumentError, "content cannot be nil" if content.nil? raise ArgumentError, "content cannot be nil" if content.nil?
raise ArgumentError, "search cannot be nil" if search.nil? raise ArgumentError, "search cannot be nil" if search.nil?
raise ArgumentError, "replace cannot be nil" if replace.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") lines = content.split("\n")
search_lines = search.split("\n") search_lines = search.split("\n")

View File

@ -25,7 +25,7 @@ RSpec.describe DiscourseAi::Utils::DiffUtils::SimpleDiff do
lin 1 lin 1
TEXT TEXT
expect(subject.apply(content, search, replace)).to eq(expected.strip) expect(subject.apply(content, search, replace).strip).to eq(expected.strip)
end end
it "raises error when no match is found" do it "raises error when no match is found" do
@ -64,7 +64,7 @@ RSpec.describe DiscourseAi::Utils::DiffUtils::SimpleDiff do
content = "line1\n line2\nline3" content = "line1\n line2\nline3"
search = "line2" search = "line2"
replace = "new_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 end
it "is forgiving of small character differences" do 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) expect(subject.apply(content, search, replace)).to eq(expected.strip)
end 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 it "handles JavaScript blocks in different orders" do
content = <<~JS content = <<~JS
function first() { function first() {