✨ Support unicode file names on Py3
If we are on py3 and thus can rely on pathvalidate, we'll now no longer slugify uploaded files names, but try to keep them as close to the original name as possible, including unicode and emoji and whatnot. This requires the underlying file system to support this, so just in case the old behaviour can be enforced by setting the config flag feature.enforceReallyUniversalFilenames to true. Closes #4078
This commit is contained in:
1 parent
ecf56b6658
commit
f912adcd33
10 files changed
+444
-265
No files matched your search
@@ -55,6 +55,7 @@
|
||||
* [monotonic](https://github.com/atdt/monotonic): Apache License 2.0
|
||||
* [netaddr](https://github.com/drkjam/netaddr/): BSD
|
||||
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
|
||||
* [pathvalidate](https://pathvalidate.readthedocs.io/en/latest/index.html): MIT
|
||||
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
|
||||
* [psutil](https://github.com/giampaolo/psutil): BSD
|
||||
* [pylru](https://github.com/jlhutch/pylru): GPLv2
|
||||
|
||||
@@ -84,6 +84,7 @@ INSTALL_REQUIRES_PYTHON3 = [
|
||||
"feedparser>=6.0.2,<7",
|
||||
"zeroconf>=0.24,<0.25",
|
||||
"immutabledict>=1.2.0,<2",
|
||||
"pathvalidate>=2.4.1,<3",
|
||||
]
|
||||
|
||||
# OSX specific requirements
|
||||
|
||||
@@ -24,7 +24,7 @@ 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.util.text import sanitize
|
||||
from octoprint.util.files import sanitize_filename
|
||||
|
||||
|
||||
class StorageInterface(object):
|
||||
@@ -468,13 +468,14 @@ class LocalFileStorage(StorageInterface):
|
||||
This storage type implements :func:`path_on_disk`.
|
||||
"""
|
||||
|
||||
def __init__(self, basefolder, create=False):
|
||||
def __init__(self, basefolder, create=False, really_universal=False):
|
||||
"""
|
||||
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
|
||||
if necessary and ``create`` is set to ``True``.
|
||||
|
||||
:param string basefolder: the path to the folder under which to create the storage
|
||||
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
|
||||
:param string basefolder: the path to the folder under which to create the storage
|
||||
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
|
||||
:param bool really_universal: ``True`` if the file names should be forced to really universal, ``False`` otherwise
|
||||
"""
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -487,6 +488,8 @@ class LocalFileStorage(StorageInterface):
|
||||
code=StorageError.INVALID_DIRECTORY,
|
||||
)
|
||||
|
||||
self._really_universal = really_universal
|
||||
|
||||
import threading
|
||||
|
||||
self._metadata_lock_mutex = threading.RLock()
|
||||
@@ -1165,22 +1168,10 @@ class LocalFileStorage(StorageInterface):
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise
|
||||
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
|
||||
``(``, and ``)`` as is.
|
||||
sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also
|
||||
strips leading ``.``s.
|
||||
"""
|
||||
name = to_unicode(name)
|
||||
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_")
|
||||
if result and result != "." and result != ".." and result[0] == ".":
|
||||
# hidden files under *nix
|
||||
result = result[1:]
|
||||
return result
|
||||
return sanitize_filename(name, really_universal=self._really_universal)
|
||||
|
||||
def sanitize_path(self, path):
|
||||
"""
|
||||
@@ -1199,7 +1190,10 @@ class LocalFileStorage(StorageInterface):
|
||||
path_elements = path.split("/")
|
||||
joined_path = self.basefolder
|
||||
for path_element in path_elements:
|
||||
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
|
||||
if path_element == ".." or path_element == ".":
|
||||
joined_path = os.path.join(joined_path, path_element)
|
||||
else:
|
||||
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
|
||||
path = os.path.realpath(joined_path)
|
||||
if not path.startswith(self.basefolder):
|
||||
raise ValueError(
|
||||
|
||||
@@ -410,7 +410,10 @@ class Server(object):
|
||||
storage_managers[
|
||||
octoprint.filemanager.FileDestinations.LOCAL
|
||||
] = octoprint.filemanager.storage.LocalFileStorage(
|
||||
self._settings.getBaseFolder("uploads")
|
||||
self._settings.getBaseFolder("uploads"),
|
||||
really_universal=self._settings.getBoolean(
|
||||
["feature", "enforceReallyUniversalFilenames"]
|
||||
),
|
||||
)
|
||||
|
||||
fileManager = octoprint.filemanager.FileManager(
|
||||
|
||||
@@ -288,6 +288,7 @@ default_settings = {
|
||||
"uploadOverwriteConfirmation": True,
|
||||
"autoUppercaseBlacklist": ["M117", "M118"],
|
||||
"g90InfluencesExtruder": False,
|
||||
"enforceReallyUniversalFilenames": False,
|
||||
},
|
||||
"folder": {
|
||||
"uploads": None,
|
||||
|
||||
@@ -50,6 +50,11 @@ from past.builtins import basestring, unicode
|
||||
|
||||
from octoprint import UMASK
|
||||
from octoprint.util.connectivity import ConnectivityChecker # noqa: F401
|
||||
from octoprint.util.files import ( # noqa: F401
|
||||
find_collision_free_name,
|
||||
get_dos_filename,
|
||||
silent_remove,
|
||||
)
|
||||
from octoprint.util.net import ( # noqa: F401
|
||||
address_for_client,
|
||||
interface_addresses,
|
||||
@@ -480,204 +485,6 @@ def get_exception_string(fmt="{type}: '{message}' @ {file}:{function}:{line}"):
|
||||
return fmt.format(**exception)
|
||||
|
||||
|
||||
def get_dos_filename(
|
||||
input, existing_filenames=None, extension=None, whitelisted_extensions=None, **kwargs
|
||||
):
|
||||
"""
|
||||
Converts the provided input filename to a 8.3 DOS compatible filename. If ``existing_filenames`` is provided, the
|
||||
conversion result will be guaranteed not to collide with any of the filenames provided thus.
|
||||
|
||||
Uses :func:`find_collision_free_name` internally.
|
||||
|
||||
Arguments:
|
||||
input (string): The original filename incl. extension to convert to the 8.3 format.
|
||||
existing_filenames (list): A list of existing filenames with which the generated 8.3 name must not collide.
|
||||
Optional.
|
||||
extension (string): The .3 file extension to use for the generated filename. If not provided, the extension of
|
||||
the provided ``filename`` will simply be truncated to 3 characters.
|
||||
whitelisted_extensions (list): A list of extensions on ``input`` that will be left as-is instead of
|
||||
exchanging for ``extension``.
|
||||
kwargs (dict): Additional keyword arguments to provide to :func:`find_collision_free_name`.
|
||||
|
||||
Returns:
|
||||
string: A 8.3 compatible translation of the original filename, not colliding with the optionally provided
|
||||
``existing_filenames`` and with the provided ``extension`` or the original extension shortened to
|
||||
a maximum of 3 characters.
|
||||
|
||||
Raises:
|
||||
ValueError: No 8.3 compatible name could be found that doesn't collide with the provided ``existing_filenames``.
|
||||
|
||||
Examples:
|
||||
|
||||
>>> get_dos_filename("test1234.gco") # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> get_dos_filename("test1234.gcode") # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> get_dos_filename("test12345.gco") # doctest: +ALLOW_UNICODE
|
||||
'test12~1.gco'
|
||||
>>> get_dos_filename("test1234.fnord", extension="gco") # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> get_dos_filename("auto0.g", extension="gco") # doctest: +ALLOW_UNICODE
|
||||
'auto0.gco'
|
||||
>>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"]) # doctest: +ALLOW_UNICODE
|
||||
'auto0.g'
|
||||
>>> get_dos_filename(None)
|
||||
>>> get_dos_filename("foo") # doctest: +ALLOW_UNICODE
|
||||
'foo'
|
||||
"""
|
||||
|
||||
if input is None:
|
||||
return None
|
||||
|
||||
if existing_filenames is None:
|
||||
existing_filenames = []
|
||||
|
||||
if extension is not None:
|
||||
extension = extension.lower()
|
||||
|
||||
if whitelisted_extensions is None:
|
||||
whitelisted_extensions = []
|
||||
|
||||
filename, ext = os.path.splitext(input)
|
||||
|
||||
ext = ext.lower()
|
||||
ext = ext[1:] if ext.startswith(".") else ext
|
||||
if ext in whitelisted_extensions or extension is None:
|
||||
extension = ext
|
||||
|
||||
return find_collision_free_name(filename, extension, existing_filenames, **kwargs)
|
||||
|
||||
|
||||
def find_collision_free_name(filename, extension, existing_filenames, max_power=2):
|
||||
"""
|
||||
Tries to find a collision free translation of "<filename>.<extension>" to the 8.3 DOS compatible format,
|
||||
preventing collisions with any of the ``existing_filenames``.
|
||||
|
||||
First strips all of ``."/\\[]:;=,`` from the filename and extensions, converts them to lower case and truncates
|
||||
the ``extension`` to a maximum length of 3 characters.
|
||||
|
||||
If the filename is already equal or less than 8 characters in length after that procedure and "<filename>.<extension>"
|
||||
are not contained in the ``existing_files``, that concatenation will be returned as the result.
|
||||
|
||||
If not, the following algorithm will be applied to try to find a collision free name::
|
||||
|
||||
set counter := power := 1
|
||||
while counter < 10^max_power:
|
||||
set truncated := substr(filename, 0, 6 - power + 1) + "~" + counter
|
||||
set result := "<truncated>.<extension>"
|
||||
if result is collision free:
|
||||
return result
|
||||
counter++
|
||||
if counter >= 10 ** power:
|
||||
power++
|
||||
raise ValueError
|
||||
|
||||
This will basically -- for a given original filename of ``some_filename`` and an extension of ``gco`` -- iterate
|
||||
through names of the format ``some_f~1.gco``, ``some_f~2.gco``, ..., ``some_~10.gco``, ``some_~11.gco``, ...,
|
||||
``<prefix>~<n>.gco`` for ``n`` less than 10 ^ ``max_power``, returning as soon as one is found that is not colliding.
|
||||
|
||||
Arguments:
|
||||
filename (string): The filename without the extension to convert to 8.3.
|
||||
extension (string): The extension to convert to 8.3 -- will be truncated to 3 characters if it's longer than
|
||||
that.
|
||||
existing_filenames (list): A list of existing filenames to prevent name collisions with.
|
||||
max_power (int): Limits the possible attempts of generating a collision free name to 10 ^ ``max_power``
|
||||
variations. Defaults to 2, so the name generation will maximally reach ``<name>~99.<ext>`` before
|
||||
aborting and raising an exception.
|
||||
|
||||
Returns:
|
||||
string: A 8.3 representation of the provided original filename, ensured to not collide with the provided
|
||||
``existing_filenames``
|
||||
|
||||
Raises:
|
||||
ValueError: No collision free name could be found.
|
||||
|
||||
Examples:
|
||||
|
||||
>>> find_collision_free_name("test1234", "gco", []) # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> find_collision_free_name("test1234", "gcode", []) # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> find_collision_free_name("test12345", "gco", []) # doctest: +ALLOW_UNICODE
|
||||
'test12~1.gco'
|
||||
>>> find_collision_free_name("test 123", "gco", []) # doctest: +ALLOW_UNICODE
|
||||
'test_123.gco'
|
||||
>>> find_collision_free_name("test1234", "g o", []) # doctest: +ALLOW_UNICODE
|
||||
'test1234.g_o'
|
||||
>>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) # doctest: +ALLOW_UNICODE
|
||||
'test12~2.gco'
|
||||
>>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]]
|
||||
>>> find_collision_free_name("test12345", "gco", many_files) # doctest: +ALLOW_UNICODE
|
||||
'test1~10.gco'
|
||||
>>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)]
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files) # doctest: +ALLOW_UNICODE
|
||||
'test1~99.gco'
|
||||
>>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"]
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) # doctest: +ALLOW_UNICODE
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Can't create a collision free filename
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3) # doctest: +ALLOW_UNICODE
|
||||
'test~100.gco'
|
||||
|
||||
"""
|
||||
|
||||
filename = to_unicode(filename)
|
||||
extension = to_unicode(extension)
|
||||
|
||||
if filename.startswith("/"):
|
||||
filename = filename[1:]
|
||||
existing_filenames = [
|
||||
to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames
|
||||
]
|
||||
|
||||
def make_valid(text):
|
||||
return re.sub(
|
||||
r"\s+", "_", text.translate({ord(i): None for i in r".\"/\[]:;=,"})
|
||||
).lower()
|
||||
|
||||
filename = make_valid(filename)
|
||||
extension = make_valid(extension)
|
||||
extension = extension[:3] if len(extension) > 3 else extension
|
||||
|
||||
full_name_format = "{filename}.{extension}" if extension else "{filename}"
|
||||
|
||||
result = full_name_format.format(filename=filename, extension=extension)
|
||||
if len(filename) <= 8 and result not in existing_filenames:
|
||||
# early exit
|
||||
return result
|
||||
|
||||
counter = 1
|
||||
power = 1
|
||||
prefix_format = "{segment}~{counter}"
|
||||
while counter < (10 ** max_power):
|
||||
prefix = prefix_format.format(
|
||||
segment=filename[: (6 - power + 1)], counter=str(counter)
|
||||
)
|
||||
result = full_name_format.format(filename=prefix, extension=extension)
|
||||
if result not in existing_filenames:
|
||||
return result
|
||||
counter += 1
|
||||
if counter >= 10 ** power:
|
||||
power += 1
|
||||
|
||||
raise ValueError("Can't create a collision free filename")
|
||||
|
||||
|
||||
def silent_remove(file):
|
||||
"""
|
||||
Silently removes a file. Does not raise an error if the file doesn't exist.
|
||||
|
||||
Arguments:
|
||||
file (string): The path of the file to be removed
|
||||
"""
|
||||
|
||||
try:
|
||||
os.remove(file)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def sanitize_ascii(line):
|
||||
if not isinstance(line, basestring):
|
||||
raise ValueError(
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
# -*- 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) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import itertools
|
||||
import os.path
|
||||
import re
|
||||
|
||||
|
||||
def _sfn_really_universal(name):
|
||||
from octoprint.util.text import sanitize
|
||||
|
||||
### taken from pathvalidate library
|
||||
|
||||
_WINDOWS_RESERVED_FILE_NAMES = ("CON", "PRN", "AUX", "CLOCK$", "NUL") + tuple(
|
||||
"{:s}{:d}".format(name, num)
|
||||
for name, num in itertools.product(("COM", "LPT"), range(1, 10))
|
||||
)
|
||||
_MACOS_RESERVED_FILE_NAMES = (":",)
|
||||
|
||||
result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_")
|
||||
root, ext = os.path.splitext(result)
|
||||
if root.upper() in (_WINDOWS_RESERVED_FILE_NAMES + _MACOS_RESERVED_FILE_NAMES):
|
||||
root += "_"
|
||||
return root + ext
|
||||
|
||||
|
||||
def sanitize_filename(name, really_universal=False):
|
||||
"""
|
||||
Sanitizes the provided filename. Implementation differs between Python versions.
|
||||
|
||||
On Python 2, the name will be ASCII-fied, using ``octoprint.util.text.sanitize`` with
|
||||
safe chars ``-_.()[] `` and all spaces replaced by ``_``.
|
||||
|
||||
On Python 3, ``pathvalidate.sanitize_filename`` will be used instead, leaving the
|
||||
name as intact as possible while still being a legal file name under all operating
|
||||
systems.
|
||||
|
||||
In all cases, a single leading ``.`` will be removed (as it denotes hidden files
|
||||
on *nix).
|
||||
|
||||
Args:
|
||||
name: The file name to sanitize. Only the name, no path elements.
|
||||
really_universal: If ``True``, the Python 2 method of sanitization will always
|
||||
be used. Defaults to ``False``.
|
||||
|
||||
Returns:
|
||||
the sanitized file name
|
||||
"""
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
name = to_unicode(name)
|
||||
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
try:
|
||||
from pathvalidate import sanitize_filename as sfn
|
||||
except ImportError:
|
||||
sfn = _sfn_really_universal
|
||||
|
||||
if really_universal:
|
||||
result = _sfn_really_universal(name)
|
||||
else:
|
||||
result = sfn(name)
|
||||
|
||||
return result.lstrip(".")
|
||||
|
||||
|
||||
def get_dos_filename(
|
||||
input, existing_filenames=None, extension=None, whitelisted_extensions=None, **kwargs
|
||||
):
|
||||
"""
|
||||
Converts the provided input filename to a 8.3 DOS compatible filename. If ``existing_filenames`` is provided, the
|
||||
conversion result will be guaranteed not to collide with any of the filenames provided thus.
|
||||
|
||||
Uses :func:`find_collision_free_name` internally.
|
||||
|
||||
Arguments:
|
||||
input (string): The original filename incl. extension to convert to the 8.3 format.
|
||||
existing_filenames (list): A list of existing filenames with which the generated 8.3 name must not collide.
|
||||
Optional.
|
||||
extension (string): The .3 file extension to use for the generated filename. If not provided, the extension of
|
||||
the provided ``filename`` will simply be truncated to 3 characters.
|
||||
whitelisted_extensions (list): A list of extensions on ``input`` that will be left as-is instead of
|
||||
exchanging for ``extension``.
|
||||
kwargs (dict): Additional keyword arguments to provide to :func:`find_collision_free_name`.
|
||||
|
||||
Returns:
|
||||
string: A 8.3 compatible translation of the original filename, not colliding with the optionally provided
|
||||
``existing_filenames`` and with the provided ``extension`` or the original extension shortened to
|
||||
a maximum of 3 characters.
|
||||
|
||||
Raises:
|
||||
ValueError: No 8.3 compatible name could be found that doesn't collide with the provided ``existing_filenames``.
|
||||
|
||||
Examples:
|
||||
|
||||
>>> get_dos_filename("test1234.gco") # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> get_dos_filename("test1234.gcode") # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> get_dos_filename("test12345.gco") # doctest: +ALLOW_UNICODE
|
||||
'test12~1.gco'
|
||||
>>> get_dos_filename("Wölfe 🐺.gcode") # doctest: +ALLOW_UNICODE
|
||||
'wolfe_~1.gco'
|
||||
>>> get_dos_filename("💚.gcode") # doctest: +ALLOW_UNICODE
|
||||
'green_~1.gco'
|
||||
>>> get_dos_filename("test1234.fnord", extension="gco") # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> get_dos_filename("auto0.g", extension="gco") # doctest: +ALLOW_UNICODE
|
||||
'auto0.gco'
|
||||
>>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"]) # doctest: +ALLOW_UNICODE
|
||||
'auto0.g'
|
||||
>>> get_dos_filename(None)
|
||||
>>> get_dos_filename("foo") # doctest: +ALLOW_UNICODE
|
||||
'foo'
|
||||
"""
|
||||
|
||||
if input is None:
|
||||
return None
|
||||
|
||||
input = sanitize_filename(input, really_universal=True)
|
||||
|
||||
if existing_filenames is None:
|
||||
existing_filenames = []
|
||||
|
||||
if extension is not None:
|
||||
extension = extension.lower()
|
||||
|
||||
if whitelisted_extensions is None:
|
||||
whitelisted_extensions = []
|
||||
|
||||
filename, ext = os.path.splitext(input)
|
||||
|
||||
ext = ext.lower()
|
||||
ext = ext[1:] if ext.startswith(".") else ext
|
||||
if ext in whitelisted_extensions or extension is None:
|
||||
extension = ext
|
||||
|
||||
return find_collision_free_name(filename, extension, existing_filenames, **kwargs)
|
||||
|
||||
|
||||
def find_collision_free_name(filename, extension, existing_filenames, max_power=2):
|
||||
"""
|
||||
Tries to find a collision free translation of "<filename>.<extension>" to the 8.3 DOS compatible format,
|
||||
preventing collisions with any of the ``existing_filenames``.
|
||||
|
||||
First strips all of ``."/\\[]:;=,`` from the filename and extensions, converts them to lower case and truncates
|
||||
the ``extension`` to a maximum length of 3 characters.
|
||||
|
||||
If the filename is already equal or less than 8 characters in length after that procedure and "<filename>.<extension>"
|
||||
are not contained in the ``existing_files``, that concatenation will be returned as the result.
|
||||
|
||||
If not, the following algorithm will be applied to try to find a collision free name::
|
||||
|
||||
set counter := power := 1
|
||||
while counter < 10^max_power:
|
||||
set truncated := substr(filename, 0, 6 - power + 1) + "~" + counter
|
||||
set result := "<truncated>.<extension>"
|
||||
if result is collision free:
|
||||
return result
|
||||
counter++
|
||||
if counter >= 10 ** power:
|
||||
power++
|
||||
raise ValueError
|
||||
|
||||
This will basically -- for a given original filename of ``some_filename`` and an extension of ``gco`` -- iterate
|
||||
through names of the format ``some_f~1.gco``, ``some_f~2.gco``, ..., ``some_~10.gco``, ``some_~11.gco``, ...,
|
||||
``<prefix>~<n>.gco`` for ``n`` less than 10 ^ ``max_power``, returning as soon as one is found that is not colliding.
|
||||
|
||||
Arguments:
|
||||
filename (string): The filename without the extension to convert to 8.3.
|
||||
extension (string): The extension to convert to 8.3 -- will be truncated to 3 characters if it's longer than
|
||||
that.
|
||||
existing_filenames (list): A list of existing filenames to prevent name collisions with.
|
||||
max_power (int): Limits the possible attempts of generating a collision free name to 10 ^ ``max_power``
|
||||
variations. Defaults to 2, so the name generation will maximally reach ``<name>~99.<ext>`` before
|
||||
aborting and raising an exception.
|
||||
|
||||
Returns:
|
||||
string: A 8.3 representation of the provided original filename, ensured to not collide with the provided
|
||||
``existing_filenames``
|
||||
|
||||
Raises:
|
||||
ValueError: No collision free name could be found.
|
||||
|
||||
Examples:
|
||||
|
||||
>>> find_collision_free_name("test1234", "gco", []) # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> find_collision_free_name("test1234", "gcode", []) # doctest: +ALLOW_UNICODE
|
||||
'test1234.gco'
|
||||
>>> find_collision_free_name("test12345", "gco", []) # doctest: +ALLOW_UNICODE
|
||||
'test12~1.gco'
|
||||
>>> find_collision_free_name("test 123", "gco", []) # doctest: +ALLOW_UNICODE
|
||||
'test_123.gco'
|
||||
>>> find_collision_free_name("test1234", "g o", []) # doctest: +ALLOW_UNICODE
|
||||
'test1234.g_o'
|
||||
>>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) # doctest: +ALLOW_UNICODE
|
||||
'test12~2.gco'
|
||||
>>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]]
|
||||
>>> find_collision_free_name("test12345", "gco", many_files) # doctest: +ALLOW_UNICODE
|
||||
'test1~10.gco'
|
||||
>>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)]
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files) # doctest: +ALLOW_UNICODE
|
||||
'test1~99.gco'
|
||||
>>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"]
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) # doctest: +ALLOW_UNICODE
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Can't create a collision free filename
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3) # doctest: +ALLOW_UNICODE
|
||||
'test~100.gco'
|
||||
|
||||
"""
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
filename = to_unicode(filename)
|
||||
extension = to_unicode(extension)
|
||||
|
||||
if filename.startswith("/"):
|
||||
filename = filename[1:]
|
||||
existing_filenames = [
|
||||
to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames
|
||||
]
|
||||
|
||||
def make_valid(text):
|
||||
return re.sub(
|
||||
r"\s+", "_", text.translate({ord(i): None for i in r".\"/\[]:;=,"})
|
||||
).lower()
|
||||
|
||||
filename = make_valid(filename)
|
||||
extension = make_valid(extension)
|
||||
extension = extension[:3] if len(extension) > 3 else extension
|
||||
|
||||
full_name_format = "{filename}.{extension}" if extension else "{filename}"
|
||||
|
||||
result = full_name_format.format(filename=filename, extension=extension)
|
||||
if len(filename) <= 8 and result not in existing_filenames:
|
||||
# early exit
|
||||
return result
|
||||
|
||||
counter = 1
|
||||
power = 1
|
||||
prefix_format = "{segment}~{counter}"
|
||||
while counter < (10 ** max_power):
|
||||
prefix = prefix_format.format(
|
||||
segment=filename[: (6 - power + 1)], counter=str(counter)
|
||||
)
|
||||
result = full_name_format.format(filename=prefix, extension=extension)
|
||||
if result not in existing_filenames:
|
||||
return result
|
||||
counter += 1
|
||||
if counter >= 10 ** power:
|
||||
power += 1
|
||||
|
||||
raise ValueError("Can't create a collision free filename")
|
||||
|
||||
|
||||
def silent_remove(file):
|
||||
"""
|
||||
Silently removes a file. Does not raise an error if the file doesn't exist.
|
||||
|
||||
Arguments:
|
||||
file (string): The path of the file to be removed
|
||||
"""
|
||||
|
||||
try:
|
||||
os.remove(file)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -15,6 +15,12 @@ _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U)
|
||||
_SLUGIFIES = {}
|
||||
|
||||
|
||||
def demojify(text):
|
||||
text = to_unicode(text)
|
||||
text = remove_unicode_variations(text)
|
||||
return demojize(text, delimiters=("", ""))
|
||||
|
||||
|
||||
def sanitize(text, safe_chars="-_.", demoji=True):
|
||||
"""
|
||||
Sanitizes text by running it through slugify and optionally emoji translating.
|
||||
@@ -47,8 +53,7 @@ def sanitize(text, safe_chars="-_.", demoji=True):
|
||||
|
||||
text = to_unicode(text)
|
||||
if demoji:
|
||||
text = remove_unicode_variations(text)
|
||||
text = demojize(text, delimiters=("", ""))
|
||||
text = demojify(text)
|
||||
return slugify(text)
|
||||
|
||||
|
||||
|
||||
@@ -11,10 +11,25 @@ import os.path
|
||||
import unittest
|
||||
|
||||
import mock
|
||||
import pytest
|
||||
from ddt import data, ddt, unpack
|
||||
|
||||
from octoprint.filemanager.storage import LocalFileStorage, StorageError
|
||||
|
||||
try:
|
||||
import pathvalidate # noqa: F401
|
||||
|
||||
HAS_PATHVALIDATE = True
|
||||
except ImportError:
|
||||
HAS_PATHVALIDATE = False
|
||||
|
||||
pathvalidate_unavailable_only = pytest.mark.skipif(
|
||||
HAS_PATHVALIDATE, reason="pathvalidate available"
|
||||
)
|
||||
pathvalidate_available_only = pytest.mark.skipif(
|
||||
not HAS_PATHVALIDATE, reason="pathvalidate unavailable"
|
||||
)
|
||||
|
||||
|
||||
class FileWrapper(object):
|
||||
def __init__(self, filename):
|
||||
@@ -238,28 +253,14 @@ class LocalStorageTest(unittest.TestCase):
|
||||
self.assertIsNotNone(copied_metadata)
|
||||
self.assertDictEqual(before_stl_metadata, copied_metadata)
|
||||
|
||||
def test_copy_file_new_display(self):
|
||||
def test_copy_file_same_name(self):
|
||||
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
|
||||
try:
|
||||
self.storage.copy_file("bp_case.stl", "bp_cäse.stl")
|
||||
self.storage.copy_file("bp_case.stl", "bp_case.stl")
|
||||
self.fail("Expected an exception")
|
||||
except StorageError as e:
|
||||
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
|
||||
|
||||
def test_move_file_new_display(self):
|
||||
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
|
||||
|
||||
before_metadata = self.storage.get_metadata("bp_case.stl")
|
||||
self.storage.move_file("bp_case.stl", "bp_cäse.stl")
|
||||
after_metadata = self.storage.get_metadata("bp_case.stl")
|
||||
|
||||
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "bp_case.stl")))
|
||||
|
||||
self.assertIsNotNone(before_metadata)
|
||||
self.assertIsNotNone(after_metadata)
|
||||
self.assertIn("display", after_metadata)
|
||||
self.assertEqual("bp_cäse.stl", after_metadata["display"])
|
||||
|
||||
@data("copy_file", "move_file")
|
||||
def test_copy_move_file_different_display(self, operation):
|
||||
self._add_file("bp_case.stl", FILE_BP_CASE_STL, display="bp_cäse.stl")
|
||||
@@ -322,9 +323,7 @@ class LocalStorageTest(unittest.TestCase):
|
||||
self.assertEqual("täst", metadata["display"])
|
||||
|
||||
def test_add_subfolder(self):
|
||||
folder_name = self._add_and_verify_folder(
|
||||
"folder with some spaces", "folder_with_some_spaces"
|
||||
)
|
||||
folder_name = self._add_and_verify_folder("folder", "folder")
|
||||
subfolder_name = self._add_and_verify_folder(
|
||||
(folder_name, "subfolder"), folder_name + "/subfolder"
|
||||
)
|
||||
@@ -441,25 +440,14 @@ class LocalStorageTest(unittest.TestCase):
|
||||
self.assertIsNotNone(copied_metadata)
|
||||
self.assertDictEqual(before_source_metadata, copied_metadata)
|
||||
|
||||
def test_copy_folder_new_display(self):
|
||||
def test_copy_folder_same_name(self):
|
||||
self._add_folder("folder")
|
||||
try:
|
||||
self.storage.copy_folder("folder", "földer")
|
||||
self.storage.copy_folder("folder", "folder")
|
||||
self.fail("Expected an exception")
|
||||
except StorageError as e:
|
||||
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
|
||||
|
||||
def test_move_folder_new_display(self):
|
||||
self._add_folder("folder")
|
||||
|
||||
before_metadata = self.storage.get_metadata("folder")
|
||||
self.storage.move_folder("folder", "földer")
|
||||
after_metadata = self.storage.get_metadata("folder")
|
||||
|
||||
self.assertIsNone(before_metadata)
|
||||
self.assertIsNotNone(after_metadata)
|
||||
self.assertDictEqual(after_metadata, {"display": "földer"})
|
||||
|
||||
@data("copy_folder", "move_folder")
|
||||
def test_copy_move_folder_different_display(self, operation):
|
||||
self._add_folder("folder", display="földer")
|
||||
@@ -744,6 +732,7 @@ class LocalStorageTest(unittest.TestCase):
|
||||
self.assertEqual(0, len(gcode_metadata["links"]))
|
||||
self.assertEqual(1, len(stl_metadata["links"]))
|
||||
|
||||
@pathvalidate_unavailable_only
|
||||
@data(
|
||||
("some_file.gco", "some_file.gco"),
|
||||
(
|
||||
@@ -753,7 +742,21 @@ class LocalStorageTest(unittest.TestCase):
|
||||
("pengüino pequeño.stl", "penguino_pequeno.stl"),
|
||||
)
|
||||
@unpack
|
||||
def test_sanitize_name(self, input, expected):
|
||||
def test_sanitize_name_pvu(self, input, expected):
|
||||
actual = self.storage.sanitize_name(input)
|
||||
self.assertEqual(expected, actual)
|
||||
|
||||
@pathvalidate_available_only
|
||||
@data(
|
||||
("some_file.gco", "some_file.gco"),
|
||||
(
|
||||
"some_file with (parentheses) and ümläuts and digits 123.gco",
|
||||
"some_file with (parentheses) and ümläuts and digits 123.gco",
|
||||
),
|
||||
("pengüino pequeño.stl", "pengüino pequeño.stl"),
|
||||
)
|
||||
@unpack
|
||||
def test_sanitize_name_pva(self, input, expected):
|
||||
actual = self.storage.sanitize_name(input)
|
||||
self.assertEqual(expected, actual)
|
||||
|
||||
@@ -787,17 +790,7 @@ class LocalStorageTest(unittest.TestCase):
|
||||
except ValueError as e:
|
||||
self.assertTrue(e.args[0].startswith("path not contained in base folder: "))
|
||||
|
||||
@data(
|
||||
("some/folder/and/some file.gco", "/some/folder/and", "some_file.gco"),
|
||||
(("some", "folder", "and", "some file.gco"), "/some/folder/and", "some_file.gco"),
|
||||
("some file.gco", "/", "some_file.gco"),
|
||||
(("some file.gco",), "/", "some_file.gco"),
|
||||
("", "/", ""),
|
||||
("some/folder/with/trailing/slash/", "/some/folder/with/trailing/slash", ""),
|
||||
(("some", "folder", ""), "/some/folder", ""),
|
||||
)
|
||||
@unpack
|
||||
def test_sanitize(self, input, expected_path, expected_name):
|
||||
def _test_sanitize(self, input, expected_path, expected_name):
|
||||
actual = self.storage.sanitize(input)
|
||||
self.assertTrue(isinstance(actual, tuple))
|
||||
self.assertEqual(2, len(actual))
|
||||
@@ -814,6 +807,34 @@ class LocalStorageTest(unittest.TestCase):
|
||||
self.assertEqual(expected_path, actual_path)
|
||||
self.assertEqual(expected_name, actual_name)
|
||||
|
||||
@pathvalidate_unavailable_only
|
||||
@data(
|
||||
("some/folder/and/some file.gco", "/some/folder/and", "some_file.gco"),
|
||||
(("some", "folder", "and", "some file.gco"), "/some/folder/and", "some_file.gco"),
|
||||
("some file.gco", "/", "some_file.gco"),
|
||||
(("some file.gco",), "/", "some_file.gco"),
|
||||
("", "/", ""),
|
||||
("some/folder/with/trailing/slash/", "/some/folder/with/trailing/slash", ""),
|
||||
(("some", "folder", ""), "/some/folder", ""),
|
||||
)
|
||||
@unpack
|
||||
def test_sanitize_pvu(self, input, expected_path, expected_name):
|
||||
self._test_sanitize(input, expected_path, expected_name)
|
||||
|
||||
@pathvalidate_available_only
|
||||
@data(
|
||||
("some/folder/and/some file.gco", "/some/folder/and", "some file.gco"),
|
||||
(("some", "folder", "and", "some file.gco"), "/some/folder/and", "some file.gco"),
|
||||
("some file.gco", "/", "some file.gco"),
|
||||
(("some file.gco",), "/", "some file.gco"),
|
||||
("", "/", ""),
|
||||
("some/folder/with/trailing/slash/", "/some/folder/with/trailing/slash", ""),
|
||||
(("some", "folder", ""), "/some/folder", ""),
|
||||
)
|
||||
@unpack
|
||||
def test_sanitize_pva(self, input, expected_path, expected_name):
|
||||
self._test_sanitize(input, expected_path, expected_name)
|
||||
|
||||
def _add_and_verify_file(
|
||||
self, path, expected_path, file_object, links=None, overwrite=False, display=None
|
||||
):
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# -*- 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) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
from ddt import data, ddt, unpack
|
||||
|
||||
from octoprint.util.files import sanitize_filename
|
||||
|
||||
try:
|
||||
import pathvalidate # noqa: F401
|
||||
|
||||
HAS_PATHVALIDATE = True
|
||||
except ImportError:
|
||||
HAS_PATHVALIDATE = False
|
||||
|
||||
pathvalidate_unavailable_only = pytest.mark.skipif(
|
||||
HAS_PATHVALIDATE, reason="pathvalidate available"
|
||||
)
|
||||
pathvalidate_available_only = pytest.mark.skipif(
|
||||
not HAS_PATHVALIDATE, reason="pathvalidate unavailable"
|
||||
)
|
||||
|
||||
|
||||
@ddt
|
||||
class FilesUtilTest(unittest.TestCase):
|
||||
@data(
|
||||
("some_file.gcode", "some_file.gcode"),
|
||||
("NUL.gcode", "NUL_.gcode"),
|
||||
("LPT1", "LPT1_"),
|
||||
(".test.gcode", "test.gcode"),
|
||||
("..text.gcode", "test.gcode"),
|
||||
)
|
||||
@unpack
|
||||
def test_sanitize_filename(self, filename, expected):
|
||||
actual = sanitize_filename(filename)
|
||||
self.assertEqual(actual, expected)
|
||||
|
||||
@data("file/with/slash.gcode", "file\\with\\backslash.gcode")
|
||||
def test_sanitize_filename_invalid(self, filename):
|
||||
try:
|
||||
sanitize_filename(filename)
|
||||
self.fail("expected ValueError")
|
||||
except ValueError as ex:
|
||||
self.assertEqual(str(ex), "name must not contain / or \\")
|
||||
|
||||
@pathvalidate_unavailable_only
|
||||
@data(
|
||||
("file with space.gcode", "file_with_space.gcode"),
|
||||
("Wölfe 🐺.gcode", "Wolfe_wolf_face.gcode"),
|
||||
)
|
||||
@unpack
|
||||
def test_sanitize_filename_pvu(self, filename, expected):
|
||||
actual = sanitize_filename(filename)
|
||||
self.assertEqual(actual, expected)
|
||||
|
||||
@pathvalidate_available_only
|
||||
@data(
|
||||
("file with space.gcode", "file with space.gcode"),
|
||||
("Wölfe 🐺.gcode", "Wölfe 🐺.gcode"),
|
||||
)
|
||||
@unpack
|
||||
def test_sanitize_filename_pva(self, filename, expected):
|
||||
actual = sanitize_filename(filename)
|
||||
self.assertEqual(actual, expected)
|
||||
Reference in new issue
Block a user