From f8e17a950939288d9688d75252ba8bc294a68f24 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:12:22 -0800 Subject: [PATCH 1/8] Treat a trashed folder ID used as the root as missing A filesystem on a folder ID listed a trashed folder as empty, while info() raised FileNotFoundError. ls() now raises too: an empty listing of the root checks that the folder is not trashed. find() and walk() return nothing, as for any missing path. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 10 ++++++- pydrive2/test/test_fs.py | 49 +++++++++++++++++++++++++++++++++++ pydrive2/test/test_fs_unit.py | 10 ++++--- 3 files changed, 65 insertions(+), 4 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ac47994b..0454e346 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1067,9 +1067,17 @@ def ls(self, path, detail=False): fields = _LIST_FIELDS if detail else _NAME_FIELDS if len(dir_ids) == 1: with self._dirs.listing(generation, dir_ids) as listing: - return self._ls_folder( + contents = self._ls_folder( listing, dir_ids[0], root_path, fields, detail ) + # A trashed folder lists as empty, so check that it is still there. + if not contents and not base and bucket not in _ROOT_ALIASES: + root = self._get_root_metadata(fresh=True) + if root.get("trashed"): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), path + ) + return contents with self._dirs.listing(generation, dir_ids) as listing: children = list(self._list_children(listing, fields=fields)) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..7f0c4d20 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -734,3 +734,52 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( fs.cp_file(f"root/{workspace_files}-link", remote_dir + "/copy") assert len(lost) == 1 assert items_below(fs_factory()[0], remote_dir) == ["copy"] + + +@pytest.fixture +def folder_with_a_file(service_auth, request): + drive = GoogleDrive(service_auth) + folder = drive.CreateFile( + { + "name": uuid.uuid4().hex, + "mimeType": "application/vnd.google-apps.folder", + } + ) + pydrive_retry(folder.Upload) + request.addfinalizer(lambda: pydrive_retry(folder.Delete)) + file = drive.CreateFile({"name": "a.txt", "parents": [folder["id"]]}) + file.SetContentString("a") + pydrive_retry(file.Upload) + return folder["id"] + + +def trash(service_auth, item_id): + pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": item_id}).Trash) + + +def assert_missing(fs, path): + with pytest.raises(FileNotFoundError): + fs.ls(path) + with pytest.raises(FileNotFoundError): + fs.info(path) + assert not fs.exists(path) + # As for any missing path, find() and walk() return nothing. + assert fs.find(path) == [] + assert list(fs.walk(path)) == [] + + +def test_folder_id_root_trashed_after_a_listing_is_missing_in_every_call( + service_auth, folder_with_a_file +): + fs = GDriveFileSystem(folder_with_a_file, service_auth) + assert fs.ls(folder_with_a_file) == [f"{folder_with_a_file}/a.txt"] + trash(service_auth, folder_with_a_file) + assert_missing(fs, folder_with_a_file) + + +def test_filesystem_on_a_trashed_folder_id_is_missing_in_every_call( + service_auth, folder_with_a_file +): + trash(service_auth, folder_with_a_file) + fs = GDriveFileSystem(folder_with_a_file, service_auth) + assert_missing(fs, folder_with_a_file) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index d9492b21..b53a9cec 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -3321,15 +3321,19 @@ def test_makedirs_rejects_file(mock_drive, path, expected): def test_explicit_bare_folder_check_refreshes_trash_status(mock_drive): root = {"driveId": "shared", "mimeType": FOLDER_MIME_TYPE} drive, requests = mock_drive( - response(root), listing(), response(dict(root, trashed=True)) + response(root), + listing(), + response(root), + response(dict(root, trashed=True)), ) fs = filesystem(drive, "FolderID") fs.makedirs("FolderID", exist_ok=True) + # An empty listing makes ls() check that the folder is not trashed. assert fs.ls("FolderID") == [] with pytest.raises(FileNotFoundError): fs.makedirs("FolderID", exist_ok=True) - first, children, fresh = requests - assert first[:2] == fresh[:2] + first, children, still_there, fresh = requests + assert first[:2] == still_there[:2] == fresh[:2] assert query(children)["driveId"] == ["shared"] From 56c53e9d567667bb7376bcee4dbd6669e466e624 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:36:46 -0800 Subject: [PATCH 2/8] Check the root's own trashed flag, not its listing On real Drive the children of a folder that was just trashed still list for a while, so an empty listing did not show that the root was trashed. ls() of a folder ID root now raises when the root's metadata says it is trashed, as info() does. A filesystem that listed the folder before learns of the change when its cache is invalidated, as the guide says for other changes made by other clients. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 19 ++++++------------- pydrive2/test/test_fs.py | 4 +++- pydrive2/test/test_fs_unit.py | 10 +++------- 3 files changed, 12 insertions(+), 21 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 0454e346..dba7ea32 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1047,11 +1047,12 @@ def ls(self, path, detail=False): ) except FileNotFoundError as exc: raise PermissionError from exc + # A trashed folder still lists its children for a while. + if root.get("trashed"): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), path + ) if root["mimeType"] != FOLDER_MIME_TYPE: - if root.get("trashed"): - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), path - ) return [_file_entry(bucket, root, detail)] match, generation = self._lookup_path(base, folders_only=True) @@ -1067,17 +1068,9 @@ def ls(self, path, detail=False): fields = _LIST_FIELDS if detail else _NAME_FIELDS if len(dir_ids) == 1: with self._dirs.listing(generation, dir_ids) as listing: - contents = self._ls_folder( + return self._ls_folder( listing, dir_ids[0], root_path, fields, detail ) - # A trashed folder lists as empty, so check that it is still there. - if not contents and not base and bucket not in _ROOT_ALIASES: - root = self._get_root_metadata(fresh=True) - if root.get("trashed"): - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), path - ) - return contents with self._dirs.listing(generation, dir_ids) as listing: children = list(self._list_children(listing, fields=fields)) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 7f0c4d20..424849dc 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -768,12 +768,14 @@ def assert_missing(fs, path): assert list(fs.walk(path)) == [] -def test_folder_id_root_trashed_after_a_listing_is_missing_in_every_call( +def test_folder_id_root_trashed_by_another_client_is_missing_after_invalidation( service_auth, folder_with_a_file ): fs = GDriveFileSystem(folder_with_a_file, service_auth) assert fs.ls(folder_with_a_file) == [f"{folder_with_a_file}/a.txt"] trash(service_auth, folder_with_a_file) + # The filesystem learns of changes by other clients when told to. + fs.invalidate_cache() assert_missing(fs, folder_with_a_file) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index b53a9cec..d9492b21 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -3321,19 +3321,15 @@ def test_makedirs_rejects_file(mock_drive, path, expected): def test_explicit_bare_folder_check_refreshes_trash_status(mock_drive): root = {"driveId": "shared", "mimeType": FOLDER_MIME_TYPE} drive, requests = mock_drive( - response(root), - listing(), - response(root), - response(dict(root, trashed=True)), + response(root), listing(), response(dict(root, trashed=True)) ) fs = filesystem(drive, "FolderID") fs.makedirs("FolderID", exist_ok=True) - # An empty listing makes ls() check that the folder is not trashed. assert fs.ls("FolderID") == [] with pytest.raises(FileNotFoundError): fs.makedirs("FolderID", exist_ok=True) - first, children, still_there, fresh = requests - assert first[:2] == still_there[:2] == fresh[:2] + first, children, fresh = requests + assert first[:2] == fresh[:2] assert query(children)["driveId"] == ["shared"] From d1577acdfe1b58f8ecda57e48bb59423cafe52ce Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 11:05:43 -0800 Subject: [PATCH 3/8] Treat paths under a trashed folder ID root as missing too Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 34 ++++++++++-------------- pydrive2/test/test_fs.py | 49 +++++++++++++++++------------------ pydrive2/test/test_fs_unit.py | 23 ++++++++++++++++ 3 files changed, 60 insertions(+), 46 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index dba7ea32..48a66632 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -223,6 +223,12 @@ def _preferred_ids(children, withdirs): return preferred +def _refuse_trashed(item, path): + # A trashed folder still lists its children for a while. + if item.get("trashed"): + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path) + + def _select_item_id(path, ids): if ids: return min(ids) @@ -722,6 +728,7 @@ def _list_params(self): metadata = self._get_root_metadata() except FileNotFoundError as exc: raise PermissionError from exc + _refuse_trashed(metadata, self.root) if "appDataFolder" in metadata.get("spaces", ()): params["spaces"] = "appDataFolder" elif metadata.get("driveId"): @@ -879,10 +886,7 @@ def _lookup_item(self, path): if base or self.root in _ROOT_ALIASES: return item_id, item_id in match.folders metadata = self._get_root_metadata() - if metadata.get("trashed"): - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), path - ) + _refuse_trashed(metadata, path) return item_id, metadata.get("mimeType") == FOLDER_MIME_TYPE def _forget_new_ids(self): @@ -974,10 +978,7 @@ def _mkdir(self, path, create_parents, exist_ok): cached = base and self._dirs.has_directory(base, self.base) if not cached and root not in _ROOT_ALIASES: metadata = self._get_root_metadata(fresh=True) - if metadata.get("trashed"): - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), root - ) + _refuse_trashed(metadata, root) if metadata.get("mimeType") != FOLDER_MIME_TYPE: if base: raise NotADirectoryError( @@ -1025,10 +1026,8 @@ def info(self, path): gdrive_file = self.client.CreateFile({"id": item_id}) fields = _INFO_FIELDS if base else f"{_INFO_FIELDS},trashed" _gdrive_retry_read(gdrive_file.FetchMetadata)(fields=fields) - if not base and gdrive_file.get("trashed"): - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), path - ) + if not base: + _refuse_trashed(gdrive_file, path) return _file_entry( posixpath.join(bucket, base).rstrip("/"), gdrive_file @@ -1047,11 +1046,7 @@ def ls(self, path, detail=False): ) except FileNotFoundError as exc: raise PermissionError from exc - # A trashed folder still lists its children for a while. - if root.get("trashed"): - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), path - ) + _refuse_trashed(root, path) if root["mimeType"] != FOLDER_MIME_TYPE: return [_file_entry(bucket, root, detail)] @@ -1434,10 +1429,7 @@ def rmdir(self, path): errno.EPERM, "Cannot remove a Drive root", path ) item = self._get_root_metadata(fresh=True) - if item.get("trashed"): - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), path - ) + _refuse_trashed(item, path) if item.get("mimeType") != FOLDER_MIME_TYPE: raise NotADirectoryError( errno.ENOTDIR, os.strerror(errno.ENOTDIR), path diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 424849dc..07f4effd 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -737,12 +737,14 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( @pytest.fixture -def folder_with_a_file(service_auth, request): +def folder_with_a_file(service_auth, fs_factory, request): drive = GoogleDrive(service_auth) + base_id = fs_factory()[1]["id"] folder = drive.CreateFile( { "name": uuid.uuid4().hex, "mimeType": "application/vnd.google-apps.folder", + "parents": [base_id], } ) pydrive_retry(folder.Upload) @@ -753,35 +755,32 @@ def folder_with_a_file(service_auth, request): return folder["id"] -def trash(service_auth, item_id): - pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": item_id}).Trash) - - -def assert_missing(fs, path): +def assert_missing(fs, root): + child = f"{root}/a.txt" + for path in (root, child): + with pytest.raises(FileNotFoundError): + fs.ls(path) + with pytest.raises(FileNotFoundError): + fs.info(path) + assert not fs.exists(path) with pytest.raises(FileNotFoundError): - fs.ls(path) - with pytest.raises(FileNotFoundError): - fs.info(path) - assert not fs.exists(path) + fs.cat_file(child) # As for any missing path, find() and walk() return nothing. - assert fs.find(path) == [] - assert list(fs.walk(path)) == [] + assert fs.find(root) == [] + assert list(fs.walk(root)) == [] -def test_folder_id_root_trashed_by_another_client_is_missing_after_invalidation( +def test_folder_id_root_trashed_by_another_client_is_missing_with_or_without_cache( service_auth, folder_with_a_file ): - fs = GDriveFileSystem(folder_with_a_file, service_auth) - assert fs.ls(folder_with_a_file) == [f"{folder_with_a_file}/a.txt"] - trash(service_auth, folder_with_a_file) - # The filesystem learns of changes by other clients when told to. - fs.invalidate_cache() - assert_missing(fs, folder_with_a_file) + root = folder_with_a_file + cached = GDriveFileSystem(root, service_auth, skip_instance_cache=True) + assert cached.ls(root) == [f"{root}/a.txt"] + pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": root}).Trash) -def test_filesystem_on_a_trashed_folder_id_is_missing_in_every_call( - service_auth, folder_with_a_file -): - trash(service_auth, folder_with_a_file) - fs = GDriveFileSystem(folder_with_a_file, service_auth) - assert_missing(fs, folder_with_a_file) + # The filesystem learns of changes by other clients when told to. + cached.invalidate_cache() + assert_missing(cached, root) + new = GDriveFileSystem(root, service_auth, skip_instance_cache=True) + assert_missing(new, root) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index d9492b21..fdaeda12 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -119,6 +119,29 @@ def test_find_trashed_root_id_skips_listing(mock_drive): assert "trashed" in query(stat)["fields"][0].split(",") +@pytest.mark.parametrize( + "operation", + [ + lambda fs: fs.info("FolderID/a.txt"), + lambda fs: fs.ls("FolderID/a.txt"), + lambda fs: fs.cat_file("FolderID/a.txt"), + ], + ids=["info", "ls", "cat_file"], +) +def test_path_under_a_trashed_folder_id_root_is_missing_while_drive_lists_it( + mock_drive, operation +): + a_file = {"name": "a.txt", "id": "A", "mimeType": "text/plain"} + drive, requests = mock_drive( + response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}), + listing(a_file), + ) + with pytest.raises(FileNotFoundError): + operation(filesystem(drive, "FolderID")) + (stat,) = requests + assert "trashed" in query(stat)["fields"][0].split(",") + + @pytest.mark.parametrize("survivors", [[], [folder("empty", "B")]]) def test_find_after_external_removal_of_a_cached_named_folder( mock_drive, survivors From eda256b2ada2255fe5443309f117cf5619e8a175 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 12:21:45 -0800 Subject: [PATCH 4/8] Find nothing under a trashed folder ID root Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 8 +++++++- pydrive2/test/test_fs.py | 1 + pydrive2/test/test_fs_unit.py | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 5d66a226..072915b5 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1159,7 +1159,13 @@ def find( if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") resolver = self._resolver() - match = resolver.resolve(base, folders_only=not (withdirs and detail)) + try: + match = resolver.resolve( + base, folders_only=not (withdirs and detail) + ) + except FileNotFoundError: + # The root is in the trash, so nothing under it exists. + return {} if detail else [] start = posixpath.join(root, base).rstrip("/") check_empty_root = False if not base and root not in _ROOT_ALIASES: diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 07f4effd..9c3a9698 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -767,6 +767,7 @@ def assert_missing(fs, root): fs.cat_file(child) # As for any missing path, find() and walk() return nothing. assert fs.find(root) == [] + assert fs.find(child) == [] assert list(fs.walk(root)) == [] diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index fdaeda12..27eca696 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -142,6 +142,21 @@ def test_path_under_a_trashed_folder_id_root_is_missing_while_drive_lists_it( assert "trashed" in query(stat)["fields"][0].split(",") +@pytest.mark.parametrize(("detail", "nothing"), [(False, []), (True, {})]) +def test_find_under_a_trashed_folder_id_root_finds_nothing_while_drive_lists_it( + mock_drive, detail, nothing +): + a_file = {"name": "a.txt", "id": "A", "mimeType": "text/plain"} + drive, requests = mock_drive( + response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}), + listing(a_file), + ) + fs = filesystem(drive, "FolderID") + assert fs.find("FolderID/a.txt", detail=detail) == nothing + (stat,) = requests + assert "trashed" in query(stat)["fields"][0].split(",") + + @pytest.mark.parametrize("survivors", [[], [folder("empty", "B")]]) def test_find_after_external_removal_of_a_cached_named_folder( mock_drive, survivors From 4a6f53fcc9e825e88cf88654510e266e95b237e2 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 5 Dec 2026 13:57:34 -0800 Subject: [PATCH 5/8] Refuse a write directly under a trashed folder ID root Drive accepts new files in a trashed folder. A write directly under the root reached the trash check only when it had to fetch new IDs, so after invalidate_cache() a filesystem that had written before uploaded into the trashed folder, while a new filesystem raised. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 18 +++++++++++++----- pydrive2/test/test_fs.py | 5 +++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 072915b5..e0253630 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -720,17 +720,22 @@ def _list_params(self): if self.root == "appDataFolder": params["spaces"] = "appDataFolder" elif self.root != "root": - try: - metadata = self._get_root_metadata() - except FileNotFoundError as exc: - raise PermissionError from exc - _refuse_trashed(metadata, self.root) + metadata = self._checked_root_metadata() if "appDataFolder" in metadata.get("spaces", ()): params["spaces"] = "appDataFolder" elif metadata.get("driveId"): params.update(driveId=metadata["driveId"], corpora="drive") return params + def _checked_root_metadata(self): + """Return the root's metadata, refusing a missing or trashed root.""" + try: + metadata = self._get_root_metadata() + except FileNotFoundError as exc: + raise PermissionError from exc + _refuse_trashed(metadata, self.root) + return metadata + @_gdrive_retry_repeatable def _get_root_metadata( self, *, fresh=False, fields="driveId,mimeType,trashed" @@ -871,6 +876,9 @@ def _get_item_id(self, path, create=False): if create and base: match = self._resolver().directory(base, create=True) return _select_item_id(path, match.folders) + if create and self.root not in _ROOT_ALIASES: + # Drive accepts new files in a trashed folder. + self._checked_root_metadata() match, _ = self._lookup_path(base) return _select_item_id(path, match.ids) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 9c3a9698..6fc83d17 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -769,6 +769,9 @@ def assert_missing(fs, root): assert fs.find(root) == [] assert fs.find(child) == [] assert list(fs.walk(root)) == [] + # Drive accepts new files in a trashed folder. + with pytest.raises(FileNotFoundError): + fs.pipe_file(f"{root}/c.txt", b"c") def test_folder_id_root_trashed_by_another_client_is_missing_with_or_without_cache( @@ -777,6 +780,8 @@ def test_folder_id_root_trashed_by_another_client_is_missing_with_or_without_cac root = folder_with_a_file cached = GDriveFileSystem(root, service_auth, skip_instance_cache=True) assert cached.ls(root) == [f"{root}/a.txt"] + # After a write the filesystem holds IDs that Drive generated for later ones. + cached.pipe_file(f"{root}/b.txt", b"b") pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": root}).Trash) From 5d2337916ab9efcd9b7c1e613e2f5faae7de9097 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 5 Dec 2026 14:15:58 -0800 Subject: [PATCH 6/8] Check the trashed flag inside _get_root_metadata Every caller refused a trashed root, so the root metadata refuses it itself and takes the error to raise for a 404 root. The helper and the six call-site checks go. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 71 +++++++++++++++++++--------------------- pydrive2/test/test_fs.py | 2 ++ 2 files changed, 35 insertions(+), 38 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index e0253630..ccf9597c 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -223,12 +223,6 @@ def _preferred_ids(children, withdirs): return preferred -def _refuse_trashed(item, path): - # A trashed folder still lists its children for a while. - if item.get("trashed"): - raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path) - - def _select_item_id(path, ids): if ids: return min(ids) @@ -720,26 +714,27 @@ def _list_params(self): if self.root == "appDataFolder": params["spaces"] = "appDataFolder" elif self.root != "root": - metadata = self._checked_root_metadata() + metadata = self._get_root_metadata(missing_error=PermissionError) if "appDataFolder" in metadata.get("spaces", ()): params["spaces"] = "appDataFolder" elif metadata.get("driveId"): params.update(driveId=metadata["driveId"], corpora="drive") return params - def _checked_root_metadata(self): - """Return the root's metadata, refusing a missing or trashed root.""" - try: - metadata = self._get_root_metadata() - except FileNotFoundError as exc: - raise PermissionError from exc - _refuse_trashed(metadata, self.root) - return metadata - @_gdrive_retry_repeatable def _get_root_metadata( - self, *, fresh=False, fields="driveId,mimeType,trashed" + self, + path=None, + *, + fresh=False, + fields="driveId,mimeType,trashed", + missing_error=FileNotFoundError, ): + """Return the root's metadata, treating a trashed root as missing. + + Drive answers 404 for a root that is gone or not shared, which raises + missing_error. + """ cached = self._root_metadata if cached and not fresh: return cached @@ -751,11 +746,13 @@ def _get_root_metadata( try: with _translate_not_found(self.root): item.FetchMetadata(f"{fields},spaces") - except FileNotFoundError: + except FileNotFoundError as exc: with self._dirs.lock: if self._root_metadata is cached: self.invalidate_cache(self.root) - raise + if missing_error is FileNotFoundError: + raise + raise missing_error from exc with self._dirs.lock: if self._root_metadata is cached: if item.get("trashed"): @@ -766,6 +763,11 @@ def _get_root_metadata( "driveId": item.get("driveId"), "mimeType": item.get("mimeType"), } + # A trashed folder still lists its children for a while. + if item.get("trashed"): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), path or self.root + ) return item.metadata def _query_children(self, parents, names=(), *, fields=_LIST_FIELDS): @@ -878,7 +880,7 @@ def _get_item_id(self, path, create=False): return _select_item_id(path, match.folders) if create and self.root not in _ROOT_ALIASES: # Drive accepts new files in a trashed folder. - self._checked_root_metadata() + self._get_root_metadata(missing_error=PermissionError) match, _ = self._lookup_path(base) return _select_item_id(path, match.ids) @@ -889,8 +891,7 @@ def _lookup_item(self, path): item_id = _select_item_id(path, match.ids) if base or self.root in _ROOT_ALIASES: return item_id, item_id in match.folders - metadata = self._get_root_metadata() - _refuse_trashed(metadata, path) + metadata = self._get_root_metadata(path) return item_id, metadata.get("mimeType") == FOLDER_MIME_TYPE def _forget_new_ids(self): @@ -981,8 +982,7 @@ def _mkdir(self, path, create_parents, exist_ok): root, base = self._split_mounted_path(path) cached = base and self._dirs.has_directory(base, self.base) if not cached and root not in _ROOT_ALIASES: - metadata = self._get_root_metadata(fresh=True) - _refuse_trashed(metadata, root) + metadata = self._get_root_metadata(root, fresh=True) if metadata.get("mimeType") != FOLDER_MIME_TYPE: if base: raise NotADirectoryError( @@ -1022,18 +1022,15 @@ def info(self, path): bucket, base = self._split_mounted_path(path) if not base and bucket not in _ROOT_ALIASES: gdrive_file = self._get_root_metadata( - fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" + path, fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" ) else: with _translate_not_found(path): item_id = self._get_item_id(path) gdrive_file = self.client.CreateFile({"id": item_id}) - fields = _INFO_FIELDS if base else f"{_INFO_FIELDS},trashed" _gdrive_retry_repeatable(gdrive_file.FetchMetadata)( - fields=fields + fields=_INFO_FIELDS ) - if not base: - _refuse_trashed(gdrive_file, path) return _file_entry( posixpath.join(bucket, base).rstrip("/"), gdrive_file @@ -1046,13 +1043,12 @@ def ls(self, path, detail=False): if not base and bucket not in _ROOT_ALIASES: cached = self._root_metadata if not cached or cached.get("mimeType") != FOLDER_MIME_TYPE: - try: - root = self._get_root_metadata( - fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" - ) - except FileNotFoundError as exc: - raise PermissionError from exc - _refuse_trashed(root, path) + root = self._get_root_metadata( + path, + fresh=True, + fields=f"driveId,trashed,{_INFO_FIELDS}", + missing_error=PermissionError, + ) if root["mimeType"] != FOLDER_MIME_TYPE: return [_file_entry(bucket, root, detail)] @@ -1442,8 +1438,7 @@ def rmdir(self, path): raise PermissionError( errno.EPERM, "Cannot remove a Drive root", path ) - item = self._get_root_metadata(fresh=True) - _refuse_trashed(item, path) + item = self._get_root_metadata(path, fresh=True) if item.get("mimeType") != FOLDER_MIME_TYPE: raise NotADirectoryError( errno.ENOTDIR, os.strerror(errno.ENOTDIR), path diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 6fc83d17..9658c87f 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -772,6 +772,8 @@ def assert_missing(fs, root): # Drive accepts new files in a trashed folder. with pytest.raises(FileNotFoundError): fs.pipe_file(f"{root}/c.txt", b"c") + with pytest.raises(FileNotFoundError): + fs.rm_file(root) def test_folder_id_root_trashed_by_another_client_is_missing_with_or_without_cache( From 3ef75f9385cc58c4da25187f71d2b13b100ef296 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 5 Dec 2026 14:16:18 -0800 Subject: [PATCH 7/8] Leave rm_file of a trashed root out of the live test for now Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_fs.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 9658c87f..6fc83d17 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -772,8 +772,6 @@ def assert_missing(fs, root): # Drive accepts new files in a trashed folder. with pytest.raises(FileNotFoundError): fs.pipe_file(f"{root}/c.txt", b"c") - with pytest.raises(FileNotFoundError): - fs.rm_file(root) def test_folder_id_root_trashed_by_another_client_is_missing_with_or_without_cache( From e63886bc35ab3df1d668bc12c5a137db76a5c30d Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 5 Dec 2026 15:02:15 -0800 Subject: [PATCH 8/8] Refuse rm_file of a trashed folder ID root rm_file of the root went straight to the delete, so on a trashed root it trashed it again or removed it from the trash for good. It now reads the root like the other calls, one request on a filesystem that has not read the root yet. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 5 +---- pydrive2/test/test_fs.py | 2 ++ pydrive2/test/test_fs_registration.py | 10 +++++++--- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ccf9597c..0665b65d 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1498,10 +1498,7 @@ def _check_empty_folder(self, item_id, path): ) def rm_file(self, path): - _, base = self._split_mounted_path(path) - match, _ = self._lookup_path(base) - item_id = _select_item_id(path, match.ids) - known_folder = item_id in match.folders + item_id, known_folder = self._lookup_item(path) self._gdrive_delete_file(item_id) self._invalidate_folder(item_id, path, known_folder=known_folder) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 6fc83d17..9658c87f 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -772,6 +772,8 @@ def assert_missing(fs, root): # Drive accepts new files in a trashed folder. with pytest.raises(FileNotFoundError): fs.pipe_file(f"{root}/c.txt", b"c") + with pytest.raises(FileNotFoundError): + fs.rm_file(root) def test_folder_id_root_trashed_by_another_client_is_missing_with_or_without_cache( diff --git a/pydrive2/test/test_fs_registration.py b/pydrive2/test/test_fs_registration.py index 342ff2ea..3c581f2f 100644 --- a/pydrive2/test/test_fs_registration.py +++ b/pydrive2/test/test_fs_registration.py @@ -213,7 +213,10 @@ def test_file_id_errors(mock_drive, tmp_path, method, status, reason): def test_trashed_file_id_is_absent_from_metadata(mock_drive): trashed = {"mimeType": "text/plain", "trashed": True} drive, requests = mock_drive( - response({"trashed": True}), response(trashed), response(trashed) + response({"mimeType": "text/plain"}), + response({"trashed": True}), + response(trashed), + response(trashed), ) fs, path = fsspec.core.url_to_fs("gdrive://FiLe", google_auth=drive.auth) fs.rm_file(path) @@ -221,11 +224,12 @@ def test_trashed_file_id_is_absent_from_metadata(mock_drive): with pytest.raises(FileNotFoundError) as error: fs.info(path) assert error.value.filename == path - trash, *metadata = requests + first, trash, *metadata = requests assert trash[1] == "PATCH" assert json.loads(trash[2]) == {"trashed": True} assert all( - "trashed" in query(req)["fields"][0].split(",") for req in metadata + "trashed" in query(req)["fields"][0].split(",") + for req in [first, *metadata] )