Skip to content

Commit

Permalink
Python 3.7 compatibility fix.
Browse files Browse the repository at this point in the history
  • Loading branch information
beatonma committed Feb 9, 2024
1 parent 7e7ecff commit a9d3bdd
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 3 deletions.
6 changes: 3 additions & 3 deletions mentions/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from urllib.parse import urljoin

from mentions import options
from mentions.util import get_domain
from mentions.util import compatibility, get_domain


def base_url() -> str:
Expand Down Expand Up @@ -97,8 +97,8 @@ def _domain_in_set(domain: str, domains: Set[str]) -> bool:
return True

if d.startswith("*."):
root_domain = d.removeprefix("*.")
remaining_prefix = domain.removesuffix(root_domain)
root_domain = compatibility.removeprefix(d, "*.")
remaining_prefix = compatibility.removesuffix(domain, root_domain)
if remaining_prefix == "" or remaining_prefix.endswith("."):
return True

Expand Down
21 changes: 21 additions & 0 deletions mentions/util/compatibility.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""Backport features of newer Python releases than our minimum target version.
All functions should contain information about their standard library equivalent
and the Python version in which it becomes available.
These should be removed and replaced with standard library equivalents when
we update our minimum target version."""


def removeprefix(text: str, prefix: str) -> str:
"""Backport of `str.removeprefix` introduced in Python 3.9"""
if text.startswith(prefix):
return text[len(prefix) :]
return text


def removesuffix(text: str, suffix: str) -> str:
"""Backport of `str.removesuffix` introduced in Python 3.9"""
if text.endswith(suffix):
return text[: -len(suffix)]
return text
Empty file.
22 changes: 22 additions & 0 deletions tests/tests/test_util/test_compatibility.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from mentions.util.compatibility import removeprefix, removesuffix
from tests.tests.util.testcase import SimpleTestCase


class CompatibilityTests(SimpleTestCase):
def test_str_removeprefix(self):
func = removeprefix
self.assertEqual(func("abcde", "ab"), "cde")
self.assertEqual(func("1248", "1"), "248")

self.assertEqual(func("abcde", "bc"), "abcde")
self.assertEqual(func("abcde", "de"), "abcde")
self.assertEqual(func("abcde", "abcdef"), "abcde")

def test_str_removesuffix(self):
func = removesuffix
self.assertEqual(func("abcde", "de"), "abc")
self.assertEqual(func("1248", "248"), "1")

self.assertEqual(func("abcde", "ab"), "abcde")
self.assertEqual(func("abcde", "abcd"), "abcde")
self.assertEqual(func("abcde", "abcdef"), "abcde")

0 comments on commit a9d3bdd

Please sign in to comment.