1"""
2Move a file in the safest way possible::
3
4 >>> from plain.internal.files.move import file_move_safe
5 >>> file_move_safe("/tmp/old_file", "/tmp/new_file")
6"""
7
8import os
9from shutil import copymode, copystat
10
11from plain.internal.files import locks
12
13
14def _samefile(src: str, dst: str) -> bool:
15 # Macintosh, Unix.
16 if hasattr(os.path, "samefile"):
17 try:
18 return os.path.samefile(src, dst)
19 except OSError:
20 return False
21
22 # All other platforms: check for same pathname.
23 return os.path.normcase(os.path.abspath(src)) == os.path.normcase(
24 os.path.abspath(dst)
25 )
26
27
28def file_move_safe(
29 old_file_name: str,
30 new_file_name: str,
31 chunk_size: int = 1024 * 64,
32 allow_overwrite: bool = False,
33) -> None:
34 """
35 Move a file from one location to another in the safest way possible.
36
37 First, try ``os.rename``, which is simple but will break across filesystems.
38 If that fails, stream manually from one file to another in pure Python.
39
40 If the destination file exists and ``allow_overwrite`` is ``False``, raise
41 ``FileExistsError``.
42 """
43 # There's no reason to move if we don't have to.
44 if _samefile(old_file_name, new_file_name):
45 return
46
47 try:
48 if not allow_overwrite and os.access(new_file_name, os.F_OK):
49 raise FileExistsError(
50 f"Destination file {new_file_name} exists and allow_overwrite is False."
51 )
52
53 os.rename(old_file_name, new_file_name)
54 return
55 except OSError:
56 # OSError happens with os.rename() if moving to another filesystem or
57 # when moving opened files on certain operating systems.
58 pass
59
60 # first open the old file, so that it won't go away
61 with open(old_file_name, "rb") as old_file:
62 # now open the new file, not forgetting allow_overwrite
63 fd = os.open(
64 new_file_name,
65 (
66 os.O_WRONLY
67 | os.O_CREAT
68 | getattr(os, "O_BINARY", 0)
69 | (os.O_EXCL if not allow_overwrite else 0)
70 ),
71 )
72 try:
73 locks.lock(fd, locks.LOCK_EX)
74 current_chunk = None
75 while current_chunk != b"":
76 current_chunk = old_file.read(chunk_size)
77 os.write(fd, current_chunk)
78 finally:
79 locks.unlock(fd)
80 os.close(fd)
81
82 try:
83 copystat(old_file_name, new_file_name)
84 except PermissionError:
85 # Certain filesystems (e.g. CIFS) fail to copy the file's metadata if
86 # the type of the destination filesystem isn't the same as the source
87 # filesystem. This also happens with some SELinux-enabled systems.
88 # Ignore that, but try to set basic permissions.
89 try:
90 copymode(old_file_name, new_file_name)
91 except PermissionError:
92 pass
93
94 try:
95 os.remove(old_file_name)
96 except PermissionError as e:
97 # Certain operating systems (Cygwin and Windows)
98 # fail when deleting opened files, ignore it. (For the
99 # systems where this happens, temporary files will be auto-deleted
100 # on close anyway.)
101 if getattr(e, "winerror", 0) != 32:
102 raise