Skip to content

Commit cc8b97f

Browse files
gh-162732: Propagate errors when traversing directories in shutil.make_archive(..., 'zip')
When shutil.make_archive(..., 'zip') cannot list a source directory, propagate the OSError encountered during traversal rather than silently omitting files and creating an incomplete archive. Signed-off-by: ANISAYAK MITRA <266799942+anisayakmitra-in@users.noreply.github.com>
1 parent 49a344e commit cc8b97f

3 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎Lib/shutil.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1134,7 +1134,11 @@ def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0,
11341134
zf.write(base_dir, arcname)
11351135
if logger is not None:
11361136
logger.info("adding '%s'", base_dir)
1137-
for dirpath, dirnames, filenames in os.walk(base_dir):
1137+
1138+
def _onerror(err):
1139+
raise err
1140+
1141+
for dirpath, dirnames, filenames in os.walk(base_dir, onerror=_onerror):
11381142
arcdirpath = dirpath
11391143
if root_dir is not None:
11401144
arcdirpath = os.path.relpath(arcdirpath, root_dir)

‎Lib/test/test_shutil.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2147,6 +2147,22 @@ def test_make_archive_owner_group(self):
21472147
owner='kjhkjhkjg', group='oihohoh')
21482148
self.assertTrue(os.path.isfile(res))
21492149

2150+
@support.requires_zlib()
2151+
def test_make_archive_zip_unreadable_dir(self):
2152+
root_dir, base_dir = self._create_files()
2153+
sub = os.path.join(root_dir, base_dir, 'sub')
2154+
base_name = os.path.join(self.mkdtemp(), 'archive')
2155+
orig_scandir = os.scandir
2156+
2157+
def fail_scandir(path='.'):
2158+
if os.path.normpath(str(path)) == os.path.normpath(sub):
2159+
raise PermissionError(f"Permission denied: {path!r}")
2160+
return orig_scandir(path)
2161+
2162+
with unittest.mock.patch('os.scandir', side_effect=fail_scandir):
2163+
with self.assertRaises(PermissionError):
2164+
make_archive(base_name, 'zip', root_dir, base_dir)
2165+
21502166

21512167
@support.requires_zlib()
21522168
@unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:func:`shutil.make_archive` with format ``"zip"`` now propagates any
2+
:exc:`OSError` encountered when traversing source directories instead of
3+
silently producing an incomplete archive.

0 commit comments

Comments
 (0)