Skip to content

Commit b820771

Browse files
[3.12] bpo-26791: Update shutil.move() to provide the same symlink move behavior as the mv shell when moving a symlink into a directory that is the target of the symlink (GH-21759) (GH-113517)
(cherry picked from commit c66b577) Co-authored-by: Jeffrey Kintscher <[email protected]>
1 parent b2ef358 commit b820771

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

Lib/shutil.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -870,7 +870,7 @@ def move(src, dst, copy_function=copy2):
870870
sys.audit("shutil.move", src, dst)
871871
real_dst = dst
872872
if os.path.isdir(dst):
873-
if _samefile(src, dst):
873+
if _samefile(src, dst) and not os.path.islink(src):
874874
# We might be on a case insensitive filesystem,
875875
# perform the rename anyway.
876876
os.rename(src, dst)

Lib/test/test_shutil.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2636,6 +2636,35 @@ def test_move_dir_caseinsensitive(self):
26362636
finally:
26372637
os.rmdir(dst_dir)
26382638

2639+
# bpo-26791: Check that a symlink to a directory can
2640+
# be moved into that directory.
2641+
@mock_rename
2642+
def _test_move_symlink_to_dir_into_dir(self, dst):
2643+
src = os.path.join(self.src_dir, 'linktodir')
2644+
dst_link = os.path.join(self.dst_dir, 'linktodir')
2645+
os.symlink(self.dst_dir, src, target_is_directory=True)
2646+
shutil.move(src, dst)
2647+
self.assertTrue(os.path.islink(dst_link))
2648+
self.assertTrue(os.path.samefile(self.dst_dir, dst_link))
2649+
self.assertFalse(os.path.exists(src))
2650+
2651+
# Repeat the move operation with the destination
2652+
# symlink already in place (should raise shutil.Error).
2653+
os.symlink(self.dst_dir, src, target_is_directory=True)
2654+
with self.assertRaises(shutil.Error):
2655+
shutil.move(src, dst)
2656+
self.assertTrue(os.path.samefile(self.dst_dir, dst_link))
2657+
self.assertTrue(os.path.exists(src))
2658+
2659+
@os_helper.skip_unless_symlink
2660+
def test_move_symlink_to_dir_into_dir(self):
2661+
self._test_move_symlink_to_dir_into_dir(self.dst_dir)
2662+
2663+
@os_helper.skip_unless_symlink
2664+
def test_move_symlink_to_dir_into_symlink_to_dir(self):
2665+
dst = os.path.join(self.src_dir, 'otherlinktodir')
2666+
os.symlink(self.dst_dir, dst, target_is_directory=True)
2667+
self._test_move_symlink_to_dir_into_dir(dst)
26392668

26402669
@os_helper.skip_unless_dac_override
26412670
@unittest.skipUnless(hasattr(os, 'lchflags')
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
:func:`shutil.move` now moves a symlink into a directory when that
2+
directory is the target of the symlink. This provides the same behavior as
3+
the mv shell command. The previous behavior raised an exception. Patch by
4+
Jeffrey Kintscher.

0 commit comments

Comments
 (0)