bpo-30693: zip+tarfile: sort directory listing (#2263)
authorBernhard M. Wiedemann <githubbmw@lsmod.de>
Wed, 31 Jan 2018 10:17:10 +0000 (11:17 +0100)
committerVictor Stinner <victor.stinner@gmail.com>
Wed, 31 Jan 2018 10:17:10 +0000 (11:17 +0100)
tarfile and zipfile now sort directory listing to generate tar and zip archives
in a more reproducible way.

See also https://reproducible-builds.org/docs/stable-inputs/ on that topic.

Doc/library/tarfile.rst
Doc/library/zipfile.rst
Lib/tarfile.py
Lib/test/test_tarfile.py
Lib/zipfile.py
Misc/NEWS.d/next/Library/2017-11-27-15-09-49.bpo-30693.yC4mJ7.rst [new file with mode: 0644]
Misc/NEWS.d/next/Library/2017-11-27-15-09-49.bpo-30693.yC4mJ8.rst [new file with mode: 0644]

index 2450716a1d912057b42013d19a5ac7c6bca4c88e..9cd07158e7f62865fa459e4e18f58237746698e4 100644 (file)
@@ -451,7 +451,8 @@ be finalized; only the internally used file object will be closed. See the
    (directory, fifo, symbolic link, etc.). If given, *arcname* specifies an
    alternative name for the file in the archive. Directories are added
    recursively by default. This can be avoided by setting *recursive* to
-   :const:`False`.  If *filter* is given, it
+   :const:`False`. Recursion adds entries in sorted order.
+   If *filter* is given, it
    should be a function that takes a :class:`TarInfo` object argument and
    returns the changed :class:`TarInfo` object. If it instead returns
    :const:`None` the :class:`TarInfo` object will be excluded from the
@@ -460,6 +461,9 @@ be finalized; only the internally used file object will be closed. See the
    .. versionchanged:: 3.2
       Added the *filter* parameter.
 
+   .. versionchanged:: 3.7
+      Recursion adds entries in sorted order.
+
 
 .. method:: TarFile.addfile(tarinfo, fileobj=None)
 
index 7c9a8c80225491a8a7d8e9fc83ff324464c662a5..c0f2a89a3a17fa631bf7d223ddc61f5d96e97e2e 100644 (file)
@@ -491,7 +491,7 @@ The :class:`PyZipFile` constructor takes the same parameters as the
       :file:`\*.pyc` are added at the top level.  If the directory is a
       package directory, then all :file:`\*.pyc` are added under the package
       name as a file path, and if any subdirectories are package directories,
-      all of these are added recursively.
+      all of these are added recursively in sorted order.
 
       *basename* is intended for internal use only.
 
@@ -524,6 +524,9 @@ The :class:`PyZipFile` constructor takes the same parameters as the
       .. versionchanged:: 3.6.2
          The *pathname* parameter accepts a :term:`path-like object`.
 
+      .. versionchanged:: 3.7
+         Recursion sorts directory entries.
+
 
 .. _zipinfo-objects:
 
index 0b8d31f85cf3eccca35e733072d2c4931fc02bf5..a24ee42abf82687836feb07ac026a88671516990 100755 (executable)
@@ -1943,7 +1943,7 @@ class TarFile(object):
         elif tarinfo.isdir():
             self.addfile(tarinfo)
             if recursive:
-                for f in os.listdir(name):
+                for f in sorted(os.listdir(name)):
                     self.add(os.path.join(name, f), os.path.join(arcname, f),
                             recursive, filter=filter)
 
index 179cbc6dfffca757ed473d5fdeec03843ca4ec30..8ef4294921b24924aee5c5999856e6818fc4e1f0 100644 (file)
@@ -1129,6 +1129,30 @@ class WriteTest(WriteTestBase, unittest.TestCase):
         finally:
             support.rmdir(path)
 
+    # mock the following:
+    #  os.listdir: so we know that files are in the wrong order
+    @unittest.mock.patch('os.listdir')
+    def test_ordered_recursion(self, mock_listdir):
+        path = os.path.join(TEMPDIR, "directory")
+        os.mkdir(path)
+        open(os.path.join(path, "1"), "a").close()
+        open(os.path.join(path, "2"), "a").close()
+        mock_listdir.return_value = ["2", "1"]
+        try:
+            tar = tarfile.open(tmpname, self.mode)
+            try:
+                tar.add(path)
+                paths = []
+                for m in tar.getmembers():
+                    paths.append(os.path.split(m.name)[-1])
+                self.assertEqual(paths, ["directory", "1", "2"]);
+            finally:
+                tar.close()
+        finally:
+            support.unlink(os.path.join(path, "1"))
+            support.unlink(os.path.join(path, "2"))
+            support.rmdir(path)
+
     def test_gettarinfo_pathlike_name(self):
         with tarfile.open(tmpname, self.mode) as tar:
             path = pathlib.Path(TEMPDIR) / "file"
index 5df7b1bf75b9d9aefb989efb4fe5a39421d66bd5..b90b60f72e2bcd984141063e3697cefaf7fa5394 100644 (file)
@@ -1940,7 +1940,7 @@ class PyZipFile(ZipFile):
                 if self.debug:
                     print("Adding", arcname)
                 self.write(fname, arcname)
-                dirlist = os.listdir(pathname)
+                dirlist = sorted(os.listdir(pathname))
                 dirlist.remove("__init__.py")
                 # Add all *.py files and package subdirectories
                 for filename in dirlist:
@@ -1965,7 +1965,7 @@ class PyZipFile(ZipFile):
                 # This is NOT a package directory, add its files at top level
                 if self.debug:
                     print("Adding files from directory", pathname)
-                for filename in os.listdir(pathname):
+                for filename in sorted(os.listdir(pathname)):
                     path = os.path.join(pathname, filename)
                     root, ext = os.path.splitext(filename)
                     if ext == ".py":
@@ -2116,7 +2116,7 @@ def main(args=None):
             elif os.path.isdir(path):
                 if zippath:
                     zf.write(path, zippath)
-                for nm in os.listdir(path):
+                for nm in sorted(os.listdir(path)):
                     addToZip(zf,
                              os.path.join(path, nm), os.path.join(zippath, nm))
             # else: ignore
diff --git a/Misc/NEWS.d/next/Library/2017-11-27-15-09-49.bpo-30693.yC4mJ7.rst b/Misc/NEWS.d/next/Library/2017-11-27-15-09-49.bpo-30693.yC4mJ7.rst
new file mode 100644 (file)
index 0000000..9c895c5
--- /dev/null
@@ -0,0 +1 @@
+The ZipFile class now recurses directories in a reproducible way.
diff --git a/Misc/NEWS.d/next/Library/2017-11-27-15-09-49.bpo-30693.yC4mJ8.rst b/Misc/NEWS.d/next/Library/2017-11-27-15-09-49.bpo-30693.yC4mJ8.rst
new file mode 100644 (file)
index 0000000..a622e7e
--- /dev/null
@@ -0,0 +1 @@
+The TarFile class now recurses directories in a reproducible way.