Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
bb9f733
Honor depth limits and include directories in recursive find
shcheklein Nov 22, 2026
9378555
Accept fsspec positional traversal options
shcheklein Nov 22, 2026
31de611
Merge branch 'fix/fs-directory-cache-invalidation' into fix/fs-find-t…
shcheklein Nov 22, 2026
ea96fec
Avoid redundant Drive lookups during find and normalize directory ent…
shcheklein Nov 22, 2026
4efb2b4
Merge branch 'fix/fs-directory-cache-invalidation' into fix/fs-find-t…
shcheklein Nov 22, 2026
7b47fa3
Group find request tests with traversal coverage
shcheklein Nov 22, 2026
230caa1
Merge branch 'fix/fs-directory-cache-invalidation' into fix/fs-find-t…
shcheklein Nov 22, 2026
939eee9
Check find depth through Drive listings, glob and expand_path
shcheklein Nov 22, 2026
c2cb47f
Merge branch 'fix/fs-directory-cache-invalidation' into fix/fs-find-t…
shcheklein Nov 22, 2026
1dc810a
Reuse the shared Drive listing fixtures for depth checks
shcheklein Nov 22, 2026
87143fd
Merge branch 'fix/fs-directory-cache-invalidation' into fix/fs-find-t…
shcheklein Nov 22, 2026
ba9aae6
Use verified directory types and shared root metadata in find
shcheklein Nov 22, 2026
7adfaf4
Merge branch 'fix/fs-create-directories' into fix/fs-find-traversal
shcheklein Nov 23, 2026
c08c32f
Use Drive listing metadata directly and guard traversal request counts
shcheklein Nov 23, 2026
069fb0f
Count Drive requests for cold and warm wide traversals
shcheklein Nov 23, 2026
01556ba
Use shared resolution for sorted, depth-bounded Drive traversal
shcheklein Nov 24, 2026
a49a872
Use upstream bounded glob support and test the supported fsspec floor
shcheklein Nov 25, 2026
1c40447
Merge the concurrent folder creation fix from #409
shcheklein Nov 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ jobs:

- name: Install dependencies
id: install
run: python -m pip install -e '.[fsspec, tests]'
# Test the minimum on Ubuntu 3.11 and resolve the latest elsewhere.
run: python -m pip install -e '.[fsspec, tests]' "${{ matrix.os == 'ubuntu-latest' && matrix.pyv == '3.11' && 'fsspec==2024.2.0' || 'fsspec' }}"

- name: Run offline tests
run: python -m pytest -m "not manual and not drive"
Expand Down
6 changes: 6 additions & 0 deletions docs/fsspec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ alias followed by a filename. As with the direct PyDrive2 filesystem,
a write creates a Drive item even when a sibling has the same name. All
reads require credentials, including files shared by link.

The filesystem extra requires fsspec 2024.2.0 or newer. Use
``find(path, detail=True)`` to request metadata. The second positional
argument specifies traversal depth. Directory names returned by ``ls()``
and ``info()`` end in a slash. ``find(withdirs=True)`` returns directory
paths without a trailing slash, like fsspec's other traversal methods.

Drive queries for directory entries exclude trashed items. For a bare file
ID, ``exists()`` returns false and ``info()`` raises ``FileNotFoundError``
when the item is in the trash. Opening or downloading by ID requests the
Expand Down
107 changes: 87 additions & 20 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import posixpath
import tempfile
import threading
import warnings
from contextlib import contextmanager
from dataclasses import dataclass, field
from itertools import chain
Expand Down Expand Up @@ -75,9 +76,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,
Expand Down Expand Up @@ -431,7 +436,9 @@ def _list_params(self):
return params

@_gdrive_retry
def _get_root_metadata(self, *, fresh=False):
def _get_root_metadata(
self, *, fresh=False, fields="driveId,mimeType,trashed"
):
cached = self._root_metadata
if cached and not fresh:
return cached
Expand All @@ -442,7 +449,7 @@ def _get_root_metadata(self, *, fresh=False):
item = self.client.CreateFile({"id": self.root})
try:
with _translate_not_found(self.root):
item.FetchMetadata("driveId,mimeType,trashed")
item.FetchMetadata(fields)
except FileNotFoundError:
with self._cache_lock:
if self._root_metadata is cached:
Expand Down Expand Up @@ -700,22 +707,25 @@ def ls(self, path, detail=False):
else:
return [content["name"] for content in contents]

