add option to zipfile.writestr to open permissions

This commit is contained in:
Raphael Dussin 2019-11-21 14:53:03 -05:00
parent be5c79e033
commit 39c5b50654
2 changed files with 13 additions and 3 deletions

View File

@ -318,6 +318,14 @@ class AbstractTestsWithSourceFile:
self.assertEqual(b_info.compress_type, self.compression) self.assertEqual(b_info.compress_type, self.compression)
self.assertEqual(b_info._compresslevel, 2) self.assertEqual(b_info._compresslevel, 2)
def test_writestr_permission(self):
zipfp = zipfile.ZipFile(TESTFN2, "w")
zipfp.writestr("b.txt", "hello world", file_perm=0o755)
b_info = zipfp.getinfo('b.txt')
perm = oct(b_info.external_attr >> 16)
assert perm == '0o755'
def test_read_return_size(self): def test_read_return_size(self):
# Issue #9837: ZipExtFile.read() shouldn't return more bytes # Issue #9837: ZipExtFile.read() shouldn't return more bytes
# than requested. # than requested.

View File

@ -1751,12 +1751,14 @@ class ZipFile:
shutil.copyfileobj(src, dest, 1024*8) shutil.copyfileobj(src, dest, 1024*8)
def writestr(self, zinfo_or_arcname, data, def writestr(self, zinfo_or_arcname, data,
compress_type=None, compresslevel=None): compress_type=None, compresslevel=None,
file_perm=0o600):
"""Write a file into the archive. The contents is 'data', which """Write a file into the archive. The contents is 'data', which
may be either a 'str' or a 'bytes' instance; if it is a 'str', may be either a 'str' or a 'bytes' instance; if it is a 'str',
it is encoded as UTF-8 first. it is encoded as UTF-8 first.
'zinfo_or_arcname' is either a ZipInfo instance or 'zinfo_or_arcname' is either a ZipInfo instance or
the name of the file in the archive.""" the name of the file in the archive. Default permission is set to 600
(rw-------) but can be specified with file_perm."""
if isinstance(data, str): if isinstance(data, str):
data = data.encode("utf-8") data = data.encode("utf-8")
if not isinstance(zinfo_or_arcname, ZipInfo): if not isinstance(zinfo_or_arcname, ZipInfo):
@ -1768,7 +1770,7 @@ class ZipFile:
zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x
zinfo.external_attr |= 0x10 # MS-DOS directory flag zinfo.external_attr |= 0x10 # MS-DOS directory flag
else: else:
zinfo.external_attr = 0o600 << 16 # ?rw------- zinfo.external_attr = file_perm << 16 # ?rw-------
else: else:
zinfo = zinfo_or_arcname zinfo = zinfo_or_arcname