diff options
-rw-r--r-- | compressor/storage.py | 17 | ||||
-rw-r--r-- | 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) |