From 39c5b50654d94b1d5e33293f23fa6ac9baf16ae9 Mon Sep 17 00:00:00 2001 From: Raphael Dussin Date: Thu, 21 Nov 2019 14:53:03 -0500 Subject: [PATCH] add option to zipfile.writestr to open permissions --- Lib/test/test_zipfile.py | 8 ++++++++ Lib/zipfile.py | 8 +++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py index 1e1854be710..32a7bbf76d7 100644 --- a/Lib/test/test_zipfile.py +++ b/Lib/test/test_zipfile.py @@ -318,6 +318,14 @@ class AbstractTestsWithSourceFile: self.assertEqual(b_info.compress_type, self.compression) 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): # Issue #9837: ZipExtFile.read() shouldn't return more bytes # than requested. diff --git a/Lib/zipfile.py b/Lib/zipfile.py index b0afb9da942..3a5df13a54c 100644 --- a/Lib/zipfile.py +++ b/Lib/zipfile.py @@ -1751,12 +1751,14 @@ class ZipFile: shutil.copyfileobj(src, dest, 1024*8) 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 may be either a 'str' or a 'bytes' instance; if it is a 'str', it is encoded as UTF-8 first. '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): data = data.encode("utf-8") if not isinstance(zinfo_or_arcname, ZipInfo): @@ -1768,7 +1770,7 @@ class ZipFile: zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x zinfo.external_attr |= 0x10 # MS-DOS directory flag else: - zinfo.external_attr = 0o600 << 16 # ?rw------- + zinfo.external_attr = file_perm << 16 # ?rw------- else: zinfo = zinfo_or_arcname