Change containment check to overlap

Due to scenarios wherein a formatted link ended up as part of a larger
raw link after parsing, change the containment check to an overlap check
and add appropriate tests for these edge cases.
This commit is contained in:
Bartłomiej Dach 2019-10-25 00:20:44 +02:00
parent cbd99cc767
commit 661dfbefaf
2 changed files with 32 additions and 2 deletions

View File

@ -333,6 +333,36 @@ public void TestMarkdownFormatLinkWithMisleadingUrlInText()
Assert.AreEqual(18, result.Links[0].Length);
}
[Test]
public void TestMarkdownFormatLinkThatContractsIntoLargerLink()
{
Message result = MessageFormatter.FormatMessage(new Message { Content = "super broken https://[osu.ppy](https://reddit.com).sh/" });
Assert.AreEqual("super broken https://osu.ppy.sh/", result.DisplayContent);
Assert.AreEqual(1, result.Links.Count);
Assert.AreEqual("https://reddit.com", result.Links[0].Url);
Assert.AreEqual(21, result.Links[0].Index);
Assert.AreEqual(7, result.Links[0].Length);
}
[Test]
public void TestMarkdownFormatLinkDirectlyNextToRawLink()
{
// the raw link has a port at the end of it, so that the raw link regex terminates at the port and doesn't consume display text from the formatted one
Message result = MessageFormatter.FormatMessage(new Message { Content = "https://localhost:8080[https://osu.ppy.sh](https://osu.ppy.sh) should be two links" });
Assert.AreEqual("https://localhost:8080https://osu.ppy.sh should be two links", result.DisplayContent);
Assert.AreEqual(2, result.Links.Count);
Assert.AreEqual("https://localhost:8080", result.Links[0].Url);
Assert.AreEqual(0, result.Links[0].Index);
Assert.AreEqual(22, result.Links[0].Length);
Assert.AreEqual("https://osu.ppy.sh", result.Links[1].Url);
Assert.AreEqual(22, result.Links[1].Index);
Assert.AreEqual(18, result.Links[1].Length);
}
[Test]
public void TestChannelLink()
{

View File

@ -104,7 +104,7 @@ private static void handleAdvanced(Regex regex, MessageFormatterResult result, i
// sometimes an already-processed formatted link can reduce to a simple URL, too
// (example: [mean example - https://osu.ppy.sh](https://osu.ppy.sh))
// therefore we need to check if any of the pre-existing links contains the raw one we found
if (result.Links.All(existingLink => !existingLink.Contains(link)))
if (result.Links.All(existingLink => !existingLink.Overlaps(link)))
result.Links.Add(link);
}
}
@ -298,7 +298,7 @@ public Link(string url, int startIndex, int length, LinkAction action, string ar
Argument = argument;
}
public bool Contains(Link otherLink) => otherLink.Index >= Index && otherLink.Index + otherLink.Length <= Index + Length;
public bool Overlaps(Link otherLink) => Index < otherLink.Index + otherLink.Length && otherLink.Index < Index + Length;
public int CompareTo(Link otherLink) => Index > otherLink.Index ? 1 : -1;
}