[ python-Bugs-851123 ] shutil.copy destroys hard links

SourceForge.net noreply at sourceforge.net
Mon Dec 1 12:03:52 EST 2003


Bugs item #851123, was opened at 2003-11-29 07:36
Message generated for change (Comment added) made by greg_ball
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=851123&group_id=5470

Category: Python Library
Group: Python 2.3
Status: Open
Resolution: None
Priority: 5
Submitted By: Gerald Schlueter (gls62)
Assigned to: Nobody/Anonymous (nobody)
Summary: shutil.copy destroys hard links

Initial Comment:
Hi, 
I am using python2.3 on a debian linux (unstable) kernel 
Version 2.4.20. 
 
shell: 
cd /tmp 
cp /etc/passwd a 
ln a b 
cp a b 
*** a and b are the same file *** 
 
python 
import shutil 
shutil.copy("a", "b") 
 
The file is destroyed and cut down to 0 Bytes! 
 
Thank you, 
 
Gerry (gls62) 

----------------------------------------------------------------------

Comment By: Gregory H. Ball (greg_ball)
Date: 2003-12-01 12:03

Message:
Logged In: YES 
user_id=11365

The problem is in function shutil.copyfile().

Unlike cp, it does not check whether the two filenames actually
link to the same underlying file.  If they do, the act of
opening the dst file for writing destroys the src file. 
This is true for symbolic or hard links.  cp notices the
link and prints a message.

A fix for this would be to replace the lines

    # check for same pathname; all platforms
    _src = os.path.normcase(os.path.abspath(src))
    _dst = os.path.normcase(os.path.abspath(dst))
    if _src == _dst:
        return

with

     # check for same file
    if hasattr(os.path,'samefile'): # Macintosh, Unix. 
        try:
            if os.path.samefile(src,dst):
                return
        except OSError:
            pass
    else:  # check for same pathname; all other platforms
        _src = os.path.normcase(os.path.abspath(src))
        _dst = os.path.normcase(os.path.abspath(dst))
        if _src == _dst:
            return

This should fix the bug under Unix (and Mac, I guess) and
leave other platforms no worse than before (I guess most
other platforms do not have hard or symbolic links anyway?)

I have posted a patch at
http://tane.cfa.harvard.edu/python/shutil.patch

Gerry, could you try it out, then perhaps I can open a patch
item.
I've included some test code.  However, it uses
tempfile.mktemp which I see has now been deprecated, so it
will need a fix for that.  Also, I'm not sure that it
properly cleans up in the event of a failure.  Perhaps this
should be fixed too.



----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=851123&group_id=5470



More information about the Python-bugs-list mailing list