From 03b0ca8a5334316c49a0464294092367b42868ab Mon Sep 17 00:00:00 2001 From: David Briscoe Date: Sat, 8 Oct 2022 00:46:45 -0700 Subject: [PATCH] Escape special chars in topic and skip mono Fix #36. If the topic contains chars that make markdown formatting difficult, escape them and omit fixed width styling. Markdown parsers are often inconsistent, so hopefully simpler markdown is more likely to display properly for more users. Never deployed or run. (I'm not setup for either.) --- bot/bot.py | 7 ++++++- test_bot.py | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/bot/bot.py b/bot/bot.py index 62c0223..b4ff962 100644 --- a/bot/bot.py +++ b/bot/bot.py @@ -154,7 +154,12 @@ def create_link_for_tag(self, tag, possible_matches, subreddit="vim"): request = requests.head(link) if request.ok: - text += "* [`{}`]({}) in _{}.txt_\n".format(topic, link, doc) + escaped, count = re.subn(r"([\[\]`])", r"\\\1", topic) + if count > 0: + topic = escaped + text += "* [{}]({}) in _{}.txt_\n".format(topic, link, doc) + else: + text += "* [`{}`]({}) in _{}.txt_\n".format(topic, link, doc) return text def start(self): diff --git a/test_bot.py b/test_bot.py index c34e6dd..97c1a07 100644 --- a/test_bot.py +++ b/test_bot.py @@ -44,6 +44,29 @@ def test_non_exact_matches(self): best_tag = next(iter(result.keys()))[1] self.assertEqual(best_tag, v) + def test_difficult_markdown(self): + """ + Test that bot falls back to simpler formatting for difficult markdown. + """ + + tests = [ + {"topic": ":make", "link": r"[`:make`]"}, + {"topic": "[I", "link": r"[\[I]"}, + {"topic": "[_CTRL-I", "link": r"[\[_CTRL-I]"}, + {"topic": "`]", "link": r"[\`\]]"}, + {"topic": "c_CTRL-F", "link": r"[`c_CTRL-F`]"}, + {"topic": "c_CTRL-G", "link": r"[`c_CTRL-G`]"}, + {"topic": "c_CTRL-L", "link": r"[`c_CTRL-L`]"}, + {"topic": "c_CTRL-R_CTRL-W", "link": r"[`c_CTRL-R_CTRL-W`]"}, + {"topic": "pattern.txt", "link": r"[`pattern.txt`]"}, + {"topic": "search()", "link": r"[`search"}, + ] + + bot = Bot() + for t in tests: + reply = bot.create_comment("`:h {}`".format(t["topic"]), None, "vim") + self.assertIn(t["link"], reply) + def test_empty_comment(self): """ Test comment is empty if nothing is found