files: a failed unzip no longer leaves its created directories behind
- Commit
0f8b6904ca480fa4bb9304bb5a8c845ee5d85f1f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 03:11 UTC (5 days ago)
- Parents
eaca1eb
The UnzipWorker's class doc promises all-or-nothing cleanup of partial output, but the failure path deleted only files: directory entries and file parents were created via bare mkdirs() calls that recorded nothing, so a zip that tripped the size budget left sub/ and emptydir/ behind in the destination (verified: budget 5 consumed by the first file, second trips, created folders survive). ensureDirectory() now records exactly the directories this run created (the missing-ancestor chain that now exists; pre-existing dirs are never recorded), and cleanup deletes files first, then created directories deepest-first — File .delete() only removes empty directories, so anything still holding content is left alone. The regression test also asserts a pre-existing keep/ folder survives cleanup. SAF mapping, sorting, collision handling, trash and ZipWorker paths were audited and cleared. Verified: :files:testDevUnitTest 124 tests pass; lint errors are pre-existing on untouched files.
Diff
files/src/main/java/com/vayunmathur/files/platform/UnzipWorker.kt
diff --git a/files/src/main/java/com/vayunmathur/files/platform/UnzipWorker.kt b/files/src/main/java/com/vayunmathur/files/platform/UnzipWorker.ktindex 179135d9bc..4ab852fdea 100644--- a/files/src/main/java/com/vayunmathur/files/platform/UnzipWorker.kt+++ b/files/src/main/java/com/vayunmathur/files/platform/UnzipWorker.kt@@ -37,17 +37,18 @@ class UnzipWorker(context: Context, params: WorkerParameters) : ProgressNotifica // Everything this run created, so a rejected archive does not leave its partial output behind. val extracted = mutableListOf<File>()+ val createdDirs = mutableListOf<File>() return try {- extractArchive(File(zipPathString), File(destPathString), budget, extracted)+ extractArchive(File(zipPathString), File(destPathString), budget, extracted, createdDirs) Result.success() } catch (e: ArchiveTooLargeException) { Log.status(TAG_UNZIP, "archive exceeds its extraction budget", e)- cleanUpPartial(extracted)+ cleanUpPartial(extracted, createdDirs) Result.failure() } catch (e: IOException) { Log.status(TAG_UNZIP, "failed to extract archive", e)- cleanUpPartial(extracted)+ cleanUpPartial(extracted, createdDirs) Result.failure() } finally { cancelNotification()@@ -58,7 +59,8 @@ class UnzipWorker(context: Context, params: WorkerParameters) : ProgressNotifica zipFile: File, destDir: File, budget: Long,- extracted: MutableList<File>+ extracted: MutableList<File>,+ createdDirs: MutableList<File> ) { val destDirCanonical = destDir.canonicalFile val zipFileSize = zipFile.length()@@ -78,6 +80,7 @@ class UnzipWorker(context: Context, params: WorkerParameters) : ProgressNotifica entry.name, entry.isDirectory, extracted,+ createdDirs, budget, totalWritten )@@ -94,13 +97,14 @@ class UnzipWorker(context: Context, params: WorkerParameters) : ProgressNotifica entryName: String, isDirectory: Boolean, extracted: MutableList<File>,+ createdDirs: MutableList<File>, budget: Long, totalWritten: Long ): Long { val entryFile = ArchiveLimits.resolveEntry(destDirCanonical, entryName) ?: return totalWritten if (isDirectory) { if (entryFile.isFile) throw IOException("Archive entry is an existing file: $entryName")- entryFile.mkdirs()+ ensureDirectory(entryFile, createdDirs) return totalWritten } // Never overwrite what was already in the destination. Truncating an@@ -111,15 +115,37 @@ class UnzipWorker(context: Context, params: WorkerParameters) : ProgressNotifica // every pre-existing file stays exactly as it was. This also covers // an archive listing the same name twice. if (entryFile.exists()) throw IOException("File already exists: $entryName")- entryFile.parentFile?.mkdirs()+ entryFile.parentFile?.let { ensureDirectory(it, createdDirs) } extracted.add(entryFile) FileOutputStream(entryFile).use { out -> return totalWritten + copyBounded(zipInputStream, out, budget - totalWritten) } } - private fun cleanUpPartial(extracted: List<File>) {+ /**+ * Creates [dir] (and any missing ancestors), recording exactly the directories this run+ * created in [createdDirs]. Pre-existing directories are never recorded, so cleanup can+ * remove this run's folders without ever touching ones that were already there.+ */+ private fun ensureDirectory(dir: File, createdDirs: MutableList<File>) {+ if (dir.isDirectory) return+ val missing = mutableListOf<File>()+ var current: File? = dir+ while (current != null && !current.isDirectory) {+ missing.add(current)+ current = current.parentFile+ }+ dir.mkdirs()+ missing.filter { it.isDirectory && it !in createdDirs }.forEach { createdDirs.add(it) }+ }++ private fun cleanUpPartial(extracted: List<File>, createdDirs: List<File>) { extracted.forEach { runCatching { it.delete() } }+ // Deepest first; delete() only succeeds on an empty directory, so anything that+ // somehow still holds content is left alone rather than emptied by force.+ createdDirs+ .sortedByDescending { it.path.count { c -> c == File.separatorChar } }+ .forEach { runCatching { it.delete() } } } /**
files/src/test/java/com/vayunmathur/files/platform/WorkersAndStorageTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/platform/WorkersAndStorageTest.kt b/files/src/test/java/com/vayunmathur/files/platform/WorkersAndStorageTest.ktindex 9a58c10761..1c96db125e 100644--- a/files/src/test/java/com/vayunmathur/files/platform/WorkersAndStorageTest.kt+++ b/files/src/test/java/com/vayunmathur/files/platform/WorkersAndStorageTest.kt@@ -150,6 +150,37 @@ class WorkersAndStorageTest { dir.deleteRecursively() } } + @Test+ fun `unzip worker removes directories it created when extraction fails`() { runBlocking {+ val dir = tempDir("unzip-dirs")+ val zipFile = File(dir, "in.zip")+ java.util.zip.ZipOutputStream(zipFile.outputStream()).use { out ->+ out.putNextEntry(java.util.zip.ZipEntry("sub/world.txt")); out.write("world".toByteArray()); out.closeEntry()+ out.putNextEntry(java.util.zip.ZipEntry("emptydir/")); out.closeEntry()+ out.putNextEntry(java.util.zip.ZipEntry("hello.txt")); out.write("hello".toByteArray()); out.closeEntry()+ }+ val destDir = File(dir, "out").apply { mkdirs() }+ // A pre-existing empty folder is not this run's output and must survive cleanup.+ File(destDir, "keep").mkdirs()+ val worker = TestListenableWorkerBuilder<UnzipWorker>(ctx)+ .setInputData(+ workDataOf(+ "zip_path" to zipFile.absolutePath,+ "dest_path" to destDir.absolutePath,+ // Exactly enough for sub/world.txt: hello.txt then blows the budget.+ "size_budget" to 5L,+ ),+ )+ .build()+ assertEquals(ListenableWorker.Result.failure(), worker.doWork())+ assertFalse(File(destDir, "sub/world.txt").exists())+ assertFalse(File(destDir, "sub").exists(), "failed extraction must not leave directories it created")+ assertFalse(File(destDir, "emptydir").exists(), "failed extraction must not leave directories it created")+ assertFalse(File(destDir, "hello.txt").exists())+ assertTrue(File(destDir, "keep").isDirectory)+ dir.deleteRecursively()+ } }+ @Test fun `unzip worker refuses to overwrite an existing file`() { runBlocking { val dir = tempDir("unzip-clash")