Skip to content

Commit

Permalink
Fixed #35323 -- Prevented file_move_safe() from trying to overwrite e…
Browse files Browse the repository at this point in the history
…xisting file when allow_overwrite is False.
  • Loading branch information
bcail authored and felixxm committed Mar 24, 2024
1 parent b6e2b83 commit 07c8d97
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
11 changes: 5 additions & 6 deletions django/core/files/move.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,12 @@ def file_move_safe(
except OSError:
pass

try:
if not allow_overwrite and os.access(new_file_name, os.F_OK):
raise FileExistsError(
"Destination file %s exists and allow_overwrite is False."
% new_file_name
)
if not allow_overwrite and os.access(new_file_name, os.F_OK):
raise FileExistsError(
f"Destination file {new_file_name} exists and allow_overwrite is False."
)

try:
os.rename(old_file_name, new_file_name)
return
except OSError:
Expand Down
7 changes: 4 additions & 3 deletions tests/files/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,9 +426,10 @@ def test_file_move_overwrite(self):
handle_a, self.file_a = tempfile.mkstemp()
handle_b, self.file_b = tempfile.mkstemp()

# file_move_safe() raises OSError if the destination file exists and
# allow_overwrite is False.
with self.assertRaises(FileExistsError):
# file_move_safe() raises FileExistsError if the destination file
# exists and allow_overwrite is False.
msg = r"Destination file .* exists and allow_overwrite is False\."
with self.assertRaisesRegex(FileExistsError, msg):
file_move_safe(self.file_a, self.file_b, allow_overwrite=False)

# should allow it and continue on if allow_overwrite is True
Expand Down

0 comments on commit 07c8d97

Please sign in to comment.