From 1c3fa18be76d1bcddb2de516913f46a32c5ed860 Mon Sep 17 00:00:00 2001 From: Brett Cannon Date: Sat, 19 Jun 2004 21:11:35 +0000 Subject: shutil.move() will raise an exception when trying to move a directory into itself. Closes bug #919012 . Thanks Johannes Gijsbers. --- Lib/shutil.py | 6 ++++++ Lib/test/test_shutil.py | 16 ++++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) (limited to 'Lib') diff --git a/Lib/shutil.py b/Lib/shutil.py index 5341786d52..10b7a27767 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -8,6 +8,7 @@ import os import sys import stat import exceptions +from os.path import abspath __all__ = ["copyfileobj","copyfile","copymode","copystat","copy","copy2", "copytree","move","rmtree","Error"] @@ -164,8 +165,13 @@ def move(src, dst): os.rename(src, dst) except OSError: if os.path.isdir(src): + if destinsrc(src, dst): + raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst) copytree(src, dst, symlinks=True) rmtree(src) else: copy2(src,dst) os.unlink(src) + +def destinsrc(src, dst): + return abspath(dst).startswith(abspath(src)) diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index 3a39ec9056..05f34d8466 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -3,6 +3,8 @@ import unittest import shutil import tempfile +import os +import os.path from test import test_support class TestShutil(unittest.TestCase): @@ -12,11 +14,21 @@ class TestShutil(unittest.TestCase): self.assertRaises(OSError, shutil.rmtree, filename) self.assertEqual(shutil.rmtree(filename, True), None) + def test_dont_move_dir_in_itself(self): + src_dir = tempfile.mkdtemp() + try: + dst = os.path.join(src_dir, 'foo') + self.assertRaises(shutil.Error, shutil.move, src_dir, dst) + finally: + try: + os.rmdir(src_dir) + except: + pass + + - def test_main(): test_support.run_unittest(TestShutil) - if __name__ == '__main__': test_main() -- cgit v1.2.1