Skip to content

Commit

Permalink
Use shutil.move() to move files.
Browse files Browse the repository at this point in the history
  • Loading branch information
aereaux committed Feb 25, 2024
1 parent dae5257 commit b18c0fe
Showing 1 changed file with 2 additions and 35 deletions.
37 changes: 2 additions & 35 deletions beets/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,10 +503,7 @@ def copy(path: bytes, dest: bytes, replace: bool = False):
def move(path: bytes, dest: bytes, replace: bool = False):
"""Rename a file. `dest` may not be a directory. If `dest` already
exists, raises an OSError unless `replace` is True. Has no effect if
`path` is the same as `dest`. If the paths are on different
filesystems (or the rename otherwise fails), a copy is attempted
instead, in which case metadata will *not* be preserved. Paths are
translated to system paths.
`path` is the same as `dest`. Paths are translated to system paths.
"""
if os.path.isdir(syspath(path)):
raise FilesystemError("source is directory", "move", (path, dest))
Expand All @@ -517,37 +514,7 @@ def move(path: bytes, dest: bytes, replace: bool = False):
if os.path.exists(syspath(dest)) and not replace:
raise FilesystemError("file exists", "rename", (path, dest))

# First, try renaming the file.
try:
os.replace(syspath(path), syspath(dest))
except OSError:
# Copy the file to a temporary destination.
basename = os.path.basename(bytestring_path(dest))
dirname = os.path.dirname(bytestring_path(dest))
tmp = tempfile.NamedTemporaryFile(
suffix=syspath(b".beets", prefix=False),
prefix=syspath(b"." + basename, prefix=False),
dir=syspath(dirname),
delete=False,
)
try:
with open(syspath(path), "rb") as f:
shutil.copyfileobj(f, tmp)
finally:
tmp.close()

# Move the copied file into place.
try:
os.replace(tmp.name, syspath(dest))
tmp = None
os.remove(syspath(path))
except OSError as exc:
raise FilesystemError(
exc, "move", (path, dest), traceback.format_exc()
)
finally:
if tmp is not None:
os.remove(tmp)
shutil.move(syspath(path), syspath(dest))


def link(path: bytes, dest: bytes, replace: bool = False):
Expand Down

0 comments on commit b18c0fe

Please sign in to comment.