From 115160794187cf3b0c270a55e41b84192618e39a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89rico=20Andrei?= Date: Sat, 26 Aug 2023 13:07:58 -0300 Subject: [PATCH] Rewrite keywords with spaces and dashes. Fixes #1 --- news/1.feature | 1 + .../mastodon/interpolators/adapters.py | 20 ++++++++++++++++++- tests/interpolators/test_tags.py | 19 ++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 news/1.feature diff --git a/news/1.feature b/news/1.feature new file mode 100644 index 0000000..830852f --- /dev/null +++ b/news/1.feature @@ -0,0 +1 @@ +Rewrite keywords with spaces and dashes [@ericof] diff --git a/src/collective/mastodon/interpolators/adapters.py b/src/collective/mastodon/interpolators/adapters.py index bffb9a2..acb20ab 100644 --- a/src/collective/mastodon/interpolators/adapters.py +++ b/src/collective/mastodon/interpolators/adapters.py @@ -5,11 +5,29 @@ from zope.component import adapter +TRANSLATION_TABLE = str.maketrans( + { + "-": "", + "_": "", + "#": "", + "$": "", + ".": "", + " ": "", + } +) + + +def tag_from_keyword(keyword: str) -> str: + """Convert a keyword to a tag.""" + keyword = keyword.translate(TRANSLATION_TABLE) + return f"#{keyword}" + + @adapter(IDublinCore) class TagsSubstitution(BaseSubstitution): category = _PM("Dublin Core") description = _("Tags") def safe_call(self): - tags = [f"#{item}" for item in self.context.Subject()] + tags = [tag_from_keyword(item) for item in self.context.Subject()] return " ".join(tags) diff --git a/tests/interpolators/test_tags.py b/tests/interpolators/test_tags.py index 08e3b20..4061081 100644 --- a/tests/interpolators/test_tags.py +++ b/tests/interpolators/test_tags.py @@ -1,9 +1,28 @@ +from collective.mastodon.interpolators.adapters import tag_from_keyword from plone import api from plone.stringinterp.interfaces import IStringInterpolator import pytest +class TestTagFromKeyword: + @pytest.mark.parametrize( + "keyword,tag", + [ + ("#Plone", "#Plone"), + ("Plone", "#Plone"), + ("plone", "#plone"), + ("Open Source", "#OpenSource"), + ("open source", "#opensource"), + ("PloneGov-BR", "#PloneGovBR"), + ("#PloneGov-BR", "#PloneGovBR"), + ("IPO$", "#IPO"), + ], + ) + def test_tag_from_keyword(self, keyword: str, tag: str): + assert tag_from_keyword(keyword) == tag + + class TestInterpolatorsTags: @pytest.fixture(autouse=True) def _init(self, portal):