def _walk_folders(self, base, start_ids, cache):
def _walk_folders(self, base, start_ids, cache, maxdepth):
# Cache entries are hints about which parents can share a request.
# Build paths only from the parent links in the current Drive listing.
frontier = dict.fromkeys(start_ids, base)
with self._cache_lock:
to_list = dict.fromkeys(frontier)
to_list.update(
{
item_id: None
for item_id, path in cache.by_id.items()
if _in_subtrees(path, (base,))
}
)
to_list = dict.fromkeys(frontier)
if maxdepth != 1:
prefix = base + "/" if base else ""
with self._cache_lock:
for item_id, name in cache.by_id.items():
if name.startswith(prefix) and (
maxdepth is None
or name[len(prefix) :].count("/") + 1 < maxdepth
):
to_list[item_id] = None
depth = 0
children: dict[str, list[dict]] = {}
visited: set[str] = set()
while frontier:
depth += 1
children.update({item_id: [] for item_id in to_list})
for item in self._gdrive_list_ids(to_list):
parent = next(
Expand All @@ -742,22 +752,79 @@ def _walk_folders(self, base, start_ids, cache):
if item_id not in visited:
following[item_id] = path
yield path, item
if depth == maxdepth:
return
frontier = following
to_list = {
item_id: None
for item_id in frontier
if item_id not in children
}

def find(self, path, detail=False, **kwargs):
def find(
self, path, maxdepth=None, withdirs=False, detail=False, **kwargs
):
# PyDrive2 historically accepted a boolean detail as its second argument.
if isinstance(maxdepth, bool):
warnings.warn(
"Positional detail is deprecated. Pass detail=True or detail=False.",
DeprecationWarning,
stacklevel=2,
)
detail = detail or maxdepth
maxdepth = None
root, base = self._split_mounted_path(path)
if maxdepth is not None and maxdepth < 1:
raise ValueError("maxdepth must be at least 1")
cache, mount = self._directory_cache()
dirs = self._resolve_path(base, cache, mount).folders
contents = [
_file_entry(posixpath.join(root, name), item)
for name, item in self._walk_folders(base, dirs, cache)
if item["mimeType"] != FOLDER_MIME_TYPE
]
match = self._resolve_path(base, cache, mount)
file = (
min(match.files, key=lambda item: item["id"], default=None)
if not match.folders
else None
)
start = posixpath.join(root, base).rstrip("/")
check_empty_root = False
if not base and root not in {"root", "appDataFolder"}:
if self._root_metadata.get("mimeType") == FOLDER_MIME_TYPE:
check_empty_root = withdirs
else:
try:
metadata = self._get_root_metadata(
fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}"
)
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 match.folders:
return {} if detail else []

contents = []
for relative, item in self._walk_folders(
base, match.folders, cache, maxdepth
):
check_empty_root = False
name = posixpath.join(root, relative)
if item["mimeType"] == FOLDER_MIME_TYPE:
if withdirs:
contents.append(_directory_entry(name))
else:
contents.append(_file_entry(name, item))

if check_empty_root:
try:
self.info(path)
except FileNotFoundError:
return {} if detail else []

if withdirs:
contents.insert(0, _directory_entry(start))
contents.sort(key=lambda entry: entry["name"])
if detail:
return {entry["name"]: entry for entry in contents}
return [entry["name"] for entry in contents]
Expand Down
11 changes: 11 additions & 0 deletions pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,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)

Expand Down
47 changes: 0 additions & 47 deletions pydrive2/test/test_fs_listing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import pytest

from pydrive2.fs import GDriveFileSystem
from pydrive2.fs.spec import FOLDER_MIME_TYPE


@pytest.fixture
Expand Down Expand Up @@ -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()
)
Loading
Loading