Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[general] add support for pathlib.Path to clean_name #1200

Merged
merged 1 commit into from Dec 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions storages/utils.py
@@ -1,4 +1,5 @@
import os
import pathlib
import posixpath

from django.conf import settings
Expand Down Expand Up @@ -30,16 +31,22 @@ def setting(name, default=None):

def clean_name(name):
"""
Cleans the name so that Windows style paths work
Normalize the name.

Includes cleaning up Windows style paths, ensuring an ending trailing slash,
and coercing from pathlib.Path.
"""
if isinstance(name, pathlib.Path):
name = str(name)

# Normalize Windows style paths
clean_name = posixpath.normpath(name).replace('\\', '/')

# os.path.normpath() can strip trailing slashes so we implement
# a workaround here.
if name.endswith('/') and not clean_name.endswith('/'):
# Add a trailing slash as it was stripped.
clean_name = clean_name + '/'
clean_name += '/'

# Given an empty string, os.path.normpath() will return ., which we don't want
if clean_name == '.':
Expand Down
18 changes: 9 additions & 9 deletions tests/test_utils.py
@@ -1,4 +1,5 @@
import datetime
import pathlib

from django.conf import settings
from django.core.exceptions import SuspiciousFileOperation
Expand All @@ -16,12 +17,15 @@ def test_get_setting(self):

class CleanNameTests(TestCase):
def test_clean_name(self):
"""
Test the base case of clean_name
"""
"""Test the base case of clean_name."""
path = utils.clean_name("path/to/somewhere")
self.assertEqual(path, "path/to/somewhere")

def test_clean_name_pathlib(self):
"""Test for pathlib.Path handling."""
path = pathlib.Path("path/to/anywhere")
self.assertEqual(utils.clean_name(path), "path/to/anywhere")

def test_clean_name_normalize(self):
"""
Test the normalization of clean_name
Expand All @@ -30,16 +34,12 @@ def test_clean_name_normalize(self):
self.assertEqual(path, "path/somewhere")

def test_clean_name_trailing_slash(self):
"""
Test the clean_name when the path has a trailing slash
"""
"""Test the clean_name when the path has a trailing slash."""
path = utils.clean_name("path/to/somewhere/")
self.assertEqual(path, "path/to/somewhere/")

def test_clean_name_windows(self):
"""
Test the clean_name when the path has a trailing slash
"""
"""Test the clean_name when the path has a trailing slash."""
path = utils.clean_name("path\\to\\somewhere")
self.assertEqual(path, "path/to/somewhere")

Expand Down