♻️ Extract slugify/sanitizing into util method

Reduces code duplication
This commit is contained in:
Gina Häußge committed 2020-11-23 17:14:57 +01:00
1 parent ad724d6e2f
commit c12447dca2
5 files changed
+64 -55

No files matched your search

+2 -20
View File
@@ -9,7 +9,6 @@ import copy
import io
import logging
import os
import re
import shutil
import pylru
@@ -21,12 +20,11 @@ except ImportError:
from contextlib import contextmanager
from emoji import demojize
from past.builtins import basestring
import octoprint.filemanager
from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode
from octoprint.vendor.awesome_slugify import Slugify
from octoprint.util.text import sanitize
class StorageInterface(object):
@@ -466,22 +464,6 @@ class LocalFileStorage(StorageInterface):
This storage type implements :func:`path_on_disk`.
"""
_UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
@classmethod
def _no_unicode_variations(cls, text):
return cls._UNICODE_VARIATIONS.sub("", text)
_SLUGIFY = Slugify()
_SLUGIFY.safe_chars = "-_.()[] "
@classmethod
def _slugify(cls, text):
text = to_unicode(text)
text = cls._no_unicode_variations(text)
text = demojize(text, delimiters=("", ""))
return cls._SLUGIFY(text)
def __init__(self, basefolder, create=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
@@ -1176,7 +1158,7 @@ class LocalFileStorage(StorageInterface):
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
result = self._slugify(name).replace(" ", "_")
result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_")
if result and result != "." and result != ".." and result[0] == ".":
# hidden files under *nix
result = result[1:]
@@ -29,6 +29,7 @@ from octoprint.server.util.flask import (
with_revalidation_checking,
)
from octoprint.util import count, monotonic_time, utmify
from octoprint.util.text import sanitize
PY2 = sys.version_info[0] < 3
@@ -47,11 +48,6 @@ class AnnouncementPlugin(
self._cached_channel_configs = None
self._cached_channel_configs_mutex = threading.RLock()
from octoprint.vendor.awesome_slugify import Slugify
self._slugify = Slugify()
self._slugify.safe_chars = "-_."
# Additional permissions hook
def get_additional_permissions(self):
@@ -366,14 +362,14 @@ class AnnouncementPlugin(
if config is None or "url" not in config or "name" not in config:
# strip invalid entries
continue
result[self._slugify(key)] = config
result[sanitize(key)] = config
self._cached_channel_configs = result
return self._cached_channel_configs
def _get_channel_config(self, key, force=False):
"""Retrieve specific channel config for channel."""
safe_key = self._slugify(key)
safe_key = sanitize(key)
return self._get_channel_configs(force=force).get(safe_key)
def _fetch_all_channels_async(self, force=False):
@@ -524,7 +520,7 @@ class AnnouncementPlugin(
def _get_channel_cache_path(self, key):
"""Retrieve cache path for channel key."""
safe_key = self._slugify(key)
safe_key = sanitize(key)
return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key))
+2 -21
View File
@@ -4,8 +4,6 @@ from __future__ import absolute_import, division, print_function, unicode_litera
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from emoji import demojize
import octoprint.plugin
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
@@ -39,7 +37,6 @@ import io
import json
import logging
import os
import re
import shutil
import sys
import tempfile
@@ -54,8 +51,7 @@ import sarge
from flask_babel import gettext
from octoprint.settings import valid_boolean_trues
from octoprint.util import to_unicode
from octoprint.vendor.awesome_slugify import Slugify
from octoprint.util.text import sanitize
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
@@ -1295,26 +1291,11 @@ class BackupPlugin(
backup_prefix = "octoprint"
else:
backup_prefix = settings.global_get(["appearance", "name"])
backup_prefix = cls._slugify(backup_prefix)
backup_prefix = sanitize(backup_prefix)
return "{}-backup-{}.zip".format(
backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT)
)
_UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
_SLUGIFY = Slugify()
_SLUGIFY.safe_chars = "-_.()[] "
@classmethod
def _no_unicode_variations(cls, text):
return cls._UNICODE_VARIATIONS.sub("", text)
@classmethod
def _slugify(cls, text):
text = to_unicode(text)
text = cls._no_unicode_variations(text)
text = demojize(text, delimiters=("", ""))
return cls._SLUGIFY(text)
@classmethod
def _restore_supported(cls, settings):
return (
+56
View File
@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
from emoji import demojize
from octoprint.util import to_unicode
from octoprint.vendor.awesome_slugify import Slugify
_UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
_SLUGIFIES = {}
def sanitize(text, safe_chars="-_.", demoji=True):
"""
Sanitizes text by running it through slugify and optionally emoji translating.
Examples:
>>> sanitize("Hello World!") # doctest: +ALLOW_UNICODE
'Hello-World'
>>> sanitize("Hello World!", safe_chars="-_. ") # doctest: +ALLOW_UNICODE
'Hello World'
>>> sanitize("\u2764") # doctest: +ALLOW_UNICODE
'red_heart'
>>> sanitize("\u2764\ufe00") # doctest: +ALLOW_UNICODE
'red_heart'
>>> sanitize("\u2764", demoji=False) # doctest: +ALLOW_UNICODE
''
Args:
text: the text to sanitize
safe_chars: characters to consider safe and to keep after sanitization
emoji: whether to also convert emoji to text
Returns: the sanitized text
"""
slugify = _SLUGIFIES.get(safe_chars)
if slugify is None:
slugify = Slugify()
slugify.safe_chars = safe_chars
_SLUGIFIES[safe_chars] = slugify
text = to_unicode(text)
if demoji:
text = remove_unicode_variations(text)
text = demojize(text, delimiters=("", ""))
return slugify(text)
def remove_unicode_variations(text):
return _UNICODE_VARIATIONS.sub("", text)
-6
View File
@@ -814,12 +814,6 @@ class LocalStorageTest(unittest.TestCase):
self.assertEqual(expected_path, actual_path)
self.assertEqual(expected_name, actual_name)
@data(("test", "test"), ("\u2764", "red_heart"), ("\u2764\ufe00", "red_heart"))
@unpack
def test_slugify(self, input, expected):
output = LocalFileStorage._slugify(input)
self.assertEqual(output, expected)
def _add_and_verify_file(
self, path, expected_path, file_object, links=None, overwrite=False, display=None
):