3

I am looking for a way to create a zipfile in memory and include a symlink inside the zipfile. So far I have found this link and try the following code:

from zipfile import ZipInfo
from zipfile import ZipFile
from zipfile import ZIP_DEFLATED, ZIP_STORED
from cStringIO import StringIO
import codecs


buf = StringIO()
zipfile = ZipFile( buf,'w')

zipinfo = ZipInfo()
zipinfo.filename = u'bundle/'
zipinfo.compress_type = ZIP_STORED
zipinfo.external_attr = 040755 << 16L # permissions drwxr-xr-x
zipinfo.external_attr |= 0x10 # MS-DOS directory flag
zipfile.writestr(zipinfo, '')


path = u'bundle/test.txt'
zipinfo = ZipInfo(path)
zipinfo.compress_type = ZIP_DEFLATED
zipinfo.external_attr = 0644 << 16L # permissions -r-wr--r--
zipfile.writestr(zipinfo, u'Test content')

dest = path

#create symbolic link (success)
zipinfo = ZipInfo()
zipinfo.filename = u'test_link.txt'
zipinfo.external_attr |= 0120000 << 16L # symlink file type
zipinfo.compress_type = ZIP_STORED
zipfile.writestr(zipinfo, dest)


#create symbolic link (failed)
zipinfo = ZipInfo()
zipinfo.filename = u'bundle1/test_link.txt'
zipinfo.external_attr |= 0120000 << 16L # symlink file type
zipinfo.compress_type = ZIP_STORED
zipfile.writestr(zipinfo, dest)

for info in zipfile.infolist():
    print u'filename %s' %info.filename
    print u'external_attr %s' %info.external_attr
    print u'header_offset %s' %info.header_offset
    print u'file_size %s' %info.file_size
    print u'crc %s' %info.CRC 
    print u'\n\n'


zipfile.close()
buf.reset()
with codecs.open('test.zip', 'w') as f:
    f.write(buf.getvalue())
buf.close()

The code above was able to create symlink successfully if the link is located directly under the root of unzip folder otherwise it is failed (after unzip if I try to open the symlink file bundle1/text1.txt, and it return an warning

The operation can’t be completed because the original item for “test_link.txt” can’t be found.

Could you please help me how to get symlink bundle1/test_link.txt works properly?

Dharman
  • 30,962
  • 25
  • 85
  • 135
ega
  • 107
  • 8

1 Answers1

2

If you create a symlink in bundle1 that points to bundle/test.txt, the target would have to be located in bundle1/bundle/test.txt. Symlinks alre always relative to their own path (unless of course they start with a /)

So to make this work, you need to change the link destination to ../bundle/test.txt.

mata
  • 67,110
  • 10
  • 163
  • 162
  • Thank you ! I figured it out that I need to check the common prefix between the source and destination path and then use relative path to create symlink. – ega Mar 10 '15 at 21:51
  • @mata : Is there something windows specific ? I am trying to create the symlink using the same technique but it is not working. http://stackoverflow.com/questions/43196350/how-to-create-symlink-in-zipfile-in-python/43196434#43196434 – ViFI Apr 04 '17 at 02:13