From bb9f7339fe332bfc24aeaafbdb17e71d080244ca Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 19:22:14 -0800 Subject: [PATCH 1/8] Honor depth limits and include directories in recursive find --- pydrive2/fs/spec.py | 109 +++++++++++++++++++++---------- pydrive2/test/test_fs_listing.py | 42 ++++++++++++ 2 files changed, 118 insertions(+), 33 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 1370d11..b8eb067 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -590,58 +590,101 @@ def ls(self, path, detail=False): else: return [content["name"] for content in contents] - def find(self, path, detail=False, **kwargs): - bucket, base = self._split_mounted_path(path) - - # Make sure the base path is cached and dir_ids below has some - # dirs revelant to this call + def find( + self, path, detail=False, *, maxdepth=None, withdirs=False, **kwargs + ): + root, base = self._split_mounted_path(path) + if maxdepth is not None and maxdepth < 0: + raise ValueError("maxdepth must be nonnegative") + # Older fsspec expand_path passes zero for a single-level listing. + if maxdepth == 0: + maxdepth = 1 cache = self._ids_cache - self._path_to_item_ids(base, cache=cache) + start_ids = self._path_to_item_ids(base, cache=cache) + if not start_ids: + return {} if detail else [] + + # Warm directories at different depths can share a single batched + # query. Measure depth from the requested path, not the batch number. + prefix = base + "/" if base else "" + + def descend(name): + if name == base: + return True + if not name.startswith(prefix): + return False + return ( + maxdepth is None + or name[len(prefix) :].count("/") + 1 < maxdepth + ) with self._cache_lock: - dir_ids = [cache["ids"].copy()] - seen_paths: set[str] = set() + known = cache["ids"].copy() + if not base: + known[root] = "" + pending = { + item_id: name for item_id, name in known.items() if descend(name) + } + start = posixpath.join(root, base).rstrip("/") + known_dir = (not base and root in {"root", "appDataFolder"}) or ( + base != self.base and any(known.get(i) == base for i in start_ids) + ) contents = [] - while dir_ids: - query_ids = { - dir_id: dir_name - for dir_id, dir_name in dir_ids.pop().items() - if posixpath.commonpath([base, dir_name]) == base - if dir_id not in seen_paths - } - if not query_ids: - continue - - seen_paths |= query_ids.keys() - - new_query_ids: dict[str, str] = {} - dir_ids.append(new_query_ids) + if withdirs or not pending: + if known_dir: + entry = _file_entry(start, {"mimeType": FOLDER_MIME_TYPE}) + else: + try: + entry = self.info(path) + except FileNotFoundError: + return {} if detail else [] + if entry["type"] == "file": + return {start: entry} if detail else [start] + if withdirs: + contents.append(entry) + + seen: set[str] = set() + while pending: + query_ids = pending + seen.update(query_ids) + pending = {} for item in self._gdrive_list_ids(query_ids): - # A root alias in the query is returned as its canonical ID. + # Drive returns the canonical ID when the query uses a root alias. parent_id = next( (p for p in item.get("parents", ()) if p in query_ids), None, ) if parent_id is None: if ( - self.root not in {"root", "appDataFolder"} - or self.root not in query_ids + root not in {"root", "appDataFolder"} + or root not in query_ids ): continue - parent_id = self.root + parent_id = root item_path = posixpath.join(query_ids[parent_id], item["name"]) if item["mimeType"] == FOLDER_MIME_TYPE: - new_query_ids[item["id"]] = item_path - self._cache_path_id(item_path, item["id"], cache=cache) - continue + item_id = item["id"] + self._cache_path_id(item_path, item_id, cache=cache) + if item_id not in seen and descend(item_path): + pending[item_id] = item_path + if not withdirs: + continue contents.append( - _file_entry(posixpath.join(bucket, item_path), item) + _file_entry(posixpath.join(root, item_path), item) ) + # An untyped mount ID can also refer directly to a file. + if not contents and not known_dir and not withdirs: + try: + entry = self.info(path) + except FileNotFoundError: + return {} if detail else [] + if entry["type"] == "file": + contents.append(entry) + if detail: - return {content["name"]: content for content in contents} - else: - return [content["name"] for content in contents] + return {entry["name"].rstrip("/"): entry for entry in contents} + return [entry["name"].rstrip("/") for entry in contents] def upload_fobj(self, stream, rpath, callback=None, **kwargs): parent, name = self._split_file_path(rpath) diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index 89426ca..bfef3ed 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -231,3 +231,45 @@ def test_failed_removal_preserves_cache(listing_fs, mocker): with pytest.raises(PermissionError): listing_fs.rm_file("root/dir") assert listing_fs.exists("root/dir") + + +@pytest.mark.parametrize("warm", [False, True]) +def test_find_honors_depth_and_directories(listing_fs, monkeypatch, warm): + tree = { + "root": [ + ("dir", "D", FOLDER_MIME_TYPE), + ("dir2", "other", FOLDER_MIME_TYPE), + ], + "D": [("file", "F", "text/plain"), ("sub", "S", FOLDER_MIME_TYPE)], + "S": [("deep", "G", "text/plain")], + } + queried = [] + + def list_ids(parents, *, name=None): + queried.extend(parents) + return ( + {"id": item_id, "name": n, "mimeType": mime, "parents": [parent]} + for parent in parents + for n, item_id, mime in tree.get(parent, ()) + if name is None or n == name + ) + + monkeypatch.setattr(listing_fs, "_gdrive_list_ids", list_ids) + if warm: + listing_fs.find("root") + queried.clear() + found = listing_fs.find("root/dir", maxdepth=1, withdirs=True, detail=True) + assert set(found) == {"root/dir", "root/dir/file", "root/dir/sub"} + assert found["root/dir/sub"]["type"] == "directory" + assert "S" not in queried and "other" not in queried + assert listing_fs.find("root/dir", maxdepth=1) == ["root/dir/file"] + assert set( + listing_fs.expand_path("root/dir", recursive=True, maxdepth=1) + ) == set(found) + assert set(listing_fs.glob("root/dir/*")) == { + "root/dir/file", + "root/dir/sub", + } + assert listing_fs._ids_cache["dirs"]["dir"] == ["D"] + with pytest.raises(ValueError, match="maxdepth"): + listing_fs.find("root", maxdepth=-1) From 93785559dde40310c8bed5ae8471b90c87e0a290 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 19:24:56 -0800 Subject: [PATCH 2/8] Accept fsspec positional traversal options --- pydrive2/fs/spec.py | 6 +++++- pydrive2/test/test_fs_listing.py | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index b8eb067..7312047 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -591,8 +591,12 @@ def ls(self, path, detail=False): return [content["name"] for content in contents] def find( - self, path, detail=False, *, maxdepth=None, withdirs=False, **kwargs + self, path, maxdepth=None, withdirs=False, detail=False, **kwargs ): + # PyDrive2 historically accepted a boolean detail as its second argument. + if isinstance(maxdepth, bool): + detail = detail or maxdepth + maxdepth = None root, base = self._split_mounted_path(path) if maxdepth is not None and maxdepth < 0: raise ValueError("maxdepth must be nonnegative") diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index bfef3ed..d4a939a 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -262,6 +262,10 @@ def list_ids(parents, *, name=None): assert set(found) == {"root/dir", "root/dir/file", "root/dir/sub"} assert found["root/dir/sub"]["type"] == "directory" assert "S" not in queried and "other" not in queried + assert listing_fs.find("root/dir", 1, True, True) == found + assert listing_fs.find("root/dir", True) == listing_fs.find( + "root/dir", detail=True + ) assert listing_fs.find("root/dir", maxdepth=1) == ["root/dir/file"] assert set( listing_fs.expand_path("root/dir", recursive=True, maxdepth=1) From ea96fec2ef31ad03fa042f96b1b247450e0b8cf2 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 22:58:51 -0800 Subject: [PATCH 3/8] Avoid redundant Drive lookups during find and normalize directory entries --- pydrive2/fs/spec.py | 92 ++++++++++++++++---------------- pydrive2/test/test_fs_listing.py | 1 + pydrive2/test/test_fs_unit.py | 59 ++++++++++++++++++++ 3 files changed, 106 insertions(+), 46 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index be368d5..6dc451c 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -66,9 +66,13 @@ class GDriveAuthError(Exception): pass +def _directory_entry(name): + return {"name": name, "type": "directory", "size": 0} + + def _file_entry(name, item): if item["mimeType"] == FOLDER_MIME_TYPE: - return {"name": name.rstrip("/") + "/", "type": "directory", "size": 0} + return _directory_entry(name.rstrip("/") + "/") size = item.get("size") return { "name": name, @@ -394,7 +398,10 @@ def _list_params(self): if self.root == "appDataFolder": params["spaces"] = "appDataFolder" elif self.root != "root": - drive_id = self._gdrive_shared_drive_id(self.root) + try: + drive_id, _ = self._root_location + except FileNotFoundError as exc: + raise PermissionError from exc if drive_id: logger.debug( f"GDrive remote '{self.path}' is using shared drive id '{drive_id}'." @@ -403,24 +410,13 @@ def _list_params(self): params["corpora"] = "drive" return params + @cached_property @_gdrive_retry - def _gdrive_shared_drive_id(self, item_id): - from pydrive2.files import ApiRequestError - - param = {"id": item_id} - # it does not create a file on the remote - item = self.client.CreateFile(param) - # ID of the shared drive the item resides in. - # Only populated for items in shared drives. - try: - item.FetchMetadata("driveId") - except ApiRequestError as exc: - error_code = exc.error.get("code", 0) - if error_code == 404: - raise PermissionError from exc - raise - - return item.get("driveId", None) + def _root_location(self): + item = self.client.CreateFile({"id": self.root}) + with _translate_not_found(self.root): + item.FetchMetadata("driveId,mimeType") + return item.get("driveId"), item.get("mimeType") def _gdrive_list(self, query): param = { @@ -560,11 +556,15 @@ def exists(self, path): else: return True - @_gdrive_retry def info(self, path): - bucket, base = self.split_path(path) with _translate_not_found(path): item_id = self._get_item_id(path) + return self._info_by_id(path, item_id) + + @_gdrive_retry + def _info_by_id(self, path, item_id): + bucket, base = self.split_path(path) + with _translate_not_found(path): gdrive_file = self.client.CreateFile({"id": item_id}) fields = _INFO_FIELDS if base else f"{_INFO_FIELDS},trashed" gdrive_file.FetchMetadata(fields=fields) @@ -640,20 +640,16 @@ def descend(name): known_dir = (not base and root in {"root", "appDataFolder"}) or ( base != self.base and any(known.get(i) == base for i in start_ids) ) - contents = [] - if withdirs or not pending: - if known_dir: - entry = _file_entry(start, {"mimeType": FOLDER_MIME_TYPE}) - else: - try: - entry = self.info(path) - except FileNotFoundError: - return {} if detail else [] - if entry["type"] == "file": - return {start: entry} if detail else [start] - if withdirs: - contents.append(entry) + root_type = None + if not base and root not in {"root", "appDataFolder"}: + try: + _, root_type = self._root_location + except FileNotFoundError: + return {} if detail else [] + if root_type != FOLDER_MIME_TYPE: + pending = {} + contents = [] seen: set[str] = set() while pending: query_ids = pending @@ -672,30 +668,34 @@ def descend(name): ): continue parent_id = root + known_dir = True item_path = posixpath.join(query_ids[parent_id], item["name"]) + name = posixpath.join(root, item_path) if item["mimeType"] == FOLDER_MIME_TYPE: item_id = item["id"] self._cache_path_id(item_path, item_id, cache=cache) if item_id not in seen and descend(item_path): pending[item_id] = item_path - if not withdirs: - continue - contents.append( - _file_entry(posixpath.join(root, item_path), item) - ) - - # An untyped mount ID can also refer directly to a file. - if not contents and not known_dir and not withdirs: + if withdirs: + contents.append(_directory_entry(name)) + else: + contents.append(_file_entry(name, item)) + + if not known_dir and (withdirs or root_type != FOLDER_MIME_TYPE): + # Without children, an untyped starting path can be a file or + # an empty directory. Check current metadata (including trash). try: - entry = self.info(path) + entry = self._info_by_id(path, min(start_ids)) except FileNotFoundError: return {} if detail else [] if entry["type"] == "file": - contents.append(entry) + return {start: entry} if detail else [start] + if withdirs: + contents.insert(0, _directory_entry(start)) if detail: - return {entry["name"].rstrip("/"): entry for entry in contents} - return [entry["name"].rstrip("/") for entry in contents] + return {entry["name"]: entry for entry in contents} + return [entry["name"] for entry in contents] def upload_fobj(self, stream, rpath, callback=None, **kwargs): parent, name = self._split_file_path(rpath) diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index b9a0a8f..1bf564a 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -290,6 +290,7 @@ def list_ids(parents, *, name=None): found = listing_fs.find("root/dir", maxdepth=1, withdirs=True, detail=True) assert set(found) == {"root/dir", "root/dir/file", "root/dir/sub"} assert found["root/dir/sub"]["type"] == "directory" + assert all(name == item["name"] for name, item in found.items()) assert "S" not in queried and "other" not in queried assert listing_fs.find("root/dir", 1, True, True) == found assert listing_fs.find("root/dir", True) == listing_fs.find( diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 23ff39d..bc3226f 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -352,3 +352,62 @@ def test_large_write_after_close_does_not_open_a_tempfile(mock_drive, mocker): with pytest.raises(ValueError, match="closed"): writer.write(b"too large") backing_file.assert_not_called() + + +@pytest.mark.parametrize("withdirs", [True, False]) +def test_find_mount_with_only_subdirectories_skips_stat(mock_drive, withdirs): + folder = { + "name": "sub", + "id": "sub-id", + "mimeType": FOLDER_MIME_TYPE, + "parents": ["FolderID"], + } + listing = response({"files": [folder]}) + drive, requests = mock_drive( + response({"driveId": "shared", "mimeType": FOLDER_MIME_TYPE}), + listing, + listing, + ) + fs = filesystem(drive, "FolderID") + for _ in range(2): + found = fs.find("FolderID", maxdepth=1, withdirs=withdirs, detail=True) + assert set(found) == ( + {"FolderID", "FolderID/sub"} if withdirs else set() + ) + assert all(name == item["name"] for name, item in found.items()) + scope, *lists = requests + assert set(query(scope)["fields"][0].split(",")) == {"driveId", "mimeType"} + assert all("'FolderID' in parents" in query(r)["q"][0] for r in lists) + + +@pytest.mark.parametrize("bare", [True, False]) +def test_find_file_returns_stat(mock_drive, bare): + obj = {"id": "Blob", "name": "note", "mimeType": "text/plain", "size": "7"} + if bare: + drive, requests = mock_drive( + response({"mimeType": "text/plain"}), response(obj) + ) + fs, path = filesystem(drive, "Blob"), "Blob" + else: + named = response({"files": [obj]}) + drive, requests = mock_drive(named, response(obj)) + fs, path = filesystem(drive), "root/note" + assert fs.find(path, withdirs=True, detail=True) == { + path: {"name": path, "type": "file", "size": 7, "checksum": None} + } + if bare: + assert all("q" not in query(r) for r in requests) + + +def test_find_empty_folder_checks_trash_when_including_start(mock_drive): + empty = response({"files": []}) + drive, requests = mock_drive( + response({"mimeType": FOLDER_MIME_TYPE}), + empty, + empty, + response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}), + ) + fs = filesystem(drive, "FolderID") + assert fs.find("FolderID") == [] + assert len(requests) == 2 + assert fs.find("FolderID", withdirs=True) == [] From 7b47fa3e5224373edc785d34d89528e12c4276ac Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 22:59:58 -0800 Subject: [PATCH 4/8] Group find request tests with traversal coverage --- pydrive2/test/test_fs_unit.py | 118 +++++++++++++++++----------------- 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index bc3226f..77cf11a 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -35,6 +35,65 @@ def test_find_accepts_canonical_parent_of_root_alias(mock_drive, root): assert query(listing)["spaces"] == ["appDataFolder"] +@pytest.mark.parametrize("withdirs", [True, False]) +def test_find_mount_with_only_subdirectories_skips_stat(mock_drive, withdirs): + folder = { + "name": "sub", + "id": "sub-id", + "mimeType": FOLDER_MIME_TYPE, + "parents": ["FolderID"], + } + listing = response({"files": [folder]}) + drive, requests = mock_drive( + response({"driveId": "shared", "mimeType": FOLDER_MIME_TYPE}), + listing, + listing, + ) + fs = filesystem(drive, "FolderID") + for _ in range(2): + found = fs.find("FolderID", maxdepth=1, withdirs=withdirs, detail=True) + assert set(found) == ( + {"FolderID", "FolderID/sub"} if withdirs else set() + ) + assert all(name == item["name"] for name, item in found.items()) + scope, *lists = requests + assert set(query(scope)["fields"][0].split(",")) == {"driveId", "mimeType"} + assert all("'FolderID' in parents" in query(r)["q"][0] for r in lists) + + +@pytest.mark.parametrize("bare", [True, False]) +def test_find_file_returns_stat(mock_drive, bare): + obj = {"id": "Blob", "name": "note", "mimeType": "text/plain", "size": "7"} + if bare: + drive, requests = mock_drive( + response({"mimeType": "text/plain"}), response(obj) + ) + fs, path = filesystem(drive, "Blob"), "Blob" + else: + named = response({"files": [obj]}) + drive, requests = mock_drive(named, response(obj)) + fs, path = filesystem(drive), "root/note" + assert fs.find(path, withdirs=True, detail=True) == { + path: {"name": path, "type": "file", "size": 7, "checksum": None} + } + if bare: + assert all("q" not in query(r) for r in requests) + + +def test_find_empty_folder_checks_trash_when_including_start(mock_drive): + empty = response({"files": []}) + drive, requests = mock_drive( + response({"mimeType": FOLDER_MIME_TYPE}), + empty, + empty, + response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}), + ) + fs = filesystem(drive, "FolderID") + assert fs.find("FolderID") == [] + assert len(requests) == 2 + assert fs.find("FolderID", withdirs=True) == [] + + def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): parents = [f"parent-{i}" for i in range(51)] shared = { @@ -352,62 +411,3 @@ def test_large_write_after_close_does_not_open_a_tempfile(mock_drive, mocker): with pytest.raises(ValueError, match="closed"): writer.write(b"too large") backing_file.assert_not_called() - - -@pytest.mark.parametrize("withdirs", [True, False]) -def test_find_mount_with_only_subdirectories_skips_stat(mock_drive, withdirs): - folder = { - "name": "sub", - "id": "sub-id", - "mimeType": FOLDER_MIME_TYPE, - "parents": ["FolderID"], - } - listing = response({"files": [folder]}) - drive, requests = mock_drive( - response({"driveId": "shared", "mimeType": FOLDER_MIME_TYPE}), - listing, - listing, - ) - fs = filesystem(drive, "FolderID") - for _ in range(2): - found = fs.find("FolderID", maxdepth=1, withdirs=withdirs, detail=True) - assert set(found) == ( - {"FolderID", "FolderID/sub"} if withdirs else set() - ) - assert all(name == item["name"] for name, item in found.items()) - scope, *lists = requests - assert set(query(scope)["fields"][0].split(",")) == {"driveId", "mimeType"} - assert all("'FolderID' in parents" in query(r)["q"][0] for r in lists) - - -@pytest.mark.parametrize("bare", [True, False]) -def test_find_file_returns_stat(mock_drive, bare): - obj = {"id": "Blob", "name": "note", "mimeType": "text/plain", "size": "7"} - if bare: - drive, requests = mock_drive( - response({"mimeType": "text/plain"}), response(obj) - ) - fs, path = filesystem(drive, "Blob"), "Blob" - else: - named = response({"files": [obj]}) - drive, requests = mock_drive(named, response(obj)) - fs, path = filesystem(drive), "root/note" - assert fs.find(path, withdirs=True, detail=True) == { - path: {"name": path, "type": "file", "size": 7, "checksum": None} - } - if bare: - assert all("q" not in query(r) for r in requests) - - -def test_find_empty_folder_checks_trash_when_including_start(mock_drive): - empty = response({"files": []}) - drive, requests = mock_drive( - response({"mimeType": FOLDER_MIME_TYPE}), - empty, - empty, - response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}), - ) - fs = filesystem(drive, "FolderID") - assert fs.find("FolderID") == [] - assert len(requests) == 2 - assert fs.find("FolderID", withdirs=True) == [] From 939eee97aa9e2aa2ff01a277dcecbada6a8688c3 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 08:49:31 -0800 Subject: [PATCH 5/8] Check find depth through Drive listings, glob and expand_path --- pydrive2/test/test_fs.py | 11 ++++++++ pydrive2/test/test_fs_listing.py | 47 -------------------------------- pydrive2/test/test_fs_unit.py | 47 ++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 47 deletions(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index cc444a6..56de02b 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -297,6 +297,17 @@ def test_find(fs, fs_factory, remote_dir): file for file in files if file.startswith(remote_dir + "/dir/c/d/") } + start = remote_dir + "/dir/c" + children = {start + suffix for suffix in ("/a", "/b", "/d")} + found = test_fs.find(start, maxdepth=1, withdirs=True, detail=True) + assert set(found) == children | {start} + assert found[start + "/d"]["type"] == "directory" + assert all(name == entry["name"] for name, entry in found.items()) + assert set(test_fs.glob(start + "/*")) == children + assert set( + test_fs.expand_path(start, recursive=True, maxdepth=1) + ) == set(found) + # General find test assert set(test_fs.find(remote_dir)) == set(files) diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index 4f154e9..95a1679 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -345,50 +345,3 @@ def test_failed_removal_preserves_cache(listing_fs, mocker): with pytest.raises(PermissionError): listing_fs.rm_file("root/dir") assert listing_fs.exists("root/dir") - - -@pytest.mark.parametrize("warm", [False, True]) -def test_find_honors_depth_and_directories(listing_fs, monkeypatch, warm): - tree = { - "root": [ - ("dir", "D", FOLDER_MIME_TYPE), - ("dir2", "other", FOLDER_MIME_TYPE), - ], - "D": [("file", "F", "text/plain"), ("sub", "S", FOLDER_MIME_TYPE)], - "S": [("deep", "G", "text/plain")], - } - queried = [] - - def list_ids(parents, *, name=None): - queried.extend(parents) - return ( - {"id": item_id, "name": n, "mimeType": mime, "parents": [parent]} - for parent in parents - for n, item_id, mime in tree.get(parent, ()) - if name is None or n == name - ) - - monkeypatch.setattr(listing_fs, "_gdrive_list_ids", list_ids) - if warm: - listing_fs.find("root") - queried.clear() - found = listing_fs.find("root/dir", maxdepth=1, withdirs=True, detail=True) - assert set(found) == {"root/dir", "root/dir/file", "root/dir/sub"} - assert found["root/dir/sub"]["type"] == "directory" - assert all(name == item["name"] for name, item in found.items()) - assert "S" not in queried and "other" not in queried - assert listing_fs.find("root/dir", 1, True, True) == found - assert listing_fs.find("root/dir", True) == listing_fs.find( - "root/dir", detail=True - ) - assert listing_fs.find("root/dir", maxdepth=1) == ["root/dir/file"] - assert set( - listing_fs.expand_path("root/dir", recursive=True, maxdepth=1) - ) == set(found) - assert set(listing_fs.glob("root/dir/*")) == { - "root/dir/file", - "root/dir/sub", - } - assert listing_fs._ids_cache["dirs"]["dir"] == ["D"] - with pytest.raises(ValueError, match="maxdepth"): - listing_fs.find("root", maxdepth=-1) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 77cf11a..83ff729 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -94,6 +94,53 @@ def test_find_empty_folder_checks_trash_when_including_start(mock_drive): assert fs.find("FolderID", withdirs=True) == [] +@pytest.mark.parametrize("warm", [False, True]) +def test_find_at_depth_one_only_lists_the_requested_directory( + mock_drive, warm +): + folder = {"name": "dir", "id": "D", "mimeType": FOLDER_MIME_TYPE} + sub = dict(folder, name="sub", id="S", parents=["D"]) + sibling = dict(folder, name="dir2", id="other") + file = { + "name": "file", + "id": "F", + "mimeType": "text/plain", + "parents": ["D"], + } + warmup = ( + [response({"files": [sub]}), response({"files": [sibling]})] + if warm + else [] + ) + drive, requests = mock_drive( + response({"files": [folder]}), + *warmup, + response({"files": [sub, file]}), + ) + fs = filesystem(drive) + if warm: + assert fs.exists("root/dir/sub") + assert fs.exists("root/dir2") + found = fs.find("root/dir", 1, True, True) + assert set(found) == {"root/dir", "root/dir/sub", "root/dir/file"} + assert query(requests[-1])["q"] == ["('D' in parents) and trashed=false"] + + +def test_find_legacy_positional_detail_and_invalid_depth(mock_drive): + item = { + "name": "file", + "id": "F", + "mimeType": "text/plain", + "parents": ["root"], + } + page = response({"files": [item]}) + drive, _ = mock_drive(page, page) + fs = filesystem(drive) + assert fs.find("root", True) == fs.find("root", detail=True) + with pytest.raises(ValueError, match="maxdepth"): + fs.find("root", maxdepth=-1) + + def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): parents = [f"parent-{i}" for i in range(51)] shared = { From 1dc810a85e2268d42dad294c541740083ae99102 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 08:50:35 -0800 Subject: [PATCH 6/8] Reuse the shared Drive listing fixtures for depth checks --- pydrive2/test/test_fs_unit.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 9a2bc65..ab03c0b 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -107,24 +107,16 @@ def test_find_empty_folder_checks_trash_when_including_start(mock_drive): def test_find_at_depth_one_only_lists_the_requested_directory( mock_drive, warm ): - folder = {"name": "dir", "id": "D", "mimeType": FOLDER_MIME_TYPE} - sub = dict(folder, name="sub", id="S", parents=["D"]) - sibling = dict(folder, name="dir2", id="other") + sub = dict(folder("sub", "S"), parents=["D"]) file = { "name": "file", "id": "F", "mimeType": "text/plain", "parents": ["D"], } - warmup = ( - [response({"files": [sub]}), response({"files": [sibling]})] - if warm - else [] - ) + warmup = [listing(sub), listing(folder("dir2", "other"))] if warm else [] drive, requests = mock_drive( - response({"files": [folder]}), - *warmup, - response({"files": [sub, file]}), + listing(folder("dir", "D")), *warmup, listing(sub, file) ) fs = filesystem(drive) if warm: @@ -132,7 +124,9 @@ def test_find_at_depth_one_only_lists_the_requested_directory( assert fs.exists("root/dir2") found = fs.find("root/dir", 1, True, True) assert set(found) == {"root/dir", "root/dir/sub", "root/dir/file"} - assert query(requests[-1])["q"] == ["('D' in parents) and trashed=false"] + assert re.findall( + r"'([^']+)' in parents", query(requests[-1])["q"][0] + ) == ["D"] def test_find_legacy_positional_detail_and_invalid_depth(mock_drive): From c08c32ff56ea8598fd61589e1bb29f8737bf973a Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 18:14:56 -0800 Subject: [PATCH 7/8] Use Drive listing metadata directly and guard traversal request counts --- pydrive2/fs/spec.py | 117 ++++++++++++++++++-------------- pydrive2/test/test_fs_unit.py | 123 +++++++++++++++++++++++++++++----- 2 files changed, 175 insertions(+), 65 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 8a12a8a..1aceda6 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -433,16 +433,24 @@ def _list_params(self): return params @_gdrive_retry - def _get_root_metadata(self): + def _get_root_metadata(self, *, file_details=False): with self._cache_lock: # A root invalidation during the request replaces this dictionary. metadata = self._root_metadata - if not metadata: - item = self.client.CreateFile({"id": self.root}) - with _translate_not_found(self.root): - item.FetchMetadata("driveId,mimeType,trashed") - if item.get("trashed"): - return item.metadata + if metadata and ( + not file_details + or metadata.get("mimeType") == FOLDER_MIME_TYPE + ): + return metadata + item = self.client.CreateFile({"id": self.root}) + fields = ( + f"driveId,trashed,{_INFO_FIELDS}" + if file_details + else "driveId,mimeType,trashed" + ) + with _translate_not_found(self.root): + item.FetchMetadata(fields) + if not item.get("trashed") and not metadata: metadata.update(item.metadata) if drive_id := metadata.get("driveId"): logger.debug( @@ -450,7 +458,7 @@ def _get_root_metadata(self): self.path, drive_id, ) - return metadata + return item.metadata def _gdrive_list(self, query): param = { @@ -486,22 +494,19 @@ def _gdrive_list_ids(self, query_ids, *, name=None): seen_ids.add(file_id) yield item - def _get_remote_item_ids( + def _get_remote_items( self, parent_ids, parent_path, name, use_cache=True, cache=None ): if not parent_ids: - return None + return if use_cache and cache is None: cache = self._ids_cache - res = [] for item in self._named_items(parent_ids, name): - res.append(item["id"]) if item["mimeType"] == FOLDER_MIME_TYPE and use_cache: self._cache_path_id( posixpath.join(parent_path, name), item["id"], cache=cache ) - - return res + yield item def _get_cached_item_ids(self, path, use_cache, cache=None): if not path: @@ -531,9 +536,10 @@ def _path_to_item_ids( parent_ids = self._path_to_item_ids( parent_path, create, use_cache, cache ) - item_ids = self._get_remote_item_ids( + items = self._get_remote_items( parent_ids, parent_path, name, use_cache, cache ) + item_ids = [item["id"] for item in items] if item_ids: return item_ids @@ -660,15 +666,11 @@ def exists(self, path): else: return True - def info(self, path): - with _translate_not_found(path): - item_id = self._get_item_id(path) - return self._info_by_id(path, item_id) - @_gdrive_retry - def _info_by_id(self, path, item_id): + def info(self, path): bucket, base = self.split_path(path) 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_file.FetchMetadata(fields=fields) @@ -701,6 +703,28 @@ def ls(self, path, detail=False): else: return [content["name"] for content in contents] + def _find_start(self, base, cache, mount_items): + """Return matching folder IDs or a file from the same Drive listing.""" + dirs = self._get_cached_item_ids(base, True, cache) + if dirs: + return dirs, None + if base == self.base and mount_items is not None: + items = mount_items + else: + parent, name = posixpath.split(base) + parents = self._path_to_item_ids(parent, cache=cache) + items = list( + self._get_remote_items(parents, parent, name, cache=cache) + ) + dirs = [ + item["id"] + for item in items + if item["mimeType"] == FOLDER_MIME_TYPE + ] + if dirs: + return dirs, None + return [], min(items, key=lambda item: item["id"], default=None) + def find( self, path, maxdepth=None, withdirs=False, detail=False, **kwargs ): @@ -714,8 +738,25 @@ def find( # Older fsspec expand_path passes zero for a single-level listing. if maxdepth == 0: maxdepth = 1 - cache = self._ids_cache - start_ids = self._path_to_item_ids(base, cache=cache) + cache, mount_items = self._directory_cache_and_mount_items() + start_ids, file = self._find_start(base, cache, mount_items) + start = posixpath.join(root, base).rstrip("/") + check_empty_root = False + if not base and root not in {"root", "appDataFolder"}: + # A cold stat verifies trash status for this call. A cached folder + # still needs a fresh check if only the root itself would be returned. + with self._cache_lock: + check_empty_root = withdirs and bool(self._root_metadata) + try: + metadata = self._get_root_metadata(file_details=True) + except FileNotFoundError: + return {} if detail else [] + if metadata.get("trashed"): + return {} if detail else [] + if metadata["mimeType"] != FOLDER_MIME_TYPE: + file = metadata + if file is not None: + return {start: _file_entry(start, file)} if detail else [start] if not start_ids: return {} if detail else [] @@ -735,28 +776,10 @@ def descend(name): with self._cache_lock: known = cache["ids"].copy() - if not base: - known[root] = "" + known.update(dict.fromkeys(start_ids, base)) pending = { item_id: name for item_id, name in known.items() if descend(name) } - start = posixpath.join(root, base).rstrip("/") - known_dir = ( - any(known.get(item_id) == base for item_id in start_ids) - if base - else root in {"root", "appDataFolder"} - ) - root_type = None - if not base and not known_dir: - try: - metadata = self._get_root_metadata() - except FileNotFoundError: - return {} if detail else [] - if metadata.get("trashed"): - return {} if detail else [] - root_type = metadata.get("mimeType") - if root_type != FOLDER_MIME_TYPE: - pending = {} contents = [] seen: set[str] = set() @@ -777,7 +800,7 @@ def descend(name): ): continue parent_id = root - known_dir = True + check_empty_root = False item_path = posixpath.join(query_ids[parent_id], item["name"]) name = posixpath.join(root, item_path) if item["mimeType"] == FOLDER_MIME_TYPE: @@ -790,15 +813,11 @@ def descend(name): else: contents.append(_file_entry(name, item)) - if not known_dir and (withdirs or root_type != FOLDER_MIME_TYPE): - # Without children, an untyped starting path can be a file or - # an empty directory. Check current metadata (including trash). + if check_empty_root: try: - entry = self._info_by_id(path, min(start_ids)) + self.info(path) except FileNotFoundError: return {} if detail else [] - if entry["type"] == "file": - return {start: entry} if detail else [start] if withdirs: contents.insert(0, _directory_entry(start)) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 6cd1fae..7a74403 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -103,23 +103,42 @@ def test_find_trashed_root_id_skips_listing(mock_drive): @pytest.mark.parametrize("mount", ["Blob", "root", "root/note"]) def test_find_file_returns_stat(mock_drive, mount): - obj = {"id": "Blob", "name": "note", "mimeType": "text/plain", "size": "7"} - if mount == "Blob": - drive, requests = mock_drive( - response({"mimeType": "text/plain"}), response(obj) + first = { + "id": "Blob", + "name": "note", + "mimeType": "text/plain", + "size": "7", + "md5Checksum": "original", + } + updated = dict(first, size="9", md5Checksum="updated") + bare = mount == "Blob" + path = mount if bare else "root/note" + drive, requests = mock_drive( + *( + response(item) if bare else listing(item) + for item in (first, updated) ) - path = mount - else: - path = "root/note" - named = response({"files": [obj]}) - mount_lookup = [named] if mount == path else [] - drive, requests = mock_drive(*mount_lookup, named, response(obj)) + ) fs = filesystem(drive, mount) - assert fs.find(path, withdirs=True, detail=True) == { - path: {"name": path, "type": "file", "size": 7, "checksum": None} - } - if mount == "Blob": - assert all("q" not in query(r) for r in requests) + for item in (first, updated): + before = len(requests) + assert fs.find(path, withdirs=True, detail=True) == { + path: { + "name": path, + "type": "file", + "size": int(item["size"]), + "checksum": item["md5Checksum"], + } + } + (get,) = requests[before:] + assert get[1] == "GET" + if bare: + assert urlsplit(get[0]).path.endswith("/files/Blob") + assert {"trashed", "size", "md5Checksum"} <= set( + query(get)["fields"][0].split(",") + ) + else: + assert "name='note'" in query(get)["q"][0] def test_find_empty_folder_checks_trash_when_including_start(mock_drive): @@ -131,7 +150,7 @@ def test_find_empty_folder_checks_trash_when_including_start(mock_drive): response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}), ) fs = filesystem(drive, "FolderID") - assert fs.find("FolderID") == [] + assert fs.find("FolderID", withdirs=True) == ["FolderID"] assert len(requests) == 2 assert fs.find("FolderID", withdirs=True) == [] @@ -162,6 +181,40 @@ def test_find_at_depth_one_only_lists_the_requested_directory( ) == ["D"] +@pytest.mark.parametrize("operation", ["glob", "expand_path"]) +def test_fsspec_traversal_lists_one_level(mock_drive, operation): + sub = dict(folder("sub", "S"), parents=["D"]) + file = { + "name": "file", + "id": "F", + "mimeType": "text/plain", + "parents": ["D"], + } + drive, requests = mock_drive( + listing(folder("dir", "D")), listing(sub, file), listing(sub, file) + ) + fs = filesystem(drive) + path = "root/dir" + children = {path + "/sub", path + "/file"} + for cold in (True, False): + before = len(requests) + if operation == "glob": + assert set(fs.glob(path + "/*")) == children + else: + assert set( + fs.expand_path(path, recursive=True, maxdepth=1) + ) == children | {path} + calls = requests[before:] + if cold: + lookup, children_request = calls + assert "name='dir'" in query(lookup)["q"][0] + else: + (children_request,) = calls + assert re.findall( + r"'([^']+)' in parents", query(children_request)["q"][0] + ) == ["D"] + + def test_find_legacy_positional_detail_and_invalid_depth(mock_drive): item = { "name": "file", @@ -177,6 +230,44 @@ def test_find_legacy_positional_detail_and_invalid_depth(mock_drive): fs.find("root", maxdepth=-1) +@pytest.mark.parametrize("bare", [True, False]) +def test_find_missing_path_uses_one_lookup(mock_drive, bare): + drive, requests = mock_drive( + error_response(404, "notFound") if bare else listing() + ) + mount, path = ("missing", "missing") if bare else ("root", "root/missing") + assert filesystem(drive, mount).find(path, withdirs=True) == [] + (lookup,) = requests + assert lookup[1] == "GET" + assert ("q" in query(lookup)) == (not bare) + + +def test_recursive_remove_does_not_relist_each_directory(mock_drive): + sub = dict(folder("sub", "S"), parents=["D"]) + file = { + "name": "file", + "id": "F", + "mimeType": "text/plain", + "parents": ["S"], + } + drive, requests = mock_drive( + listing(folder("dir", "D")), + listing(sub), + listing(file), + listing(file), + response({}), + response({}), + response({}), + ) + fs = filesystem(drive, trash_only=False) + fs.rm("root/dir", recursive=True) + assert [req[1] for req in requests] == ["GET"] * 4 + ["DELETE"] * 3 + assert [ + urlsplit(req[0]).path.rsplit("/", 1)[-1] for req in requests[-3:] + ] == ["F", "S", "D"] + assert all("q" in query(req) for req in requests[:4]) + + def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): parents = [f"parent-{i}" for i in range(51)] shared = { From 069fb0ffcd2e9c53b8c54a86a772fcd22b82ce46 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 18:20:11 -0800 Subject: [PATCH 8/8] Count Drive requests for cold and warm wide traversals --- pydrive2/test/test_fs_listing.py | 47 --------------------------- pydrive2/test/test_fs_unit.py | 54 ++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 47 deletions(-) diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index 5cd70cd..1b9fca6 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -4,7 +4,6 @@ import pytest from pydrive2.fs import GDriveFileSystem -from pydrive2.fs.spec import FOLDER_MIME_TYPE @pytest.fixture @@ -62,49 +61,3 @@ def parents(): assert list(result) == [{"id": "last"}] assert len(consumed) == 51 assert list_query.call_count == 2 - - -@pytest.mark.parametrize("detail", [False, True]) -def test_find_wide_directory(listing_fs, monkeypatch, detail): - folders = [f"folder-{index}" for index in range(251)] - - def list_query(query): - parents = re.findall(r"'([^']+)' in parents", query) - assert 0 < len(parents) <= 50 - if parents == ["root"]: - return iter( - { - "id": folder, - "name": folder, - "mimeType": FOLDER_MIME_TYPE, - "parents": ["root"], - } - for folder in folders - ) - return iter( - { - "id": f"data-{parent}", - "name": "data", - "mimeType": "application/octet-stream", - "parents": [parent], - "size": "7", - "md5Checksum": "checksum", - } - for parent in parents - ) - - monkeypatch.setattr(listing_fs, "_gdrive_list", list_query) - files = listing_fs.find("root", detail=detail) - expected = [f"root/{folder}/data" for folder in folders] - assert list(files) == expected - if detail: - assert all( - item - == { - "name": path, - "type": "file", - "size": 7, - "checksum": "checksum", - } - for path, item in files.items() - ) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 7a74403..7c77a77 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -215,6 +215,60 @@ def test_fsspec_traversal_lists_one_level(mock_drive, operation): ) == ["D"] +@pytest.mark.parametrize("detail", [False, True]) +def test_find_wide_directory(mock_drive, detail): + ids = [f"folder-{index}" for index in range(251)] + folders = [dict(folder(i, i), parents=["root"]) for i in ids] + files = [ + { + "id": f"data-{parent}", + "name": "data", + "mimeType": "application/octet-stream", + "parents": [parent], + "size": "7", + "md5Checksum": "checksum", + } + for parent in ids + ] + # Cold, the root must be listed before its 251 children are known. + # Warm, the root and the first 49 parents fit in the same query. + cold_pages = [listing(*folders)] + [ + listing(*files[i : i + 50]) for i in range(0, len(files), 50) + ] + warm_pages = [listing(*folders, *files[:49])] + [ + listing(*files[i : i + 50]) for i in range(49, len(files), 50) + ] + drive, requests = mock_drive(*cold_pages, *warm_pages) + fs = filesystem(drive) + expected = [f"root/{parent}/data" for parent in ids] + for expected_calls in (7, 6): + before = len(requests) + found = fs.find("root", detail=detail) + assert list(found) == expected + if detail: + assert all( + item + == { + "name": path, + "type": "file", + "size": 7, + "checksum": "checksum", + } + for path, item in found.items() + ) + calls = requests[before:] + assert len(calls) == expected_calls + batches = [ + re.findall(r"'([^']+)' in parents", query(req)["q"][0]) + for req in calls + ] + assert all(0 < len(batch) <= 50 for batch in batches) + assert [parent for batch in batches for parent in batch] == [ + "root", + *ids, + ] + + def test_find_legacy_positional_detail_and_invalid_depth(mock_drive): item = { "name": "file",