From 00910e0bd5295044befacdad7b88249ec7bbf142 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C4=93teris=20Caune?= Date: Sun, 3 Apr 2022 15:09:16 +0300 Subject: Remove delete() call from CompressorFileStorage.get_available_name (#1107) * Remove delete() call from CompressorFileStorage.get_available_name * Add a testcase for duplicate handling in save() --- compressor/storage.py | 17 ++++++++++------- compressor/tests/test_storages.py | 6 ++++++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/compressor/storage.py b/compressor/storage.py index a9d7a0c..5d12eb8 100644 --- a/compressor/storage.py +++ b/compressor/storage.py @@ -33,13 +33,16 @@ class CompressorFileStorage(FileSystemStorage): def modified_time(self, name): return datetime.fromtimestamp(os.path.getmtime(self.path(name))) - def get_available_name(self, name, max_length=None): - """ - Deletes the given file if it exists. - """ - if self.exists(name): - self.delete(name) - return name + def save(self, filename, content): + temp_filename = super().save(filename, content) + # If a file already exists in the target location, FileSystemStorage + # will generate an unique filename and save content there instead. + # When that happens, we move the file to the intended location using + # os.replace() (which is an atomic operation): + if temp_filename != filename: + os.replace(self.path(temp_filename), self.path(filename)) + + return filename compressor_file_storage = SimpleLazyObject( diff --git a/compressor/tests/test_storages.py b/compressor/tests/test_storages.py index 8a99e45..9168510 100644 --- a/compressor/tests/test_storages.py +++ b/compressor/tests/test_storages.py @@ -61,3 +61,9 @@ class StorageTestCase(TestCase): context = {'STATIC_URL': settings.COMPRESS_URL} out = css_tag("/static/CACHE/css/output.e701f86c6430.css") self.assertEqual(out, render(template, context)) + + def test_duplicate_save_overwrites_same_file(self): + filename1 = self.default_storage.save('test.txt', ContentFile('yeah yeah')) + filename2 = self.default_storage.save('test.txt', ContentFile('yeah yeah')) + self.assertEqual(filename1, filename2) + self.assertNotIn("_", filename2) -- cgit v1.2.1