Skip to content

Commit c66b577

Browse files
authored
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)
1 parent 1b19d73 commit c66b577

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
@@ -885,7 +885,7 @@ def move(src, dst, copy_function=copy2):
885885
sys.audit("shutil.move", src, dst)
886886
real_dst = dst
887887
if os.path.isdir(dst):
888-
if _samefile(src, dst):
888+
if _samefile(src, dst) and not os.path.islink(src):
889889
# We might be on a case insensitive filesystem,
890890
# perform the rename anyway.
891891
os.rename(src, dst)

Lib/test/test_shutil.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2688,6 +2688,35 @@ def test_move_dir_caseinsensitive(self):
26882688
finally:
26892689
os.rmdir(dst_dir)
26902690

2691+
# bpo-26791: Check that a symlink to a directory can
2692+
# be moved into that directory.
2693+
@mock_rename
2694+
def _test_move_symlink_to_dir_into_dir(self, dst):
2695+
src = os.path.join(self.src_dir, 'linktodir')
2696+
dst_link = os.path.join(self.dst_dir, 'linktodir')
2697+
os.symlink(self.dst_dir, src, target_is_directory=True)
2698+
shutil.move(src, dst)
2699+
self.assertTrue(os.path.islink(dst_link))
2700+
self.assertTrue(os.path.samefile(self.dst_dir, dst_link))
2701+
self.assertFalse(os.path.exists(src))
2702+
2703+
# Repeat the move operation with the destination
2704+
# symlink already in place (should raise shutil.Error).
2705+
os.symlink(self.dst_dir, src, target_is_directory=True)
2706+
with self.assertRaises(shutil.Error):
2707+
shutil.move(src, dst)
2708+
self.assertTrue(os.path.samefile(self.dst_dir, dst_link))
2709+
self.assertTrue(os.path.exists(src))
2710+
2711+
@os_helper.skip_unless_symlink
2712+
def test_move_symlink_to_dir_into_dir(self):
2713+
self._test_move_symlink_to_dir_into_dir(self.dst_dir)
2714+
2715+
@os_helper.skip_unless_symlink
2716+
def test_move_symlink_to_dir_into_symlink_to_dir(self):
2717+
dst = os.path.join(self.src_dir, 'otherlinktodir')
2718+
os.symlink(self.dst_dir, dst, target_is_directory=True)
2719+
self._test_move_symlink_to_dir_into_dir(dst)
26912720

26922721
@os_helper.skip_unless_dac_override
26932722
@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)