backup: two files sharing a name restore side by side instead of overwriting
- Commit
913d39f50ac8ff73905afbab4d4d1697003ccd67- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 14:27 UTC (4 days ago)
- Parents
31c0c0e
restoreTarget derives the output file purely from relativePath + displayName, so two distinct backed-up files with the same directory and display name (same-named photos from two volumes: distinct fileIds, distinct blobs) restored onto the same file — the first was silently overwritten, yet restoreAll returned 2 and reported both restored. Targets are now claimed per run by absolute path -> fileId: a later distinct fileId claiming a taken target restores to a sibling with its id inserted before the extension (photo-id2.jpg, then -2/-3), while re-restoring the same fileId keeps the plain name — non-colliding restores are byte-unchanged. Regression test: returned count 2 must now match 2 files on disk with the right contents (failed pre-fix: 2 claimed, 1 present). Crypto, SAF/WebDAV, transport and scheduling were audited and cleared. Verified: :backup:testDevUnitTest 79 tests pass; lint/check failures are pre-existing on untouched files.
Diff
backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.kt b/backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.ktindex fb36ee58ab..9b58ca1925 100644--- a/backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.kt+++ b/backup/src/main/java/com/vayunmathur/backup/data/files/FileBackupManager.kt@@ -71,13 +71,20 @@ class FileBackupManager( val baseDir = File(context.getExternalFilesDir(null), "BackupRestore") onProgress(0, entries.size) var restored = 0+ // Targets already claimed in this run, by file: two distinct+ // backed-up files can share a directory and display name (e.g.+ // same-named photos from two storage volumes). Writing both to+ // the same file would silently drop the first while counting it+ // as restored, so a later claimant is disambiguated instead.+ val claimed = HashMap<String, String>() for ((i, e) in entries.withIndex()) {- val outFile = restoreTarget(baseDir, e)+ val outFile = claimedTarget(restoreTarget(baseDir, e), e, claimed) val result = runCatching { outFile.parentFile?.mkdirs() FileOutputStream(outFile).use { repo.readEncryptedTo(BackupRepository.filePath(e.fileId), it) } } if (result.isSuccess) {+ claimed[outFile.absolutePath] = e.fileId restored++ } else { // Do not leave an empty/partially decrypted file behind:@@ -110,6 +117,35 @@ class FileBackupManager( return File(dir, name) } + /**+ * [target], unless a different backed-up file already restored to it in+ * this run — then a sibling name carrying this entry's file id, so both+ * files survive. Re-restoring the same file id to the same target (a+ * repeated manifest entry) keeps the plain name.+ */+ private fun claimedTarget(target: File, entry: FileEntry, claimed: Map<String, String>): File {+ if (claimed[target.absolutePath].let { it == null || it == entry.fileId }) return target+ val suffix = entry.fileId.filter { it.isLetterOrDigit() || it == '-' || it == '_' }+ .ifEmpty { "duplicate" }+ var candidate = File(target.parentFile, disambiguatedName(target.name, suffix))+ var attempt = 2+ while (claimed[candidate.absolutePath].let { it != null && it != entry.fileId }) {+ candidate = File(target.parentFile, disambiguatedName(target.name, "$suffix-$attempt"))+ attempt+++ }+ return candidate+ }++ /** [name] with [suffix] inserted before its extension (`photo.jpg` → `photo-id2.jpg`). */+ private fun disambiguatedName(name: String, suffix: String): String {+ val dot = name.lastIndexOf('.')+ return if (dot > 0) {+ name.substring(0, dot) + "-" + suffix + name.substring(dot)+ } else {+ "$name-$suffix"+ }+ }+ private data class Item(val uri: Uri, val entry: FileEntry) private suspend fun enumerate(): List<Item> = withContext(Dispatchers.IO) {
backup/src/test/java/com/vayunmathur/backup/data/files/FileRestoreCollisionTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/data/files/FileRestoreCollisionTest.kt b/backup/src/test/java/com/vayunmathur/backup/data/files/FileRestoreCollisionTest.ktnew file mode 100644index 0000000000..0251b8dbce--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/data/files/FileRestoreCollisionTest.kt@@ -0,0 +1,47 @@+package com.vayunmathur.backup.data.files++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.backup.data.backend.BackupRepository+import com.vayunmathur.backup.data.backend.InMemoryBackend+import com.vayunmathur.backup.domain.crypto.Crypto+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class FileRestoreCollisionTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val key = ByteArray(32) { (it + 2).toByte() }++ @Test fun restoreKeepsBothFilesThatSharePathAndDisplayName() = runBlocking<Unit> {+ val repo = BackupRepository(InMemoryBackend(), Crypto(key))+ val manager = FileBackupManager(ctx, repo)+ // A backup set holding two distinct backed-up files (distinct blobs)+ // that share a directory and a display name, e.g. same-named photos+ // from two storage volumes. Both must survive the restore.+ val entries = listOf(+ FileEntry("id1", "photo.jpg", "Pictures/", "image/jpeg", 3, 100L, "image"),+ FileEntry("id2", "photo.jpg", "Pictures/", "image/jpeg", 4, 200L, "image"),+ )+ repo.writeEncrypted(+ "files/index.json",+ Json.encodeToString(FileIndex.serializer(), FileIndex(entries)).toByteArray(),+ )+ repo.writeEncrypted(BackupRepository.filePath("id1"), "abc".toByteArray())+ repo.writeEncrypted(BackupRepository.filePath("id2"), "wxyz".toByteArray())++ assertEquals(2, manager.restoreAll())++ val base = File(ctx.getExternalFilesDir(null), "BackupRestore/Pictures")+ val restored = base.listFiles().orEmpty().filter { it.isFile }+ assertEquals(2, restored.size)+ assertEquals(setOf("abc", "wxyz"), restored.map { it.readText() }.toSet())+ assertTrue(File(base, "photo.jpg").exists())+ }+}