diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0a15012..124a9cc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -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" diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 4ce5d67..ba756a6 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -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 diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 933e42c..2241772 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -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 @@ -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, @@ -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 @@ -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: @@ -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( @@ -742,6 +752,8 @@ 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 @@ -749,15 +761,70 @@ def _walk_folders(self, base, start_ids, cache): 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] diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 4ae1a60..4abfaf8 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -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) 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 1c20778..8bcafe2 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -46,6 +46,321 @@ 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") + fs.makedirs("FolderID", exist_ok=True) + 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", + "trashed", + } + assert all("'FolderID' in parents" in query(r)["q"][0] for r in lists) + + +@pytest.mark.parametrize("withdirs", [False, True]) +def test_find_empty_named_mount_uses_its_listing_type(mock_drive, withdirs): + drive, requests = mock_drive( + listing(folder("empty", "E")), listing(), listing() + ) + path = "root/empty" + fs = filesystem(drive, path) + for _ in range(2): + assert fs.find(path, withdirs=withdirs) == ([path] if withdirs else []) + lookup, first, second = requests + assert "name='empty'" in query(lookup)["q"][0] + assert all( + "'E' in parents" in query(req)["q"][0] for req in (first, second) + ) + + +def test_find_trashed_root_id_skips_listing(mock_drive): + drive, requests = mock_drive( + response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}) + ) + fs = filesystem(drive, "FolderID") + assert fs.find("FolderID", withdirs=True, detail=True) == {} + (stat,) = requests + assert "trashed" in query(stat)["fields"][0].split(",") + + +@pytest.mark.parametrize("mount", ["Blob", "root", "root/note"]) +def test_find_file_returns_stat(mock_drive, mount): + 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) + ) + ) + fs = filesystem(drive, mount) + 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): + 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", withdirs=True) == ["FolderID"] + assert len(requests) == 2 + 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 +): + sub = dict(folder("sub", "S"), parents=["D"]) + file = { + "name": "file", + "id": "F", + "mimeType": "text/plain", + "parents": ["D"], + } + warmup = [listing(sub), listing(folder("dir2", "other"))] if warm else [] + drive, requests = mock_drive( + listing(folder("dir", "D")), *warmup, listing(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 re.findall( + r"'([^']+)' in parents", query(requests[-1])["q"][0] + ) == ["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"] + + +@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 = sorted(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, + ] + + +@pytest.mark.parametrize("operation", ["find", "expand_path"]) +@pytest.mark.parametrize("maxdepth", [1, 2, 3]) +def test_bounded_traversal_from_root(mock_drive, operation, maxdepth): + folders = [ + dict(folder("a", "A"), parents=["root"]), + dict(folder("b", "B"), parents=["A"]), + dict(folder("c", "C"), parents=["B"]), + ] + drive, requests = mock_drive( + *(listing(item) for item in folders[:maxdepth]) + ) + fs = filesystem(drive) + expected = ["root", "root/a", "root/a/b", "root/a/b/c"][: maxdepth + 1] + if operation == "find": + assert fs.find("root", withdirs=True, maxdepth=maxdepth) == expected + else: + assert ( + fs.expand_path("root", recursive=True, maxdepth=maxdepth) + == expected + ) + assert len(requests) == maxdepth + + +@pytest.mark.parametrize("pattern", ["root/*", "root/**"]) +def test_expanding_a_bounded_glob_does_not_list_children(mock_drive, pattern): + drive, requests = mock_drive( + listing(dict(folder("a", "A"), parents=["root"])) + ) + found = filesystem(drive).expand_path(pattern, recursive=True, maxdepth=1) + assert "root/a" in found + (lookup,) = requests + assert "'root' in parents" in query(lookup)["q"][0] + + +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) + with pytest.warns(DeprecationWarning, match="detail"): + legacy = fs.find("root", True) + assert legacy == fs.find("root", detail=True) + for depth in (0, -1): + with pytest.raises(ValueError, match="maxdepth"): + fs.find("root", maxdepth=depth) + + +@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 = { diff --git a/pyproject.toml b/pyproject.toml index 046cc47..075359e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,7 +46,7 @@ Source = "https://github.com/iterative/PyDrive2" Changelog = "https://github.com/iterative/PyDrive2/releases" [project.optional-dependencies] -fsspec = ["fsspec>=2021.07.0"] +fsspec = ["fsspec>=2024.2.0"] tests = [ "pytest>=4.6.0", "timeout-decorator",